pax_global_header00006660000000000000000000000064132150352250014510gustar00rootroot0000000000000052 comment=2911709ffa4eb3eea133c2b516f501a7bdb4918a open-vm-tools-stable-10.2.0/000077500000000000000000000000001321503522500155575ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/README.md000066400000000000000000000273061321503522500170460ustar00rootroot00000000000000# General ## What is the open-vm-tools project? open-vm-tools is a set of services and modules that enable several features in VMware products for better management of, and seamless user interactions with, guests. It includes kernel modules for enhancing the performance of virtual machines running Linux or other VMware supported Unix like guest operating systems. open-vm-tools enables the following features in VMware products: - The ability to perform virtual machine power operations gracefully. - Execution of VMware provided or user configured scripts in guests during various power operations. - The ability to run programs, commands and file system operation in guests to enhance guest automation. - Authentication for guest operations. - Periodic collection of network, disk, and memory usage information from the guest. - Generation of heartbeat from guests to hosts so VMware's HA solution can determine guests' availability. - Clock synchronization between guests and hosts or client desktops. - Quiescing guest file systems to allow hosts to capture file-system-consistent guest snapshots. - Execution of pre-freeze and post-thaw scripts while quiescing guest file systems. - The ability to customize guest operating systems immediately after powering on virtual machines. - Enabling shared folders between host and guest file systems on VMware Workstation and VMware Fusion. - Copying and pasting text, graphics, and files between guests and hosts or client desktops. ## Can you provide more details on the actual code being released? The following components have been released as open source software: - Linux, Solaris and FreeBSD drivers for various devices and file system access. - The memory balloon driver for reclaiming memory from guests. - The PowerOps plugin to perform graceful power operation and run power scripts. - The VIX plugin to run programs and commands, and perform file system operations in guests. - The GuestInfo plugin to periodically collect various statistics from guests. - The TimeSync plugin to perform time synchronization. - The dndcp plugin to support drag and drop, and text and file copy/paste operations. - The ResolutionSet plugin to adjust guest screen resolutions automatically based on window sizes. - The guest authentication service. - The toolbox command to perform disk wiping and shrinking, manage power scripts, and time synchronization. - The guest SDK libraries to provide information about virtual machines to guests. - Clients and servers for shared folders support. - Multiple monitor support. - The GTK Toolbox UI. ## Is open-vm-tools available with Linux distributions? Yes. open-vm-tools packages for user space components are available with new versions of major Linux distributions, and are installed as part of the OS installation in several cases. Please refer to VMware KB article http://kb.vmware.com/kb/2073803 for details. All leading Linux vendors support open-vm-tools and bundle it with their products. For information about OS compatibility for open-vm-tools, see the VMware Compatibility Guide at http://www.vmware.com/resources/compatibility Automatic installation of open-vm-tools along with the OS installation eliminates the need to separately install open-vm-tools in guests. If open-vm-tools is not installed automatically, you may be able to manually install it from the guest OS vendor's public repository. Installing open-vm-tools from the Linux vendor's repository reduces virtual machine downtime because future updates to open-vm-tools are included with the OS maintenance patches and updates. **NOTE**: Most of the Linux distributions ship two open-vm-tools packages, "open-vm-tools" and "open-vm-tools-desktop". "open-vm-tools" is the core package without any dependencies on X libraries and "open-vm-tools-desktop" is an additional package with dependencies on "open-vm-tools" core package and X libraries. The open-vm-tools packages available with Linux distributions do not include Linux drivers because Linux drivers are available as part of Linux kernel itself. Linux kernel versions 3.10 and later include all of the Linux drivers present in open-vm-tools except the vmhgfs driver. The vmhgfs driver is required for enabling shared folders feature. ## Will there be continued support for VMware Tools and OSP? VMware Tools will continue to be available under a commercial license. It is recommended that open-vm-tools be used for the Linux distributions where open-vm-tools is available. VMware will not provide OSPs for operating systems where open-vm-tools is available. ## How does this benefit other open source projects? Under the terms of the GPL, open source community members are able to use the open-vm-tools code to develop their own applications, extend it, and contribute to the community. They can also incorporate some or all of the code into their projects, provided they comply with the terms of the GPL. # License Related ## What license is the code being released under? The code is being released under GPL v2 and GPL v2 compatible licenses. To be more specific, the Linux kernel modules are being released under the GPL v2, while almost all of the user level components are being released under the LGPL v2.1. The SVGA and mouse drivers have been available under the X11 license for quite some time. There are certain third party components released under BSD style licenses, to which VMware has in some cases contributed, and will continue to distribute with open-vm-tools. ## Why did you choose these licenses? We chose the GPL v2 for the kernel components to be consistent with the Linux kernel's license. We chose the LGPL v2.1 for the user level components because some of the code is implemented as shared libraries and we do not wish to restrict proprietary code from linking against those libraries. For consistency, we decided to license the rest of the userlevel code under the LGPL v2.1 as well. ## What are the obligations that the license(s) impose? Each of these licenses have different obligations. For questions about the GPL, LGPL licenses, the Free Software Foundation's GPL FAQ page provides lots of useful information. For questions about the other licenses like the X11, BSD licenses, the Open Source Initiative has numerous useful resources including mailing lists. The Software Freedom Law Center provides legal expertise and consulting for free and open source software (FOSS) developers. ## Can I use all or part of this code in my proprietary software? Do I have to release the source code if I do? Different open source licenses have different requirements regarding the release of source code. Since the code is being released under various open source licenses, you will need to comply with the terms of the corresponding licenses. ## Am I required to contribute back any changes I make to the code? No, you aren't required to contribute any changes that you make back to the open-vm-tools project. However, we encourage you to do so. ## Can I use all or part of this code in another open source package? Yes, as long as you comply with the appropriate license(s). ## Can I package this for my favorite operating system? Yes! Please do. ## Will the commercial version (VMware Tools) differ from the open source version (open-vm-tools)? If so, how? Our goal is to work towards making the open source version as close to the commercial version as possible. However, we do currently make use of certain components licensed from third parties as well as components from other VMware products which are only available in binary form. ## If I use the code from the open-vm-tools project in my project/product, can I call my project/product VMware Tools? No, since your project/product is not a VMware project/product. # Building open-vm-tools ## How do I build open-vm-tools? open-vm-tools uses the GNU Automake tool for generating Makefiles to build all sources. More information about Automake can be found here: http://www.gnu.org/software/automake/ ## Project build information: The following steps will work on most recent Linux distributions: ``` autoreconf -i ./configure --without-kernel-modules make sudo make install sudo ldconfig ``` ## Getting configure options and help If you are looking for help or additional settings for the building of this project, the following configure command will display a list of help options: ``` ./configure --help ``` When using configure in the steps above it is only necessary to call ./configure once unless there was a problem after the first invocation. # Getting Involved ## How can I get involved today? You can get involved today in several different ways: - Start using open-vm-tools today and give us feedback. - Suggest feature enhancements. - Identify and submit bugs under issues section: https://github.com/vmware/open-vm-tools/issues - Start porting the code to other operating systems. Here is the list of operating systems with open-vm-tools: * Red Hat Enterprise Linux 7.0 and later releases * SUSE Linux Enterprise 12 and later releases * Ubuntu 14.04 and later releases * CentOS 7 and later releases * Debian 7.x and later releases * Oracle Linux 7 and later * Fedora 19 and later releases * openSUSE 11.x and later releases ## Will external developers be allowed to become committers to the project? Yes. Initially, VMware engineers will be the only committers. As we roll out our development infrastructure, we will be looking to add external committers to the project as well. ## How can I submit code changes like bug fixes, patches, new features to the project? Initially, you can submit bug fixes, patches and new features to the project development mailing list as attachments to emails or bug reports. To contribute source code, you will need to fill out a contribution agreement form as part of the submission process. We will have more details on this process shortly. ## What is the governance model for managing this as an open source project? The feature roadmap and schedules for the open-vm-tools project will continue to be defined by VMware. Initially, VMware engineers will be the only approved committers. We will review incoming submissions for suitability for merging into the project. We will be looking to add community committers to the project based on their demonstrated contributions to the project. Finally, we also plan to set up a process for enhancement proposals, establishing sub-projects and so on. ## Will you ship code that I contribute with VMware products? If so, will I get credit for my contributions? Contributions that are accepted into the open-vm-tools project's main source tree will likely be a part of VMware Tools. We also recognize the value of attribution and value your contributions. Consequently, we will acknowledge contributions from the community that are distributed with VMware's products. ## Do I need to sign something before making a contribution? Yes. We have a standard contribution agreement that covers all contributions made to the project. It gives VMware and you joint copyright interests in the code you are contributing. The agreement also gives VMware flexibility with licensing and also helps avoid any copyright/licensing related issues that may arise in the future. In order for us to include your contribution in our source tree, we ask that you send us a signed copy of the agreement. You can do this in one of two ways: Fax to +1.650.427.5003, Attn: Product & Technology Law Group Scan and email it to oss-queries_at_vmware.com Agreement: http://open-vm-tools.sourceforge.net/files/vca.pdf # Other ## Mailing Lists Please send an email to one of these mailing lists based on the nature of your question. - Development related questions : open-vm-tools-devel@lists.sourceforge.net - Miscellaneous questions: open-vm-tools-discuss@lists.sourceforge.net - General project announcements: open-vm-tools-announce@lists.sourceforge.net open-vm-tools-stable-10.2.0/ReleaseNotes.md000066400000000000000000000075531321503522500205040ustar00rootroot00000000000000# open-vm-tools 10.2.0 Release Notes Updated on 14 Dec 2017 ##What's in the Release Notes The release notes cover the following topics: - What's New - Internationalization - Compatibility - Installation and Upgrades for This Release - Known Issues ## What's New - **FreeBSD support**: freebsd.iso is not available for VMware Tools 10.2.0 and later as it has been discontinued in favor of open-vm-tools. For more information, see Compatibility Notes section of this release notes. ## Internationalization open-vm-tools 10.2.0 supports the following languages: - English - French - German - Spanish - Italian - Japanese - Korean - Simplified Chinese - Traditional Chinese ## Compatibility - open-vm-tools 10.2.0 is compatible with all supported versions of VMware vSphere ESXi 5.5 and later, VMware Workstation 14.0 and VMware Fusion 10.0. See VMware Compatibility Guide for more information. - Starting with VMware Tools version 10.2.0, Perl script based VMware Tools installation for FreeBSD has been discontinued. Going forward, FreeBSD systems are supported only through the open-vm-tools packages directly available from FreeBSD package repositories. FreeBSD packages for open-vm-tools 10.1.0 and later are available from FreeBSD package repositories. ## Installation and Upgrades for This Release The steps to install open-vm-tools vary depending on your VMware product and the guest operating system you have installed. For general steps to install open-vm-tools in most VMware products, see https://github.com/vmware/open-vm-tools/blob/master/README.md ## Resolved Issues * **Summary page of the VM does not list the IP address of the VMs in the right order** The configuration option to exclude network interfaces from GuestInfo and set primary and low priority network interfaces is added to the tools.conf configuration file. This issue is resolved in this release. * **Guest authentication fails with a SystemError fault when the requested password is expired** Attempting to authenticate with an expired password, for example when attempting Guest Operations, fails with a SystemError fault. This issue is resolved in this release. Authentication with an expired password now fails with an InvalidGuestLogin fault in order to provide a more precise error code for such a case. * **The free space reported in vim.vm.GuestInfo.DiskInfo for a Linux guest does not match with df command in the guest** Prior to VMware Tools version 10.2.0, the free space reported in vim.vm.GuestInfo.DiskInfo for a Linux guest included file system specific reserved blocks. This led to guest file system usage in vSphere clients reporting more free space than what was reported by df command in the guest. This issue has been resolved in this release by not including the file system specific reserved blocks in the free space reported in vim.vm.GuestInfo.DiskInfo for Linux guests by default. The default behavior can be reversed with a configuration in ```/etc/vmware-tools/tools.conf``` file in the Linux guest operating systems: ``` [guestinfo] diskinfo-include-reserved=true ``` * **VMware user process might not restart after upgrades of open-vm-tools** When the VMware user process receives a SIGUSR2, it restarts itself by executing vmware-user and terminates itself. This is used on upgrades to ensure that the latest version of vmtoolsd is running. vmware-user was not available in open-vm-tools.. This issue is fixed in this release. ## Known Issues * **Shared folder shows empty on Ubuntu 17.04 with open-vm-tools**. On rebooting Ubuntu 17.04 with open-vm-tools installed, the shared folders /mnt directory is empty. This issue is observed even after installing Ubuntu 17.04 using easy install, enabling shared folders in VM settings and selecting Always Enabled. Workaround: Disable Shared Folders in the interface and enable after the VM is powered on with VMware Tools running. open-vm-tools-stable-10.2.0/open-vm-tools/000077500000000000000000000000001321503522500202765ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/.gitignore000066400000000000000000000020501321503522500222630ustar00rootroot00000000000000*~ *.swp *.o *.ko # autoconf generated files *.cache .deps .libs INSTALL Makefile Makefile.in aclocal.m4 config !common-agent/etc/config config.log config.status configure libtool m4 # project generated files *.la *.lo checkvm/vmware-checkvm docs/api/build docs/api/doxygen.parsed.conf docs/api/warnings.log hgfsclient/vmware-hgfsclient hgfsmounter/mount.vmhgfs lib/guestRpc/nicinfo.h lib/guestRpc/nicinfo_xdr.c lib/include/guestrpc libguestlib/guestlibIoctl.h libguestlib/guestlibIoctl_xdr.c libguestlib/guestlibV3.h libguestlib/guestlibV3_xdr.c libguestlib/vmguestlib.pc rpctool/vmware-rpctool scripts/build/rpcgen_wrapper.sh scripts/poweroff-vm-default scripts/poweron-vm-default scripts/resume-vm-default scripts/suspend-vm-default services/plugins/vmbackup/vmBackupSignals.c services/plugins/vmbackup/vmBackupSignals.h services/vmtoolsd/svcSignals.c services/vmtoolsd/svcSignals.h services/vmtoolsd/vmtoolsd toolbox/vmware-toolbox-cmd vmware-user-suid-wrapper/vmware-user-suid-wrapper vmware-user-suid-wrapper/vmware-user.desktop xferlogs/vmware-xferlogs open-vm-tools-stable-10.2.0/open-vm-tools/AUTHORS000066400000000000000000000011301321503522500213410ustar00rootroot00000000000000The VMware Guest Components Team Contributors to open-vm-tools: Steve Wills Correct __IS_FREEBSD__ macro in vm_basic_defs.h (clang) - https://github.com/vmware/open-vm-tools/pull/136 Bernd Zeimetz Fix gcc6 build issues in linuxDeployment.c file. - https://github.com/vmware/open-vm-tools/pull/107 Josh Paetzel Add support for 64-bit inodes in FreeBSD 12 - https://github.com/vmware/open-vm-tools/pull/190 Sebastian Parschauer Add support to properly report SLES12-SAP - https://github.com/vmware/open-vm-tools/pull/123 open-vm-tools-stable-10.2.0/open-vm-tools/COPYING000066400000000000000000000634711321503522500213440ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! open-vm-tools-stable-10.2.0/open-vm-tools/ChangeLog000066400000000000000000016321051321503522500220600ustar00rootroot00000000000000commit b6b01435c5d2eaaa66734392d0de754509b655fb Author: Oliver Kurth Date: Thu Dec 14 13:46:57 2017 -0800 update build number commit 09a044d2a4496e5f6adcfceb4070ea55001655ee Author: Oliver Kurth Date: Thu Dec 14 13:42:36 2017 -0800 update copyright header commit 702f79c5bc3de1b33ec7cdadef23df39d310fc8e Author: Oliver Kurth Date: Thu Dec 14 13:42:01 2017 -0800 add modinfo version commit f58396af22966f23610bff164247771c82f2687f Author: Oliver Kurth Date: Fri Dec 8 18:57:38 2017 -0800 CAF MA Performance Issues CAF MA Performance Issues Vmware CAF ManagementAgentHost service was polling every 5 secs to check if Guest Network "Tunnel(port 6672)" was enabled to preconfigure & bring up Vmware CAF CommAmqpListener service. This resulted in more CPU Utilization as opposed to previous release in CAF & caused regression in vmtools 10.2.0. We are increasing the Poll rate to 5 mins, which fixed the issue & is giving us the same CPU/memory utilizations as in vmtools 10.1.0. We were checking for the different stages of listener preconfiguration status from the listenerpreConfigure.txt files in the polling time interval, which caused increased IO operations. To fix that we have stored the value of listener preconfiguration status from the files into a variable locally & using the same at all places instead of file access. commit 68ecbd767b84a4fd11dd00556eaac0ef09955640 Author: Oliver Kurth Date: Thu Nov 30 15:17:27 2017 -0800 Update the Tools-10.2.0 GA Open Source License Files. commit e41c45536332a9195f5336bdcd0a94e11f8e9cfb Author: Oliver Kurth Date: Thu Nov 30 15:17:27 2017 -0800 VGAuth changes: - add calling LoadUserProfile()/UnloadUserProfile() in VGAuth impersonation/unimpersonation code paths - VMTools side code change to use the new VGAuth SDK. commit aa59fb2fd5f15b2514b1494171de40e082e46ba5 Author: Oliver Kurth Date: Thu Nov 30 15:17:27 2017 -0800 VGAuth changes: - add calling LoadUserProfile()/UnloadUserProfile() in VGAuth impersonation/unimpersonation code paths - VGAuth part of code change plus tools vix plugin make file. commit 6bf279de6298f999abf66079e7e824d5498abd31 Author: Oliver Kurth Date: Thu Nov 30 15:17:27 2017 -0800 Remove guestStats that are beyond ESXi 6.0 U1 scope. The guestStats in R10 Tools release follow ESXi 6.0 U1 scope. Remove the guestStats that are not in scope for ESXi 6.0 U1. commit e5e2057a423028dc58a8cf753a12c1d38903a823 Author: Oliver Kurth Date: Thu Nov 30 15:17:27 2017 -0800 Fix memory leak in vmtoolsd. commit 3e7058028ce4352c39dcc2d3a012aa32ed50c421 Author: Oliver Kurth Date: Thu Nov 30 15:17:27 2017 -0800 Tools: GuestInfo: ESX: dynamically load libvmkmemstats.so The new version of the vmware tools will be installed on older version of ESX. But these older versions do not come with libvmkmemstats.so and a dynamic linking error occurs. This patch changes the code to deal with the case where the lib is not available. Instead of relying on the linker to dynamically link with libvmkmemstats.so, g_module_open() is used to open the library, if available, and gracefully handle any eventual errors. Before the patch, the whole libguestinfo would stop working and after the patch only the memory stats are unavailable. commit 41196c78ae6bd330f2f595071fe86e1082d19a85 Author: Oliver Kurth Date: Thu Nov 30 15:17:27 2017 -0800 Adding copyright notice to a few CAF related files bundled in Open-VM-Tools. commit 59bf741d25837028c8464a71ac5f4f65558fcd6a Author: Oliver Kurth Date: Wed Nov 15 13:32:56 2017 -0800 GuestInfo: add primary-nics and low-priority-nics options Add the options 'primary-nics' and 'low-priority-nics' for GuestInfo. The options accept a list of comma separated patterns for interface names which can be considered as 'primary' or 'low priority' network interfaces. This will cause the NicInfo to be put on top of the list for primary interfaces, and to the bottom for low priority interfaces. Example: primary-nics=eth1 will make sure that the IP address(es) for eth1 will be sorted on top of the list of IP addresses. primary-nics=eth* will make sure that any one of the addresses of all interfaces matching eth* will be sorted on top of the list of IP addresses, but won't guarantee which one if there is more than one. low-priority-nics=eth* will work analogously, but interfaces will be sorted to the bottom. In case the limit of the number of interfaces to be reported is reached, low priority interfaces are the first to be skipped. commit 60719485b84d2d227d8950c50aa4a6c3c171de10 Author: Oliver Kurth Date: Wed Nov 15 13:32:56 2017 -0800 Additional 2017 copyright updates. commit ce05ffb4c8422e769f03f12e2529d0792668dda1 Author: Oliver Kurth Date: Wed Nov 15 13:32:55 2017 -0800 Update copyright year to 2017 for open-vm-tools 10.2.0. commit c1aea05a4ab27c93d8664a6d1803a4a5cb936bb3 Author: Oliver Kurth Date: Wed Nov 15 13:32:55 2017 -0800 DragNDrop plugin change for VMware Tools on Windows; not applicable to open-vm-tools. commit 6a9a7f9093af7f0378b134cd26ef2d2d61f0760b Author: Oliver Kurth Date: Wed Nov 15 13:32:55 2017 -0800 Add SUSE Server for SAP Applications to hostinfoPosix.c On SLES-SP1-SAP the "lsb_release -sd" command returns the string "SUSE Linux Enterprise Server for SAP Applications 12 SP1". Parsing in HostinfoGetOSShortName() detects the sub-strings "suse" and "enterprise" but not "server 12". STR_OS_SLES is returned resulting in displaying of "SUSE Linux Enterprise 8/9" in the summary screen of the vSphere client. This is wrong. Instead, search for the sub-string "server for sap applications 12" and return STR_OS_SLES_12. SLES11-SAP is not affected. Please see: github.com/vmware/open-vm-tools/pull/123 commit 0c5e736804c5a95c998e5361aa2d41ab5dbf7ef5 Author: Oliver Kurth Date: Wed Nov 15 13:32:55 2017 -0800 [Tools] Fix crash issue when stopping vmtoolsd(vmuser) When stopping vmtoolsd, the code tries to unload all plugins. The signal TOOLS_CORE_SIG_CAPABILITIES is emitted before really starting to unload plugins. If the plugin should try to call RpcChannel_Send while processing the signal and the RPC channel has been shutdown, an ASSERT is triggered. The fix is to check whether rpc exists and if unavailable, avoid sending the TOOLS_CORE_SIG_CAPABILITIES signal. commit aaab4ead2428c2aa40766054bd3457db5458e695 Author: Oliver Kurth Date: Wed Nov 15 13:32:55 2017 -0800 open-vm-tools: make building with gtk3 the default This makes building with gtk3 the default, and sets sane defaults when building with/without gtk2/gtk3. commit 1c854b407d9fcbf02f8d80542a6c731e3048193a Author: Oliver Kurth Date: Wed Nov 15 13:32:54 2017 -0800 VMware Tools 10.2.0 L10n message updates. commit 005db5fdbc6fae9d7f365cd02494c80da5fe7904 Author: Oliver Kurth Date: Wed Nov 15 13:32:54 2017 -0800 Add new GOS definitions for virtual hardware version 14. RHEL 8 64-bit CentOS 8 64-bit Oracle 8 64_bit SLES 15 64-bit Asianux 8 64-bit Other 4.x Linux Kernel Other 4.x Linux Kernel 64-bit FreeBSD 12 FreeBSD 12 64-bit Darwin 18 64-bit commit 6e138c678923940ea8c3a3b8759036f3c5c2bf0d Author: Oliver Kurth Date: Wed Nov 15 13:32:54 2017 -0800 GuestInfo: enable nic/iproute information for Linux without libdnet Linux glibc (since 2.3) fully supports getting ip addresses using getifaddrs() for both IPv4 and IPv6. Use of getifaddrs() was already implemented in nicInfoPosix.c for tools for ESXi. This change enables that code also for Linux, if libdnet is not used. The change also enables the iproute information, which does not depend on libdnet, except by the use of addr_stob(), which can be replaced easily with the existing function CountNetmaskBits(). commit c7bedd5b0729edfed3a7cd53eed7966f9efcc16f Author: Oliver Kurth Date: Wed Nov 15 13:32:54 2017 -0800 Make disk free space reporting consistent with Linux 'df' command. On Linux, statfs syscall reports free space in two fields. From http://man7.org/linux/man-pages/man2/statfs.2.html: 1. f_bfree => Free blocks in filesystem 2. f_bavail => Free blocks available to unprivileged user For file systems that maintain reserved space for system activities f_bfree > f_bavail because f_bfree includes the reserved space in the file system. The reserved space is typically 5% for 'ext4' file systems. Newer distros like RHEL 7.x use 'xfs' by default and report same value for both the fields. The Linux 'df' command uses f_bavail in its reporting. Tools reports, conditionally, f_bfree for root and f_bavail for non-root. However, since vmtoolsd runs as root, Tools always reports f_bfree, which is more free space than 'df' would report (depending on amount of reserved space). In order to be consistent with Linux 'df' command, report f_bavail as the disk free space by default. This does change the behavior a little bit in that Tools will report less disk free space than before, the difference being the same as the reserved space on the file system, typically 5%. This should be OK in general because it makes the space reporting a bit conservative. If this change in behavior is not desired for some use cases, the old behavior can be restored by setting the following newly added configuration in this change: [guestinfo] diskinfo-include-reserved=true The existing callers that are outside the guestInfo plugin will continue to include reserved space in their space accounting as before. Also fixed a few minor stuff/touchups in vmtoolsConfig.c. commit 2795cc29fb5243f0dd91bbe233ea267a0f5ff764 Author: Oliver Kurth Date: Wed Nov 15 13:32:54 2017 -0800 Add Str_Strncpy Add a Str_Strncpy function that, unlike strncpy, guarantees NUL-termination. commit 36627cdec863b57cfbc544d489075891982aaec7 Author: Oliver Kurth Date: Wed Nov 15 13:32:54 2017 -0800 Fix a segfault when log file isn't set and conf is reloaded. When vmsvc.handler=file, but vmsvc.data isn't set, vmtoolsd crashed on reloading the config file. This was caused by using a NULL value as an argument to a strcmp(). This change fixes this by using g_strcmp0 which handles NULL pointers gracefully, and setting confData to a default value before calling g_strcmp0(). This also fixes a case where a change in the log file would be ignored. commit 8803b5e1361c20fae371113e6a71d2bbb76fe840 Author: Oliver Kurth Date: Wed Nov 15 13:32:53 2017 -0800 guestOS: Uniquely run time identify Photon Currently VMware Photon 2 is identified at run time as a Linux 4.x kernel. This is correct, but the Photon distro has an LSB compliant identification file. Attempt to check the LSB compliant identification file for Photon. If present, identify the guest as "vmware-photon". commit fddd4c7f1c270d5bcf183afac084d4729153215f Author: Oliver Kurth Date: Mon Oct 2 15:28:57 2017 -0700 With the build of VMware Tools 10.2.0 product shifted to the product release branch, changing the 10.2.0 release macros to reflect that change of status. commit ffa6a60b1f98ce0564238f3a2abe0046d54ac2ea Author: Oliver Kurth Date: Mon Oct 2 15:28:57 2017 -0700 Update the Tools-10.2.0-Beta Open Source License Files. commit 631907ab8989ad07d3b8c03829f5700bb2e3ee1a Author: Oliver Kurth Date: Fri Sep 15 11:47:09 2017 -0700 copy README.md from master commit 962d4f21e2365e81d68ca2920175c0f1edbb6770 Author: Oliver Kurth Date: Fri Sep 15 11:32:25 2017 -0700 update version to 10.2.0 commit 1604e7c59f9491e0f98e39dc511a534ffea68879 Author: Oliver Kurth Date: Fri Sep 15 11:35:01 2017 -0700 sync libDeployPkg files commit 2ec91a3f67059cff2d47c662e2177714742a241f Author: Oliver Kurth Date: Fri Sep 15 11:23:58 2017 -0700 GuestStats: Report memNeeded on ESX as a guest commit f439d57482f7dd42e359fb0792269573c63c55a7 Author: Oliver Kurth Date: Fri Sep 15 11:23:58 2017 -0700 GOSTable: Add MacOS 10.14 and FreeBSD 12 commit 1d661a68fced6b91e6c5e757915cddf8b7c7eb15 Author: Oliver Kurth Date: Fri Sep 15 11:23:58 2017 -0700 Guest OS: Add CentOS 8, OracleLinux 8, and AsiaNux 8 commit 8b2369ac8512b1436dbe2de5617e0265b522ee3a Author: Oliver Kurth Date: Fri Sep 15 11:23:58 2017 -0700 lib/file: Remove long dead functions from file.h These routines no longer exist. Remove them from the header file. commit e2da656025ba8ddb8a8b223f9e73c0057a2eeeb9 Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 Revert part of the previous commit. Remove the VIM mapping for now. commit 6ca6d42820b0ae44b02187925ebce7d2d21ab5e0 Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 guestOS: Add SLES 15 and RHEL 8 commit 31a6c06caeb75afd7d6a7e017c3b95b60ca9b6f0 Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 Change to common header file; not applicable to open-vm-tools. commit 1b9b067c39da8446cb28a66914ff61dabadc71e9 Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 0c0f3e3c1fa82a1d63b75ccf6d8d775d915c66cf Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 Changes to common header files; not applicable to open-vm-tools. commit c8811a844992cd610e0043998f8554989e843bd7 Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 91cd3e4fcf02ac4d5ada8723e6e6b285768d351b Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 lib/file: Improve File_CreateDirectoryHierarchy error detection commit 84f5ee1d65982ced4f4e0dd847cfe7658e77b873 Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 Fix processing RPC data in TimeSync RPC handler RPC data is whitespace delimited string and any leading whitespaces need to be ignoreed before processing data. The data here indicates whether timeSync should do a backward sync on this RPC callback. commit 31f97a69bf993057f56ea16e2899c2f55c84f8d6 Author: Oliver Kurth Date: Fri Sep 15 11:23:57 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 9291087e5c01b0dab662bb61530d3ee5ce469a13 Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 Adjust some logging levels Make some of the more common vgauth failure cases show up at default debug level. commit 0f94e2468307d13b9d70938e1ad817bceeb2e2b2 Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 Add support for 64-bit inodes in FreeBSD 12 FreeBSD 12 is switching to 64-bit inodes which will cause some ABI breakage in user code. This fix modifies the getdirentries() syscall used in hgfsServerLinux.c for that FBSD 12 64-bit inodes. The fix was provided by Josh Paetzel in open-vm-tools pull request https://github.com/vmware/open-vm-tools/pull/190 commit b851f91268e947ab4e7aff8c6bc9e3c84f7d81f4 Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 Enable bsd_vsnprintf for __ANDROID__ Remove the __ANDROID__ check from Str_Vsnprintf, et al. It's not supposed to be there anymore. commit 75c55bc6c01624884515b71af7e1a7a7843519e6 Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 Add support to check if a native guest time sync service is running. This change adds support to VMware tools timesync to identify if a guest native time synchronization service is running. If a native sync service is running, then a resync command is issued. If native time sync service is not running, we fall back on legacy VMware tools onetime sync to do guest time correction. We also post a callback to do legacy VMware tools onetime sync after a timeout period. A timeout can be configured if guest native resync command fails to sync guest time. commit 695ab7662e4c9d25a5f86d298f04d777cd400cbf Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 Fix some compatibility issues between bsd_vsnprintf and bsd_vsnwprintf Fix some compatibility issues between bsd_vsnprintf and bsd_vsnwprintf so that the lib/string unit tests can have consistent results. * bsd_vsnprintf used uppercase hexadecimal digits for %p but bsd_vsnwprintf used lowercase. vsnprintf has much more inertia, so use uppercase in both. * bsd_vsnprintf's floating point output was adjusted for bug 704706, but corresponding changes were not made to bsd_vsnwprintf. commit deb3feeefd8f653d1fe0e54e6708d8cacde5ab1d Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 lib/file: Continue simplifying and optimizing Since we're UTF8 only, there are simplifications and optimizations that can be done to lib/file, particularly in the routines that look for directory separators and ASCII characters like '.'. We don't need to use the unicode library to deal with these type of code points. This is the second in a sequence of changes to improve lib/file. commit a1290e66021b3d1e9d0f3c45edea80c5e7fb8488 Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 27d72451d479d96f1d1de901cb76820f5bdac38e Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e30c97abc0fb8f0f6034d56d93b63b629365e2cb Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 Fix lib/string unit tests Updates to lib/string.str.c and its unit tests. * On Linux, Str_Vsnwprintf uses vswprintf from glibc[1]. However, glibc's vswprintf implementation appears to be broken by not NUL-terminating the destination if truncation occurs. Make Str_Vsnwprintf explicitly NUL-terminate along this path. * The unit tests expected that Str_Vsnwprintf use %s for wchar_t* arguments (and %S for char* ones). That is a Microsoft-ism (necessary for TCHAR-based printf functions to use the same format strings with or without _UNICODE). Our bsd_vsnwprintf function instead uses %s for char* (and %S for wchar_t*). Existing callers to Str_...wprintf use use the BSD implementation and expect the BSD behavior (which is consistent with standard C in this regard), so go with the existing behavior and adjust the tests. * Some of the tests passed int arguments for floating-point format specifiers. This is undefined behavior. * Some of the tests had more format specifiers than arguments. More undefined behavior. * Finally, the existing Str_...printf tests are fundamentally flawed: they compare output against the system's printf functions. However, the whole point of having our own is to have consistent behavior across platforms and to work around bugs; the output therefore cannot be expected to consistently match. Instead rewrite the tests to compare Str_...printf output against fixed strings.[2] Additionally, enable these tests only if HAS_BSD_PRINTF/HAS_BSD_WPRINTF are enabled; I see no point in testing the system versions (which won't have consistent output), and IMO the BSD implementations are the only ones we should be supporting. [1] I do not understand why HAS_BSD_WPRINTF is enabled on Linux only for < gcc 2.96 (and not at all for macOS). This probably should be fixed, but not as part of this change. (I also don't know why HAS_BSD_WPRINTF is distinct from HAS_BSD_PRINTF.) [2] bsd_vsnwprintf is not consistent with bsd_vsnprintf for all format specifiers. I plan to deal with this later, but for now, make the expected strings match the actual output so we have a starting point where everything passes. commit d04babd5bc7de9015c0fe881652723498069e7fa Author: Oliver Kurth Date: Fri Sep 15 11:23:56 2017 -0700 lib/file: Cleanly handle directory separators We want to handle Windows allowance of "/" and "\" as directory separators. Let's have an easy way to check things and use it. This is first in a sequence of changes to improve our handling of directory separators in lib/file. commit f72d3ce3571f93e9dc8a404bece8264e8081e493 Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 Add missing "const" to previous commit. commit a518cc08a6e6f77a665eefa0f29b19e5077a8445 Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 lib/file: Rework File_ReplaceExtension and File_RemoveExtension Fix a bug and simplify the code. commit 24de06bc3d445d68ebee9b55efd5393520ef8dab Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit a53bde7ecfdd3c544010559f1b84c11396fa9f7d Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit d840729ea449e19f9f2b6d5105c053c09085c364 Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 Rename some parameters The generic parameter names for Posix_Symlink/Posix_Link are rather confusing. Rename them. commit 1917d98e6b002670095cec13b363f5894ab8cc0f Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 Revert previous commit. commit fbc7387c1edb0bc619cc05fecb84030809c38867 Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 lib/file: File_ReplaceExtension fails in the root directory On Linux, File_ReplaceExtension returns an incorrect path name for a file in the root directory. The code, as written, doesn't differentiate "test.txt" from "/test.txt". Fix this. commit 0f386a32789574bb73f75f0e8e82e80f0511416c Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 Update AUTHORS with pull request for fixing gcc6 build issues. The issue in linuxDeployment.c has been fixed. This change is to udpate the AUTHORS file. - https://github.com/vmware/open-vm-tools/pull/107 - https://github.com/vmware/open-vm-tools/pull/107/files#diff-ffeb9f9be2f25b5b92ecf9101fa3aae5 commit 2ad25b6bfe88e47dc9b2b995eba5af1a317aacd0 Author: Oliver Kurth Date: Fri Sep 15 11:23:55 2017 -0700 Update __IS_FREE_BSD__ macro in vm_basic_defs.h The __IS_FREEBSD__ macro in vm_basic_defs.h uses "defined" in the definition. That is undefined behavior and the FreeBSD default compiler, clang (LLVM), warns about this pervasively misused construct. With all warnings equivalent to an error, builds fail. The object-like macro __IS_FREEBSD__ has been rewritten in a manner acceptable to the current C standard. Open-vm-tools pull request: https://github.com/vmware/open-vm-tools/pull/136 commit c1c9b66c580bdda09d0c1e41d3d01e2803a9221f Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 39b3a708936a663d24a5ab8c6f4c45cd44dc12bb Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 Include new CAF PMT files in open-vm-tools Add new CAF PMT files CmonitorListener.cpp, CMonitorListener.h, and preconfigure-Listener.sh to open-vm-tools. commit fcee9fe84ab642d88230a0cb7b8db6fe6e2207d2 Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 Re-instate ASSERTS in circList.h commit 136eab69cc5fcd9e4bdb2766810f5cb0a791c0ad Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 services/plugins/dndcp/dnd/dndCPMsgV4.c: - Rework DnDCP v4 message validation. commit aa18cc61e5f1233cafff489be63b5660d9b8458b Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 deployPkg: Fix duplicate log message issue Use linebuffer to prevent duplicate log message for forked off processes during customization. commit 321eaaafc80bc4d7e7c07b779d8021ff7adb27fc Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 Make TimeUtil_GetTimeFormat avoid a null pointer dereference if ctime_r fails ctime_r potentially could return NULL on failure. Instead of blindly dereferencing the result, TimeUtil_GetTimeFormat should check for that and also return NULL (which callers should already expect on failure). commit 74fab8557791b3b546c39a0a833ff9b5d9914d40 Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c4b6c83951aef605686f6313be4d0e18fb5abf9f Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 resolutionSet: Should not free RandR12Info when RandR12GetInfo failed If for some reason RandR12GetInfo failed to return RandR12Info, it should not follow the cleanup path to free it. Instead it should return FALSE. commit ff8a4800edf33a887efcce487efd763f9343c71f Author: Oliver Kurth Date: Fri Sep 15 11:23:54 2017 -0700 Export and call a valist version of Msg_Append This change exports a valist version of Msg_Append. commit e43c3c193057843232471bb7c427781c22774832 Author: Oliver Kurth Date: Fri Sep 15 11:23:53 2017 -0700 Common header file change: not applicable to open-vm-tools. commit e28fabf2876cd256b80ad863a0d610d103fd121e Author: Oliver Kurth Date: Fri Sep 15 11:23:53 2017 -0700 VThreadID: change to uintptr_t commit 2c2426bd2120546d93f0b7b49a22e9b3689556c0 Author: Oliver Kurth Date: Fri Sep 15 11:23:53 2017 -0700 Add 10.1.15 update release to vm_tools_version.h commit a02ecfdc12e18aa9aa1b4f9e1d6c61fa3eb9cdd3 Author: Oliver Kurth Date: Fri Sep 15 11:23:53 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 182df3e67dcd21f143aa5e1741ba4381067a21ee Author: Oliver Kurth Date: Fri Sep 15 11:23:53 2017 -0700 lib/file: Posix FileLock_Lock pathName handling Locking "/tmp" should create a lock "/tmp.lck". Locking "tmp" should create a lock "./tmp.lck". commit 06c0cf16d765c4718825cc28ad9997476b5b0423 Author: Oliver Kurth Date: Fri Sep 15 11:23:53 2017 -0700 Add vmx config options for guest time service resync. VMware tools timeSync can be enabled in a guest that also has a native time service running. This can lead to race conditions when both the time services are trying to correct system time. Particularly, when both of these services tries to do a step correction on certain events, guest time behaves in an undesirable manner that could cause guest applications to fail. This change introduces a couple of vmx config options that can be used to eliminate or atleast reduce the chance of race condition between VMware tools timeSync and guest native time service (like w32time or NTP). The basic idea is to utilize native time service to resynchronize and recalibrate its parameters and force to do a step correction if necessary. VMware tools timeSync would send a service request to native guest time service when it needs to do a step correction, rather than correcting system time itself. This helps in having a single service responsible for correcting guest system time and eliminates/reduces race condition. "time.synchronize.guest.resync"= controls whether this new method of guest time synchronization is enabled or not. There might be situations where native guest time service resync request is not successful. This could happen if the native time service is not configured correctly or if there is an intermittent network outage, etc. We would like to fall back to using legacy way of VMware tool timeSync onetime correction in such failure scenarios. "time.synchronize.guest.resync.timeout>=0" vmx option allows us to achieve that. Tools timeSync would initiate a resync request, then wait for 'timeout' period of time and would fall back of legacy timeSync onetime sync behavior. This allows us to correct guest time even in case of native guest time service failure. commit bb819650082a6714d0435831bf2bbf31c66718c5 Author: Oliver Kurth Date: Fri Sep 15 11:23:53 2017 -0700 Common source file change; not directly applicable to open-vm-tools. commit 433f1f2b4db1e55e9576ab5bb0bf02a4e040a299 Author: Oliver Kurth Date: Fri Sep 15 11:23:53 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 63e4a016d5bba58121cbbebb8f7711a0bf70436c Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 VThread: factor out common thread-name assignment commit 4a08aedc1a3bfbe666896d13380265f3948684ac Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 Hgfs OSX Server: Create and use server callback table for change notifications There are now three different callbacks into the Hgfs server from the file change notification component. So we now pass these in a table to the nofify module when it is initialized instead of ad hoc. Previously, the same callback is passed for every subscriber watch event and therefore duplicated and stored in each subscriber. Note that the feature is currently switched off by default until these changes are complete. A user will explicitly have to enable the VMX file setting and would cause a VMX assert to be triggered. Details: - The server now creates a table for its notification callbacks and passes it to the notify initialization function. - The server now includes the async thread registration callbacks previously ifdef'd out. - The Notify_Init function APIs are updated to reflect the new argument for callbacks. - The HgfsNotify_AddSubscriber argument does not include the callback as it is now passed once at the initialization time. - The HgfsNotifyEventReceiveCb type has been modified now it is an entry in the callback table. - The subscriber callback function call is now validated to be non-NULL before calling. - The Mac notify module adds the server callback table to its FS event context which is passed to the event generating submodule for the Mac implementation. - The Mac notify module adds its own FS event callbacks for thread register and unregister called from the FS event module when registering and unregistering its FS event thread. commit 3633fa4ab2b5cbd97bfed0cdc14cda842675bd9e Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 CAF - Preconfigure the listener + follow guest proxy Listener is auto configured during the install upon MA being started. Listener is started/stopped automatically when tunnel is enabled/disabled. commit 1f72b0f9878355ea2263d57b16dd35682b2720f9 Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e854fc4e547c5f7f4c989e38e233e6567d588386 Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 Add error logging to lib/file/file.c create folder functions commit 7e5f9a8025926b56e77d63f11cff70b606dfd0be Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 Re-gen rabbitproxy key if its perms are bad Make sure nothing has played with our keyfile permissions. The old (9.10) VB script that generated the key left it world-readable, and it's also possible someone could mess up the perms. This change checks the perms, and if they're wrong, regenerates the cert & key. commit ad4f5db55d031ce7d1b75ddc64c3f046c24469de Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 GuestInfo: Add option to exclude network interfaces VMs running docker can have hundred of virtual network interfaces. Also, docker creates one virtual network interface 'docker0' with an IPv4 address. This address is useless outside the VM, and should not be propagated via GuestInfo, or even as the primary network address. This change adds on option for tools.conf to exclude specific network interface names using patterns with wildcards. This makes it easy to exclude virtual docker interface names with the option exclude-nics=docker*,veth* For convenience, the option is set to docker*,veth* by default, except for Windows, where it is "vEthernet*". To send information of all interfaces, including docker* and veth*, the option needs to be set to an empty value: exclude-nics= commit 6a74858200ae2fb5908b74676da56124d83a8285 Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 Fix vm_basic_types.h broken in previous commit. commit 6cc7edaf4294f47d6210af45c1ba64d967a031a2 Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 8b50e2372fbf110a1e41225c9e67fb6720344f8b Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit d36368429913b21291917e4b00bc2ba92e2d3c0a Author: Oliver Kurth Date: Fri Sep 15 11:23:52 2017 -0700 Remove VThread_WaitThread commit cd7b6d0c9575f9728f425d3043fc87639bc2cab0 Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 VThreadBase: Final cleanups commit a10c8df8b9f9609e025d231fe596e2fce6b8e750 Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 Tools Hgfs Plugin: Refresh Hgfs drives on client start In order to get Explorer to see that VMware Shared Fodlers drives are available when the feature is enabled, we touch each drive that is mapped as a VMware Shared Folder. This is to prevent users being confused when they have the feature enabled but Explorer creates the user's drive mappings before the tools service has initialized the Hgfs plugin and started the Hgfs client. In this situation the drives are marked as red (disconnected) until the user clicks on the mapped drive when Explorer will refresh the connction and set it to green (connected). Details: - Main service will usually create otheriwse open a named event to synchronize with the user service. - Main service will start the HGFS client redirector (as before this is not new). - Main service will set the synchronization event to signalled. - User service will usually open the named event (or create it if first). - User service will enumerate all the mapped network drives and, if they are provided by the VMware Shared Folder redirector, reconnect them. - The named event will be created with Administrators group all access and Everyone with modify state to signal it and synchronize to wait on it. commit d4a5693af649e7c8f87667c60b7e6575b15faa0e Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 Emphatically close virtual disk. Sometimes I/O stack modules return EBUSY during teardown. This may be due to an external process opening files at inopportune moments. The workaround is to retry the affected operations. commit 04d01f93f26b748d0fbb6bc1ea571e90fbc005d7 Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 lib/file/filePosix.c: Implement File_GetMountPath() for POSIX - The change implements File_GetMountPath() for POSIX, using realpath(3) and readlink(2). Changes to common header files; not applicable to open-vm-tools. commit 47ffaf37a9f604ffc1099d249dba21857dd426d3 Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 VThreadBase: Switch to "stable" thread IDs Now that lib/thread no longer has a dependency on small-numbered VThreadIDs, and now that lib/thread has ceeded control of assigning VThreadIDs to threads, we can make VThreadBase really simple. commit c6f360fc8e9b25d9478864903886895cedeff4e0 Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 lib/lock: Clarify comments commit d98582711a87185657cd9f125d58f3fdd48dbc0a Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 Clear vmusr as resolution_server when resolutionKMS is enabled Whenever resolutionKMS is enabled, send "tools.capability.resolution_server toolbox-dnd 0" to clear resolutionSet as resolution server. commit 22c3f23f55153f08e788db6c4ae7a96d555ed8ca Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 Changes to common source files; not applicable to open-vm-tools. commit eecfdd625b3e134830a7c012fc8aadda36bfd4da Author: Oliver Kurth Date: Fri Sep 15 11:23:51 2017 -0700 Use correct osname for FreeBSD 11. For FreeBSD 11 and later the correct osname is "freeBSD11". Without the correct osname, guestInfo ends up with the wrong guestId and guestFullName. Also cleaned up some unused code. commit 0ca5c37c17a9631533de41eba1f770ca833c07e9 Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit fbead2824b81be34cb2a61e1310da9188adc383f Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit fbd04d3227be7adeb307b508d7994236161927f5 Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 74e48b8fc16e6cfe765a32568e437a98d3ad1548 Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 00b13522c0f12774b2d39e999855216f53648c1a Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 407459a2ceee1d845a5055a856b5947ca00836f4 Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 VSOCK: Add getsockopt to determine stream socket disconnect cause This is the vSocket part of adding support for getting the disconnect cause of a vSocket stream socket. This adds a getsockopt option to determine stream socket disconnect cause as registered by the underlying VMCI queue pair. commit ad5c63faa35f3b3e8e6a035e76ba1c043ae8c756 Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Convert Util_GetCurrentThreadId to VThreadBase_GetKernelID This code now "lives" in VThreadBase since it is thread-related. The two functions behave (very) similarly. Some locations should use VThreadIDs instead of KernelIDs. Convert them. Remove the util.h and lib/misc bits. commit 55a1aa0c2917bf69c919bd6b202464d8b3febee3 Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Remove Util_GetCurrentThreadId from VIX Some cleanup now that VThreadBase_GetKernelID() is available in VIX code, we log the thread which made certain API calls. The thread name is already logged in our Log() implementation, so having the thread ID merely wastes bytes. Remove it. (Thread IDs like this are useful for correlating with kernel logs. Which in practice does not apply to VIX). commit b8912055edb714afd8c0b1124a64502c712f0f6c Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Add some tweaks to make it easier to test old tokens At times its useful to be able to play with SAML tokens which have expired assertions but we still care about signing or aliasStore configuration issues. This change makes it easy to tweak the code and run these old tokens through. commit 241fd29fa3352d17aacc13754de3304538d0a3d4 Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 Enable XML manifest by default. Enable Tools enableXmlManifest by default for quiesced snapshots on Linux. commit 3b80a0df4bac2f5de52117096a482ab3f490f52a Author: Oliver Kurth Date: Fri Sep 15 11:23:50 2017 -0700 lib/file: Must be errno safe lib/file is documented to be safe about returning errno. This is true on Window and Posix platforms. We've had a bug where free can change errno. We created Posix_Free to protect errno but haven't used it consistently. Make lib/file use Posix_Free universally. commit 0dd222a31a10c0591a95009e7ca7c60046b6e6b3 Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Changes to common header files; not applicable to open-vm-tools. commit 94e8e7478d2528466d0eecbd29aa441f748a4235 Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Hgfs Server: Fix the tools build Make the HgfsServerAsyncInfoIncCount to be VMX code only as the current usage is not in the tools implementation. commit 3466376924a5338b3b596d8f960942e30b0ecef7 Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Hgfs Server: Move async request globals into the Hgfs session This change moves the async request globals into the Hgfs session. They are only applicable to a session and only used during a session's lifetime, so making them global is not necessary and means that they take up resources when not used. Details: - Move the previous globals into a structure for async requests. - Add the async requests structure to the HgfsSessionInfo object. - Create a set of helper functions to init, exit and manipulate the async requests structure. - Remove the calls to init and teardown the globals now they don't exist. - Add the helper calls to the session creation and destruction. - Add the helper calls to replace adding a new async request, removing an async request, and waiting for all async requests to complete. commit 93f1036f2d69c6c50780a536eb6b2a15b198c03a Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Remove dead FileMacos_IsOnExternalDevice function. FileMacos_IsOnExternalDevice does not have any callers. commit 0db66edd78699e10f069476998cb3469c42da316 Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 10eed7e90059f666e50a0ca4df1de2f4947bd62b Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Add MacOS 10.13 to guest os tables commit dec55c31e7dcdbb747647123ad60cc2cde4e0635 Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Avoid loading resolutionSet when support for resolutionKMS available Loading resolutionSet with display NULL will cause a segmentation fault in vmtoolsd user process. This change only avoids the SEG fault. Still need to channel the resolution/topology request to correct channel presenting the capabilities. commit 4fe253f4e6234f3bb78b270c371d8fdba967ff0d Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 3a9fa9be672b582088c3219420b2dfcb37b60376 Author: Oliver Kurth Date: Fri Sep 15 11:23:49 2017 -0700 Formalize VThreadBase "Stable" and "Kernel" IDs Unrelated to open-vm-tools. commit 932781290802e9c152b219c656d18ca03bf4df43 Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 lib/file: Less variation on file lock waits The wait time are large enough that less variance will prevent too frequent polling. This is important due to the randomized waiting now. commit ffc043963f8da7e83bc091262301876ce7016a76 Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 Remove definition for "solaris12-64" commit 964e7623701cd03bd4b8529abab0a083b94e8570 Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 24a6ab223b139fdc191b913d8d551ed61ca07e01 Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit a6ce51f170a2073b5b39680c2526de9e4de865b2 Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 Fix Atomic_SetBit64 being miscompiled when the bit argument is a constant. commit d7a7fca30e47414827528163a4c96145dcd6043e Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 lib/include/sha1.h: - Clean up - change unnamed struct to "struct SHA1-CTX" in SHA1_CTX typedef. commit 22b146ef9a291b9c4cd8a604de3e042cec886eda Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 lib/thread: Prune a little more Remove automatic VThread_SetName for unmanaged threads. Other minor removals and tweaks: - modify "safe" name in VThreadBase to use gettid or pthread_threadid_np if available - Move lib/thread name computation to child thread to remove dependency on VThreadID in parent. - Convert VThreadFreeID to VThreadFree (and avoid a lookup) - Move VThreadBase_ForgetSelf to VThreadDestroyThread to make VThreadHostDestroyThread straightforward. - The 'priority' field had become write-only after earlier cleanups to replace AdjustThreadPriority with SetThreadPriority. Remove it, and some dead comments mentioning it. - Remove unused 'signalNestCount' atomic. - Remove two unimplemented VThreadInt prototypes. - Remove a vacuously-true ASSERT in VThreadHostExitThread() commit b1c4f77f80b8ecfe3c97bd8d14b42e8543b12303 Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 564668d513a4fdb595fd4440f4e640c752c24e12 Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 lib/file: Add a comment on why sleeps for file locks are randomized The randomization prevents lock cadence issues (thundering herds). commit 087e74c292fcad86afa08d6a21b88cb57ab3bc7e Author: Oliver Kurth Date: Fri Sep 15 11:23:48 2017 -0700 Hgfs OSX Server: Reinstate checkpoint synchronization and process session First reinstate the server checkpoint synchronization routine by adding it into the table the HGFS server session callback table which is returned to the transports upon initialization. These transports will then call into the HGFS server when asked by the HGFS server manager which receives the check point synchronization calls. When processing the synchronization request for the operation type - freeze or thaw we must pass through the session information to the activation and deactivation calls into the file system change notification subsystem. These calls will require the session for register-unregister any active threads generating events. This change just plumbs through the session as the argument. Follow on changes will make use of the session argument passing it on to the event generating component. Bonus here is that we can delete an unwarranted global from the HGFS server. A to do comment is added to move the async globals into the HGFS server session object as they should be a per HGFS session and are useful only on a per session basis. No session then no need for them to be around and if the session does have asynchronous support then again will not be required. For example, if the transport does not support this behavior no need to check them. commit 774bfbf5d5752b22947dd975b14734c30aec6379 Author: Oliver Kurth Date: Fri Sep 15 11:23:47 2017 -0700 Improve a comment commit a7c6fce7191365c07b1e70abee314e18295b49c9 Author: Oliver Kurth Date: Fri Sep 15 11:23:47 2017 -0700 Clarify a comment. Spell out the units. commit 35683b97ced00c29b0e3f65ee50ec6740e143a8d Author: Oliver Kurth Date: Fri Sep 15 11:23:47 2017 -0700 lib/file: Use MIN macro commit 9c13bf3fb45c4ce5711cedbde11272fd3dd39511 Author: Oliver Kurth Date: Fri Sep 15 11:23:47 2017 -0700 lib/file: consistant usage of msec We now want msec to be at the end, to be consistant with our current usage. commit a2165e98d3edac4f0c395549bd12a905038f9e81 Author: Oliver Kurth Date: Fri Sep 15 11:23:47 2017 -0700 lib/lock: msec consistancy We want the "msec" at the end of variables. This improves readability and is consistant with the usage elsewhere. commit 8da9461f220ed391f60a78c4f0a9509c474f4d12 Author: Oliver Kurth Date: Fri Sep 15 11:23:47 2017 -0700 lib/file: FileLockSleeper issues While waiting for a contended file lock, FileLockSleeper was using fixed values for how long to sleep between attempts. This can lead to a "thundering herd" of waiters - several waiters all on the same cadence. Randomize waiting to avoid any cadence. Waiting for a lock should wait no longer than the specified time. Fix This. commit 174644096520c5cd6d26a4a9cf3d8e5a410af52a Author: Oliver Kurth Date: Fri Sep 15 11:23:47 2017 -0700 Fixing the UTF-8 locale dependency in CAF. CAF currently has hard dependency on UTF-8 locale which is resulting in Tools and CAF failures in environments without UTF-8 support. Modify the existing code to fallback to ANSI C locale if UTF-8 is not found. commit d3491185377ec39e8031b1ffb806fe781f329c1f Author: Oliver Kurth Date: Fri Sep 15 11:23:47 2017 -0700 VThreadID: widen to uint64 Convert VThreadID to uint64. commit de798a4a4ab0d09bb3c0366f383bf8a46bf7d194 Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 TimeUtil_GetTimeOfDay reports incorrect time on Windows The conversion from FILETIME to Unix time was off. commit 8ba9c76d322b24dc56b9bf51b018a0925f9f6d1d Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 Unify mapping tables between VMX and VIM guest OS keys There are multiple places that maintain their own tables mapping VMX guest OS keys to or from VIM guest OS keys. Unify them to make the situation a bit less cumbersome. Put the mapping table into guest_os_tables.h. The different sites use the mappings in different ways (some code wants the VIM guest OS keys as strings, whereas other code wants them as enum identifiers), so use preprocessor macros to extract the data. commit 211e99aad3da1a9c755e30bf4cf02667ff5480c4 Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 Save errno after kill() fails, restore the saved errno after logging the error. commit e1d6a45ccceb058eb428baca7d0b1a72c29c9fe5 Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 Fix error introduced in strutil.c commit 3c12e7db4c252e67a1f9a8e758408a0af387850c Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 timeutil.c code cleanup. commit 324bec1a2057ceb7d37469709ed2b8db2ca6348e Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 The check for overflow in StrUtil_SafeStrcat needs work. Might as well avoid protential overflow while also checking for "insane" string lengths. commit 9363088bda0da2ff1798fb0ac39117054cc83421 Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 Common source file changes that are not applicable to open-vm-tools. commit 7f80d52ddbe15f33b666eb429e64852becff1696 Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 Remove obsolete product version definitions commit 3b63e7702a0c945bd9a87b24ef5cfd54574227a2 Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 Don't call FreeLibrary with NULL. According to the documentation and annotations of FreeLibrary, NULL is not a legal value to pass. All other calls to FreeLibrary are correctly handled. commit d8c55cda2442b948d12de3c542c3c30c2daa9926 Author: Oliver Kurth Date: Fri Sep 15 11:23:46 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 765d498b9aadd37a72cd3a0f79f67dd6a878ef90 Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 Common header file change; not applicable to open-vm-tools. commit e5fd332b6ce8e712dffa7d8e828e3e4a47a3f063 Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 Common header file change: not applicable to open-vm-tools. commit 84cf06912d4060ce29fd7a3b765eb34917dd1501 Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 Remove logic for unsupported versions of macOS. We no longer support macOS 10.4-10.7. Remove the old logic that supported these versions. commit bccd28961d9c23271126fee1a2b45c9acd698107 Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 Create symlink for vmware-user When the vmtoolsd user daemon receives a SIGUSR2, it restarts itself by executing 'vmware-user' and terminates. This is used on upgrades, to make sure the current version of vmtoolsd is running. In the tar installer, /usr/bin/vmware-user is a symlink to vmware-user-suid-wrapper. Unfortunately, that symlink was not installed by open-vm-tools. Package maintainers should send this signal to the vmtoolsd user process when open-vm-tools is updated. commit 4e7e626ceef413b02c3831cc25f70be970bc9829 Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 AsyncSocket: - Fix issue where the listening socket becomes bad and the callback function is invoked unexpectedly. - Change not directly applicable to open-vm-tools. commit c85fe685b518311d3fa1f2ce44b6c7ba38500d2d Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 err.h: Add missing include err.h is missing any include that would provide a definition for DWORD. Fix by including vm_basic_defs.h (which includes windows.h) commit 05d0f730fb032f80de169318d90fb973012a9d93 Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 Common source file change: lib/include/strutil.[ch] - Add function StrUtil_GetLastItem() and static functions StrUtilStrcmp(), StrUtilStrncmp(), StrUtilStrcasecmp(), StrUtilStrncasecmp(), StrUtilHasListItem() and StrUtilRemoveListItem(). commit 836575d370458bd2c34324f921d561c551a6b0d1 Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 Remove N_PLAT_NLM (NetWare) Long ago, we supported NetWare. That's long since gone, but a few of the macros have managed to survive fumigation since. This removes all such macros. commit 237cb3a758d23355f559756ce159f59f6dea8c5c Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 Update the open source license files for Tools. commit b51fee38c87ecccd7774107e22b85f0eea1a7309 Author: Oliver Kurth Date: Fri Sep 15 11:23:45 2017 -0700 Revert previous commit. commit f68ecb12ebc92592463c0cdcd97f50bc5abb8ea2 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 lib/misc: StrUtil_SafeStrcat length overflow checking The check for overflow in StrUtil_SafeStrcat needs work. Might as well avoid protential overflow while also checking for "insane" string lengths. commit ecdc55d43ab00c0a0454af1bc15a8b215f086c55 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 lib/thread: Change VThread_CreateThread prototype Change the VThread_CreateThread prototype from this: VThreadID VThread_CreateThread(void (*fn)(void *), void *data, VThread tid, const char *name); to this: Bool VThread_CreateThread(void (*fn)(void *), void *data, const char *name, VThread *tid); The new prototype returns essentially the same information, with one important advancement: we can contractually guarantee the 'tid' field is populated BEFORE the child thread starts. This neatly avoids all sorts of interesting race conditions where the child starts running before the CreateThread function passes back its return value. This style of design is preferred by operating systems (see Posix pthread_create, Win32 CreateThread). commit 998f79aaf08b7d1f94693441a71c7f8dba4be34c Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 Don't try to use broken RPC channel Make sure RPC channel exists before trying to use it. commit 5c3e95565dc086143e1311e53f0b5cacacca8233 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 Check for Xen, VirtualPC etc., only if VMware not detected This is a workaround to avoid random vmtoolsd crashes when running on a VMware VM. This fix ensures that we check for Xen and VirtualPC only if we haven't already detected a VMware hypervisor. commit 8dac3e7b85c8c19168c89ddae32d2e99c2b693c5 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 5799596b11f1a907a35549952812bd20c48a84d5 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 strutil.c: code clean up commit d2321f07f86157886bbfa96c05c5bf4598151696 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 Atomic_CMPXCHG64: pass by value and remove gcc-2.96-isms commit e2247e5ba1830c5ed70153027df4834285cd1041 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 Revert the previous commit. commit 42ac2a1eca59453870d8f09b83948f3c04c559c3 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 Get rid of convertutf and bsd_printf for all non-Windows Tools Eliminate the use of convertutf8.c for all non-Windows Tools. The MsgFmt_* functions are referenced in a few utilities related to VMware Tools. This change replaces the MsgFmt_* with a stub. This also affects the Windows version. commit 8484528eef9106be5a58885b29083a8622bcdc76 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 fileIO.h: Clean up some comments Make the comment style consistent commit 9fbb5a9c0eb6aa1571689c1b960ab7acf7cb7b19 Author: Oliver Kurth Date: Fri Sep 15 11:23:44 2017 -0700 lib/file: support POSIX O_CLOEXEC On POSIX systems add support for O_CLOEXEC - close the file descriptor if the program does a variant of the exec system call. commit f5f0d2872ff77a586a24a8959a74e85cbf30654e Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Hgfs Server: Fix snapshot synchronization callback Currently when snapshots occur, the VMX calls the HGFS server manager synchronization callback to notify the Hgfs server to freeze or thaw the Hgfs file IO activity. First, this Hgfs server synchronization callback is called regardless of the Hgfs Shared folders feature and server is enabled or not. Consequently, the Hgfs server callback lamely uses a global variable to track the server state just for this call and returns without doing anything if not initialized. Second, the HGFS server now requires the transport connection in order to extract the Hgfs session as the file notification component requires the session to allow its event generating thread to callback to the server to register and unregister through the transport which uses the PhysMem APIs. This change fixes: - call the Hgfs server only if Shared Folders and the server are enabled - call through the channel manager and channel transport to the Hgfs server - Hgfs server session callback table is extehded with a server quiesce callback. - HgfsServerSessionQuiesce callback now replaces the old HgfsServer_Quiesce exported API. - Make the quiesce callback use an enum to the thaw-freeze op instead of a bool - remove the Hgfs server initialized global now it is not required The tools implementation of the Hgfs server code does not use this API and thus the guest Hgfs manager and transport channel do not implement any code which will use the session quiesce callback. commit 4dbe96f4970bd8878bfe3da2b2ed46c9c4ccf099 Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 FreeBSD: Use the "dhclient" command to renew a DHCP IP address. On FreeBSD, "/etc/rc.d/netif" is sufficient to stop a network interface when suspending a VM. When resuming a VM, DHCP configured interfaces must be restarted with "/etc/rc.d/dhclient". This fix is courtesy of Steve Wills, maintainer of open-vm-tools on FreeBSD, and Shuai Wang. Pull request: https://github.com/vmware/open-vm-tools/pull/142 commit 27a9808452e78dfb76234c8c8c983ec3ccd04dc0 Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Add utilZero.h to open-vm-tools commit 7bffaf26f46a28893e07df2a46bfdb612b8a15c2 Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Remove memory zero related functions from util.h Add a new header utilZero.h commit 88358a74766f2302f85d4e614a07fd07dbed9a37 Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Log xmlsec1 version details For better debugging of open-vm-tools, log the xmlsec1 version info. commit 21dc0516201085e760d831d187b5232acf3a17d0 Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Hgfs Server: Fix a memory leak on server exit not destroying the shares This change fixes a memory leak on server exit not destroying the shares. The list of shares is not destroyed and left. Fix this at the Hgfs server tear down by calling the shares reset with an empty list which will cause all shares to be treated as stale and so deleted. commit cec1221e1a48db9e127ad271d6e7ddfc7fe27dce Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit a11b7dda01aaefa63f57cbe2f15352c06f2c55eb Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 CnP formatted text doesn't keep text format in Fedora 25 In Fedora24, the selection target name for rtf is text/richtext. In Fedora25, the selection target name for rtf is changed to text/rtf, which Tools did not support. Add support for the new selection target name "text/rtf". commit 99ee155b5923cc036c7412b494c36e7d7dd38f50 Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Support building open-vm-tools only for FreeBSD 10 and later. Implemented a check for FreeBSD version and abort if the detected version is less than 10. commit 6091407c4a7e191925bb1b668a99df4ca7e2fab5 Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Stop building open-vm-tools for LINUX systems with glibc < 2.12. Implemented a check for glibc version and abort if the detected version is lesser than 2.12 (This affects RHEL5 and older generations). Implemented a config switch '--disable-glibc-check', which when specified, will skip checking for compatible glibc version. Modified the tools-pkg.make file to specify --disable-glibc-check while executing "./configure" for open-vm-tools. Note: glibc check is done only for Linux systems. commit 94509955865e6bef7818675761d6dbb9d83df6e5 Author: Oliver Kurth Date: Fri Sep 15 11:23:43 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 888d4a7a8394e4391b9abb09b3884f7e1d5971b9 Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 Hgfs Server: Remove the register share callback and usage part 2 Now the function is not being called at all it is time to remove it along with the callback table entry for it. commit ec6c1f40fb15ffb0d8d6658b9a99c21c706ccb59 Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 Dynamic socket options API for async sockets lib/asyncsocket/asyncsocket.c: lib/asyncsocket/asyncSocketInterface.c: lib/asyncsocket/asyncSocketVTable.h: lib/include/asyncsocket.h: - Add AsyncTCPSocketSetOption(), AsyncTCPSocketGetOption() and AsyncSocket_EstablishMinBufferSizes functions. - Remove/deprecate specific option set functions to be subsumed by ->setOption(). - ->useNodelay() (TCP_NODELAY), ->setTCPTimeouts (3x TCP_... options), ->setBufferSize (SO_{SND|RCV}BUF), ->setSendLowLatencyMode() (non-native option regarding buffering/callback behavior). lib/rpcIn/rpcin.c: services/plugins/grabbitmqProxy/grabbitmqProxyPlugin.c: - replace AsyncSocket_SetBufferSizes() calls with AsyncSocket_EstablishMinBufferSizes() calls. Common header file change: not applicable to open-vm-tools. commit 63b5e3c8138c8d8561f2be8391ac3dc062e6afa1 Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 Remove BDOOR_CMD_FAS_GET_NVDIMM_FMT_CODE Now that our guest FW can read the NVDIMM format interface code (FIC) from the NVDIMM controllers MMIO space we have no need for a backdoor call to do the same thing. This change removes the backdoor call for reading the FIC and makes it's callers read the FIC from the NVDIMM controllers MMIO space instead. commit 028854fd377698d261aad7787723e4d3db1069b9 Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 Hgfs Server: Remove the register share callback and usage Remove the register share callback and usage which is an HGFS server libray function passed back to the VMX Hgfs server manager and policy manager. This tracked shares as they were individually added and removed. It carried with it VMDB behavior which was erroneous for the HGFS server share tracking. This API has been replaced by piggybacking on the Hgfs server InvalidateObjects callback which informs the Hgfs server when the VMDB has finished updating the Hgfs policy manager with shares and the Policy manager's list is complete. At this point the Hgfs server can close any open handles on stale shares and remove those stale shares and add new shares. commit f8d262a1dd1467b097b55f646ac3302531e4aef0 Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 lib/misc/strutil.[ch]: New functions added; not applicable to open-vm-tools - Added functions StrUtil_GetNextItem, StrUtil_HasListItem, StrUtil_HasListItemCase, StrUtil_AppendListItem, StrUtil_RemoveListItem, StrUtil_RemoveListItemCase commit 2edd97267f299ec18b9c60cf613bef99497729b3 Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 Hgfs Server: Fix shares update for change notification This change fixes UI updates of the shares which currently update by a poorly designed algorithm which causes change notification subscriptions to be deleted and not restored and also unnecessary deactivation and activation of the events generation. Currently, the UI updates the HGFS shares in the HGFS server via the RegisterShare callback. This is done from HGFS VMX policy code which handles updates from the UI and maintains the HGFS shares. The UI calls the policy code for each share to remove it until the list of shares is empty. It then calls back for each share to add the existing shares back to the list. Currently, the policy code calls the HGFS server RegisterShare callback to delete the share as it removes them and then again to add each one back in that added to the policy shares list. Unfortunately, as the shares are removed any existing subscribers for change notifications on the deleted share are also destroyed. Furthermore, when the shares list is empty, the count of subscribers will also be zero at this point causing a deactivation of the file change event generator. Once, the shares are added back in via the RegisterShare callback no event subscribers will be restored as they are not tracked and the event generation will also not be activated due to that reason. The fix is to make the shares tracking be handled in the same manner as the HGFS server does for open handles on shares. The HGFS policy waits until the shares list updates are complete as the UI is done updating the shares. The HGFS policy then calls the HGFS server InvalidateObjects callback with the new complete list of shares which may or may not be different from the previous list. The HGFS server InvalidateObjects goes through its current list of shares and searches for each share in the new list of shares and if it fails to locate it, then closes all open handles on that share. Once the list has been exhausted, all open handles remaining will be on shares that still exist. The same callback is now used for resetting the list of shares for the current subscribers of change events and not the RegisterShare callback which should be removed altogether. We now make sure that the reset of file change event shares only removes shares not found on the new list thereby only removing subscribers on those stale shares. All subscribers for shares remaining on the lists are not deleted, remain intact and unaffected. Furthermore, file system event generation will also not be deactivated unless all subscribers happen to be for shares that were deleted. This change is the first part which as code to piggyback on the HGFS server InvalidateObjects callback to compare any shares in its list with the new list and delete shares not found. The RegisterSharecallback function code is deleted and temporarily is an empty callback. This will be deleted along with the callback code from the HGFS policy manager in a subsequent change. Details: HgfsServerRegisterShare - is gutted and just an empty function just logging that it is called. HgfsServerCleanupDeletedFolders is effectively renamed to HgfsServerSharesDeleteStale w/o the lock acquistion/release. HgfsServerSharesDeleteStale now free the share name as well as the share object to stop memory leak. HgfsServerShareAddInternal is extracted from the old defunct HgfsServerRegisterShare w/o the lock acquisition/release. HgfsServerShareAdd acquires and releases the lock and calls HgfsServerShareAddInternal HgfsServerSharesReset is created and called from the HgfsServerInvalidateObjects HgfsServerEnumerateSharedFolders now calls the new HgfsServerShareAdd for all shares which is used to initialize the shares on HGFS server start. HgfsServerGetLocalNameInfo now does not get the Shared Folder handle from the VMX policy host, instead getting it from the existing HgfsServerGetShareHandle (the server maintained list of shares). This is only used for setting subscribers from the client when using handles and not path names. HgfsServerSetDirWatchByName now uses the handle returned by the HgfsServerGetLocalNameInfo call. markedForDeletion is now removed as holding stale state is not needed since stale shares are deleted and resources freed immediately. commit 357f5304834d40ce8a1e97838766f34cc6d89ddd Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 2ca4b125656100d69c9f7868bccbb55d0547e852 Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 94028b39e929b162ebc320f455fb2f5b3af53f04 Author: Oliver Kurth Date: Fri Sep 15 11:23:42 2017 -0700 Check timeout setting for scsi device before setting The rule to set the timeout value for SCSI devices was too generic, and caused error messages, when the timeout field was set when it didn't exist. This is not harmful, but generates unnecessary noise. This change adds a check if the timeout field exists. commit 5c77f471ccb8b87dd80f3928b313480aeb8edf0a Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit dc81979e78e1b8f42639aeb7aaec69f7ea49eb79 Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 Remove convertutf and bsd_printf The license for convertutf.c and convertutf.h does not explicitly permit, or prohibit, modification of the files, and restricts use to "products supporting the Unicode Standard". This is a problem for distribution with Debian, which complies to strict guidelines. See details at https://github.com/vmware/open-vm-tools/issues/148 and https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=823100 The code is not essential for open-vm-tools. It's needed by code in bsd_printf.c and related code, which in turn is needed by msgfmt.c and msgList.c. The latter code is not needed for open-vm-tools, and can therefore be eliminated from the open-vm-tools package. When HAS_BSD_PRINTF isn't set, Str_Snprintf() and Str_Vsnprintf will fall back to vsnprintf(), and Str_Asprintf()/Str_Vasprintf() will fall back to vasprintf(). Under Linux and FreeBSD these functions are properly implemented, and support %ls and %S. commit 131e4a60fa2d2db0c30920d826d23aec44d8ab09 Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 Remove Linux kernel modules Remove Linux kernel modules from open-vm-tools. commit 5034ce882ff4ab49fc4a874009ce638b377bcdaa Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 optimize clamped uadd functions For unsigned adds, if there's no overflow, the result will be larger or equal than either source operand. Consequently, if there's an overflow, the result will be smaller than both, and checking against one source operand is sufficient. Found accidentally... (With just one comparison, gcc is in fact able to figure out the comparison is really the same as the add overflowing and will omit the comparison. But it won't do this with two comparisons.) commit ce18b4a333b1d0e757ba3e9b3f650f5d860f35c9 Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 VThread_Init: remove VThreadID parameter With the removal of static VThreadIDs, there is no longer any need to specify a specific VThreadID when initializing the VThread library. We can simply auto-assign an ID instead. Remove the VThreadID parameter from all callsites. Remove all VTHREAD_xxx_ID macros (except VTHREAD_INVALID_ID). Slightly adjust vthreadBase.c to "know" that VThreadIDs now start at 1, not 5. commit 92259d4832396c82d50b7a678ab294dceca34907 Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 Changes to guest_os.h for Solaris 11 commit 45212bdaa54e336f53327f571b0aad48b89c787d Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 Replace ASSERT_DEVEL(p) with DEVEL_ONLY(ASSERT(p)) It wasn't clear when ASSERT_DEVEL was enabled: was it for all VMX86_DEVEL builds or for the intersection of VMX86_DEVEL and VMX86_DEBUG? Replace ASSERT_DEVEL(p) with DEVEL_ONLY(ASSERT(p)) to make it clear that it's the latter. commit 3bf9c558ae09cb518d654643ee1d435de5b3a93f Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 Include syncManifest.c in open-vm-tools only on Linux The VMTools build includes syncManifest.c only on Linux and not on other OSes such as FreeBSD. The open-vm-tools build needs to do the same. commit 1183d2b3ab8a75cb42272caacec8cc7f193e4651 Author: Oliver Kurth Date: Fri Sep 15 11:23:41 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 3ff49cad5bced6a1a2806a4791d42c33adfa8d25 Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 Common header file change; not applicable to open-vm-tools. commit b78434e97e937eb74c373c870d9c5b9e0b8296e8 Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 VMCI: Reset datagram buffer pointer on dealloc A customer was seeing a guest crash when unloading the VMCI driver - but only when upgrading to a specific version of UEK. It turns out, that a BH may run during module unload, and attempt to deliver datagrams to the datagram buffer after it has been deallocated. It turns out that the tasklet may not have been scheduled yet, so add a tasklet_disable to guard against this. Also, reset the datagram buffer pointer when the buffer is deallocated to indicate that it is no longer there. commit e146ddb85e0f620faff25decc716ad406b4486e8 Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 Hgfs Server: Fix a memory leak of the transport connection This change fixes a memory leak of the transport connection object which was not being released on the final reference removal when the HGFS server is being torn down. This separates the initialization and destruction of the transport object into their own transport init and exit functions. Added the lock destruct and free call of the transport object to the exit function that were previously missing. Corrected or added some missing logging for debugging. Additionally, fixed the VMCI interface to correct its tear down order of functions which relied on the transport not being deleted. This involved moving the draining of out of band HGFS server requests or replies to the guest from being called after the HGFS server transport has been destroyed. Now it is moved to the correct place, where the sequence is now: - disconnect the HGFS server (i.e., stop generating any new request/replies out of band, - drain the existing out of band HGFS requests/replies - close the VMCI transport and shared memory callbacks - close and teardown the HGFS server session and transport - teardown the VMCI channel itself commit 7e50fb73f7920a305f7c29bf957eef3ef0b4cd72 Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit b7512d420ef13408426928df08d0505c46c6522a Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 45c2246c6c84ff1923ac3f33d884b124530db8e6 Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 Port X11 resolutionSet off gtk Replaced gtk calls with XOpenDisplay to obtain X Display. Also moved getting the display logic (XOpenDisplay) from ResolutionToolkitInit to ResolutionBackendInit and corresponding XCloseDisplay in ResolutionBackendCleanup. ResolutionInfoX11Type is used as back-end specific handle and canUseResolutionKMS bool variable to communicate to loader about resolutionCheckForKMS. Removed gtk header from ResolutionX11.c and ResolutionRandR12.c. commit a61a342fd48b248fc794d639c6690e42a4ebc7fb Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 resolutionSet/resolutionKMS: Force load the vmwgfx kernel module When testing for resolutionKMS system support, make sure the vmwgfx kernel module is loaded before trying to obtain an open file descriptor to it. Otherwise both the resolutionKMS- and resolutionSet tests might fail. commit 38f7adb5e37a49b6696f467efa5183d906538eee Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 Changes to common source files; not applicable to open-vm-tools. commit 5949be840ee39f0853e98741bcae30e559914f00 Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 9f3c5f179ed252f31c15e71ca45c83ae33a4dc62 Author: Oliver Kurth Date: Fri Sep 15 11:23:40 2017 -0700 Generate backup manifest files for quiesced snapshots on Linux. After a successful quiesced snapshot of a Linux guest, the snapshot is reported as not quiesced. The underlying cause is: - a snapshot is identified as quiesced if and only if a backup manifest file was provided for the snapshot; and - backup manifest files are not provided for quiesced snapshots on Linux. To fix the problem, VMTools will generate backup manifest files for quiesced snaphots taken on Linux, and VMX will accept and store such files. This change is for the VMTools side of the change. The VMX change defines a new VMBACKUP_EVENT value relied on by the VMTools change. Changes in this commit include: - new source files syncManifest.h and syncManifest.c with code to generate the manifest file, and updates to syncDriverOps.c to invoke that code. - a new "SyncDriver_GetAttr" interface in the syncDriver code, used by the SyncManifest code to obtain the name of the backend provider and whether or not it is capable of quiescing. - makefile and configure boiler plate to add the two new source files to open-vm-tools and tools-for-linux. - a new tools.conf setting enableXmlManifest that specifies whether VMTools generates backup manifests for Linux. For now, the default value of this setting will be false. commit 5bb569f29cd9780872eb212fc5a6dda9d85d2711 Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 Add a generic interface for accepting backup manifest files. The interface provided by VMX to allow VMTools to notify it that there is a backup manifest file to be transferred from the guest is specific to Windows guests. A more generic interface is being implemented to enable backup manifest files for Linux guests. A new vmbackup event is added for passing to vmx the guest's path for the manifest file, along with code for handling the event. commit 4a9834cedf0bc1c0303e2b078db87f8754c99564 Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 Spawn a new thread to handle deployPkg.deploy RPC Deploypkg takes some time to complete, so separating it to a new thread helps guarantee that the main tools thread can still respond to VMX ping/heartbeat messages. Before this change, the state changes on the vmx side are: ToolsDeployPkg_Begin ToolsDeployPkg begin finished ToolsDeployPkg finished copy deployPkg.deploy deployPkg.update.state 3 -- TOOLSDEPLOYPKG_DEPLOYING deployPkg.update.state 4 0 -- TOOLSDEPLOYPKG_RUNNING deployPkg.update.state 4 103 -- TOOLSDEPLOYPKG_RUNNING GUESTCUST_EVENT_ENABLE_NICS deployPkg.update.state 4 104 -- TOOLSDEPLOYPKG_RUNNING GUESTCUST_EVENT_QUERY_NICS ToolsDeployPkg finished deploy ToolsDeployPkg_Begin ToolsDeployPkg deploy state: 4 deployPkg.update.state 5 0 -- TOOLSDEPLOYPKG_DONE After this change, the state changes are: ToolsDeployPkg_Begin ToolsDeployPkg begin finished ToolsDeployPkg finished copy deployPkg.deploy deployPkg.update.state 3 ToolsDeployPkg finished deploy deployPkg.update.state 4 0 deployPkg.update.state 4 103 deployPkg.update.state 4 104 ToolsDeployPkg_Begin ToolsDeployPkg deploy state: 4 deployPkg.update.state 5 0 There are no specific changes on vmx side. commit 32df9c92ce5e9df85cabb7e488c5ed18faa41914 Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit aabfe8a76e82644caac0d026bff2357be943ce6e Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit db1c14fb0e23d0d400567ac1a90b5c4fb08b6665 Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 Common source file changes; not directly applicable to open-vm-tools. commit c68f83bfc9dad7ac2e46780b84255bf102fdc977 Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 Log output from network script Log all output from the network script to help debugging. commit 32c82dc60b2963924ef9f407916e17880ae20b04 Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 Report version data via guestinfo vars Set up some guestVars to report Tools version info (version, build number, etc). commit f01a8f551cfd6c82ae2d851d51dcf4173493e674 Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 Rename VThread_IsXxx() to VMX_IsXxxThread() Unrelated to open-vm-tools. commit 5617d9a776d51fa56f46e56e3484070cf704f8cb Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 AsyncSocket: Fix lock rank violation introduced by WaitForReadMultiple There's a lock call that should be an unlock. commit 17de351b6300c16aa91ea609bfae22c71ac8fc39 Author: Oliver Kurth Date: Fri Sep 15 11:23:39 2017 -0700 ARM: Better decode CPU Model Name Instead of always returning "ARM64", the CPU model name will now be the CPU vendor followed by the core name and revisio, eg. ARM Limited Cortex-A57 r1p2 hostinfoPosix arm64 hack to always return "armv8 unknown" is removed, and will forward the CPU Model Name. commit ef1e7f13ccd5878fb57f394cf709874e3dc11990 Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 6c72a0e9670327ed2060ae8ca3d529f69de0a385 Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 file: Report correct error message when file is locked. commit 7397d21db121bb3b5498a44027f990381974e1f1 Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 Check for gdk_pixbuf_xlib-2.0 in configure script gdk_pixbuf_xlib-2.0 is no longer part of gdk-pixbuf2 in newer distributions (for example Fedora 26), so it's no longer pulled in as a dependency from the gtk devel packages. Therefore we need an extra check for it. commit d50f3e6ba1e35020bcf7450701f492ba0ffb75a3 Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 Clean up overflow NIC issues If we hit the max number of IPs, we just keep going and try to add the next one. This makes for extra work and produces lots of log spew. commit c85ace8f7e180929f179dea9e21097c70e2e7e82 Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 Common header file change; not applicable to open-vm-tools. commit e5bf6e89f1f634f00a403c9e1ae3be96534a9d5a Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 MKS Thread: make VThreadID dynamic Unrelated to open-vm-tools. commit c2b6423692888f1f0534131c03c5aacc5d1632f2 Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 Smarter handling of large numbers of disk mounts Instead of just giving up if we find more than 255 mounts, expose what we can. commit 5965ba1d8ad2803f83771b25dc13b499a8a6c9e8 Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 Log DRM version in the debug message. The additional version in the message proved very useful while debugging resolutionKMS functionality. commit 834787e0887697286e63b61c643771de2de6656a Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 Remove ufs code There is currently no use case for it. commit efcc77506932a563951908c5c0f9087cc0432c31 Author: Oliver Kurth Date: Fri Sep 15 11:23:38 2017 -0700 modules/shared/vmxnet/vmxnet3_defs.h: - Code restructure of some MACROS. commit 04cf8f685846a7c817072f9fcfac6f6d9618b8c5 Author: Oliver Kurth Date: Fri Sep 15 11:23:37 2017 -0700 Downgrading 10.2.0 Tools to 10.0.9 fails to start CAF. Create the cafenv.config file required by 10.0.9 Tools from cafenv.appconfig of 10.2.0 Tools. Clean up CAF files after Tools uninstall. commit 3091d0b0e1143b49ba6f33d3bb2e4900c6b4c12b Author: Oliver Kurth Date: Fri Sep 15 11:23:37 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e5f98a856b27e39c06b9d9244adf9e4f195f28b8 Author: Oliver Kurth Date: Fri Sep 15 11:23:37 2017 -0700 Add new AsyncSocket API to wait on multiple sockets at once Currently, there is no way to poll/select on multiple sockets through the asyncsocket library. VRDMA is encountering a use case for such functionality, so add such an API to asyncsocket. It is only defined for AsyncTCPSocket, and is mostly just a wrapper around AsyncTCPSocketPoll. commit d49040684aa60e696d615ec330ea8329c134ed0e Author: Oliver Kurth Date: Fri Sep 15 11:23:37 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 4c3c80df2b8c246e1441a9f34fb11b25dc344e97 Author: Oliver Kurth Date: Fri Sep 15 11:23:37 2017 -0700 Avoid name strings other than vmusr/vmsvc in vmtoolsd command line. Add name checking when parsing command line. commit 699f7e7403fa3010a382d804806a9c5b50a38239 Author: Oliver Kurth Date: Fri Sep 15 11:23:37 2017 -0700 Changes to common header files; not applicable to open-vm-tools. commit c6422b6c922a88a47e9c8121d9f45d2bb250c0b1 Author: Oliver Kurth Date: Fri Sep 15 11:23:37 2017 -0700 Change defined(linux) to defined(__linux__) in open-vm-tools files. Reported by open source developer on GitHub, see github.com/vmware/open-vm-tools/pull/81. commit dbce6217a9ba2e33bf536437393cf6fc4bb4eaa9 Author: Oliver Kurth Date: Fri Sep 15 11:23:37 2017 -0700 Stop using deprecated glib APIs in vgauth Replace some static mutexes with the modern versions. commit 9367d3e3cf8819b198dd52cd4e1f19872efcfefe Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Fix HostinfoGetCmdOutput to return NULL on failure HostinfoGetCmdOutput unconditionally calls DynBuf_DetachString along its success path. DynBuf_DetachString never returns NULL, so that broke callers expecting a NULL return value if the command had no output (which can happen if HostinfoGetCmdOutput attempts to run a non-existent executable; note that this does not trigger any of the failure paths). Restore the old code that checked if the DynBuf is non-empty before retrieving its contents. Bonus: * Fix incorrect documentation to Posix_Popen. * Adjust the StdIO_ReadNextLine documentation to clarify its behavior. commit 15626c9d3a81d4d629902504ed7fd21d04f5e4b6 Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Changes to common source files; not applicable to open-vm-tools. services/plugins/dndcp/stringxx/string.cc: services/plugins/dndcp/stringxx/string.hh: - Change utf::string::toUpper() and related functions to default the locale argument to a NULL pointer. commit bea370f7deb0e216206223301dfe1db974e0ffee Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Update vm_tools_version.h with Tools 10.1.x update and patch versions. Updating the VMware Tools version information for the known vmtools 10.1.x updates and patches. 10.1.6 - vmtools_prod-cpd-ep3: CLN 4984516 10.1.10 - vmtools-prod-cpd: CLN 5016060 commit f6d5355574b0342ad7ad471fbc2fbcb75bdb25dc Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Check alignment in Atomic_* functions for the VMKernel Unrelated to open-vm-tools. commit 47c77211f47644e1e999621d3974ebd09af84312 Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Fix i18n symbol violations Fix some of the illegal symbols that are flagged. Also changed the wrapper for unsetenv to return an int to match the glibc-2.2.2 and later version. Tools build for FreeBSD appears to be using an older libc so it always reports success in that case. commit e9c2208a3240e36e590b0be9bda8b2a7510aae2c Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 8e0b9513236e4494f089cdaee641af5e80adc5c8 Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit a4ba5b7e40c384c76cf35209bdd421f97d70e142 Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 5be59c7691509e30ffc44b67f8a6eba66e141d3d Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Revert the previous commit. commit 94702b2a09cdbad725f6e536203c4bab1bdcf9c0 Author: Oliver Kurth Date: Fri Sep 15 11:23:36 2017 -0700 Check alignment in Atomic_* functions for the VMKernel Unrelated to open-vm-tools. commit f424d59444ae7718f5e47ebcd5b417df8acea456 Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Re-enable ASAN for DynBuf_Append() The problem is incorrectly instrumented callers. commit 5f94953bafbbb2348ae2abe6d958828b311d1f6b Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Common header file change: not applicable to open-vm-tools. commit f0df01ce187c5bfca5d361f45a6ca2f38a4bd934 Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 3525fd7385f6c8185305d20d149fa59d5ebf9c5e Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 New common header file: lib/include/product.h. Move public product types enum from lib/include/productState.h to product.h Common header file change; not applicable to open-vm-tools. commit afb42f5edc9502a877d48aabaa1f8af31a959619 Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit a71c02a67c6a78179449d3153751584873452016 Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Revert previous commit. commit 6320d542cb1eb9cd1fed41ff22b4b2d42cd179c9 Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Interpose dlopen() to only allow root-owned library Only allow dlopen() on library that meets the following: - the library file is root-owened - the directory is root-owned, and not others-writable. commit 5fe82108703e3c0448e9243f2b58fada8f790d2a Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Restrict panic's int3 assembly to x86(_64). Panic could also be used for iOS. commit 7e2a13784c6d3cc7ef4d57957608e1bd9e8b4b59 Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Delete unused COMPILER_FORCED_LOAD_AND_MEM_BARRIER Delete the macro definition. commit d484f11a6b14d41ee202c3378a2c6174aa3d4784 Author: Oliver Kurth Date: Fri Sep 15 11:23:35 2017 -0700 Memory barriers: LD_LD_MEM_BARRIER -> SMP_R_BARRIER_R Delete the now unused, old macro name. commit 93c968d5034cbc6f6948caa5129fd5fcfb18619c Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers: LD_ST_MEM_BARRIER -> SMP_R_BARRIER_W Delete the now unused, old macro name. commit ba6870484de7e795b394c3bf7674f5e28c17960f Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers: LD_LDST_MEM_BARRIER -> SMP_R_BARRIER_RW Delete the now unused, old macro name. commit 79a815083e2ba1b2f6c03b5aa4ae5275e0416a95 Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers: ST_LD_MEM_BARRIER -> SMP_W_BARRIER_R Remove the now unused old macro name. commit b89f4124fd5476dbba5a9f18d9c246c5a3f3543b Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers: ST_ST_MEM_BARRIER -> SMP_W_BARRIER_W Remove the now unused old name. commit 996d7bdf489f968c9c49adace1c1ac0a525a4c77 Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers: ST_LDST_MEM_BARRIER -> SMP_W_BARRIER_RW Delete the now unused macro. commit 8e417a5ea04edece3bcd88a9a03feb822b26646e Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers: LDST_LD_MEM_BARRIER -> SMP_RW_BARRIER_R Deleted the old macro name. commit 8d3de0c6acc829d3f9c283abf4f107b506e95d20 Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers: LDST_ST_MEM_BARRIER -> SMP_RW_BARRIER_W Delete the now unused old macro. commit 1cdb544b9962def25bfacd329c8850a0c45d199d Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers: LDST_LDST_MEM_BARRIER -> SMP_RW_BARRIER_RW Delete the old macro that is now unused. commit b3bf1f137b45232e7e9b2474127ba2d3e1411162 Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Memory barriers Unrelated to open-vm-tools. Previously added new barriers for arm64 and x86_common, but forgot to handle arm32. This change does that, and fixes a mangled comment. commit 7c1f57a6f005d299b4254a295f6794f3e41a09b4 Author: Oliver Kurth Date: Fri Sep 15 11:23:34 2017 -0700 Common header file change; not applicable to open-vm-tools. commit c024d866ac746474487fea646f4787875e2dacdd Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 Remove NOT_TESTED() from EINTR handling in lib/file When FileIO_Read() & friends receive EINTR, they log NOT_TESTED, and retry read. It seems innocent - until you provide your own function to handle logging. Now imagine that you create bidirectional communication protocol, and run it over the pipe. And you do logging over this very same pipe. Application is waiting for message, so it invoked FileIO_Read(), and is blocked on read(). Now you attach strace to the process. That will interrupt pending read() with EINTR and log NOT_TESTED(). This logging performs FileIO_Write() on this very same pipe, and then performs FileIO_Read() to retrieve status of logging request. If it receives status of logging request, all is good. Code returns from logging, and reexecutes read(), waiting for request from server. But if logging function receives anything else (f.e. other side sends request at same time strace was attached), it gets queued into internal data structures of the app for processing once code returns to main application loop. Problem is that FileIO_Read() will reenter read() without returning to the caller. And that read() will block forever: other end already send request that is now pending in the request list, and so won't send anything until it sees we processed that pending request. Hang. There are two possible fixes: 1. Return EINTR from FileIO_Read(), or 2. Do not do any logging from FileIO_Read() Approach #2 is much easier, as API semantic does not change, and currently it is broken. So there is no need for NOT_TESTED() anymore... commit ba915c1445124f6369a49788b9be2e8c2886bc10 Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c8200f190cffb6cf91db9d3660bc2736f66fb448 Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 In DnD transport V3 check packet and payload size to prevent OOB read or write. commit 11094b0656ea13eff9b88cc207a4826f6ecd47b4 Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 Better Panic_BreakOnPanic implementation on macOS. There's actually a documented way to check whether a process is being debugged on macOS. This change updates panic lib to use it. commit 1fedc4083703a4438bb33617e9a56bacda41fd39 Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 Hgfs Server: Very minor clean up of server callback table Another very minor clean up for final part for making the Hgfs server callback table constant. commit 42494944951a72057279afb58deddfc72674a889 Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 lib/include/vm_assert.h: - Remove unused ASSERT_* macros. modules/shared/vmxnet/vmnet_def.h: - Fix definition mismatch of VMNET_CAP_RX_LRO and VMK_PORT_CLIENT_CAP_HW_DCB. commit c20933cea62e27e30f75e8e68251627bc06a1dee Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 Fix tools build dynbuf.c and sigPosix.c are consumed by tools. commit 4752c44c3bd6406b9b4d829ca99c0044555face9 Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 Changes for userspace ASAN This is mostly disabling ASAN for some functions and adjusting overheads. Code, touching the guest memory, currently cannot be instrumented. commit 861ad9d03153c9428f21b8a8af9762230ade2ca3 Author: Oliver Kurth Date: Fri Sep 15 11:23:33 2017 -0700 Make CAF consume the same version of GLIB (and dependencies) used by Tools. Summary of changes- 1. Linux: Make the following libraries point to their Tools counterparts by updating the LD_LIBRARY path in CAF makefile: -libglib-2.0.so.0 -libiconv.so.2 -libpcre.so.1 -libz.so.1 -libffi.so.6 -libgthread-2.0.so.0 -libstdc++.so.6 -libgcc_s.so.1 2. Linux: Add a new environmental variable INSTALL_MODE = tools/standalone in makefile, setting it to "tools" by default, to handle copying of the required GLIB (and dependencies) for CAF "standalone" installation. 3. Linux: Update setupCafConfig function to add the INSTALL_MODE property if not present already to handle build2build upgrade case. commit ae05d32a9303f27ff642ab39bb49abc46e3ba78b Author: Oliver Kurth Date: Fri Sep 15 11:23:32 2017 -0700 Add constants for macOS os major versions. MacOS versions can get a bit confusing because there are two parallel versioning schemes. There is the marketing version (e.g. 10.6, 10.7.5, etc.) which is what everybody uses when discussing the OS but is very hard to get at via code, and there is the kernel version (e.g. 10.0.0, 11.4.2) which is what is returned by POSIX syscalls like uname. The confusion sets in because in comments we tend to use the marketing version, but then the code actually checks for the kernel version. This change adds constants for the marketing version for comparisons with HostInfo_OSVersion(0) (the major version), which makes checking for 10.6 vs 10.7 vs 10.8 etc. much more readable. commit 03b89a4c99f257e724d90eff5c15560a4f9f2919 Author: Oliver Kurth Date: Fri Sep 15 11:23:32 2017 -0700 Add vgauth smoketest Provide the vgauth smoketest so open-vm-tools builders can validate VGAUthservice. commit 57aac16fc9054bd20ccf004dfd09e02bdd127795 Author: Oliver Kurth Date: Fri Sep 15 11:23:32 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c1ef635e08ecd4c4aafc48a480ccd651935ce1e5 Author: Oliver Kurth Date: Fri Sep 15 11:23:32 2017 -0700 Remove BDOOR_CMD_HOSTCOPY backdoor handler. The BDOOR_CMD_HOSTCOPY command has been under VMX86_DEVEL and is no longer used. Remove it. commit 7ca594dc06fc0b129265d19c51bb367333b01358 Author: Oliver Kurth Date: Fri Sep 15 11:23:32 2017 -0700 Fix building without ICU Building vgauth failed when building without ICU (with the --without-icu option). This was caused by not using cxx link options which are needed by xml-security, but only enabled when using ICU. Also fix the warning "invalid suffix on literal;". commit d77b6c7ba1dc5a38e38c35c321eabe7ccbc801c1 Author: Oliver Kurth Date: Fri Sep 15 11:23:32 2017 -0700 Tools Hgfs Transport: Make the server callback table constant Simple change to make the Hgfs tools transport use the server table of callbacks as a constant. commit 880750417a7af90ad9b510524285e2d628d9a25d Author: Oliver Kurth Date: Fri Sep 15 11:23:32 2017 -0700 Common header file change: not applicable to oprn-vm-tools. commit e02005e5b01e6335b233a2ab9d15f294a46a11e5 Author: Oliver Kurth Date: Fri Sep 15 11:23:32 2017 -0700 Fix tools build For open-vm-tools there is code that strips off the "VMware Confidential" part of the msgfmt.c header. When the copyright years were updated in msgfmt.c, it broke the pattern matcher. commit 4a61bffe80e57aeab0400813403c47a94e2acd1c Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 Replace Atomic_MFence with architecture-independent barrier primitives Atomic_MFence was used to implement a full memory barrier on x86 architectures. In an effort to clean up duplicate code, this change removes Atomic_MFence and replaces all previous uses with the most conservative architecture-independent barrier primitive (LDST_LDST_MEM_BARRIER). Since LDST_LDST_MEM_BARRIER is also a full memory barrier, this change does not affect any existing ordering semantics. commit 34ff407a2ff5cbc0095fb95b30b1ba4e66f0f0c7 Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 Fix timesync state to be uncalibrated when adjustment is large (>60ms). VMtools has timesync plugin to adjust guest time to match host time. Timesync relies on a state machine (Uncalibrated, calibrating and PLL states) to adjust the amount of guest time to match host time. If the guest and host time differ by more than 60ms, state machine should reset to uncalibrated state. There is a bug currently that would leave the state in PLL mode even if the guest and host times differ by more than 60ms since absolute value of adjustment is not considered. This causes the time sync to happen slower than expected. commit 488aea219340e6821b25fb4240791fa9e7903023 Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 Specify the proper size while sending deploypkg.update.state RPC message. Due to a recent change, the VMX handler for 'deployPkg.update.state' RPC ignores the message if the specified argument size doesn't match with the string size. In the current code, in a certain error code path, deploypkg plugin specifies one extra byte in the size for 'deploypkg.update.size' RPC message. This results in an error at the VMX layer. Fixed the code to specify the proper string length while sending the RPC. commit 40ac04d8f3df4ea7eff9b890055fa565b368f4e3 Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 Implement ST_LD_MEM_BARRIER on x86 with a locked xor Microbenchmarks on modern Intel architectures show that a memory barrier implemented with locked xor operation performs about 30% better when compared to a barrier implemented with mfence, while providing the same memory ordering guarantees. This patch changes the implementation of ST_LD_MEM_BARRIER on x86 architectures to use the faster, locked xor operation. Additionally, support for Microsoft's compiler is added. commit dda3fcee5a7382cdbd47e2eb5cb0af3f72b9b8e3 Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 atomic asm snippets: Remove unnecessary uses of "clrex" In our atomic asm snippets, we do not need to use "clrex". commit 81fec44ea5303efa27fb0f04ba06f162ffdfb2df Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 atomic asm snippets: Replace "memory" clobber with "Q" constraint In our atomic asm snippets, using the "Q" constraint, (https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html tells gcc which exact memory is modified i.e. the bytes covered by the atomic variable), is better than using the "memory" clobber (tells gcc that all memory is modified, effectively a compiler memory barrier which prevents compiler optimizations). commit 24bb7361bb1ed63201030841282369e571490f8b Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 resolutionSet/resolutionKMS: Work around DRM control node removal DRM control nodes were removed in linux 4.10. Work with an updated version of the vmwgfx kernel module and target render- or primary nodes instead. commit a7c41d1f862473b1fcde3c4fcb552ff5a648d022 Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit dc91538f50ff7d3f3ccc8f2310f7ce79266c6153 Author: Oliver Kurth Date: Fri Sep 15 11:23:31 2017 -0700 vm_{atomic,uninterruptible}.h: Flip the polarity of the 32-bit function names Initially, we only had 32-bit atomic functions, so their names did not have a "32" suffix. Then, we added 64-bit functions. So, 1) We used a "64" suffix for them. 2) We provided additional names with a "32" suffix for the 32-bit functions, for consistency. The hope was that, over time, references to unsuffixed names would disappear. This change sends a stronger signal to developpers that the suffixed names are the ones to use, and that the unsuffixed names are the undesirable legacy ones to avoid. commit d1721610e10cd7cc5f1009f608d7a2b12e5bfb54 Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 vm_{atomic,uninterruptible}.h: Consistency cleanup This change brings a few dissidents back in line with the rest of the code. Also deleted Uninterruptible_FetchAndAdd64(): o It was unused. o It provided the same functionality as Uninterruptible_ReadAdd64(), with a worse name and implementation. commit 9cb35ce39ee24ea40fca08a0913dac79c662cf2d Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 Add an error return to asyncsocket Change asyncsocket to return a ASOCKERR_REMOTE_DISCONNECT when a disconnection is detected during a send attempt. commit 69b7e1f9423fe565b2cbe2ec784068b7f55a8247 Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 Include sysmacros.h directly as mandated by glibc-2.25. glibc-2.25 generates a deprecation warning for using 'major' macro without including sysmacros.h. https://sourceware.org/glibc/wiki/Release/2.25 This is breaking Fedora builds of open-vm-tools because Fedora 26 is switching to glibc-2.25. commit b379074c3c635f684ef1630ea156eb2eefb04973 Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 8afe56f5d1d33593d29b0247b0be5e2eba65d0a4 Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 Remove FileIO_GetVolumeSectorSize commit a7886e7a44582fbc019e995afa2147eb0efd6710 Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 Fixed invalid class pointer access if VSS provider not installed Some customers may disable VSS support by not installing VMware snapshot provider, which may lead to the VSS provider not being able to be initialized, which in turn could lead to a invalid class pointer access during complete initialization. This change checks provider initialization status before initialize completer to fix the issue. commit c02d20001fbfd06558891fe5cf87c9aae33765cb Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 Tools Hgfs Transport Logging: Migrate the to common tools conf logging Migrate the tools implementations of the HGFS policy, server manager and transport channels to use the common tools conf logging with the "hgfsd" domain setting. This allows the HGFS server core and the server managerand transport components to be independently logged. Changes are: - Move the logging definitions into the server manager lib common header - Add some log statements into the server manager public APIs - Redefine the policy manager (share handling) logging to the general tools logging. commit 5034d1fb0aef6455a79d719c2f97ccf7f44c831a Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 vm_atomic.h: Build Atomic_uint128 upon uint128 instead of __int128 Atomic_{8,16,32,64} are built upon uint{8,16,32,64}. Atomic_uint128 is built upon __int128, which is inconsistent. This change builds it upon uint128 instead. commit 20a42400e5ab98c4a2a6da254968c29d748d5d58 Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 vm_atomic.h: Implement Atomic_Bool operations on top of Atomic_uint8 operations The atomic code was inconsistent: o On one hand we had Atomic_uint{16,32,64,128} basic types, on top of which we auto-generated more elaborate types such as Atomic_Ptr and Atomic_Int. o On the other hand we had no Atomic_uint8, we had Atomic_Bool implemented as a basic type, and we had CMPXCHG1B (based on uint8, defined for vmkernel and vmm only, with an x86-specific name) that was implemented similarly to Atomic_ReadIfEqualWriteBool (based on Atomic_Bool, defined for everybody, with an architecture-neutral name). This change brings a little bit of consistency: o It defines Atomic_uint8 as a basic type. o It auto-generates Atomic_Bool on top of it. o It deletes CMPXCHG1B. Also added a void * argument to AtomicUndefined(), which is used to "consume" function parameters to prevent some compilers from warning about unused parameters. commit 92a2f1e908e7e132eea2beba57926ac2fee34902 Author: Oliver Kurth Date: Fri Sep 15 11:23:30 2017 -0700 Revert the previous commit. commit 3e732d788ef472bdf07dc53a32bc2c3b271a1ee5 Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 vm_atomic.h: Implement Atomic_Bool operations on top of Atomic_uint8 operations The atomic code was inconsistent: o On one hand we had Atomic_uint{16,32,64,128} basic types, on top of which we auto-generated more elaborate types such as Atomic_Ptr and Atomic_Int. o On the other hand we had no Atomic_uint8, we had Atomic_Bool implemented as a basic type, and we had CMPXCHG1B (based on uint8, defined for vmkernel and vmm only, with an x86-specific name) that was implemented similarly to Atomic_ReadIfEqualWriteBool (based on Atomic_Bool, defined for everybody, with an architecture-neutral name). This change brings a little bit of consistency: o It defines Atomic_uint8 as a basic type. o It auto-generates Atomic_Bool on top of it. o It deletes CMPXCHG1B. Also added a void * argument to AtomicUndefined(), which is used to "consume" function parameters to prevent some compilers from warning about unused parameters. commit 93efbb2335349fda6587cda662a389b8b99724b4 Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 Accelerate some Atomic_* operations Unrelated to open-vm-tools. commit 04af878bf5b1c56a9513b606895c41c46def687c Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 Hgfs VMCI Transport: Part I fix the shared memory interface to not assert THe HGFS VMCI transport uses the shared memory access functions to extract HGFS protocol packets for the HGFS server processing and for returning results. This interface recently changed to add thread tracking for these operations with the addition of register and unregister functions. The HGFS transport interface was missed on the initial change and hence now triggers an assert as the register function call has not been made. This is the first part of a change which addresses the assertion failure by adding the register and unregister calls for the HGFS VMCI transport interface which uses this shared memory. The calls are part of a set of callbacks provided by the supported transports to the HGFS server code for the VMX and tools. Since the backdoor transport does not make use of the shared memory and access calls it just sets the function callbacks to NULL. This is done for both the VMX backdoor channel and tools backdoor channel for packets routed into the HGFS server. This change does the following: - Adds the register and unregister callbacks to the channel callback table. - Modified the VMX VMCI channel to add the register and unregister callbacks and initialize the callback table with these new functions which are then passed to the HGFS server. - Modified the VMX and tools backdoor channels to NULL out the function pointers for the register and unregister callback functions. - Add the Hgfs server directory notification callbacks for register and unregister which are termporarily protected by ifdef statements as they are not yet called from the directory notification component. These simply callback to the channel register and unregister functions to do the real work if present for the channel in use. (Only VMCI will use this.) commit 3393f1082b454052a37e33f241e6ceb20fcb29f2 Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 Hgfs Server: Clean up logging macros and enable Hgfs Server tools logging The HGFS server logging macros are scattered throughout and repeated in each source file. This makes it difficult to modify between the VMX implementation and the tools. The tools side suffers currently and is thus hard to debug. This is the first in a couple of small changes to clean up the logging. First the cleanup by moving the server logging statements for LOG to a centralized private header file for the server code and not repeated in every source file. Second, move the HgfsServer LOG from hgfs to its own HgfsServer setting. New VMX file setting is: Loglevel.hgfsServer = "10" The current existing setting of "hgfs" will capture logging for the VMX such as the HGFS manager, policy and transport interfaces (VMCI/Backdoor). Third, the HgfsServer LOG statements for the tools builds (which go into both instances of the vmtoolsd sevice/daemon) and the upgrader application are now mapped to g_debug and Debug function calls respectively. This now allows the tools configuration logging to set the following which will capture all the Hgfs server logging: hgfsServer.level = "debug" Follow up changes will be made to check the tools backdoor transport interface log setting which currently uses something like: hgfsd.level = "debug" commit 1cb088a145faa1db071fd71f82a46f8398e04682 Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 Remove LISP in vm_{atomic,uninterruptible}.h Unrelated to open-vm-tools. commit c04c7f646558a39445d2348dd99beec90ad587a6 Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 Add Util_Memdup(); replace DynBuf_AllocGet() calls with Util_Memdup(). Remove Util_CombineStrings() and Util_SeparateStrings(). - lib/dynxdr/dynxdr.c - lib/include/dynbuf.h - lib/include/util.h - lib/misc/dynbuf.c - lib/misc/utilMem.c - lib/user/util.c commit 166ec44767193a5f2c6430effe56ac83fccc9c74 Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 vm_{atomic,uninterruptible}.h: De-duplicate asm snippets Unrelated to open-vm-tools. commit e2ac716f06f7343f69b2313f2c2b07d03fda7bd1 Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 Revert previous commit. commit a22be75ad0fe2426dec3edcf77397b35e1aa4255 Author: Oliver Kurth Date: Fri Sep 15 11:23:29 2017 -0700 vm_{atomic,uninterruptible}.h: De-duplicate asm snippets Unrelated to open-vm-tools. commit 549d415899e788f110b4b591240166feac5ef148 Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 3787bcd2f4a9855e4776d772b82a86e8b389bc34 Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 lib/log: Remove GuestLog_* declarations from log.h commit 4d65be46b0eab5641bdad4ee3b50ff9cdd35e4ce Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 11c8e52f1f4032eff096cc0ba6aadfacae2ed0d3 Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 lib/uuid: UUID routines can fail If a UUID routine can fail, make this so. Document this and make it clear what the failure indicator is. This is the first step to having the UUID routine caller handle an error. The next steps require visiting the callers and plumb error detection. commit 8d7ff7f20313100863e48f4e4ceaf6af020076a6 Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c94d3ba624d5f3911977b028148357c178c68d8b Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 lib/lock: Make MXUser_CreateSingleton* an inline This will speed up the common case nicely, protects type safety, and provides data encapsulation. commit a418e3a9bf2bdb32cc86b295319024e3d6f3a128 Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 Revert previous commit. commit 881b9938c8d89d2fa15911aa34cf512393ec92a1 Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 lib/lock: Make MXUser_CreateSingleton* an inline This will speed up the common case nicely, protects type safety, and provides data encapsulation. commit 181f8877e93ec215cfb24a2c23041371e5e5da89 Author: Oliver Kurth Date: Fri Sep 15 11:23:28 2017 -0700 Map certain PAM errors to VGAUTH_E_AUTHENTICATION_DENIED. VGAuth maps most PAM errors to VGAUTH_E_FAIL. As a result, some authentication failures result in error messages reporting general failure rather than authentication failure. To provide more useful error reporting, this change maps most PAM errors to VGAUTH_E_AUTHENTICATION_DENIED instead. commit 025158629d36851a1a190abd3427747e41842aa2 Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 3446664945da9e57031fad8892b43b2b5a6ab76f Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 lib/asyncsocket/asyncSocketBase.c: - Avoid infinite recursion with ASOCKLOG() and DecRef. lib/asyncsocket/asynsocket.c: lib/include/asyncsocket.h: - Fix race between AsyncSocket_DoOneMsg and the read callbac.k Changes to common header files: not applicable to open-vm-tools. commit d014389df605a45b282bb2cc55334c7eecb487c0 Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 Exclude non-directory and non-existing paths during quiescing. A stale mount point or a special path that can't be opened could break quiescing operation in the Linux guest. We need to tolerate such cases by skipping such paths. commit 1285fffabe27c98ab90012c5d89fd2d17bd48606 Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 Make AsyncSocket_Close() idempotent; move dec-ref out of AsyncSocket_Close(). Changes to common source files; not applicable to open-vm-tools. commit 8cf4ff17a7f7f687a55075f67f8988bd45950704 Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 Stop defining Atomic_MFence() in cross platform code No functional change to open-vm-tools. commit 8bc03fbb6c41be9f501b409a8391af5d63ecebdb Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit d8f465ade3ffd332017dc367fea8df806348f2d0 Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit a77e97df5b8145f29cb097bced90f7d91e2ff548 Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 Add Posix_Free and try harder to avoid clearing errno free() can clear errno. Apparently POSIX will prohibit that in a future version of the standard; in the meantime, add a Posix_Free function that guarantees errno preservation and start using it. Similarly, make Util_ZeroFree, Util_FreeList, etc. also preserve errno. commit 4ce5f44e0bd0789f65fe4710df5293e71eb6d1c0 Author: Oliver Kurth Date: Fri Sep 15 11:23:27 2017 -0700 ProductState: fix indent commit 1aaa5e267bb500a77a2d3771e780ffb09134fc10 Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 Allow enabling or disabling timesync multiple times. Toolbox cmd sends a presumed old value for timesync GuestRpc when enabling or disabling timesync. VMX side expects the guest side to be aware of old value and therefore errors out whenever guest repeats the operation. Previously the implementation was silently ignoring the error. Avoid sending the guestRpc to enable or disable timesync when it is already in the desired state (enabled or disabled respectively). It is optimal and also avoids the unnecessary error. commit 77c47a809b27a6b15d7c5bec739fd33983ceacd1 Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 Fix whitespace in localization file commit 7cbc6d60863ef0b02f15814178ef2f318fcf697c Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 Fix build breakage introduced in hostinfo hypervisor detection changes. ARM builds are breaking because Hostinfo_HypervisorPresent is defined but not used [-Werror=unused-function]. This change defines Hostinfo_HypervisorPresent only for i386 and x86_64 architectures. commit 2bf0056a956888da2aeb07f62b4ae05f5cb5427e Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 Hostinfo hypervisor detection changes. commit f639109e1e33718f9ed6eddb614aa6fc018ded99 Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 More cleanup of productState.h commit 71d4840904ff0cb97f6bfb38a7b7295aa11dba73 Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 Clean up productState.h commit da6d3a5187e285bebcb2c7dbe2e5902e0b1c49b9 Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit b5c16034cf33adda41d4b970dbf72ee25581db4a Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 HgfsServer: Rename the directory change notify callback to be more consistent. When setting a directory notification request we pass a callback for receiving directory change events which is currently poorly named. This simply renames the callback to be HgfsServerNotifyReceiveEventCb. This is being done for consistency and clarity when called by the notification component. commit 5188c85f06c061a657809eb5a705a8da771ced0a Author: Oliver Kurth Date: Fri Sep 15 11:23:26 2017 -0700 Disable building VGAuth, deployPkg, grabbitmqProxy by default on non-Linux. VGAuth, deployPkg and grabbitmqProxy are not supported/tested for non-Linux guests. Tar installer does not even install these components on these guests. In order to avoid having non-Linux open-vm-tools users (like FreeBSD) go through disabling these manually, use the correct default in configure script. commit c1eb3bb5e7fbff13156d05a037bf652cf2bdc384 Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 Fixes for VThread change Two fixes for build issues - numVCPU.c: Windows compiler apparently doesn't like empty initalizer lists. Fill in with a value. - vthreadBase.c: when VTHREAD_INVALID_ID went from -1 to 0, missed some adjustment code in VThreadBaseSetLocal and VThreadBaseGetLocal which "adjusted" the value by +1/-1 so default-zero would work correctly. The value no longer needs adjustment. This did not impact Linux because Linux uses have a thread-local cache which returned before this slow path. commit 2263933eb6569de38dd523ffab0786d237039502 Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 VThread: change VTHREAD_INVALID_ID, move VTHREAD_MAX_THREADS Two tiny but wide-ranging changes. - Now that there are no remaining users of VTHREAD_MAX_THREADS outside the lib/thread library itself, reduce the scope of that declaration to vthreadInt.h. - Change VTHREAD_INVALID_ID to a value of 0 instead of a value of ~0. (And correspondingly, bump the ~4 hard-coded VThreadIDs that remain). This reflects that the ID may now be default-initialized. commit d218f7a6c23c1c88b4f92ddaf1f6fbfb554cc115 Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 VThreadBase: move TLS macro to header Detecting thread-local storage support would be helpful in lib/lock. Move the detection logic from vthreadBase.c to vthreadBase.h. Bonus cleanup: inline VThreadBaseSetNameRaw commit ecc7259e47548e13189a79544fc66324d87e00e2 Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 Move VThread_CurName() entirely to thread-local storage A previous change switched VThreadBase to store thread names in thread-local storage on most platforms (all except mobile). This change is the follow-up: removing the old storage location for thread names. Briefly, this change removes the "name" field from VThreadBaseData and handles all the fallout. That's mostly straightforward, though lib/thread ended up storing a thread name in the "reserved" thread structures - this is mostly so the name passed to VThread_ReserveID would be preserved until VThread_CreateThread is called. After this, vthreadBase.c complexity only remains for VThreadIDs, which is the next step of this effort. commit d17b458c340f76112707ede1e277b575e6e4301b Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 Check the RPC return value in timesync enable/disable commands. toolbox-cmd timesync enable/disable commands always return success even when the command failed. Added a check for the return value of the RPC call and also print the error message using a generic message which required renaming existing "disk.wiper.error" key. commit 58279b25999003b34eed8553732ea6239c1b819a Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 VThread: put thread names in thread-local storage Next step in the "stop allocating per-thread memory" effort. This change moves thread name storage to thread-local storage. (VThreadIDs are the hardest and will come last). This is also only half the work; a it adds new storage but does not remove the old storage, which was left out to keep this change simpler. For platforms that have thread-local storage, the implementation is pretty straightforward, though initialization is inherently lazy. For platforms lacking thread-local storage (at this point: iOS and Android, see comment in vthreadBase.c), life is much harder. Added a very large comment contemplating different solutions and ultimately concluding that unnamed threads on such a platform will get a best-effort (read: racy) name from a global buffer. Note that threads which are explicitly named WILL get a (non-racy) name, but it requires an explicit naming attempt. commit ff41cba8ec3e90f7c1367f524defeaeb3bce2bff Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 hange to shared header file unrelated to open-vm-tools. commit 8828236506e107831d6456d39f60f36b5e02632b Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 fileLock.h: fix comments commit a391909df76d7e94e7ec768b5946d448dc4ce55b Author: Oliver Kurth Date: Fri Sep 15 11:23:25 2017 -0700 Multiple changes: lib/file/file.c: - Add new function File_ContainSymLink(). lib/file/filePosix.c: - Add new function File_GetMountPath() lib/include/file.h: - Add new function declarations. lib/include/dynbuf.h: - Clean up documentation. - Rename DynBuf_ConcatString() to DynBuf_Strcat(). - New inline static function DynBuf_GetString(). lib/misc/dynbuf.c: - Clean up documentation comments. - New function DynBuf_DetachString(). lib/misc/hostinfoPosix.c: - Utilize new DynBuf functions. lib/misc/strutil.c: - Clarify documentaion comments based on DynBuf changes. lib/misc/utilMem.c: - Adjustment to comments. Common source file changeis; not applicable to open-vm-tools. commit 5beba526e988e6c8605509343df2c58b50b45cd0 Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 Update copyright year for recently modified files. commit 009d683ad725f34a0d7e497e6fa7d406af428847 Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 Bump the VMware Tools update release to version 10.1.5 commit ccd1627ba7e4581a4066c99e6a76aa295b8fd7ba Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 566c7114a43b73431ca9fca31658d38884e0b316 Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 vmci changes to enhance void functions to return errors commit 7cf255f467e45b1613c89e489ca85d26d80e956a Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit da695443ecee6103552d44a0b174f00d24881372 Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 vm_basic_types.h: rename macro IsBool to IS_BOOL, remove IsBool2. commit 577ebaddbcfed70548c5bea89ff74f40d9a9d1cf Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 Update tools copyright to 2017 commit 545b02d45b27c392f9c4046f3043d19b5da82fe0 Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 Change ISO mapping for centos and oraclelinux from frozen ISO to linux.iso in gos table commit 64c3d03340e7ef1d2694b7dac36d4f5b7179ad91 Author: Oliver Kurth Date: Fri Sep 15 11:23:24 2017 -0700 Tools Daemon: Do not use kernel client mount HGFS when FUSE unavailable When FUSE is not installed in new OS versions that are kernel 4.0 and newer the vmhgfs-fuse client is unavailable to use. Previously, the mount RPC handler would fall back to mounting Shared Folders using the kernel client. This really should not be done as it would entail the user running with an untested vmhgfs kernel driver client or worse the driver fails to build. Instead the RPC should really fail to mount. The RPC Mount Shared Folders should only mount the Shared Folders using the kernel client when FUSE is not supported by our HGFS FUSE client i.e., when the Linux kernel version is older than 4.0. To check for these conditions the vmhgfs-fuse component is run with the enabled option which returns with success for enabled, 1 for not enabled (older OS kernel) and 2 for newer kernel but FUSE is missing. These return values should be checked and only if value 1 is returned then the mount using the kernel client should be attempted. Not as currently done with an unsuccessful result of 1 or 2. This matches the installer which does the same check. This fix is related to a bug which came about due to a user custom building and installing a newer kernel 4.0+ on top of a 3.x kernel with tools, and without FUSE. When the VM was rebooted using the 4.0+ kernel and running tools config script the script will to try and use the HGFS kernel client. The tools daemon RPC handler to mount the Shared Folders will also use the kernel client, too, in this scenario. This is bad as the HGFS kernel client is running untested by VMware. Both issues need to be closed, this change addresses the tools daemon RPC handler only. commit fa7d640c18bb421159d6749c83eba8e8372a6519 Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 disklib change unrelated to open-vm-tools On NFS, provide a way to revert to direct-write method for descriptor updates. commit e1f94428ec7fd468b7f316bd5a09bd839428bf2d Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit f543bb5ed11b393065d9449f7f5a34653cd0faf0 Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 Common source file change; not directly applicable to open-vm-tools. commit c2d88806b6c12fd074d5eeb8c3b5be6282774d4e Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 Remove TICKS_TO_USECS and USECS_TO_TICKS from poll.h Back before tickless kernels (which we now always require on Linux), there was a 50Hz-200Hz kernel "tick" for timekeeping. It is no longer used in our code. commit f7ada47b69f78b665325d633e7e45fa25bdc1232 Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e8b47cd8ea1af1f30a1a2fdfc45d41e7a0a3b992 Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 pollInt.h Mac compiler is picky about an int->enum conversion, and requires a typecast. commit 4a8aecf2d148ce11afbad939beb7b629a8970263 Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 lib/poll: Trim PollClassSet We no longer need per-VCPU poll classes, trim PollClassSet down to a non-array size. Tweak a few pollInt.h algorithms so that compile-time-constant PollClass values can be constant-folded. commit 73fe327f66448de81c324093a5d6fabd431f567e Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit d6b169cc5ec51fef82127cd64aa155faf6dd695e Author: Oliver Kurth Date: Fri Sep 15 11:23:23 2017 -0700 VThread: some thread-local storage doc updates '0' is a safe default for pthread_key_t for all platforms which still use pthread_getspecific() instead of using __thread. This change updates the documentation in vthreadBase.c, and slightly simplifies the pthread_key_t initialization logic. commit 124f09fedf4ea14b1c9817ddd3a72823c79eea50 Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c00e009050f59d450eebcadf4db7f8d4f93d8533 Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Update guest OS strings in guest_os.h: - Update "Other Linux 3.x kernel" to "Other Linux 3.x or later kernel". Add checks to services/plugins/dndcp/dnd/dndCPMsgV4.c to validate packet and payload size to prevent out-of-bounds read and writes. Correct the requestNextCmd parameter used when asking for the next piece of a big binary transfer in RpcV4Util::RequestNextPacket(). Common header file change; not applicable to open-vm-tools. commit ac62637033af811fb3c9ac433ecc83ab1c9b03ff Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Fix the recursive inclusion for vmtools_version.h Fix the recursive include file complication for 'vmtools_version.h' when the new tools component is consumed. Add necessary macros to check and include the tools header file only if it was not already included. commit 472477d674909ac24767dc1441187f790ce8d31b Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Consume VMware Tools Header files from Tools build. The 'tools' build component publishes the VMware Tools header file as 'vmtools_version.h'. All products / components which consume 'tools' should be built with the header file published by the 'tools' build instead of the one archived in the include directory. commit eb1375c6212d49f1d35bf5895b235b4a56dca851 Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Changes to common header files; not applicable to open-vm-tools. commit 8e9a9eb20b70820f5c5d091db37a7d93c0653932 Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 3b84457bab61db9402404bcc3eff6fced9339dc6 Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 02575ca8d15904552aa3e836978a59a124b862e7 Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c5732c9b32f53d29b64a8b4b20620788a9fa6e3d Author: Oliver Kurth Date: Fri Sep 15 11:23:22 2017 -0700 Add VMware Tools version 10.1.1 to the version history. commit 47a8b6dce4f39c822c5371225adc7d8017a2918f Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 847f522f678d7ae4a894eed5dcaee0504ff2044c Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Fix comment. commit 87f0f71f9929b29fb0c9b4643d92622b1a58a69c Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Add alias for 'verbose' for vgauth logging People keep using 'debug' instead of 'verbose'; make both work. commit 5d4fb852891e7fc0944d49dc11b4ec3b7fc4b1d1 Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Improve debugging Clarify some debugging messages. commit 981cdc84c1903c259b2cf791b5c3903354f9bc5e Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Add -h support to hgfsclient commit 63fb12f0d7fc5e0d22c9c6b9a8185367e7a8247d Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Improve usage for rpctool commit 5dfef556fa4220a87c67177c3d3a82c1cd74bc5f Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 add -h/--help for xferlogs commit 39ebc8c154c54e4d467e267ce08f8ddbfdabd4b6 Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Common source file change; not directly applicable to open-vm-tools. commit 79fa1cd8c12b7ecee95785aecd141f5cd57267ee Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Common header file change; not applicable to open-vm-tools. commit c3d4bcc3ddb52b0c5875f7bf429c996ebe8921e5 Author: Oliver Kurth Date: Fri Sep 15 11:23:21 2017 -0700 Enhanced log messages and a few new log messages. commit 7a32f21bb655be311de1eaac658f332245a9c5a0 Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Thaw filesystems if the snapshot commit message to VMX fails If it takes a long time to freeze filesystems, vmx may timeout the snapshot operation so the commit fails. After this happens we should thaw the frozen filesystems. commit 2bb835b72b2e9071a8ad9547deff0515d015849f Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Don't try indefinitely to kill a process Some processes just can't be killed, and if guestOps try, Tools will just get stuck forever. commit 09e467656e1faa49034f314878548bec870894f5 Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e958a883452adff46d788bdd51518d859c48d556 Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit afff26f7e749a416483c59431f17f09d311bac2d Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit af8cf1d9864d41617dc1e53cc1106c71dfbcd8d5 Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Add an ASSERT The issue is classified as "Intentional" since the value in question will never be negative in practice. Add an ASSERT to make this clear. While here, add two missing function entry g_debug statements. commit 5a6248591c5c7b02c0d32efe117814a680db4d06 Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Remove several LoadLibrary calls All the callsites in this change use LoadLibrary to work around functions not being present in Win2K or WinXP. We no longer support those platforms, so can link directly to the correct functions w/o dynamic loading. commit 5eadbaf0b029c4ba7b60ae2f06e80dc9a2f3346f Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e0addb1131dc3ce9ec3aa6c32c29285893b3eec3 Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit dc70c048c4006741b4878b4e8c61276ad3490f35 Author: Oliver Kurth Date: Fri Sep 15 11:23:20 2017 -0700 GOSTable: Add basic support for Solaris 12 Add support for Solaris 12. Split out Solaris 10, 11, and 12 explicitly. commit 751a92ec8f2781caa5e9da96ab11e5b28d9ae142 Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 lib/file: consistent ASSERT policy ASSERTs on pointers are against NULL commit 5ad8a6869b293d8c8fb6276d227e12dbb5563d32 Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 lib/file: Unable to perform file rotation in the root directory This was caused by improper detection of the root file system. commit 2b7bbda895a221e26424fe3a09147cd3fcccb8ab Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 lib/file: some cleanup Line things up; style made common commit d3bf42683a887081fca903a70666685a581c76ef Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 Change to util_misc.c to delete unused variable. commit 903d5ddf13cf3feab01a80c37d0681985b0162ca Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 Fix the help message for --disable-xml-security-c option. The help message printed for '--disable-xml-security-c' option is wrong. The existing help message is best suited for '--enable-xml-security-c'. 1. Modified the help message to show the option as '--enable-xmlsecurity' 2. Modified the option name from --xx-xml-security-c to --xx-xmlsecurity in order to maintain consistency between --disable/enable and --with/without options. commit 794d2d4626115a23aa7d1ff6436d6de6abb86b26 Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 Add Atomic_ReadIfEqualWrite128 This enables atomic CAS of a 128 bit entity. As gcc >= 4.6 already provides intristics for it, the funciton is just a simple wrapper, and built only for those compliers. commit 57612be42c1e13a178e4fcf4581246b8420aa192 Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 Revert previous commit. commit 934252b4d48eb69c3466fac8fe49305308c7f228 Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 Add Atomic_ReadIfEqualWrite128 It enables atomic CAS of a 128 bit entity. As gcc >= 4.6 already provides intristics for it, the funciton is just a simple wrapper, and built only for those compliers. commit 416e2c5a0d4459ef63d05eb23e514e18532a6baf Author: Oliver Kurth Date: Fri Sep 15 11:23:19 2017 -0700 Changes in file.c File_GetSizeEx() to be 64 bit compatible and treat the size of temporary file that disappears between the File_ListDirectory() and File_GetSize() calls as size 0. Common header file change; not applicable to open-vm-tools. commit 15e43152056346d3490d22d9a13e5018bea4f4b0 Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Hgfs Linux: Fix mounter versioning constants Currently, to allow for the mount information structure, which is passed from the user mode mounter application to the Linux and OSX HGFS kernel mode drivers, to be modified and support backwards compatibility, the structure is versioned. However, the version field uses a badly named constant implying it is the HGFS protocol version. This now clashes with a new enum for the HGFS protocol version added for tracking and reporting the protocol version in use. The mount information structure version should have the version constants named for their intended purpose e.g. HGFS_MOUNTINFO_VERSION. This change modifies the contant and uses an enum. This effects the mounter and HGFS kernel and OSX kernel mode components. commit 8fc9d9d5b8308134115665168355f82ef4536a68 Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Remove SAML bypass from vixTools.c. commit 76c0d8f2f48560d74f11ae6fdb37a5ff535dba6b Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Build resolutionCommon when KMS is enabled When ./configure is called with the '--without-x' option, the resolutionKMS plugin failed to build because disabling X disabled resolutionCommon as well. This changes enables resolutionCommon when either X or KMS are enabled, or both. commit f36f5da9f0a1134325495872f8853e01cadf51ad Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Fix help messages related to xerces and xmlsecurity libraries. When configuring open-vm-tools, if the system doesn't have xmlsecurity and xerces libraries, the 'configure' step stops and gives a hint that the user should try with '--without-xerces-c' and '--without-xml-security-c' options. Those options are wrong and the right ones are '--without-xmlsecurity' and '--without-xerces'. Fixed the configure.ac script to print the proper '--without-xxxx' messages in the warnings. commit 9a29c78975c870a2bf2bd12213c4f7e3acbbd23a Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Reset gGuestInfoLastGatherTime on channel reset. Reset gGuestInfoLastGatherTime on a channel reset to avoid unnecessary warning during resume and snapshot restore. Also rename global variables vmResumed -> gVMResumed and guestInfoLastGatherTime -> gGuestInfoLastGatherTime. commit bcd6bdc0c64ee3ea306598d2be9bfaf468e69100 Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 uuid.h: style changes commit 907a656a708c8730f3a98d5c34ea7f1bab6fd187 Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Common header file change; not applicable to open-vm-tools. commit f20c79b5f779cd0910c57aaa744b9a5823173f00 Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 01292c6c69dc514ada450a8decc3b1aa733e7903 Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Hgfs Protocol: remove unused constants for version Create a new protocol version enum for subsequent use and remove the unused constants and one misnamed clashing constant. The misnamed one for MountInfo will be fixed in a subsequent change. commit 614afdd309e71ddfcbab349c3c135822cb048cdb Author: Oliver Kurth Date: Fri Sep 15 11:23:18 2017 -0700 Remove extern "C" commit 48cc781074c88ed5347ee0a809f2e1d22c9fee7d Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 lib/file: consistent style commit f119378a1b745873c8ae0d3183d47ff65fad9f6b Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c8497284a62807fc69955681f24ca1d16bb82ffa Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 Bump Tools version to 10.2.0 Bump the Tools version to 10.2.0 for the next feature release. commit c713911ec2d41e845e18293d73b059f0f7190008 Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 Extern "C" commit 9e4713f300302650581ae6223e9fc06e556d7996 Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 Minor cleanup in public/backdoor_def.h commit f8f76e2237254d56775fcc99f27542a93e1b005a Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 Fix build error in message.c commit e29770d0d0cac4abc65b35102abadece597d04cd Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 Remove extern "C" commit 805301a3caf702b2b6e57cb790565f2872934808 Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 Remove extern "C" commit 29052188e4874e3cbb035a59d7027a4304af49c3 Author: Oliver Kurth Date: Fri Sep 15 11:23:17 2017 -0700 Remove extern "C" commit 1213229802046c9f1cc57811546f6b512e4759e8 Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Revert previous commit. commit 5e9ecc4923fb6043c9e1ca94b87cf2fca1788c7f Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Remove extern "C" commit 92e764dc82ee0195e0a4fa2a3d5e2d0dbe252b6f Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 lib/file, lib/misc: style commonization commit 63237e872772c61299c423123cb41373c35a76ea Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 lib/file: style commonization commit bdf4795f81c2f17b9918917b39dbe11363059bcb Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Remove extern "C" commit da40ed7745a5173953a3be5d939825e4b105db88 Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Remove extern "C" commit a315228823edb6391294f8e55b27d42c8cd17fa0 Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Remove extern "C" commit d82b1ff5363b81a66575fbc92db07839aa31d22f Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Remove extern "C" commit 6d2db8c281212a4ae0e55bde487d0ad7f8bed969 Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Remove extern "C" commit 73e7e44715c615c56c28589642ec579ca063297f Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Hgfs FUSE Client: Improve write error log message A simple improvement to provide a more complete error message when an error occurs writing data to the HGFS server. commit 1b4051b027a2b4c7743f8d81b92dd04676182c0a Author: Oliver Kurth Date: Fri Sep 15 11:23:16 2017 -0700 Remove extern "C" commit e4e0670e746b892da52ae7446e7fc526caf8be61 Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 lib/file: style fixes Some changes were against the style of lib/file. Fix this. commit aa84e68d0b85662725f54108efb77addfc2b1afd Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 Revert previous commit. commit 602a113ec5931fb806d7831336d8f62bdcec1c8e Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 Uninline CodeSet_Utf8FindCodePointBoundary It's a bit too big... commit 31162d6d147a2a2c3cd58f70c29a4a4c88c724a4 Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 Hgfs FUSE client: fix broken attribute caching on writes The FUSE write implementation incorrectly invalidated the cache of file attributes. The return code for the write operation checked for only invalidating attribute cache if the result was zero. However, this result is negative for an error (in which case the cached attributes should not be invalidated) and anything else is the number of bytes written. The fix for the broken attribute caching on writes is made to check the result for greater than zero so any success. If no bytes were actually written we take the conservative approach of still invalidating the cache as so all the files attributes for that file will be reset in the FUSE client. This should be rare at best. commit 2f852bc476c65815244016ce379c46127977a98d Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 Fix typo in open-vm-tools OSL. commit edf9be0fa0c0037292daebba2b79b625b68f42c2 Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 Set up pid/socket directory earlier /var/run/vmware is used for both the sockets and the pid file. In fresh open-vm-tools scenarios, it tends not to exist when we need it for the pid file. Refactor the code and make sure it exists soon enough to be used for the pid file. commit 6c1f7f329400177030f0b9e1ac2554da72dde242 Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 Use realloc_n instead of realloc Now that we have a modern glib, use g_realloc_n() since its a bit safer. commit 5979cbda3b735737eab3569403bb21dea84ecb61 Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 Update the Open Source License Files for Tools-10.1.0 and open-vm-tools. commit 4d9a7c52d11c4f99c589fdb286d1d745d7a3e02c Author: Oliver Kurth Date: Fri Sep 15 11:23:15 2017 -0700 codesetBase.c should have no dependencies These are routines that can be used anywhere without being tied to the rest of codeset. commit aba2e60151d5711fb49df32c638687c8c7d085c1 Author: Oliver Kurth Date: Fri Sep 15 11:23:14 2017 -0700 Add some missing debug logs in vixTools.c. Add log messages corresponding to VIX error VIX_E_FILE_NAME_INVALID (=22). commit 3cf3bc33a1b4f698d67e0cc5506645f149f4b025 Author: Oliver Kurth Date: Fri Sep 15 11:23:14 2017 -0700 Remove extern "C" commit 2cdfa5027a8693ed19f8a94193c471a287158971 Author: Oliver Kurth Date: Fri Sep 15 11:23:14 2017 -0700 Copyright changes commit 2a4d7a289dec5a8287d9508caacdff2fa1e1624c Author: Oliver Kurth Date: Fri Sep 15 11:23:14 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit dcc99f692159012ca146a9dab59a2d2b671d45f8 Author: Oliver Kurth Date: Fri Sep 15 11:23:14 2017 -0700 Remove extern "C" commit 20379cb590d604eeaa51e6c60af07bd671a7c67c Author: Oliver Kurth Date: Fri Sep 15 11:23:14 2017 -0700 Copyright changes commit 03e61194c29732e96c7b9d82f6c4adc5c034df05 Author: Oliver Kurth Date: Fri Sep 15 11:23:13 2017 -0700 Copyright changes commit 46bde5bb2157dd58cc8f6e0953e7097526262974 Author: Oliver Kurth Date: Fri Sep 15 11:23:13 2017 -0700 Copyright changes commit 44b43b144395b583b50c3dda37605b886e700ac9 Author: Oliver Kurth Date: Fri Sep 15 11:23:12 2017 -0700 Copyright changes commit e22ce95e059d9bec1a9904c6cb98c8f0d51a1af9 Author: Oliver Kurth Date: Fri Sep 15 11:23:12 2017 -0700 Changes to common header files; not directly applicable to open-vm-tools. commit 238deba5cfb44f5b314c99ec58812d29043a1ac8 Author: Oliver Kurth Date: Fri Sep 15 11:23:12 2017 -0700 Log level change in CAF - Changing default log level to ERROR commit 5fe94065d513b826c74aa362f9d6de548c33e945 Author: Oliver Kurth Date: Fri Sep 15 11:23:12 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 1bc9ee62e989da0af468fc8e14046f08e63d289a Author: Oliver Kurth Date: Fri Sep 15 11:23:12 2017 -0700 vm_atomic needs to have an internal extern "C". commit 289f6ae5a8c6e543d32010a17efc4c7f646d4c2f Author: Oliver Kurth Date: Fri Sep 15 11:23:12 2017 -0700 C++ extern clean up issue commit c93385a40bba7acf5eee7188da9e93fa590f3018 Author: Oliver Kurth Date: Fri Sep 15 11:23:12 2017 -0700 Remove extern "C" commit 240fdbc396a364025e2ec1105252b71b99aaf161 Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Remove unnecessary extern "C" commit 756b771290c3b1b303252ca42142e8e9874c4b1b Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Formatting/indentation fixes to lib/file. commit 1beeea1f0b3467735579d1d2c58585a80afdd52b Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Formatting/indentation fixes to lib/file. commit 013c3d530d203baa3ec02ad767d641cd495923a6 Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Revert previous commit. commit e86169d49c461e3e5ce2fa8de3d03586cff1656b Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e5b0240bd6036a600603abd6ceb81476756baad8 Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Consistent #ifdef style in err.h commit c4c8e1819a4de4dd7a269b1d0fe6d27b519fed09 Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Revert previous change commit af4b0fdb43083c297d08c2c6a88f3c7c470eed25 Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 strerror is not thread safe Replace with Err_Errno2String. commit 783c4a9e62dc83edc5707232e0e2d0dafa89a83c Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Switch to Err_Errno2String for thread safety Start cleaning up strerror usage. commit 64ccb7fc149dc786503d0b0e1eab9d84ed65228f Author: Oliver Kurth Date: Fri Sep 15 11:23:11 2017 -0700 Remove Hostinfo_OSIsSMP commit adf3be560d65d0d910d4d4b2988aef152a797720 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 make System_GetTimeMonotonic() really monotonic Solaris has an issue where times() can return a lower value than it returned earlier, making it non-monotonic. This change works around this by saving the last returned value and returning that if the times() function return a lower value. commit 3f2da0682aa201132449eb73fda0f0272c09d5e1 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit fbad4c6ddd25e8af9c7bd7c6c9879c03b4542a54 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Properly configure xmlsec1 for CentOS Some distros build xmlsec1 with dynamic crypto, so do things slightly differently. Also work around an issue with the way Redhat & SuSE package xmlsec1. They built it with -DXMLSEC_NO_SIZE_T, but that flag isn't properly exposed by xmlsec1-config. This results in a bunch of xmlsec1 data structures (anything with an xmlSecSize in it) being different between the lib and our code, and it tends not to work when our code references fields in the data structure. This change always sets -DXMLSEC_NO_SIZE_T. commit 69700e93427aaca77897e66cad3a8ab6ab526a9b Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Backout asyncSocket change to not exit recv loop early when SSL_Pending is zero Change being reverted: After reading some bytes with SSL_Read() and firing any callbacks, we would make a call to SSL_Pending() and, if that returned zero, we would break out of the read loop and return. We would only make a second call to SSL_Read() if Pending() returned a non-zero value. There are several problems with this. Firstly, having bytes buffered up within SSL is a reason to continue performing SSL_read()s, but not having bytes buffered is not a reason to stop. If the socket does not have SSL enabled, for instance, Pending() always returned zero, so non-SSL sockets would never actually loop here and every read would bounce back through Poll. Even in the case where SSL is enabled, this function returns only the number of bytes buffered inside the SSL context and provides no information about whether the socket itself has bytes available for immediate read. So, again, if SSL_Pending() is non-zero, we want to keep on reading data with SSL_Read(), and if it is zero, we *still* want to keep on reading data the socket itself may have more data immediately available. commit 9ab704e9061cccd6eb6fe9a962a0a9c11ba5be27 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Use /etc as default dir for pam instead of sysconfdir sysconfdir evaluates to $(prefix)/etc by default, which evaluates to /usr/local/etc by default. This is (almost?) never a correct path for pam config files except for FreeBSD, so set the default to /etc, with the exception of FreeBSD. commit 4597af473e063e5ef13484d3a22298746fc3b0c9 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 18fe499f9dac3a4fc0538ee2280fd47cde6df3b4 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 97369f9f83795eecf186ce3e360e06faa53d0da9 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Additional AsyncSocket API clean-up. - Convert void-returning asyncsocket entrypoints to have an integer return type, returning ASOCKERR_*/ - Do not exit recv loop early when SSL_Pending is zero; the socket itself may have more data immediately available. - Allow a small number of recursives uses of the send callback. Common header file change; not applicable to open-vm-tools. commit 89212bfbe833d06db94e642676b6b4e7c35219e2 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Bump tools version to 10.0.10 commit e6da3bd40f8c83eba18fd8f1f05d9e06a3e56006 Author: Oliver Kurth Date: Fri Sep 15 11:23:10 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c1cd45f716b974925a12e7c59f89eb5bf6731d20 Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Hgfs Linux Kernel Client: Fix RHEL 7 system backports RHEL 7.3 introduced some backport changes for the Linux kernel which broke some of the assumptions about wait_on_bit function arguments. This fixes the test of wait_on_bit compile which accidentally tests the function in kernel 3.17.0 which will always fail instead of intentionally failing with the pragma. commit 4d2fef98fd292552466757c65671c095667580f8 Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Hgfs Linux Kernel Client: fix RHEL 7 system backports RHEL 7.3 introduced some backport changes for the Linux kernel which broke some of the assumptions about wait_on_bit function arguments. commit 811233a972be67259dacc4c005afabde78739831 Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 4da8e30cc2fdaccd4e2c21eb71345046d0c0e944 Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Move include of rateconv.h in hostinfoPosix rateconv.h is only needed for the Mac system timer conversion. Move the include. commit 4faccaf54449ecb7b553bcf6c02a6e046aa43292 Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 26374b47147b1fa4c9c8a5f7ded23a34f407475d Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Improve network recovery for Linux Virtual Desktop Infrastructure. Client needs to react to an unexpected disconnect and reconnect with a saved session id and path. Common header file change; not applicable to open-vm-tools. commit cfc624cc948674e1ddc53121194f84f08db1ba89 Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Hostinfo_SystemTimerNS On Apple, switch from using floating-point to fixed-point for nanosecond time conversions on iOS. (Note: x86 is 1:1 so never used floating point). Fixed point is easily faster, plus uses a 128-bit multiply that avoids overflow. Added some comments to point out "interesting" cases that show why we do not use Apple's documented method. commit c0b2e65062e4107c9812b33b7a9df2f7ed177304 Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Fix localization code The code that loads a message catalog attempted to handle continuation lines. However, it ended up dropping anything it decided wasn't a continuation line. The end result is that any message catalog that had multiple valid entries without any empty lines between them would lose valid data. commit 2f4fda1ef463fca0b990580e4f3fbbb02edc5f15 Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Changes to common header files; not applicable to open-vm-tools. commit a6856e53eded0b6dbae606b9713fd2286115baad Author: Oliver Kurth Date: Fri Sep 15 11:23:09 2017 -0700 Revert the change to add DarwinPre15 to the guest os table. commit 4d0e744ebb69ef6b4d9d6d4884d1d35bad8b6b1b Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 Hostinfo_SystemTimerNS: Inlining Now that we require glibc-2.5+, we can also require the glibc-2.4 clock_gettime() call be implemented. CLOCK_MONOTONIC is required for all clock_gettime() implementations (per POSIX), so the implementation here just became Really Easy. This is intended as a code simplification / standardization; there is no expected performance impact. commit 258e66b6a4e8cade7d3f3a9464958d9063cd286c Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 Add linuxDeploymentUtilities to libDeployPkg commit 50a89b5ff8e3787f77f1c6122099d2eac89bbfde Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 Revert previous change. commit f7d38d24e357f2738aadd0e2fbf68e884d9a288a Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 Hostinfo_SystemTimerNS: Inlining Now that we require glibc-2.5+, we can also require the glibc-2.4 clock_gettime() call be implemented. CLOCK_MONOTONIC is required for all clock_gettime() implementations (per POSIX), so the implementation here just became Really Easy. This is intended as a code simplification / standardization; there is no expected performance impact. commit b110d03125ff8d6a558427625196664b9337b07f Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 8e2cca63b4b8ed5d399e647291af6b405c3e188e Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 Hostinfo_SystemTimerNS: Update Tools build files The tools build files need some light touch-ups to make librt.so mandatory (Linux and Solaris only). - configure.ac: Linux already required librt, add a Solaris requirement - vmtoolslib.make: add a Solaris requirement commit ad9206ea40608d32f07af5548430a57575caf8d4 Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 Update glib and pcre for FreeBSD and Solaris Update glib, pcre, and additional libraries they require for FreeBSD and Solaris. With this change, a release note will be needed to advise users to add the following lines to /etc/libmap.conf before installing vmtools on FreeBSD 6.x: [/usr/local/lib/vmware-tools/] libpthread.so.2 libthr.so.2 libpthread.so libthr.so The presence of these lines will cause the run-time linker to use libthr.so.2 whenever it encounter a dependency on libpthread.so.2 in an executable whose path starts with /usr/local/lib/vmware-tools. The reason for the release note is as follows. FreeBSD provides a threads library called libthr.so.2. In FreeBSD 6.x, this library is separate from and incompatible with libpthread.so.2. In FreeBSD 7 or later, libpthread.so.2 is a symlink to libthr.so.2. vmtoolslib is linked against libthr.so.2, while libgthread-2.0.so.0 and libglib-2.0.so.0 are linked against libpthread.so.2. On FreeBSD 7 or later, this works fine since libpthread.so.2 is a symlink to libthr.so.2, as noted above. However, on FreeBSD 6.x, vmtoolsd core dumps because libthr.so.2 and libpthread.so.2 are separate libraries, hence both are loaded and their incomatibility results in a core dump. Adding the above lines in /etc/libmap.conf will keep libpthread.so.2 from being loaded, thereby allowing vmtoolsd to run. commit 43e4a3d6309d9f84332042fdec902ac5c3d6a28e Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 Update the guest OS table for darwinPre15 if the GOS is 10.10 and earlier. commit d88042ca14d20f10319498b5b249363e1cc4ed9d Author: Oliver Kurth Date: Fri Sep 15 11:23:08 2017 -0700 More AsyncSocket changes. In AsyncTCPSocketBlockingWork(), do not block necessary. Reverse the order of the read/write and poll/select opterations. This reduces latency when the socket is ready for the I/O operation. This low latency option is "off" be default. Changes to common header files; not directly applicable to open-vm-tools. commit a0e7e23614c69c61e81b6241add014f0df92ef01 Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 Update glib and pcre for Tools for Windows, Linux and ESXi. This change adds a new glib.mk whose scope is local to the tools build. The new version of glib depends upon libpcre, libiconv and libffi. commit 71142cf3a04cf0adeaec94a3a73de9e5185b4490 Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit c706325151147b62532bc3c437741492c4ecd952 Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 Update VGAuth source for compilation with OpenSSL 1.0.x or 1.1.0 OpenSSL 1.1.0 is about to released. With that release comes a number of changes that include making several types opaque. Along with this, new or renamed setter/getter functions appear. The API changes and the impact on open-source products is discussed at: https://wiki.openssl.org/index.php/1.1_API_Changes. Updated man pages are available at: https://www.openssl.org/docs/manmaster/ The impact to open-vm-tools is that the message digest type MD_CTX has become opague. Local (stack) MD_CTX objects are not supported. The required change is to dynamically allocate MD_CTX objects as needed using the 1.1.0 API xxx_new() and xxx_free() or the pre-1.1.0 functions xxx_create() and xxx_destroy(). commit e24ce91afc3b275933e7e300002c5b8734f81cc7 Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 Add string concatenation function to DynBuf The DynBuf code operates on both strings and non-strings. To add a string at the end of a DynBuf is easy: DynBuf_AppendString() appends a copy of the input string, including its NULL-termination. Sometimes strings are repeatedly concatenated, such that a version of this function without NULL-termination is needed. This change implements DynBuf_ConcatString() which explicitly does not copy the NULL at the end of a string. commit c7b05cadcce82aadafcff985c51ae348c906a675 Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 Remove AsyncSocket_ConnectProxySocket() declaration from asyncsocket.h. commit 95882ca05e584ffa43ecf1edbe5431b0faa431fd Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 POSIX FileIOErrno2Result should not log when it is called POSIX FileIOErrno2Result logs when an errno doesn't map well. This can cause callers to have unexpected logging. In fact, the Log Facility got caught by this. Log write errors generated more logs! This has, at times, lead to spew in the logs. Logging could occur on each I/O failure! If an error needs to be logged, the caller should check the error status and react accordingly. They can use Err_Errno to get the native error in a platform independent way. Remove the logging in FileIOErrno2Result; Add logging for open failures that are from "unusual" errors; remove logging from I/O errors. commit 54a8a3c29be94d6cfb155041221c7ead6f21522c Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 lib/file: Explcitly catch EIO in fileIOPosix.c No need to log as EIO is a known possibility. commit 89ad718885b0141d3a0a46d34f164cb933830a1f Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 More remove extern "C" commit f001a9ed146c86a8ef7cafd20b6403343406d166 Author: Oliver Kurth Date: Fri Sep 15 11:23:07 2017 -0700 Change to shared header file unrelated to open-vm-tools commit a30a9c33ed858c1e201c7e74ca0434273d111dfb Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 VThreadBase: missing typecast on mac Seems the mac tools compiler is a wee bit picker, and needs an implicit typecast instead of implicit. Obvious fix. commit 96791075ee5594e81551cc78b2e5d0e3e3e09b5e Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 VThreadBase signal counting: remove malloc This is the easy first half of rewriting VThreadBase to not malloc within signal handlers. The second half is still under construction. The core problem is that malloc() inside a signal handler can deadlock; consider especially the case of malloc() detecting heap corruption -> SEGV -> signal handler -> malloc() and self-deadlocking. Thus, the overall plan is to stop malloc()ing and instead use TLS variables ... as the new comment points out, we can now count on good TLS behavior since Linux and Windows minimum OS versions bumped. In the signal handler case this is easy: if __thread is available we can just use that as a counter. Life is a little more tricky without __thread (see: macOS and Android), where we need to use pthread_{get,set}specific() calls. Use a constructor/destructor to manage the TLS keys, which is a strategy dependent on the TLS destructor being NULL. (Specifically, on library unload the destructor function can remove the TLS key but cannot fire the TLS destructor on all threads, which would leak). One small note, the use of an atomic is not needed here because only the current thread can set the value and, if interrupted by a signal, the stack preserves the correct value. Two other minor things deserve mention: first, remove the TID parameter from VThreadBase_SetIsInSignal(); it was only used for self. Second, re-ordered setting is-in-signal and the first VThread_CurID() in the signal handler; this means the VThread_CurID() implementation can check whether we are in a signal handler, a feature that will matter in a future change. Net result: the signal counting part can now run without any memory allocations whatsoever. Memory allocation is thus needed only for the thread ID and name. Stay tuned for TID/name in a future change. commit 8d9d99705dd43679a5da913131345c8bd470a8a9 Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 Reorganization of the AsyncSocket API layer into an interface dispatch layer and separate disjoint socket implementations. Common header file change; not applicable to open-vm-tools. commit c9b9e6a0bd6719f6577b9bc263e9c525b402397b Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 Final cleanup of xmlsec1 work Do a final cleanup pass commit de6822facfd0b3a61cdc5982397fd15020ec1c72 Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 Restore AC_VMW_DEFAULT_FLAGS([XERCES]) The command AC_VMW_DEFAULT_FLAGS([XERCES]) was lost with a prior change. Restore it. commit 82503bb34195d02cff666c4774e35b6056858439 Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 Change to shared header file unrelated to open-vm-tools commit 35d5500e8711708860efe1988fab226c435a89cf Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 Change to shared header file unrelated to open-vm-tools commit 61eb3825719ee883c5c4b275993dc21c84f3a8a4 Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 link resolution plugins with -ldl commit 69470031736260c62f09ba1b52a85b800b639399 Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 Minor dead code removal Hostinfo_GetPCFrequency: function has no callsites. And now that Windows Hostinfo_SystemTimerNS is Really Fast(tm), amortizing ticks-to-nanosecond conversions doesn't make sense. Util_TokenHasInteractPriv: has only one callsite, used in a log message. Delete. commit af6cb15dc6f0e4f95b3381848b0b59d7138d0d0a Author: Oliver Kurth Date: Fri Sep 15 11:23:06 2017 -0700 lib/lock: MXUser syndrome bits problem For UWP use GetTickCount64 (since GetTickCount is gone). Unfortunately, the lock library needs to run on Win2K which doesn't have GetTickCount64. An ifdef restores the non-UWP environment. commit 08cc58799f16f32276b90c0d7862917553dd5edd Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 Change to shared header file unrelated to open-vm-tools commit d1ec74708ae1ad1cfb84eada2e6eb70624637c6b Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 Add xmlsec1 to open-vm-tools Add the new files to open vm tools and add a switch to turn it on. xml-seccurity-c remains the default for now. Also clean up the service Makefile, which was using the client lib (which also dragged in stuff it shouldn't have) for common code instead of building it in. commit 03e97029b0e2a84e2179a32dbb5d756ecf47e88f Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 Updating glib and dependent libraries for CAF to latest version Update glib libiconv, pcre, zlib and libffi. commit ed2e2348dd6af823f9458c5959c89acf2f13a952 Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 Remove libproc linking and packaging (it's dead since v9.10.5). procps/libproc dependency was killed in Tools v9.10.5. Clean this up and remove the unnecessary linking and packaging of libproc that's no longer needed. All references from Tar Tools, OSPs and open-vm-tools are removed. vm_procps.h was being used for libproc only, so get rid of that, too. commit 124c3e19891fa71123f9ddea9d6053b8503841bd Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 Make headers C++-friendly Add `extern "C"` blocks to various header files. commit 410285953a2afab963cfabb6f389cf515d9f08f4 Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 Remove Hostinfo_CPUCounts (hosted) The Hostinfo_CPUCounts function has an unhappy history where not all OSes (especially Mac) make it easy to discover the CPU topology. There is a good reason for this: the CPU topology generally does not matter. In fact, it does not matter for us. So let's remove this enumeration code and instead report a single CPU package with nCores == nThreads == what the host OS claims. (Especially as the host OS does not really expose cores versus threads information...). Then rip out the underlying functions, all the way down. commit df26946e952539a2f90fcf983dbd0a4f7d3304ee Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 Return default value in case of NULL key instead of ASSERTing. The configKey is NULL for NullProvider, so VMTools_ConfigGetBoolean should return default value if any of the input args is NULL. commit 6daa2753d394391ce9c319581d200ce5f1cc4fea Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 More C++ goodness err.h: Includes before C++ Fix this file. commit c23472eab7d7ec8b24f52d8ecb69c027e0ee4a1b Author: Oliver Kurth Date: Fri Sep 15 11:23:05 2017 -0700 More C++ goodness C++ after the includes commit 76f7e0f43e95edb6cffe3dd5294ce2d4a65ff1cf Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 More C++ goodness commit da66defc097e7b88cc94a7080e00bc5fb108443f Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 Backout update of glib and dependent libraries for CAF to latest version commit ba8d985127f1f7c8852fe06e3c7cdb5c6482daac Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 More C++ goodness Messed up a file, fix the build. commit 6db382eb3d5ccc8044a6fcf9f6b8cab217f882b6 Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 C++ goodness continues commit 2549e58a4ac0025100c03232169e57ead8ca57f5 Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 More C++ goodness Add extern "C" to header files. commit d9f7cd4aae81fef9fbcaf72c1b8c45c1e4ef084d Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 More C++ happiness Add extern "C" to header files. commit a8c9491f7a29b6c015b0787ff288c3489efcf10b Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 Update guest_os_tables.h for darwinPre15.iso for Mac OS < 10.11. commit 447bbf0118b88937728805164ef9313fb7e4dd50 Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 Update bsdfmt.h license 2016 now commit 4e1edd1a3b60c6aa4c585c788796b15959275eab Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 Do schema validation with xmlsec1 in vgauth Add schema validation for xmlsec1 based SAML verification. commit cfc2ee979176d914c17e7e84be54cbf2cbf48e38 Author: Oliver Kurth Date: Fri Sep 15 11:23:04 2017 -0700 Fix pointer inequality comparison against NULL. A pointer is being tested for whether it's less than 0. Check for equality with NULL instead. commit aeff7f0b8d14d5a23fe4037e6dccc4de8c189295 Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 Change to shared header file unrelated to open-vm-tools commit 2ef6e3dc02e0238184a814d978d733bd2b5a540c Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 Tools 10.1 translations commit bb446f9e8b7cc88271e6553db0f800eea944b39e Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 Update glib and dependent libraries for CAF to latest version commit af2a149d77694fc680a6719ec221746e2dd7e7ed Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 Fixes to get vmnet to build on 4.7 kernel 4.7 kernels removed dev->trans_start, instead there is wrapper called netif_trans_update(). commit 4ccfee744d5e4001c5adb8f91860c38433983b34 Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 The lib/AsyncSocket layer on supports SSL_Accept() and the certificate file is reloaded every time a connection is accepted by calling SSL_Accept(). Add support for an SSL_AcceptWithContext to allow cahing of the SSL context and avoid loading the certificate file every time. modified: lib/asyncsocket/asyncsocket.c, lib/asyncsocket/asyncSocketInt.h lib/asyncsocket/asyncSocketInterface.c, lib/include/asyncsocket.h Common header file change: not applicable to open-vm-tools. commit d8a9f44d31bf970367f7dc80dc95730b097ab2c0 Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 Dynbuf: Improve documentation InitWithMemory is a better name. Improve the init function descriptions. commit 19405c3edf186cb2278ce0698480022c837f9775 Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 Thaw/resume guest file system when VMX aborts the operation. When the operation is aborted by VMX after quiescing the guest, we need to thaw/resume the guest. In response to VMX message "vmbackup.abort", when guest sends "vmbackup.eventSet req.aborted 4 Quiesce aborted." message, it receives "Unknown command" response because VMX side RPC handler for vmbackup event is removed before guest gets a chance to respond. That is the behavior without this fix. With this fix, in addition to the message above the new message "vmbackup.eventSet req.done" added by this fix also receives "Unknown command" response. We can fix these by keeping the RPC handler for longer, but its not worth it because the operation is being aborted anyway and vmbackup code in the guest is able to tolerate these errors. commit aa3e981b9def57c605948bbfbf0df3e28354269a Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 common version: use disable-tools-version for old hosts only Use disable-tools-version for old hosts only, and add a hide-tools-version flag. Set disable-tools-version to "true" again for OSPs. commit 3263360ef1965a230ba800aa3835782845d85c0e Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 DynBuf: Start smaller DynBuf operations are mostly concerned with strings - and most strings are less than 128 bytes long. Shorten the initial allocation. commit cd84020ca36953893771a208f03826d155905c5b Author: Oliver Kurth Date: Fri Sep 15 11:23:03 2017 -0700 dictionary: Limit line data growth The dictionary code keeps the raw input line around. Since the length of the line is unknown at parsing time, a DynBuf is used to allocate the memory for the line. The DynBuf initial allocation is large - 1K - and this wastes space when lines are rarely over 64 bytes long. The fix is to have the dictionary code preallocate a 64 byte buffer before allowing appends to the DynBuf. This will prevent many time consuming and memory fragmenting realloc operations. commit 5d51154ddc74340652317f3b3ff1537b80375cbf Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Split FreeBSD in the GOSTable Split FreeBSD into freeBSD (old) and freeBSD11 (going forward). This is to cover driver differences. commit f25e6759cf0d274a87d740cd418c49eb306a1fe2 Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Hgfs Server: write op move argument checks security fixes Complete the argument verifications in the common code adding the missing checks for the write request packet size checks and the write request data size (separated from the request itself as in V4 of the HGFS protocol). This will now catch any attempts from a client to pass a write request containing a data size argument for the data to write that is greater than the amount of data in the HGFS packet or data buffer passed. commit 12890cf51047a0d5837a93a6c38d8eaf0adf02ab Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit bd4f98a472370c8d840d3ba949b0c5656e6b1fd4 Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Changes to shared header file unrelated to open-vm-tools commit 245bcf456f0376344eb71c0edbbfbba4c2e7e3b3 Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Hgfs Server: write op move argument checks security fixes Consolidate the argument verifications to the common code as these are often duplicated. This will now explicitly perform the Hgfs write operation argument verification in the common handler before calling the platform specific code to actually perform the write. commit 19fe2c9f63be291c7ab215e244c93ea179e48cde Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Fix some memory leaks in vgauth commit c00cbf53a1477211b6413bcf561d0f2a8267dc52 Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Change to shared header file unrelated to open-vm-tools commit 578cb08c2ebae1a376aad7f6a3e41b9f145314b0 Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Update tools version to 10.0.12 on the frozen tools branch. commit 70e8dbab91f28238c3c8bd06d12b5370d47497bb Author: Oliver Kurth Date: Fri Sep 15 11:23:02 2017 -0700 Hgfs Server: add write op arg basic validate write op for security fixes Add the basic write operation argument validation routine to obtain the data sizes of the request and data to write for the supported HGFS protocol versions (1 through 4). Add a call to it from the main write operation handler. Note the argument validation checks will be added in the next change and moved from the platform specific routines. commit af27acff59f7ec8193fdad6ca717eac9bb2bd153 Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 Revert previous change. commit 8f68cd2b71d87c612d8a5aa8b8bee8158d048d13 Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 Changes to shared headers files unrelated to open-vm-tools. commit c930424d027864df22d5052f31951570a00fb50b Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 Guest DNDCP: Remove unused private variables. Updating the mac tools to build with clang found some unused private variables in the DNDCP classes. commit 540b899ea0b0c946fca0d303093e35c760e6b4af Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 Tools RPC: Fix XDR invocation on mac and an uninitialized variable. Switchng mac tools to clang found these two: 1. Uninitialized variable in rpcin.c: clang's static analyzer seems to have had trouble figuring out that it is impossible for execution to reach the "if (status == FALSE) {" line without being set. To appease it, initialize it to FALSE. 2. xdrproc_t: On many platforms, xdrproc_t is an unprototyped function pointer that can take either 2 or 3 arguments. Apple changed their implementation to always take 3 arguments and recommend replacing calls with 2 arguments to add a 0 3rd argument. commit b0d2f41dcacd2181b36855fa5b2a2b43def8e216 Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 CAF changes to prevent NamespaceDB frequent polling. commit f969faf20c307a9da02f2a3ba200ecb138d07b47 Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 The vthreadBase library was not designed to be unloaded and simply leaks the TLS keys it creates. Since plugins statically link it, loading and unloading may hit the OS limit. This fix adds a hook into vthreadBase to delete the TLS keys at plugin unload time. commit 357d2011d6221c5ade35d6b4a71c63192df1ce68 Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 Hgfs Server: write ops clean up for security fixes Very minor write ops clean up for security fixes which renames the arguments and local variables to be more consistent. This is in preparation for moving some of the common argument checks into a common routine and enhancing the checks to verify the write data size and buffer. commit fe067916d63a1aafbf82cdaef756c414dbf9c984 Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 Require rabbitmq >= 0.8 when building with caf enabled caf requires rabbitmq >= 0.8, so check for this version in the configure script. commit 87c2e132c57114bf20dfe877cd69101f1001060b Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 XP cleanout: remove pre-Vista code. We now require Vista or later. The CondVar APIs are unconditionally available. commit b521f51b5f7225017499611a20a3cc640204e606 Author: Oliver Kurth Date: Fri Sep 15 11:23:01 2017 -0700 File rename to prep for new xmlsecurity Rename the xml-security-c version of saml verification as a step towards also supporting xmlsec1. commit e7ea6167d184015266a33ba47997819bf676a490 Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Tools RpcIn: fix an assert triggered by a race condition RpcIn open channel asserts that the current channel is NULL. This was being triggered under stress testing. The guest tools service ran slowly, so the VMX timed out and reset the channel. This caused the tools service to do a channel check reset and which then called the RpcChannelRestart to stop and start the channel again. Unfortunately, this call modified the channel global without synchronizing with the other threads sending RPCs. DiskWipe plugin was in the middle of a RpcChannel_Send (with the lock acquired) when the restart call ran concurrently. To fix this issue the RpcChannelRestart now acquires the same channel lock to around the channel stop and start calls so that all sending threads wait or complete first. commit 393e900846e401dc70aee68dad87f805e924edcc Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Revert previous change. Missed updating the OVT build. commit fae37aaf9dc1514345a25b18740bfda925e6f76a Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 File rename to prep for new xmlsecurity Rename the xml-security-c version of saml verification as a step towards also supporting xmlsec1. commit 01217f4b0e858df5f3465240df2896c013491fa0 Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Hgfs Server: more minor clean up of write operations More clean up in preparation for write operation security fixes. commit 05dcd02c81bef7a49f15c9c1645bf2bf15e83e3b Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Update Tools ISO mapping in guest_os_tables.h Update Tools ISO mapping in guest_os_tables.h for potentially old/unsupported Linux distros. Use frozen ISO linuxPreGlibc25.iso for: 1. "otherlinux" because it usually refers to unidentified old Linux distros. We have "other26xlinux" and "other3xlinux" for newer versions. 2. "sles" and "suse" because these refer to unidentified old SuSE. 3. "redhat" because it refers to unidentified old Red Hat versions. 4. "turbolinux" because it is not under active development. commit f23de806de72d3ef992b565c8841c8c789cb2530 Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Update vm_tools_version.h with tools versions 10.0.8 and 10.0.9 commit 03542fe6cfdb9a7a601792714b048b073356876d Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Common header file change; not directly applicable to open-vm-tools. commit ce83118368eb727ef332e436b18ca667f194e5ce Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Hgfs Server: minor clean up of request header size Consistently use the correct function for determining the header size for the HGFS packet to be used. This is necessary due to the different protocol versions that exist, and originally the request and reply contained different protocol headers. commit cf015ea15ad08bd5863c78b3a2cd270f152ce723 Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Change "OS X" to "macOS" in the GOSTable. Apple rebranded, so react accordingly. Also fix a misspelled message. commit 77dc61498c64972abccd149dc7e55600dc9a0b61 Author: Oliver Kurth Date: Fri Sep 15 11:23:00 2017 -0700 Fix indentation in lib/misc commit 1be7624511bd7767a2fa6e5788051d494594dc6b Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 TLS 1.2 changes for common-agent commit 71cb61c333d8813cf7ef22cfb09bb61c095fc328 Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 9bdc9393e630f6a7d9cf4ab22a881ea6f7ddcc25 Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Linux drivers: get_user_pages API changed to get_user_pages_remote. Linux 4.6.1 introduces a new get_user_pages_remote() which is a replacement for when get_user_pages() is called. Still use 'newer' get_user_pages but with less args. commit cdf0864f5dfa55c535f362bd66c5e00f8725a936 Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Reapply ICU change. Atomic_Bool isn't implemented for ARM32, but Atomic_Int is, so use that instead. commit 64f8760c1915e224d3d905cabb76a63f897296dc Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Revert previous change. commit fb66ea0adcb4dceca686cb7cefb7f857ccf6e74b Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Apply various ICU patches between ICU 4.4.1 and 57.1 Parts of ICU 3.8 and 4.4.1 are included in bora/lib/unicode. ICU is now at version 57.1 (which would have been 5.7.1 in its old version numbering scheme) and has had some security-related patches during that time. Directly updating the ICU bits in bora/lib/unicode with the corresponding bits from ICU 57.1 no longer seems feasible because the ICU code has made increasing use of C++ (including C++11), which is something that we'd like to avoid in widely shared libraries like lib/unicode and lib/misc. Picked out a handful of fixes (particularly security-relevant changes) that are applicable to our forked copy: * r28300: ticket:7783: error checking in U16_GET() * r29214: ticket:8238: Implement max subpart policy for UTF7 toUnicode, don't consume valid bytes after err * r30175: ticket:8569: Terminate the UTF-7 byte buffer with MINUS when flushing * r30326: ticket:8265: Fix race (=> U_FILE_ACCESS_ERROR) when loading full set of ICU data * r31914: ticket:8235: do not call memcpy()/memmove()/... with a NULL/invalid source pointer * r31948: ticket:9340: Use bit mask instead of cast to avoid buffer overflow * r32021: ticket:9340: Fix potential out of bound error in ICU4C ISCII converter * r32041: ticket:9432: fix value of UDATA_FILE_ACCESS_COUNT * r32242: ticket:9481 : handled segmentation fault issue with uenum_next * r32529: ticket:9601: from-UTF-8 m:n conversion: properly revert to pivoting for m:n matching * r32574: ticket:9398: avoid use of utf8_countTrailBytes[], rewrite/optimize U8_COUNT_TRAIL_BYTES() & U8_NEXT_UNSAFE(), test _UNSAFE macros only with (mostly) well-formed UTF-8 text * r32907: ticket:9687: Propagate the ambiguous alias warning when opening converter * r37670: ticket:11776 Thread safety fixes in data loading. * r37889: ticket:11765: fix utrans_stripRules() source overruns from a comment or an escape at the end of the source string; make U8_SET_CP_LIMIT() work with index after NUL terminator, consistent with U16_SET_CP_LIMIT(), although strictly speaking this behavior is undefined * r38086: ticket:11979: Fix max char size for iso-2022-kr in icu4c * r38185: ticket:12015: Update the array size to avoid buffer overflow Diffs for the ICU changes (with associated links to their tickets) can be found at: http://bugs.icu-project.org/trac/changeset/REVISION where REVISION is the corresponding numeric value. Notes: * r32907 makes a slight change to ucnv_open's return value and isn't strictly necessary, but is included as a matter of correctness and because we would eventually need to handle the new behavior anyway. Changed sites that checked directly against U_ZERO_ERROR to use U_SUCCESS/U_FAILURE instead. * Included r30326 and r37670 (which both involve race conditions when loading ICU data), but we do not execute those code paths. commit 608a7e966c88b37265f062e9b02b30fe65b24b2d Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 58c1585e5aa76dde81e578444bc769caa4cb00bd Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Extend AsyncSocket code to handle a "network unreachable" error on a Linux connect() system call. modified: lib/asyncsocket/asyncSocketInt.h, lib/asyncsocket/asyncWebSocket.c, lib/asyncsocket/asyncsocket.c, lib/include/asyncsocket.h, Changes to common header files; not applicable to open-vm-tools. Reorder the includes in services/plugins/dndcp/xutils/xutils.cc to build with Gtk+ 3.x at a later date. commit b99cd226533c04d90397815a4c49848212d95424 Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit efd6c9ad4d0ea0198de7107afeb72d2bc8a2b8f2 Author: Oliver Kurth Date: Fri Sep 15 11:22:59 2017 -0700 Add support for gtk3 Changes to support building open-vm-tools with gtk3. #ifdef statements have been added for conditional compiling for GTK2/GTK3. commit 6dbe90a0c7231c3f48a24d94dc6c410db2109cf8 Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Change to header file unrelated to open-vm-tools. commit 188c60b0e0d69c76e73a0d1de7d3dbd24a3b2daf Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Stop building Linux kernel drivers by default in open-vm-tools. All drivers have been upstreamed as of Linux kernel version 3.9, so inhibit building them starting with kernel version 4.0. Users can specify they want kernel modules by invoking configure with "--with-kernel-modules". Note one aspect of AC_WITH_ARGS that is not obvious is that specifying --with-kernel-modules will automatically set with_kernel_modules=yes, while specifying --without-kernel-modules will set it to no. commit a5c07080a4e7e38f2520ea8c5bba86d82328cbcf Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Hgfs Win Client: fix upgrade of driver by changing the Hgfs install settings Some upgrades of the vmhgfs driver are requiring an additional reboot even after the initial reboot. The Difx APIs replace the driver with the new one on reboot, but after the old one is loaded. This means that after the reboot everything looks good on the surface but the old driver is running and not even on the disk at that point. To mitigate this we can change the driver start type and fix missed install settings both of which makes the HGFS driver compatible with the rest of the Windows redirectors. Perform to system registry changes to the vmhgfs driver service: - set the HGFS driver dependent on the MUP component which it is anyway. - set the driver start type to be demand start and not a standard system driver. This makes that the vmtools system service responsible for starting the Shared Folders client driver. This is again more compatible with the Windows redirector model. commit a9f545e1ebb6d5486f0d44a87e9c436156165277 Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Hgfs Win Client: prevent Windows upgrades breaking HGFS When Windows 10 performs system upgrades it breaks HGFS by removing our registry entry in the network provider list. When the client driver is loaded, it checks the entry and sets it accordingly. commit d3c08cf36fffaa8b235375b880fa89a6f2440b46 Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Fix crashes in vgauth SAML verification The reference checker doesn't sanity check that a URI is set before trying to work on it. commit 8781e18ba29ad01fdf9ebdf4bb46ee0ea08b1f39 Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Check for a valid shell in pam configuration When a program is run in a VM using vmrun from the host, the user account is not checked for a valid shell. This changes adds this to the pam configuration for vmtoolsd. Note that /sbin/nologin is a valid shell in CentOS and RHEL, but not in Ubuntu. Valid shells are those that are listed in /etc/shells. commit 8d607518c494947102ef30b47afc90ba0c973bec Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Change to header file unrelated to open-vm-tools. commit 460d38a44a56b279e21014fc8550e80c9acd4751 Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Remove work-around for AMD Rev F Erratum 147. modified: vm_atomic.h, lib/misc/hashTable.c, lib/misc/Makefile.am, lib/misc/vtheadBase.c, libvmtools/vmtools.c deleted: lib/misc/atomic.c commit 379cf86f2b71c0040acf66e763ca416ef1bc8c8a Author: Oliver Kurth Date: Fri Sep 15 11:22:58 2017 -0700 Change to header file unrelated to open-vm-tools. commit 018e3832fcafe9393f799217ff981759b3df0b03 Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 80a6e3944ba3a75c63b8e4a05fc8941663ab8b3f Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 6d72467feb2416ae8198c6a880d5f993132ab79d Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Make Vsock RPC code handle the ECONNRESET VMX might delay releasing a vsock when the client side closes the end point first. This makes a later client vsock connect attempt fail with ECONNRESET using the same source port as the closed one. Note that the client binds OK on the reused source port, since the client side has released the socket on that port. Rewrote the connect code as to clarify it. Explicitly separated the retry logic. Added code to return the system errno, and added additional information about which socket API call failed. commit 159ff344d17fb4605aa7d4c5934360719e190f24 Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Hgfs Fuse Client: fix attribute caching from hardcoded 5 seconds The default attribute caching of 5 seconds is too long and is not cleared by modifications to the file. This leaves users' applications receiving stale attribute information for a file which can cause applications to crash. Set the default setting for the cache timeout to 1 so that corresponds to the same as the kernel client. Fix the rename that purges the cache of stale attribute data for the target of the rename. commit 23606612dd1711e21d7683639be2da1f8ea5a2ee Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Common header file change; no applicable to open-vm-tools. commit 3c23abdb53cf3edf8ca07cecfaf927a4dac44aa3 Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e78b0cafb4ca3c3a79ded9a6e4b66f13129e3d0f Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit e36a8fa9478734a06c7a63b086d5476e69e24757 Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Revert previous change. commit 04feecbd07b946e4aab0c642f6c9363775bd7f5c Author: Oliver Kurth Date: Fri Sep 15 11:22:57 2017 -0700 Make Vsock RPC code handle the ECONNRESET VMX might delay releasing a vsock when the client side closes the end point first. This makes a later client vsock connect attempt fail with ECONNRESET using the same source port as the closed one. Note that the client binds OK on the reused source port, since the client side has released the socket on that port. Rewrote the connect code as to clarify it. Explicitly separated the retry logic. Added code to return the system errno, and added additional information about which socket API call failed. commit d3b7ba4897934eff9a2e79f783b195a40cd58356 Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 fileIOPosix.c: Add new function FileIO_CreateRetry(). fileIO.h: Add new function FileIO_CreateRetry(). config.h: Add new function Config_TriToBool(). hostinfo.h: Add new function Hostinfo_EnumerateAllProcessPids(). hostname.c: Allow hostname to be UTF8. posixPosix.c: Using __GLIBC__ define to control use of euidaccess(). vmxnet3_defs.h: Update the coalescing configuration through the guest OS. Bump the Tx Data Desc Max Size to 2048. The drag-n-drop plugin clipboard updated to allow the clipboard size to be adjusted by the consumer via new CPClipboard_InitWithSize() function. Common source and header file changes that are not applicable to open-vm-tools. commit 4ca9fd8b08aec527c83941909015f846bbae634a Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 Dump gErr on regex failures With pcre moving outside glib, there are new errors, such as pcre not being built with UTF-8 support, that can be caught here. commit df8d0e4561bfd07b4f2a4ee13d14c7cd5de67e76 Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 Fix HGFS mount call to create mount point For FUSE clients and open-vm-tools installations the package might not create the shared folders mount point. The only reliable way to ensure that we have one is to create it ourselves. This seems okay to do since it is a hardcoded path and has always been set to this same path without any regard for configuration by users, although that may change in later change sets. This also ensures if a user has inadvertently deleted the mount point after installing tools and before enabling the Shared Folders feature the mount will be robust enough to still mount. Secondly, did some clean up of the mount function to move the check for already mounted into a separate function. This will prove useful if a umount call is added on a disable of the feature. Finally, the mount file table check now uses the common mount info macros and the system calls are replaced with ProcMgr exec calls. The file access checks now use the glib routines as do the mkdir and rmdir for mount point creation and deletion. commit 21ee819ff7b6f83943c4cfedad62939a89d0b4e3 Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 Increase the scope of 'opLock' to avoid the race in VmBackupAsyncCallback. A previous change fixed a race between worker thread and main thread VmBackupAsyncCallback that could lead to premature release of 'currentOp' from 'gBackupState'. If the 'currentOp' was set after VmBackupAsyncCallback had queried status of the 'currentOp' but VmBackupAsyncCallback was not done with 'status' value check, it could release the 'currentOp' prematurely because 'status' was initialized to VMBACKUP_STATUS_FINISHED. The fix was to initialize the 'status' to VMBACKUP_STATUS_PENDING. The fix broke tests that invoke quiescing with 'execScripts = false' option and in that case there is no 'currentOp' setup by the VmBackupStartScripts() call that leaves VmBackupAsyncCallback in its initialized 'status' VMBACKUP_STATUS_PENDING forever. This fix reverts the previous fix by restoring the 'status' initial value to VMBACKUP_STATUS_FINISHED and increases the scope of the lock 'opLock' to address the race condition. This change also adds some Tools configuration settings to make it easy to test HBR scenario. As reading configuration is common functionality, moved the common functions to vmtoolslib. commit 528d091623208cb6e9780289ae8949de3d1f5704 Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 104a965a37d9347ebf87301093b88e220fedc52d Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit 0d057132ad3494f730ee94b69d66aefaeac6dce7 Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 Hgfs Fuse Client: increment version for connection unavailable fix Increment version for connection unavailable fix from 1.6.3 to 1.6.4 commit 675c07bb089fb4cfd07932563da21b251d12c70b Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 Hgfs Fuse Client: fix for backdoor not available The client dropped errors for failing to open the backdoor returning FALSE, when the HGFS server was not enabled which migrated to a protocol error. This could mislead users when mounting the FUSE file system when the feature was disabled into thinking there was a different issue when actually enabling the feature was required before mounting. It was not a protocol mismatch between the client and server. The main entry point now logs a message for the user if the transport init fails and so the mount does not occur. i The main issue to prevent the mount being created when the feature is disabled is addressed by the transport init function now trying to open the transport and generate an initial connection. This fails when the HGFS server is disabled because the feature is disabled. Hence, there will not be a mount made and an error is reported to users. If a mount is created when the feature is enabled and then later disabled via the UI settings, the mount will still exist as there is no umount made at that point. This will be addressed in later fixes. However, it should be noted that the leftover mount which is now not accessible reports that the "Transport endpoint is not connected" instead of the previous error of "protocol error". commit 795be8ba52f52c49c10dd948d79fd401ba524c12 Author: Oliver Kurth Date: Fri Sep 15 11:22:56 2017 -0700 Don't include errno.h in vsockSocketWrapper.h. A recent change added errno.h to vsockSocketWrapper.h. Since errno.h is intended for UNIX compatibility, whereas vsockSocketWrapper.h redefines the error values to their Windows equivalentsr, it needed to be removed. commit e16b8bda77ce238dff5b51c228a24d933f39452e Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 Use pkg-config directly instead of $PKG_CONFIG $PKG_CONFIG isn't set in the configure script, but we do check for pkg-config in the path. So use it directly to determine udev directory path for udev rules. commit a8ea36fdc44d110bf8a0257782aa91d6f3555876 Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 vthreadBase.c: Update copyright and cleanup tabs and trailing whitespace. commit fbb9ff847ec87e6cddc399627ce4c651a7cdbe11 Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 Fix open-vm-tools build on Fedora using gcc 6. There were two problems: 1. VMW_BIT_MASK in x86cpuid.h generated an error when trying to set all 32 bits. This was due to using 33 bits in an intermediate calculation. The fix is to keep the calculation within 32 bits. 2. static const VMCI_HANDLE was defined in vmci_defs.h, but not used in one place that included the header. The fix is to add -Wno-unused-const-variable to CFLAGS to disable the new warning. commit 23bcb7e2cc001f83886cf61244f56f987cdb2ecc Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 Change to shared header file unrelated to open-vm-tools. commit f9446a65854c575d660315d6473a878bbf6f48ed Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 Common header file change; not applicable to open-vm-tools. commit 622e55c0101f13c8f8da41fa18b7a25c0a05d61e Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 Allow SAML authn to bypass impersonation if the user is unchanged vmwsu can't create an impersonation token for SYSTEM since its not a 'real' account. So bypass the impersonation phase since toolsd is already running as SYSTEM. commit 7c68f9f81bf0a438702585fe82861124f1c68c06 Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 Remove an assert and save vSock family reference in vmsvc only. VMCISock_GetAFValueFd API does not open a vsock device if kernel has upstreamed drivers. So, the ASSERT for vsock fd is not valid in such cases and has to go. Instead, save the reference only when family as well as fd are valid, because there is no need to save the reference in case of upstreamed drivers case anyway. If 'vmusr' holds a reference to vSock address family, it could come in the way of upgrade because 'vmusr' keeps running during upgrade. To avoid that issue and given that we just need one reference, we limit the reference to main service only. Also fix the VMCISock_GetAFValueFd API to initialize outFd in case of upstreamed drivers. commit bb680f5b3f1f6b079ec214cf214738c99f4716c4 Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 Changes to support valgrind with Tools Allow Tools to be built with valgrind support. With these changes, adding "export USE_VALGRIND=1" in Local.mk will build a version of Tools that works with valgrind. Also includes a change to turn off appLoader for vmtoosld and toolbox-cmd. commit 5d1554e30aaa31f18978eedcb06dda1c659c18af Author: Oliver Kurth Date: Fri Sep 15 11:22:55 2017 -0700 add toolbox-cmd for tools.conf config entries Add a generic tools.conf set/get mechanism that can be used for any config entry. The first specific use case is to enable/disable the allowLocalSystem pref for SRM. commit 6e07974b38f94cd27aafe8c23a213c47acc51521 Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 Common header file changes; not applicable to open-vm-tools. commit ec256d66c638dae94a15d9ebcee8f5c0f29472fb Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 Make sure the Windows version of namespacetool logs to stdio Make sure the Windows version of namespacetool logs to stdio instead of logging to debugger. The Windows version of namespacetool didn't print the warning messages under the verbose option. commit a8e4830a0d27ee0dd528c4b8c310a1c2929e9d30 Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 Rename IsPowerOfTwo() to IsZeroOrPowerOfTwo() The function accepts 0. Make the behavior explicit in the name. commit a82237f35a142b025f1a3b7ab3333b325106b5c5 Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 vmhgfs-fuse: remove unused label An unsused label caused an error when building on FreeBSD. It is not used, so remove it. commit fc251c97d74439a81feb6f5cb60f592a4d4b38bb Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 Replace RpcOut_sendOne with RpcChannel_SendOne in vmtoolsd commandline. "vmtoolsd --cmd=" uses RpcOut_sendOne which is a backdoor only implementation. It should try vSocket before falling back to backdoor. commit d730ed8efc710f9187be5214c89d5db151a60432 Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 Don't auto-retry RpcChannel_Send when error is final. RpcChannel_Send retries in case of any error. However, retry makes sense only when there is a transport error. When there is a failure returned from VMware in handling the RPC command, the error is final and retrying does not make any sense. We need to avoid retry when it is not a transport error. In order to differentiate between the two types of errors the internal function signatures required changes. As there are not many direct consumers for RpcOut_send, fix all of its callers to check rpcStatus along with the return value of the function. New API behavior also allows removal of some string comparisons on "reply". There are no other behavioral changes intended in RpcChannel_Send, so all the callers of this function remain untouched. commit 280f7726ff8fc72df9554f411146e02c54842209 Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 open-vm-tools: use $(srcdir) in Makefile.am for udev rule Building in a separate directory was broken for installing the udev rule. We need to use $(srcdir) in Makefile.am, otherwise 'make install' will fail. commit d5555e64369cb5a00be7d41da220c29f914d25c6 Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 Fix the namespace tool verbose option. Fix the the namespace tool verbose option to print out the debug and warning messages of the vm libs to stdio. Introduce a new function that console apps can call to log to stdio. commit ed3f6f7b096dd54f4f0545d360b4f997781de7f0 Author: Oliver Kurth Date: Fri Sep 15 11:22:54 2017 -0700 Fix guestproxycerttool to properly handle non-ASCII filenames Filenames are being passed as UTF-8, but file opens (both CreateFile and fopen()) were assuming ASCII. Switch to a conversion & CreateFielW and g_fopen(), which handles full UTF-8 filenames. Also tweak the error logging to dump the error code for easier debugging on non-english OSes. commit 0006b0091758a229469c4e92fda186227c8525fb Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 Fix a namespace tool crash. The namespace tool core-dumps when running the following command vmware-namespace-cmd -V get-value name -k key This is because glib options parser removed the -V from the argv, and passed the ValidateNsCommands() check. However, the later RunNamespacecommand shall ASSERT() on the NULL nscmd. commit 8a5e316cd54edfcc06b00f74bba4b7b30e2de293 Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 Changes to shared header file unrelated to open-vm-tools commit 0a92586c6ab3cbb18571b0cf99958a97a97198d7 Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 Coding standard updates Fix a few things to conform to the coding standard. commit f069fff44c6d0b7e210cb13aa7de9b6d1003c17b Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 open-vm-tools: add udev rules to set scsi timeout To avoid volumes going read-only of offline, a longer timeout is needed, see bug #271286. This is already done for tar tools and OSPs using udev rules, but not yet for open-vm-tools. This change adds a udev rule for open-vm-tools. A static file is used, and it will be installed for Linux always and only. There used to be a different format for udev rules, but that is very old (before 2010 at least), and used for RHEL up until RHEL 5 and SLE until SLE 10. It is not thought that we need to support these old udev versions for open-vm-tools. commit 09681d7ce54f556fd5929b9c196a625369a4eb5b Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 Make NullProvider race-free to be thread-safe. NullProvider start function was sending 'prov.snapshotCommit' message to VMX which was being done on the worker thread. This led to a race condition where VMX state machine advanced faster than guest side state machine. Later, when VMX state machine sent 'vmbackup.snapshotDone' to vmbackup plugin it did not like it because it was not ready for that message. In order to fix this issue, we need to split the code that sends 'prov.snapshotCommit' message into a separate callback that gets called by the main thread instead of the worker thread. To do that, we needed to create a VmBackupOp for NullProvider so that it can be monitored by the top level state machine. While there also fixed a subtle race found by Victor in VmBackupAsyncCallback. Basically, it can prematurely release an op if the op was set by worker thread between QueryStatus and Release calls (i.e. line 483-488). This is possible due the initial value of status. Fixed the initial value of status to make it impossible. commit 95a253cdcdad9a3f31cb38d7ede79c25587fd8d3 Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit 4ef4b195cad27835b8a5fa98fc7e2313e809e812 Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit f986bdbaebdb6937f2c26606dcdbd12e73ca1d8a Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 ToolsCore_InitVsockFamily() must tolerate the lack of an RPC channel when the backdoor has been disabled. commit 8a9529e714141ab425b09ea9e0a4bf702f9cae1b Author: Oliver Kurth Date: Fri Sep 15 11:22:53 2017 -0700 Bulk updates to the common-agent (CAF) source. commit c745e998dd05438e1713e53e7a847e2ab14f44e6 Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 Changes to common header file; not applicable to open-vm-tools. commit a74bd9604cdb98b1f0aa8c88557f14c006daff32 Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit 4389d0b1092a59307527b2b83f4daa42e991a797 Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 [Tools GuestInfo] Return proper osname for Centos 6 / 7 (again) Updated the code to detect Centos 6 and Centos Linux 7 and return proper osname acocrdingly. commit 73124d51a3ef2db737bf9313d93dd206851bec99 Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 [Tools GuestInfo] Return proper osname for Oracle Linux 6 / 7 Updated the code to detect Oracle Linux 6 and Oracle Linux 7 and return proper osname acocrdingly. commit 7ea377da1d85f0d3f691fa8d17d7650117f57351 Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit 7b8be4232011660d2fda9964815cfa2fed2f1978 Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 Hold a reference to vSocket address family in vmtoolsd. On old hosts that do not support secure guestRpc vmtoolsd falls back to use backdoor. However, there could be vmci and vsocket drivers loaded in the guest that make vSocket consumers (e.g. guestLib and namespace-cmd) try vSocket all the time before falling back to backdoor. On old Linux guests like RHEL 5, 6 (kernels below 3.9 that do not have upstreamed vmci and vsocket drivers) this causes log spew in guest system logs because of vSocket address family being registered and unregistered on each RPC call (RpcChannel_SendOne). This could be solved in multiple ways involving some work from user. In order to solve this problem in a user friendly way, we hold a reference to vSocket device in vmtoolsd service, so that the reference goes away during Tools upgrade. commit f9ca53c4a687a98d59252da4ef01f7aeca567c6c Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 Check for bad length fields for input byte buffers in dataMap code. commit 2e8e7ad263ea50e654daf0059bbc9848bc07777d Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 Change to common header file that is not applicable to open-vm-tools. commit 2d1e452455547c53440376f11beafb5a2353d4ad Author: Oliver Kurth Date: Fri Sep 15 11:22:52 2017 -0700 Common header file change that is not relevant for open-vm-tools. commit 25c80a2d761895fa0e5d1ed81b57d3beb0013de4 Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 Common header file change that is not relevant for open-vm-tools. commit 9d8ec66013825637450a45545e43856edef1d31f Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 open-vm-tools: fix build error in Ubuntu 16.04 The -std=c++11 causes an error when used with the GNU C compiler, but it is in GTKMM_CPPFLAGS. So this change moves GTKMM_CPPFLAGS from libdndcp_la_CPPFLAGS to libdndcp_la_CXXFLAGS in services/plugins/dndcp/Makefile.am. This also fixes building for current Debian sid. commit 21f3c28eb8313b438eba527d8682facdb38ffbe3 Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 Hgfs Linux Client: fix editor prompts for file changes When using some editors such as gedit to modify files on the HGFS shares the editor can become confused thinking that the file has been modified remotely and therefore needs to refresh the contents. This occurs due to the file's modify and change times being updated after the last writes from the editor and the modify/change times in the inode not being updated immediately. commit 540e28c3bc64036544ec6ad4fd699c9e0ac042aa Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 Fix a couple more Coverity-reported issues in tools. commit ff25bb230a11fc2ffdfe083c431954431aec8f5b Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 Common header file change associated with adding Misc. debug messages for the toolsversion module. Change is not directly applicable to open-vm-tools. commit ad5594513039ccef144f50bebef5a92e959336b2 Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 Change to common header file that is not relevant to open-vm-tools. commit 81b7df238e07f9751d5c4c7708ef6798eab0ff91 Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 Changes to common header file that are not relevant to open-vm-tools. commit 2657d8b086c690c907ee9d081b2d9180d5a00400 Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 Fix additional Coverity issues in tools and hgfs. commit 92efdf7562187cb1d165b2b91850663c013dedc4 Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 CAF does not synchronize correctly with Namespace DB. commit 0b509208ad839e448f0edd6ccb8432933ca72e01 Author: Oliver Kurth Date: Fri Sep 15 11:22:51 2017 -0700 Detect slow running systems in guestInfo. - Added a new function in guestInfo. The new function checks the last time when the guest info was captured and prints a warning and sends a RPC message to the VMX if the elapsed interval was more than the expected poll interval. commit 95729ef369d7ca470ecb725e7174aaddbcfc0ac9 Author: Oliver Kurth Date: Fri Sep 15 11:22:50 2017 -0700 Improving CAF build time, especially for open-vm-tools. commit 47f51db7077ed034ab4b9a39814deb47fc7d36dc Author: Oliver Kurth Date: Fri Sep 15 11:22:49 2017 -0700 Improving CAF build time, especially for open-vm-tools with additional files. commit 1224c7aecd5e803ce687f3c7595285e532eeb89f Author: Oliver Kurth Date: Fri Sep 15 11:22:49 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit ec268d17c45a056493dde0166351a5cff5bc56d3 Author: Oliver Kurth Date: Fri Sep 15 11:22:49 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit 16d2e8adc837c29dded94b2c29c3b176c92f8342 Author: Oliver Kurth Date: Fri Sep 15 11:22:49 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit dc95efcb7d4bb7d865b7d37f9aaafe6fb8009e59 Author: Oliver Kurth Date: Fri Sep 15 11:22:49 2017 -0700 Tools: Implement resolutionKMS for linux tools: Enable the use of the PKG_CHECK_MODULES macro for open-vm-tools Adds a path to the pkg-config utility and sets up the open-vm-tools test build environment to be aware of its m4 macros. Also sets up a local directory for .pc files and adds the libdrm and libudev pc files to that directory (during open-vm-tools configure time) to prepare for resolutionKMS testing. tools: Prepare resolutionSet for resolutionKMS on Linux - Add a set of utilities for detecting the DRM version, the Xorg driver version and to dlopen libudev and libdrm if they are not available at build time. The utilities also include opening and closing a DRM file descriptor from a given type of device node. - Change the check for Xorg driver version in resolutionX11 to use the new utility - Pass a ToolsAppCtx to the resolutionSet backend for access to the configuration database. - Finally, detect if there is system and / or configuration support for resolutionKMS and in that case back off resolutionSet - Added some license information to resolutionDL.h - Added an include to resolutionDL.h - Fixed some ifdefs around HAVE_RESOLUTIONKMS - Modified other backends for the new resolutionToolkitInit() interface. tools: Add the resolutionKMS plugin What's resolutionKMS ResolutionKMS is a plugin that takes over the resolutionSet functionality, but as a vmsvc plugin rather than a vmusr plugin. Instead of talking to the X server it talks to the Kernel Mode Setting (KMS) functionality of the vmwgfx kernel module. This enables the following functionality. - Resolution / Topology switching at the login screen - Resolution / Topology switching when multiple users have launched multiple X servers as part of fast user-switching. - Resolution / Topology switching for new native compositors that support the KMS way of communicating resolution / topology (as preferred mode and connector properties) As far as I know, only gnome-shell / Wayland can do the topology switching today, since I implemented the missing support for it. We need to address this issue also with Mir and other Wayland implementations. New dependencies. The new code requires libudev and libdrm. For open-vm-tools, I've opted to require those libraries at configure time. There's no option to build linux open-vm-tools without resolutionKMS support, although that should be easy to add if needed. For vmware-tools, there is code to enable resolutionKMS iff libudev.so.1 and libdrm.so.2 are present at load time and can be dlopened. For vmware tools there are no new build dependencies introduced at load time AFAIK. (dlopen?) Enablement ResolutionKMS requires vmwgfx 2.10.0+ and xf86-video-vmware 13.2.0+ to guarantee that we don't lose functionality compared to old resolutionSet. The vmwgfx kernel module has a way to check version at runtime. For the xorg driver the situation is different since resolutionKMS is typically launched before Xorg. Therefore we fall back to the hackish way previously implemented in resolutionX11.c to find the driver file and scan it for version info. Oh well. In any case, there is also an option to override this and enable or disable resolutionKMS in the tools.conf file. If resolutionKMS is disable either by lacking system support or by configuration, the old resolutionSet functionality kicks in. Extensive debugging info will be present in the tools daemon logs. commit a52a972596c8224b9a3c21b5e724b3b7bb1dbda0 Author: Oliver Kurth Date: Fri Sep 15 11:22:49 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit 256d7b2ef23dcb8b5eda287f353a877b2bea17ce Author: Oliver Kurth Date: Fri Sep 15 11:22:49 2017 -0700 Fix unused function errors thrown by clang 3.4 commit 94d23bfaea56d6a81a09ea821fca8be3b62e50e3 Author: Oliver Kurth Date: Fri Sep 15 11:22:48 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit 4ab6be4b1e100995f32f6b02499f573a64af96a1 Author: Oliver Kurth Date: Fri Sep 15 11:22:48 2017 -0700 Common header file change that is not relevant to open-vm-tools. commit e0d6775f32940f4d0b04eaf7d71c0496567cbb33 Author: Oliver Kurth Date: Fri Sep 15 11:22:48 2017 -0700 Common header file change; not relevant to openb-vm-tools. commit 9556561f31678cec6c6fd5c77c29a38ae7938768 Author: Oliver Kurth Date: Fri Sep 15 11:22:48 2017 -0700 Fix additional tools issues reported by Coverity. Fix some issues found by the latest Coverity scan of tools 10.1, plus a few related nits. commit 30af262e97092bb4f53e59e78f9ab251fbd84980 Author: Oliver Kurth Date: Fri Sep 15 11:22:48 2017 -0700 Change to common header file; change is not relevant to open-vm-tools. commit f07c2501fbc0d5e590b248861abefbad048d7bde Author: Oliver Kurth Date: Fri Sep 15 11:22:48 2017 -0700 Bulk changes for the common-agent service. commit 0ecb4e2697efaeb96e864653182371ba137cb504 Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Common-agent Framework Makefile additions. commit e6398247d4ba37df3755a18c86585bc7c83d873f Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Backout previous change to common header file; change is not relevant to open-vm-tools. commit aff5db3088785e5b2f3f472d40fec8562c172d67 Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Hgfs Fuse Client: increment the client version to 1.6.3 commit 0bacc86a825cd6844edf97c9780b70539e79c649 Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Hgfs Fuse Client: fix symlinks Symlinks were not being handled correctly for some cases. The symlink creation call tried to make the target an absolute path which it should not do. Only the source is passed as the absolute path which is created and links to the target which can be relative or absolute but is dependent on what the user passes. The readlink was broken and incorrectly creating a target name to pass to the FUSE library. This was obvious when alternative mount points are used e.g. .host:/Users -> /Users instead of .host:/ /mnt/hgfs This was discovered when used in the containers environment with docker. However, it is a standard option for HGFS client usage in any hosted product. commit 8468f4d9c6e1aa445e518fe9843bb93582fad614 Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 vmxnet3_defs.h: Common header file changes; not directly relevant to open-vm-tools. - Fix Rx Ring2 max size - Add Tx Data Ring Desc Size config support commit 071fb8f0322461caeec876cb24a67be94c7916a3 Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 syncDriverLinux.c: Revert of "fdCnt" from ssize_t back to size_t. commit 0408b14f7ba45c4b5e03555e13c2051d9e1c07eb Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Common header file change; not relevant to open-vm-tools. commit b9382f4cbb636d9663e878a416b5b9727ab42d6f Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Correct the freeze and thaw ordering for mount points There were two issues with the way we were doing quiescing on Linux: 1. Thaw was following the same order as freeze, actually it should follow the reverse order of freeze. Fixed the thaw order. 2. Freeze was following the order provided by getmntent API which is the order in which system created the mount points. This could be problematic when a mount point depends on other mount point, e.g. loopback mount point. In order to honor the dependency among mount points, we need to reverse the order of mount points listed by getmntent API. While reviewing this change it was found that the interface used for passing the mount points around was not very clean. It was a ':' separated string of mount points. There were multiple problems with it. We were converting a list of strings into one string and then tokenizing it later. As part of this change, we fix that interface too by replacing the string with single-linked list, GSList. Using GSList brings glib dependency to lib/syncDriver. commit a9fee8fc8c7fc7f4062815aa97141b7572c0638e Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Changes tp common header file; not relevant to open-vm-tools. commit 66b06a4658db665c902745bfe830ed23d25a9257 Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Common header file changes; not relevant to open-vm-tools. commit 421ed81330addabc27288df3e029c42fb679d1dd Author: Oliver Kurth Date: Fri Sep 15 11:22:47 2017 -0700 Changes to common files. - lib/file/fileIO.c: Make Fil3_SwapFilesi() path more robust wrt resource contentions. - Common header file change; not relevant to open-vm-tools. commit 02846fb1238894d196ba60540b09631b64027bbf Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 Change to common header file; not applicable to open-vm-tools. commit b8937cc84b75be2c53d693448b74853c88f49508 Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 Change to common header file; not applicable to open-vm-tools. commit ebc26216ee0db2c7d80215ffc0b930a5560f2696 Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 Remove unreferenced functions for common header file; not applicable to open-vm-tools. commit 3f41e75df9c7a3f19f1ed98e35607e8c463dd543 Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 lib/file/file.c: minor cleanup to File_GetSizeEx() - Make the code consistent with the rest of lib/file. commit 6d9a970fe99f6f9deeb4adcb742ee9a16a8a2072 Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 Bulk updates to the common-agent (CAF) code. commit e5e137c279c3e69a509610b16e57548a04b4b9c0 Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 Hgfs Win Client: fix PFD issues part II - Header file changes related to PREfast analysis which centers around buffers and locks. commit 98e46fc11a1f396e17de54955714d09d485b0bd3 Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 Change to common header file; not applicable to open-vm-tools. commit 69586aa7734f05532020036bf5d4941466b272d4 Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 Update the COPYRIGHT_YEARS macro definition. Other common header file changes that are not applicable to open-vm-tools. commit 3138663e346e46edbb2dbb3f6d3da6c53f6db5d6 Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 lib/string: Str_Strncat boundary check improvement to prevent buffer overflow. commit f90b4ba957c5882a42e16866c664561f83ed012a Author: Oliver Kurth Date: Fri Sep 15 11:22:46 2017 -0700 Reversal of common header file change; not relevant to open-vm-tools. commit c0cb8c0fa80e51922e1884c7b96af1ea124df286 Author: Oliver Kurth Date: Fri Sep 15 11:22:45 2017 -0700 Change to common header file; not relevant to open-vm-tools. commit 5d49218af0bf446a53634326210b7d975fa60e15 Author: Oliver Kurth Date: Fri Sep 15 11:22:45 2017 -0700 Bulk update (merge) of common-agent Communications, Framework, InternalProviders, and ManagementAgent source code. commit 40e2d2aecc77978d9fdcf45222d965b14909e0ab Author: Oliver Kurth Date: Fri Sep 15 11:22:45 2017 -0700 Fix buffer overflow in Str_Strncat() found by Coverity. commit a2ebd45dba6f81f18095c4ec4fb37570e16ad889 Author: Oliver Kurth Date: Fri Sep 15 11:22:45 2017 -0700 Common header file change; not relevant to open-vm-tools. commit 73e51edb60bba741d4596e4050ecca017aa2f428 Author: Oliver Kurth Date: Fri Sep 15 11:22:45 2017 -0700 Reversal of common header file change; not relevant to open-vm-tools. commit 6728bf7f0a6eeb1fd57259222d54d0fc02bb0af5 Author: Oliver Kurth Date: Fri Sep 15 11:22:44 2017 -0700 Update the Copyright Year to 2016 in all files released to open-vm-tools. commit 73cc2517fd13410fe425d9f311dbe7d99f480a7a Author: Oliver Kurth Date: Fri Sep 15 11:22:44 2017 -0700 Implemented StrUtil_ReplaceAll() function in lib/misc/strutil.c. commit 54cd36c00ecde5a4695f87cf6685bcdb051503fc Author: Oliver Kurth Date: Fri Sep 15 11:22:44 2017 -0700 Common header file change; not relevant to open-vm-tools. commit 08c8209dfb01ff07d82ba1e1cdbe26ead51ba5d9 Author: Oliver Kurth Date: Fri Sep 15 11:22:44 2017 -0700 Fix some leaks found by valgrind. - leaking the 'data' pref value for a log handler. - leaking an rpc message response if the caller doesn't want it. - leaking username/password for every guestOp commit de63075c8db55b9f2c56a33fcb6bdb7022442f4a Author: Oliver Kurth Date: Fri Sep 15 11:22:44 2017 -0700 Updated license file for open-vm-tools 10.0.7 release. commit ea43b765eae7ecd90c9de235d603ae0a67c233f1 Author: Oliver Kurth Date: Fri Sep 15 11:22:44 2017 -0700 Adding CPUID leaves to common header x86cpuid.h. Change not relevant to open-vm-tools. commit 459de87474e55edbaf41045203dafec281a3a25c Author: Oliver Kurth Date: Fri Sep 15 11:22:44 2017 -0700 Fix setlocale() usage to address valgrind diagnostics. On Linux, the return value points to static memory, so we have to make a a local copy. commit 36c02b436573532aca9d4122457b6e2166447a09 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 Update copyright year in two open-vm-tools files. commit ec39982bf2441c6d018f5b586ecd0db541634738 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 Update vm_assert.h header file to avoid false positive diagnostics from Coverity. Make Panic_NoSave a NORETURN function. commit ddf410de23d33737d2ce92673ee0c0e8ad95cc2c Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 Common header file update; not applicable to open-vm-tools. commit ec88ceddf4df201a75e026ed70acd34a7ffbc9a0 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 lib/hashMap: Remove unused HasMap_Store() and _Retrieve() functions. CheckSanity() should only be compiled if VMX86_DEBUG is set to avoid an unused function warning from clang 3.4. commit e566d0b0b46f97368f9337f5edf1683e29d96bd6 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 lib/log: make the default log level accessible - and use it The default log level is known interally to the Log Facility. It needs to be available "everywhere". Do that and deploy it to all places that should use it. commit 1c6c46cbbde90641cf576232aa057c5143eb9bd2 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 Revise dtoa() to use ecvt_r/fcvt_r on Linux/ESX an thus avoid using a pthread_mutex_lock. commit 693447e4cb16520c5e3e30912bb6627f7da5bd12 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 vmci/vsock driver changes for Windows; not applicale to open-vm-tools. commit 125541c04a7aeac6e152fb5a622ba9052bfca294 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 Multiple fixes for common source code. - File_FullPath() revised to return the canonical path of a file or directory that exists or is about to be created as a child of an existing directory. - Common header file updates; not related to open-vm-tools commit 82b8208469fe93a6ebd38fa2fc2f01b1c8285ba6 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 Shared header file update; no impact on open-vm-tools. commit ba4c8e31b7399c973018dfb78c22de83b7a5e2a3 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 Shared header file update; no impact on open-vm-tools. commit 2e2da21bc35ee3f549fdeb3bfd2d603e1ad4975b Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 The Linux network script has been updated to prefer 'ip' command over the 'ifconfig' command for gathering network information. commit 61f75b64bff213d2684a3c605a769a4ac1bb4571 Author: Oliver Kurth Date: Fri Sep 15 11:22:43 2017 -0700 Shared header files update; no impact on open-vm-tools. commit 287e43342dc28d3f9025473e426ed0546778b653 Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Shared header files update; no impact on open-vm-tools. commit 5c08abe5acffa318c13c202c0e460865ab5b0af8 Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Shared header file update; no impact on open-vm-tools. commit 64ae3e26c53a068239d4cfba6bccce8dc727dc40 Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Shared header file update; no impact on open-vm-tools. commit e2586abb3ddd050f994e1cfd8c9409ff22d0a4c4 Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Update vmtools version history for the 10.0.7 update release. commit 6d79bbad4cc9d240435eef81976c47cd87c73d46 Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Update vmtools version history for the 10.0.6 update release. commit ab4f4e18d5113d417b9bf71bc025c13754fa033b Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Shared header file update; no impact on open-vm-tools. commit 7fd1a75c6c9bd5a13a4d6edc46bc788b45477b8b Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Shared header file update; no impact on open-vm-tools. commit c542715b609f97bc7edf8f0f7cc93432ce38e768 Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Shared header files update; no impact on open-vm-tools. commit 918ceee2070d734719522f08316fe51a5fc1dd06 Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Shared header file update; no impact on open-vm-tools. commit 8784dbd4a5de1407e1e46bb3027c02cc7f3c3c60 Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Korean messages for the toolbox-cmd have been updated. commit 58bb1478d18e9f46e92c65b2336f4c274073e98e Author: Oliver Kurth Date: Fri Sep 15 11:22:42 2017 -0700 Bulk updates to the common-agent (CAF) code. commit af47b4c8c2a5afc12bb026ba5206a6788977ac16 Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 The Posix_GetAddrInfo and Posix_GetNameInfo wrapper functions are modified to convert between UTF-8 and UTF-16 encodings. commit 1a037dfaf1fba399bd69bf16f3dba0c679c79e03 Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 Updates to CAF accessory files. commit 55aec4b1557853abac4a66e76a1d70ddf82d9735 Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 The namespacetool links with the vmtools lib which has implemented the functions "Debug" and "Panic". The locale definitions of these functions in the namespacetool source has been removed. commit 5114233485a7d1da81b265515c584dfce21a056d Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 open-vm-tools: Fixes to build with FreeBSD - amd64 in host_cpu means 64bit, add that to configure.ac - use 'z' for FMTSZ in FreeBSD, just like Linux commit 94fb4c14aaa3e58047f66ba7a8f075611be1a7df Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 Update copyright years for CAF Makefiles commit 62136174788796a89f8c38b74eaf7aeea6b059a8 Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 Default shared-secret authentication to unsupported (disabled). commit 2b654ed9f3285f5e31b55babc0e51b73f72fb501 Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 Make VSS BackupComplete as final steps of the vmbackup process. VSS process break up to two steps when CreateSnapshotEx(WindowsQuiesceSpec) & App-quiescing is applicable: 1) VSS quiesce and DoSnapshotSet (perform backup and commit snapshot) 2) VSS SetBackupSucceeded/BackupComplete (VSS notify app BackupCompleted) Add a new operator to wait for VMX snapshot complete notification. commit a63f28583c1b2cef40884a5593181f7f439ef066 Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 Common header file update; not needed by open-vm-tools. commit 5a7dff47d34af440679a4681dced79fa2438a0ca Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 Some source code clean up in vmcisockets 1. Remove a typedef that didn't def a type (newer compilers warn). 2. Rename a local that had the same name as a var in a higher scope. (note: there is no confusion or lost error case luckily here) commit 25d7c89552c6761dab6eb182f475e8825a38aa3f Author: Oliver Kurth Date: Fri Sep 15 11:22:41 2017 -0700 Remove wmemchr() from bsd_output_shared.c since it is no longer required. commit fddbf299e58ed60705188c8b1ea90eaefeb40d57 Author: Oliver Kurth Date: Fri Sep 15 11:22:40 2017 -0700 Updated shared header files, not relevant to open-vm-tools commit 6c61db33226c0d5a47be3a9a2e91ec736d6213a4 Author: Oliver Kurth Date: Fri Sep 15 11:22:40 2017 -0700 GuestRPC vmbackup.h header file update. A new RPC messages has been added: VMBACKUP_PROTOCOL_SNAPSHOT_COMPLETED commit 0066453d3d86095b22c5450ee7362b08ad9bfcd6 Author: Oliver Kurth Date: Fri Sep 15 11:22:40 2017 -0700 CAF changes to support release in open-vm-tools. commit 37ca884eaa72248dce6d20bbd960663a8c482d42 Author: Oliver Kurth Date: Fri Sep 15 11:22:40 2017 -0700 Update of the common-agent (CAF) service source from the development team. commit c7b7fc7386900037169e4c17999f4c63ac9d65b3 Author: Oliver Kurth Date: Fri Sep 15 11:22:40 2017 -0700 L10n messages updates for toolbox commit 5fdc593389e1ad5a593aad36cbddbb646ed98dc6 Author: Oliver Kurth Date: Fri Sep 15 11:22:40 2017 -0700 VGAuth cmdline parser improvements Restore support for '=' between option and value. commit e64c2a0782218c06c6e8b24d59795e7ba99b466d Author: Oliver Kurth Date: Fri Sep 15 11:22:40 2017 -0700 Use the primary connection remote IP for the secondary UDP connection. commit 409e01197d45e88ef9b1a1591963b19b44fee479 Author: Oliver Kurth Date: Fri Sep 15 11:22:40 2017 -0700 Improve VGAuth logging Make the default logging more useful by converting a number of Debug() calls into Log() calls. Request basics and errors are dumped. Tokens are hidden for security concerns and certs are hidden to reduce the noise level. commit dc23a48e0ea22921099ea8af8693f553a1ade5f1 Author: Oliver Kurth Date: Fri Sep 15 11:22:39 2017 -0700 Common source code merge - Update poll timer callback's to use 64bit integers for delay. - Avoid creating substrs if unnecessary in Unicode_CompareRange. - Vmxnet3: Add Receive Data Ring Support. - Comment cleanup. commit 3184e983998b9cafbcf8e5f719fccd0200e5900b Author: Oliver Kurth Date: Fri Sep 15 11:22:39 2017 -0700 Fix the CAF upgrade script to handle upgrades from an "old" (pre cafenv-appconfig) version of CAF. commit 80bab95be93b4e26aaaa118086f009528f410bab Author: Oliver Kurth Date: Fri Sep 15 11:22:39 2017 -0700 Build change; not related to open-vm-tools. commit 1108b3852688839e7aeb15d25d830929f027e6a1 Author: Oliver Kurth Date: Fri Sep 15 11:22:39 2017 -0700 lib/poll: Attempt to use IPv6 sockets first for Windows socket pair We should always use IPv6 sockets even for loopbacks if IPv6 is supported so that we can work properly in IPv6-only environments where IPv4 has been disabled. If the IPv6 socket fails to create then we can fallback to IPv4. commit 01974d9d73fb20f50ecd7dfc47ffaff672e1c8de Author: Oliver Kurth Date: Fri Sep 15 11:22:39 2017 -0700 Update the Copyright year to 2016. commit 71aedd8d535ebeaf29a2ffa780176f8bb72cb87c Author: Oliver Kurth Date: Fri Sep 15 11:22:39 2017 -0700 Add a stolen time interface for guests This change adds a cheap stolen time interface for guests. Guests must use the backdoor port to register a per-VCPU object in memory called the "stealclock" with the monitor. From then on, until the clock is disabled, the monitor publishes clock values whenever stolen time is accumulated. A complete specification of the interface is included in this change, as a text document: bora/doc/stealclock.txt. Pending clock updates are represented by an idempotent monitor action, posted whenever stolen time is accumulated. In the current implementation, this is whenever we update stolen time on transit from host to vmm. In the future, it may an action posted by the vmkernel, whenever stolen time is updated. commit 3ac9ac2858f67652f296013e263c6ea1da9f4887 Author: Oliver Kurth Date: Fri Sep 15 11:22:39 2017 -0700 VMkernel build change; not related to open-vm-tools. commit 07cf66aba6d36407896a519c4f4f229702ed8b0a Author: Oliver Kurth Date: Wed Sep 13 16:46:38 2017 -0700 except common-agent/etc/config from .gitignore commit 2953dedddaf479d00661c4a0c64e7708492a4a22 Author: Dyno Hongjun Fu Date: Mon Nov 23 22:00:25 2015 -0800 add .gitignore commit ef9ffadbdee99fce285bd0af5a8c9799c0aa8a10 Author: Oliver Kurth Date: Fri Sep 15 11:06:34 2017 -0700 reset buildNumber.h to 10.0.5 version commit 5a00e4e76c6deb863cfba4adb6aeca4608fafaac Author: Oliver Kurth Date: Wed Sep 13 16:24:53 2017 -0700 clobber to create a starting point for the development branch commit 538ea037a1549b6fd4e57529f7448a3fd2aa47af Author: Dyno Hongjun Fu Date: Mon Nov 23 22:59:42 2015 -0800 changelog for 10.0.5 commit b75dbce79523a0145345f97afcdc06bed11dc46f Author: Dyno Hongjun Fu Date: Mon Nov 23 22:33:40 2015 -0800 version bump to 10.0.5 commit ae82fa65627575567ead1b0d30eff1777b567ff1 Author: Dyno Hongjun Fu Date: Mon Nov 23 22:28:27 2015 -0800 [Bug 1526360] fix timestamp check commit b510107055b144bc28c7e03a17176211860df6f8 Author: Dyno Hongjun Fu Date: Mon Nov 23 22:27:40 2015 -0800 [Bug 1531545] Add an error handler to X11 resolutionSet commit adab9c550cd86f759c85294aa53b1870ec58affa Author: Dyno Hongjun Fu Date: Mon Nov 23 22:26:38 2015 -0800 [Bug 1503195] Kill tasklet when unloading vmci module commit 35bcc69ef81bbae1a21187d1e8e8a572169a5abe Author: Dyno Hongjun Fu Date: Mon Nov 23 22:19:34 2015 -0800 [Bug 1519223] Avoid warning message when logging group is missing. commit 581f2d0e93a3aacd7bbf252963d2fbd1720bab15 Author: Dyno Hongjun Fu Date: Mon Nov 23 22:17:59 2015 -0800 [Bug 1473600] Skip freezing autofs mounts. commit 8184e9291c7db41781c127d8541cc75ff243902a Author: Dyno Hongjun Fu Date: Mon Nov 23 22:17:12 2015 -0800 [Bug 1507819] Workaround fix to avoid rpc warning messages flooding by changing log level to debug. commit eb47321942fccebe76344ade5b52d8f95bcbbbbf Author: Dyno Hongjun Fu Date: Mon Nov 23 22:10:33 2015 -0800 [Bug 1526327] make vmhgfs compatible with Linux kernel 4.2 commit 54c10e813bf2a7b60b075d3bfe9204670e1aec4c Author: Dyno Hongjun Fu Date: Mon Nov 23 22:01:24 2015 -0800 remove cache files commit aa0790cd582e3dcf7c665c6f1dedf11117442ed2 Author: Dyno Hongjun Fu Date: Mon Nov 23 22:00:25 2015 -0800 add .gitignore commit 85a99f4253dddf7e47e873fec4c43c15b7d8c2bc Author: dsouders Date: Tue Sep 1 17:04:28 2015 -0400 Update ReleaseNotes.md commit 6994576b2b44d2301daa736b893feb9828b0b816 Author: Douglas Souders Date: Tue Sep 1 08:56:05 2015 -0400 Adding Release Notes commit ebed1074323950b03d25b31c54741eaa128c3e0c Author: Douglas Souders Date: Fri Aug 28 09:56:56 2015 -0400 release 10.0.0 from build 3000743 commit 39228f1efb8b4070d1ca2636e4f552c106346f46 Author: Sankar A Tanguturi Date: Fri Aug 21 18:00:04 2015 -0700 Update README.md commit 5fce57c2e30069a2ba14356827743e7f575b5168 Author: Ravindra Kumar Date: Fri Aug 21 12:01:29 2015 -0700 Corrected URL for automake commit 7bac35f4e8787553f68972feae7966b0236c06ac Author: Douglas Souders Date: Tue Jun 16 17:49:24 2015 -0400 release 9.10.2 from build 2822639 commit 0696234c3905bf91cfba2cf909dbf92fc30ee6fc Merge: b23378e aaa2085 Author: Oliver Kurth Date: Thu Mar 19 11:11:07 2015 -0700 Fix README.md Merge commit 'aaa20859c29247ca89a68f47c1a7b1a3b15bae09' into stable-9.10.x commit aaa20859c29247ca89a68f47c1a7b1a3b15bae09 Author: Oliver Kurth Date: Wed Mar 18 17:25:02 2015 -0700 Update README.md commit b23378e336a7b0ecc7a4584c9a5f185b40e1ef5a Author: Oliver Kurth Date: Wed Mar 18 15:52:50 2015 -0700 release 9.10.0 from build 2476743 commit 08d7040ebfe99f74478f7282d9bb98cfcadf4a4a Author: Oliver Kurth Date: Wed Mar 18 17:07:24 2015 -0700 Update README.md commit 5568d3e1d0bd4b4297111a67e75d820c54a17124 Author: Dyno Hongjun Fu Date: Tue Jul 1 16:12:29 2014 -0700 Update README.md commit 8b89d5b01f0b6d97e306648236869ce10b056293 Author: Dyno Hongjun Fu Date: Tue Jul 1 16:10:59 2014 -0700 Update README.md commit 9188c775bedccd3975c001cf6100124225918d53 Author: Dyno Hongjun Fu Date: Tue Jul 1 16:08:29 2014 -0700 Update README.md commit 86c542caae41b54f297be910c9b92f6f38b32164 Author: Dyno Hongjun Fu Date: Tue Jul 1 16:04:48 2014 -0700 Update README.md try markdown commit ba9118e19d98c8ded12791869d9d1166631ae985 Author: Dyno Hongjun Fu Date: Tue Jul 1 15:56:12 2014 -0700 Create README.md this is the README file inside open-vm-tools/ commit f815ec597079716da64d51465f2a33c65427053b Author: VMware, Inc <> Date: Sun Sep 22 22:56:07 2013 -0700 Updating open-vm-tools version for release 2013.09.16-1328054. Signed-off-by: Dmitry Torokhov commit 112e1dfdd1884f189363ce5692c991170b0791fb Author: VMware, Inc <> Date: Tue Sep 17 20:43:28 2013 -0700 AsyncSocket: Update AsyncSocket_GetRemoteIPAddress for IPv6 support. AsyncSocket_GetRemoteIPAddress offered the return of the IP in integer and string formats, none of the callers cared for the integer return so remove it. Update name appropriately AsyncSocket_GetRemoteIPAddress->AsyncSocket_GetRemoteIPStr. AsyncSocket_GetRemoteIPAddress only supported the returning of a IPv4 string, utilize Posix_GetNameInfo that uses getnameinfo which is IPv6 compliant. Signed-off-by: Dmitry Torokhov commit 76713ae5c4d5f7a4616d3005137c276535d654fa Author: VMware, Inc <> Date: Tue Sep 17 20:43:03 2013 -0700 AsyncSocket: Removed unused AsyncSocket_BindUDP. AsyncSocket_BindUDP is unused, and looking at it I am not sure if it ever worked as described, since it did not actually bind to the port specified, just a UDP listener. Signed-off-by: Dmitry Torokhov commit adead816acb768fb9c4a91942c93f464894902f9 Author: VMware, Inc <> Date: Tue Sep 17 20:42:40 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 06b51461bb1a2e01282d0244ff0f47b8d5ae8bea Author: VMware, Inc <> Date: Tue Sep 17 20:42:24 2013 -0700 Allow for future use of AF_UNSPEC in AsyncSocket library Create a socketFamily switch in AsyncSocket_Connect and AsyncSocket_ConnectWebSocket for future IPv6 integration. Allow for future use of AF_UNSPEC when a connection does not care if it is AF_INET or AF_INET6. Since AsyncSocket does not fully support AF_INET6 yet and our AF_INET6 test bed is not yet completed, hard code all callers to AF_INET. Signed-off-by: Dmitry Torokhov commit b81233bd0375e5358a55b387e638e9f569a0cc53 Author: VMware, Inc <> Date: Tue Sep 17 20:42:16 2013 -0700 Provide a kill-switch for using vsocket in RpcChannel. Adding "void RpcChannel_SetBackdoorOnly(void)" API to allow to disable vsocket if needed. Signed-off-by: Dmitry Torokhov commit c634402c98c2eb419d111797c39e4907aa35a8eb Author: VMware, Inc <> Date: Tue Sep 17 20:42:05 2013 -0700 Update AsyncSocketResolveAddr to allow AF_UNSPEC and AF_INET6 ai_family. AsyncSocketResolveAddr currently only accepts searches for AF_INET. Update it to search for AF_INET6 or both with AF_UNSPEC. Since we no longer need to return sockaddr_in for AsyncSocket_SendTo, only populate sockaddr. Also add a convenient IP string generation after resolve so all callers do not need to do the same operation tp log the IP string with port number. Signed-off-by: Dmitry Torokhov commit 9644250ed9110aa38d5a8f467499b3d9678f7a05 Author: VMware, Inc <> Date: Tue Sep 17 20:41:58 2013 -0700 VMCI/VSOCK: Bump version 9.5 => 9.6 for next release We shipped 2013 with 9.5, so the next release will have 9.6. Signed-off-by: Dmitry Torokhov commit 6d6386468f1189621245bc99d0b4a55b4253a97b Author: VMware, Inc <> Date: Tue Sep 17 20:41:38 2013 -0700 Remove AsyncSocket_SendTo Nobody is using it anymore. Signed-off-by: Dmitry Torokhov commit bf72ff33d02e9c1b0d6d2d3ab0a9b13c7a2747a9 Author: VMware, Inc <> Date: Tue Sep 17 20:41:16 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 5eadb43a7d115dfb9e93875b0308d6f88c2c330f Author: VMware, Inc <> Date: Tue Sep 17 20:41:27 2013 -0700 desktopEvents: Leave libICE rug firmly under libSM. While the libICE spec's section on error handling suggests applications close libICE connections in response to I/O errors, libSM (which sits atop libICE) continues to refer to such deceased libICE connections, and doing so during shutdown leads to an app crash. (libSM should've registered an I/O error handler of its own which would run before the application's, but it doesn't. Oh well.) To work around this, we'll detach the ICE connection from our application event loop but leave its handle alone. Signed-off-by: Dmitry Torokhov commit c9200b341b7612be273c4402a3381e507766e526 Author: VMware, Inc <> Date: Tue Sep 17 20:41:07 2013 -0700 Remove ASSERT_OR_IN_PANIC() from public/vm_assert.h Signed-off-by: Dmitry Torokhov commit c297a757b88435ca43bfe0dcf71b97c5d8a3e41a Author: VMware, Inc <> Date: Tue Sep 17 20:40:51 2013 -0700 Get rid of ASSERT_LENGTH. It was used way back in ancient times in the binary translator but today no more uses remain. So let us remove this global Signed-off-by: Dmitry Torokhov commit b102cb180bc724f3656a7d3a27af954b2ebe7e20 Author: VMware, Inc <> Date: Tue Sep 17 20:40:45 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit c093dcb7a99a32aaf76fad143ff4a276f8d4bc22 Author: VMware, Inc <> Date: Tue Sep 17 20:40:38 2013 -0700 Get rid of ASSERT_ALWAYS_AVAILABLE Signed-off-by: Dmitry Torokhov commit 163a622e1fc4c4a68849a09448ee2aae662713ae Author: VMware, Inc <> Date: Tue Sep 17 20:40:17 2013 -0700 Fix AsyncSocket reference leak when using IVmdbPoll A reference is taken when an AsyncSocket callback is registered in IVmdbPoll to protect the AsyncSocket from being freed while the callback has been scheduled to run. That reference is released when the callback is unregistered if the callback is not going to run, or from the callback itself if it is already scheduled. The current code does not correctly handle the case when the callback unregister itself, as it needs to explicitly release the reference in that case. This change also adds a Bool to AsyncSocket so we can distinguish between send callback that is registered as a timer callback so that we know which type of callback to remove, which is necessary to keep the reference count correct. Signed-off-by: Dmitry Torokhov commit 1b62c3e36a56980733f7aaacb1c6b741f5c8670d Author: VMware, Inc <> Date: Tue Sep 17 20:39:53 2013 -0700 Report correct OS name for ESXi guests Prior to this change, vi client would say that the Guest OS was "Other (32 bit)" whenever Tools were running in an ESXi guest. Now, the Guest OS is reported as "VMware ESXi 5.x." Note that Tools do not run in ESXi 4.x guests. Signed-off-by: Dmitry Torokhov commit a9635c0923caeef61b51afc5580b51ccb65fd7f5 Author: VMware, Inc <> Date: Tue Sep 17 20:39:48 2013 -0700 Implement VMware Tools for ESXi 6.0 guests. This change provides limited VMware Tools support for ESXi 6.0 guests. The powerOps and guestInfo plugins are supported. Only IPv4 addresses are reported, since those are the only ones we can get through the vmkuser library. VMware Tools for ESXi 6.0 are packed as two VIBs on a single ISO image. One VIB contains the glib libraries that are missing from the standard ESX distribution, and the other VIB contains the tools themselves. Signed-off-by: Dmitry Torokhov commit 3a9f2297a82b9c109e894b5f8ea17753e68830ac Author: VMware, Inc <> Date: Tue Sep 17 20:39:34 2013 -0700 Harden HostinfoOSData against $PATH attacks. We are doing a popen("lsb_release... ") when attempting to determine host details in hostinfoPosix.c. Using popen means that $PATH is walked when looking for the lsb_release binary, and that may give an attacker the ability to run a malicious version of lsb_release. This change does two things, a) Hard code the path to lsb_release. I've searched around the web and I believe the path is always "/usr/bin/lsb_release" so let's not leave this up to chance. b) Stop running HostinfoGetCmdOutput with elevated privileges. Drop to non-root when possible. If someone sneaks in a new call to HostinfoGetCmdOutput and doesn't use a full path, then we will hopefully avoid a firedrill. I'm only applying this to Linux because the Fusion build barfed when I tried to compile with without the vmx86_linux. I think either (a) or (b) would be enough but I'm doing both, because each individually is correct. Also note that in the blog post by Tavis Ormandy calls out doing (a) as not enough, http://blog.cmpxchg8b.com/2013/08/security-debianisms.html His example uses a bash feature that allows functions to be exported. I haven't been able to get that to work on my Ubuntu machine. To test I'm manually run Linux WS and Fusion and verified that the logs look correct. Signed-off-by: Dmitry Torokhov commit 3869012deb7658b9aab10ab028d71b32b89a2a85 Author: VMware, Inc <> Date: Tue Sep 17 20:39:28 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit cb790dbad75717d0ffb99bc268ee9ed6214c93ba Author: VMware, Inc <> Date: Tue Sep 17 20:39:21 2013 -0700 Fix nested logging for VmxLogger with vsocket channel. Signed-off-by: Dmitry Torokhov commit 155eb8d6615c947b71167fabe44b2fbca70a1e39 Author: VMware, Inc <> Date: Tue Sep 17 20:39:10 2013 -0700 HGFS: Clean up HGFS server unpack file name V3 arguments The HGFS server unpack file name argument for V3 packets generates coverity warnings as it stands. It is also just plain dubious in its usage using the out argument even when not initialized in the failure case. Signed-off-by: Dmitry Torokhov commit 63b4fa8d551de8e90101b6de4646d8573f764329 Author: VMware, Inc <> Date: Tue Sep 17 20:38:49 2013 -0700 Internal branch sync. Included in this change: . Support Linux Quiescing for vSphere Replication . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit ac4e72c01eec5565d3ac8d0c84cb4072d9e3e08e Author: VMware, Inc <> Date: Tue Sep 17 20:38:24 2013 -0700 Change glib logging in RpcChannel to use Debug/Warning/Panic. Change glib logging in RpcChannel to use Debug/Warning/Panic so RpcChannel logging can be controlled by different logging stubs in different applications(rpctool/vgauth/toolsd etc). Signed-off-by: Dmitry Torokhov commit 4335f533c88d45fc05fb31b040d42eb0e3db3274 Author: VMware, Inc <> Date: Tue Sep 17 20:37:35 2013 -0700 Add a new SetDisplayScaling RPC to the list of capabilities. Signed-off-by: Dmitry Torokhov commit 5ccfbb3cc3da0f026ed8628dbdb07bc187c3bc16 Author: VMware, Inc <> Date: Tue Sep 17 20:36:27 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 4a527c999422eaba9795b18e89b69fbeefda8583 Author: VMware, Inc <> Date: Tue Sep 17 20:36:04 2013 -0700 HGFS: Make Linux client compile on kernels 3.11 HgfsReaddir has been replaced with HgfsIterate for the newer releases of the kernel 3.11 and newer. Signed-off-by: Dmitry Torokhov commit 2946894f1783f7a735d2e3d3770853b9b29f95ea Author: VMware, Inc <> Date: Tue Sep 17 20:35:50 2013 -0700 HGFS: Partial fix for corruption when using different file handles to the same file File is corrupted while our customer using two threads to read or write a file via Linux HGFS client. This is because the read handle interferes with the writes by causing a revalidation of the inode's file attributes. These were mishandled wrt to flushing out the cached pages. If the new attributes were different for modification time or file size then the pages in the cache were invalidated. This causes pages of valid data to be thrown away and the writes lost. Therefore resulting in a file with gaps of blocks of zero bytes where writes were not sent to the HGFS server. This is fixed by replicating what NFS does in this regard, which is only invalidate the cache if the HGFS server returned file size only differs from the cached inode value and only then if the new size is greater. Cleaned up the write begin and end which was initially causing problems due to very buggy code. Have now based this on simplicity from fs/libfs.c and the simple_write_begin/simple_write_end which shows what the minimal settings should do handling writes to pages and partial page writes. These can be viewed under you favorite linux source cross-reference website. Signed-off-by: Dmitry Torokhov commit 1a3eb34dd0ad5aa3e51d586cf1fcf310c1f4350e Author: VMware, Inc <> Date: Tue Sep 17 20:35:40 2013 -0700 Fix AssertOnCompileFailed for GCC 4.8 (kernel 3.10+) GCC 4.8 now includes -Wunused-local-typedefs as part of -Wall. This causes it to spew a gazillion warnings when compiling our modules on 3.10+ kernels. Because it's a typedef we can't use the (void) cast trick, so we need to use attributes. This change introduces UNUSED_TYPE to vm_basic_types.h and uses it where appropriate to make the compiler happy when building our modules. Signed-off-by: Dmitry Torokhov commit 1dd5464914032fe986710bddaa2359c70a0e2c82 Author: VMware, Inc <> Date: Tue Sep 17 20:35:32 2013 -0700 Change FileIO_AtomicUpdate to not close files prior to rename on Posix. Windows rename fails if the target files are open. Posix does not have that restriction. Signed-off-by: Dmitry Torokhov commit 23f95ad9ba8896d1b3a2215ceaf336a0d776d449 Author: VMware, Inc <> Date: Tue Sep 17 20:35:16 2013 -0700 VMCI: make guest driver work with virtual IOMMU Right now we use vmalloc()/alloc_page() for our guest queuepair pages (and bitmap page) and then do a virt_to_phys() before passing them down to the device. That's not going to work if DMA remapping is enabled, since the IOMMU has no idea about the mappings. Switch to pci_alloc_consistent() instead. We still allocate each page individually, since there's no guarantee that we'll get a contiguous block of physical for an entire queuepair (especially since we allow up to 128 MiB!). Also made split between guest and host in the kernelIf struct much clearer. Now it's obvious which fields are which. Finally, drop the PINNED flag from Linux. That was only ever used by vVol-Filter, and that's been moved over vPageChannel, which doesn't use queuepairs but has custom rings. Once this is in I'll port it to upstream. I considered doing upstream only, but that would mean pre-3.9 guests would be unable to use IOMMU support. We should really freeze the in-house driver after this... Signed-off-by: Dmitry Torokhov commit c6f49a9aa54be295fb2a8537a0924a8c806cbb19 Author: VMware, Inc <> Date: Tue Sep 17 20:35:10 2013 -0700 Internal branch sync. Included in this change: . turn on vgauth for authn checks . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 1722668cba1cad69bc537ec836f479d1c05e8cc7 Author: VMware, Inc <> Date: Tue Sep 17 20:34:44 2013 -0700 HGFS: Linux client logging improvements Add more logging for tracing file IO calls. Signed-off-by: Dmitry Torokhov commit c0a9de0c3cc97503bb65a53bb391343232160cc0 Author: VMware, Inc <> Date: Tue Sep 17 20:34:33 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 074d772ec4b0f2afcba169c2b6da3ed5a2baeb2f Author: VMware, Inc <> Date: Tue Sep 17 20:34:28 2013 -0700 Bump up tools version to 9.6.0 for WS 10 RTM. Signed-off-by: Dmitry Torokhov commit d8fe065a8fb1e13ebb2ed980b8460d2d6c4c2ce9 Author: VMware, Inc <> Date: Tue Sep 17 20:34:19 2013 -0700 HGFS: Clean up and improve Linux client logging Enhancing existing log statements to be useful, moving open flags utility function into the utility file as in the future it should be used by open and create entry points. Signed-off-by: Dmitry Torokhov commit c1bebef1add802f897e3fc120afb66833343359e Author: VMware, Inc <> Date: Tue Sep 17 20:34:03 2013 -0700 HGFS: Improve Linux client logging Minor improvements to improve the logging of messages during debugging. Remove the less than helpful messages that are extremely chatty. Signed-off-by: Dmitry Torokhov commit 6b07756ed5974aaed6dec4fc14ae52fe031ae00d Author: VMware, Inc <> Date: Tue Sep 17 20:33:46 2013 -0700 Fix stringxx to call Unicode_Free() instead of free() Signed-off-by: Dmitry Torokhov commit 61276a6bde5fa8931c9f4ae142611a296b0cf0c0 Author: VMware, Inc <> Date: Tue Sep 17 20:33:35 2013 -0700 Housecleaning: VMIROM is dead VMI was gone a long time ago. There are a few remnants still present. - includeCheck has a VMIROM macro that can go, plus all locations it was copy-n-pasted into - vmcore/public/paravirtualInterface.h was totally unreferenced. Signed-off-by: Dmitry Torokhov commit 119645bbb27989ddae45926a8918bc31d9ae34d2 Author: VMware, Inc <> Date: Tue Sep 17 20:33:20 2013 -0700 VIX: add opcode for RemoveAliasByCert Trying to be tricky and sharing an opcode doesn't work when it comes to tools-side disabling. So add an opcode for it and plumb it through. Signed-off-by: Dmitry Torokhov commit 1ed1ec7e22d20401b388ebb08e09ac2b74326c45 Author: VMware, Inc <> Date: Tue Sep 17 20:33:01 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 339f41660410a6928c6c657f35b20d8623989fdd Author: VMware, Inc <> Date: Tue Sep 17 20:32:57 2013 -0700 HGFS: Fix Linux client inode 512B block count The Linux HGFS client miscalculated the number of 512 byte blocks to set in the inode for the file size. It was incorrectly using the HGFS hardcoded block size instead of 512, which was 1024. This causes the block count to be half the correct number and so du on a file reports the incorrect size. fstat also retrieves this block count in the stat structure so it is likely more applications will break. Signed-off-by: Dmitry Torokhov commit edffc5fad3c601e1ee3e391532fbc623f8b19519 Author: VMware, Inc <> Date: Tue Sep 17 20:32:52 2013 -0700 Change GuestLIB SDK to use new RpcChannel API. Change GuestLIB SDK to use new RpcChannel API. 1) Change RpcOut_* calls to RpcChanneel_* calls. 2) guestlib SDK now has extra dependency on GLIB and vmtoolslib as secure guestRPC brings a lot new dependencies (rpcin, asyncsocket, ssl, datamap, hashmap etc). 3) ship new glib and vmtoolslib for linux and windows packages. 4) merge logging functions (Debug(), Warning()) in vmtools and guestlib into one to avoid having same function names defined in two libs. 5) update build in open vm tools. 6) app monitor needs to do similar thing, which will be handled by HA team. Signed-off-by: Dmitry Torokhov commit e55039cb8452777c2024ce3a13cd3439f36fd554 Author: VMware, Inc <> Date: Tue Sep 17 20:32:40 2013 -0700 HGFS: Fix Linux client symlinks The kernel buffer holding the symlink name was being freed incorrectly when it was used by the VFS layer. This resulted in corruption and invalid names being used when trying to lookup the symlink's target. The HgfsFollowlink should not be calling vfs_follow_link but calling nd_set_link to save the link target name that HGFS allocated. To deal with the release of the name, HgfsPutlink has now been added which the VFS layer will call as needed and this function retrieves the name from the name structure using nd_get_link and releases the buffer. Then for completeness calls nd_set_link with NULL to clear it from the name structure. The VFS layer internally calls vfs_follow_link after the HgfsFollowlink call passing the link target name from the name object that HGFS stored. Hence, why HGFS should not call it directly. Signed-off-by: Dmitry Torokhov commit 0d5581ae35aaca0a1e645d8ffccaae77c0e39d4a Author: VMware, Inc <> Date: Tue Sep 17 20:32:28 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 81536c78e78200c58825b65cb5d188704b70c15f Author: VMware, Inc <> Date: Tue Sep 17 20:32:18 2013 -0700 HGFS: Fix a Linux client memory corruption When doing partial page writes the Linux HGFS client would trash the initial part of the page leading up to the start of the write and also trash the remaining part of the page after the written segment of the page. This trashing of the initial part of the page was incorrect and overwrites earlier partial page writes to that page. This was also incorrect as the arguments for the offsets into the page were miscalculated. Signed-off-by: Dmitry Torokhov commit a4f7f191d0cb1d260f1b13e2545340109be4631d Author: VMware, Inc <> Date: Tue Sep 17 20:32:13 2013 -0700 Add 4 new guestRPC commands for namespace manager. Signed-off-by: Dmitry Torokhov commit 79b0afe51c9fe9002ad1613ad8eb1437ef5eafd0 Author: VMware, Inc <> Date: Tue Sep 17 20:32:06 2013 -0700 Internal branch sync. Included in this change: . Fix FileIO_CloseAndUnlink() to handle unlink failures. . Add Debuan 7,1 to the list of known OSes . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 159e1ec4d24ca2e3b41f13c5f0976a1ecd1fb8b8 Author: VMware, Inc <> Date: Tue Sep 17 20:31:40 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 518fab531f95c6a31f15f3fb7ae8a43d0eab4064 Author: VMware, Inc <> Date: Tue Sep 17 20:31:31 2013 -0700 Fix parsing logic in guestInfo to parse vlan configured NICs The regular expression used to parse routes /proc/net/route and /proc/net/ipv6_route fail when the device names contain "." eg: eth0.80 which is how the interface names appear when we have VLANs configured. This fix modifies the regex to handle this case by parsing until a whitespace character is encountered. Signed-off-by: Dmitry Torokhov commit b086090409081a4efdad46f6fba27df1b94f916a Author: VMware, Inc <> Date: Tue Sep 17 20:31:22 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit e6117c29424490908f1abbbe135cbdaef66258af Author: VMware, Inc <> Date: Tue Sep 17 20:31:10 2013 -0700 HGFS: Improve the Linux kernel client logging Add more logging to make tracking requests and their respective arguments to aid debugging. Signed-off-by: Dmitry Torokhov commit a302d14e247c3acd0ce83fa5455f9e759730778c Author: VMware, Inc <> Date: Tue Sep 17 20:30:58 2013 -0700 Use g_debug instead of g_warning in RpcChannel_Error With esx5.1GA Tools, when there are more two Terminal Sessions connect to a Windows VM, each TS sould have one vmtoolsd running but actually only max two vmtoolsd run. The Windowds Application Event log fills up with the warning messages of "[vmusr:vmusr] Error in the RPC receive loop: RpcIn: Unable to send." repeatly until close some TS' to have max two TS connected. Some customers had vmtoolsd crashed but some didn't. This message is from RpcChannel_Error. After replace g_warning() by g_debug(), the problem is resolved. This is a workaround for esx5.1x. Signed-off-by: Dmitry Torokhov commit 566b7aa41af9f0c40b2c53f8a19f1e718c8bb3d5 Author: VMware, Inc <> Date: Tue Sep 17 20:30:52 2013 -0700 Re-enable vsocket guestrpc in tools. 1) Fix some assertion for reconnect. 2) Call VMCISock_GetAFValueFd so we do not hold vsock usage all the time. 2) Cut off the dependency of SIGUSR1 with dndcp plugin. 3) Change function name vmware_unblock_vmware_user to send_vmware_user_sigusr1. Signed-off-by: Dmitry Torokhov commit c1a77415dc90d322b8ffddd93c2f820bfab76a09 Author: VMware, Inc <> Date: Tue Sep 17 20:30:43 2013 -0700 Avoid logging non-fatal messages without logging system initialization. Logs that come before logging system intialization spam the console output. Therefore, we make the logging a no-op for non-fatal messages until logging system has been initialized. Usually, we initialize the logging system when process starts up, so we will swallow only those non-fatal log messages that are generated during very early stages of process initialization. Signed-off-by: Dmitry Torokhov commit 1c9c43caa766bfd6222ee994e9d97f0fefeeedf9 Author: VMware, Inc <> Date: Tue Sep 17 20:30:26 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 88c5964db6aaf5437872c1f553b27c07453dd12f Author: VMware, Inc <> Date: Tue Sep 17 20:30:00 2013 -0700 HGFS: clean up of server Send packet part II Now remove the two unused reply and reply size arguments that are in the HgfsPacket object from the server internal send function. Signed-off-by: Dmitry Torokhov commit cdfb73d3f965ceb791a4ba18d044ad90f29bf645 Author: VMware, Inc <> Date: Tue Sep 17 20:29:52 2013 -0700 Fix lspci command in vm-support. Change runcmd "lspci -t -v -nn -F /tmp/lspci1.$$.txt" "/tmp/lspci2.$$.txt" to runcmd "lspci -t -v -nn -F ${OUTPUT_DIR}/tmp/lspci1.$$.txt" "/tmp/lspci2.$$.txt" because previous command: runcmd "lspci -M -vvv -nn -xxxx" "/tmp/lspci1.$$.txt" would remove /tmp/lspci1.$$.txt in the last step. Signed-off-by: Dmitry Torokhov commit 8e8095e66632b9a29c89add36ec469d00a8ba6bf Author: VMware, Inc <> Date: Tue Sep 17 20:29:44 2013 -0700 HGFS: Clean up server send packet callback While cleaning up the usage of the HGFS packet abstraction it meant that the arguments to the HGFS server packet send callback could be cleaned up. The arguments for the packet buffer and size are now unused as this too arguments are extracted from the HGFS packet object. Therefore, remove the unused arguments from the send callback. Signed-off-by: Dmitry Torokhov commit f51b4f5725fa0df44c200e1c33e17d28c07ea7e5 Author: VMware, Inc <> Date: Tue Sep 17 20:29:34 2013 -0700 nternal branch sync. Included in this change: . Tools,DND,X11: Constrain detection window to desktop work area . dndcpx11: Adjust style to match Hosted UI guidelines . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 1e7a9a273f62a53d0c9046499cf24b421aa2528b Author: VMware, Inc <> Date: Tue Sep 17 20:29:02 2013 -0700 Bump up the tools version to 9.4.0 for RTM. Its time to bump up the tools version from 9.3.3 to 9.4.0 for RTM. Added new macros and new version for tools in bora/public/vm_tools_version.h file. Signed-off-by: Dmitry Torokhov commit 05f41deaeb8e129915cb501b6a1ce18b46f1c902 Author: VMware, Inc <> Date: Tue Sep 17 20:28:39 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit d7debe58f9ebeffc21193c56286ca36266d05142 Author: VMware, Inc <> Date: Tue Sep 17 20:28:22 2013 -0700 Internal branch sync. Included in this change: . Untangle Util_Backtrace and friends so they don't pull in lib/file . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 9f3ea592f1651fc43c715bf2c74499bf63b47ab7 Author: VMware, Inc <> Date: Tue Sep 17 20:27:51 2013 -0700 HGFS: Server packet abstraction part XI Deal with the broken reply packet part of the abstraction. Fix the get reply packet function call to separate out the reply data size passed in and the reply packet buffer size which is returned. Add the reply data size field in the HgfsPacket object so that the reply data size and reply buffer size can be separated out and not overloaded. This allows the transport channel send routines to extract the reply details from the packet object and not need the buffer and size arguments. The send function channel callback API will be cleaned up in a separate change. The get reply function for the packet now sets the meta packet data size too when it is used for the reply packet. This is used by the VMCI channel which now only maps and copies the correct amount of reply data into the guest VM shared memory. The reply packet size is randomly overwritten from the total packet size available for the reply to hold the amount of written data in the reply. This however, does not have any effect, since, the reply data size is passed to the send function which then knows how much data to send, and for VMCI, the meta part of the packet is used to transfer data to the guest shared memory so the reply part is essentially unused. This is now deleted. Signed-off-by: Dmitry Torokhov commit 8fcfef8b4b65a34d9d24686ee9d378b724d56744 Author: VMware, Inc <> Date: Tue Sep 17 20:27:44 2013 -0700 MPN to MPN 64 conversion for Hosted. This change is supporting a 64bit MPN for hosted products. Assumptions taken: 1. Kindly note that currently we do not have systems supporting 64bit memory. So hosted vmmon 64 bit MPN is a container to store whatever monitor passes to it. The underlying assumption is that the higher 32bits will be zero. 2. Physmem tracker still does page walk using 32 bit values and we have put checks to make sure that MPN64 is just a container with actually 32 bit values. This was a design decision taken after talking to kevinc and jpool. 3. The CrossPage code is still 32 bit and I typecast MPN64 to accept 32 bit values for the crosspage code. 4. Vmkernel already has another definition of MPN64 and I have retained their definition for vmkernel specific code. typedef uint8 * MPN64; typedef uint64 MPN64; 5. Additional changes were required in bora-vmsoft vmballoon module which earlier used MPN and called functions expecting MPN64 as an input. I have however *NOT* changed the PageHandle code of Vmballoon. I have typecasted to MPN64 where common MacOS page handling functions which require MPN64 are used. Signed-off-by: Dmitry Torokhov commit 946a1fed90796096501f5650ca0344f2223d8140 Author: VMware, Inc <> Date: Tue Sep 17 20:27:32 2013 -0700 Disable vsocket connection temporarily to work around a bug. Signed-off-by: Dmitry Torokhov commit 66f441a5673d90fc18c084afeb02a8e8e703a555 Author: VMware, Inc <> Date: Tue Sep 17 20:27:19 2013 -0700 Pass RPCI channel info to guestrpc command hanlders. Since now we have secure guestRpc, some commands like namespace manager needs to handle vsocket/backdoor connections differently. main changes are in guest_rpc.c, guest_rpc.h, and namespaceMgr.c. Changes in other files just function sinature changes. Signed-off-by: Dmitry Torokhov commit 659dde93cfc12789309b42278892667e75914ca4 Author: VMware, Inc <> Date: Tue Sep 17 20:27:07 2013 -0700 Tools/DnD X11: Logging improvements and cosmetic touchups. ===== Logging ===== A large chunk of the Tools DND code included function call tracing via log entries at the debug level. However, it had some problems, such as generating a lot of noise in all buildtypes. (Remember that Tools only has 3-4 log levels: debug, info, warning, and error.) There was also a problem with inconsistency w/r/t logging when a function went out of scope. To address this, I whipped up a dummy tracing object and shove it in bora-vmsoft/lib/public. By including tracer.hh, one just inserts TRACE_CALL(); at the beginning of a function to log entry/exit. Additionally, it works only in developer builds; it's a ifdef'd out everywhere else. Another thing I did was centralize logging of GuestCopyPasteMgr's session ID and state updates. We now long old/new values upon update. More of the DND code has been fixed to log to the dndcp GLib log domain, making it easier for folks to isolate dndcp logs. (This explains the switch from Debug to g_debug.) ===== Readability ==== There was a list of some 10+ sigc signals that, due to indentation and such, was kinda hard to read & easily skim. I replaced this with a macro which reduces each signal hookup to one line. Signed-off-by: Dmitry Torokhov commit 3ef9ccaea708f123f020fe592cb3883ad54034ab Author: VMware, Inc <> Date: Tue Sep 17 20:26:35 2013 -0700 Fix send retry on vsocket channel. Signed-off-by: Dmitry Torokhov commit cbfdc1a390497f46bc15d1bff0dd91f9775a3780 Author: VMware, Inc <> Date: Tue Sep 17 20:26:30 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 26c693664f4424ce0cf090b9c85df210c8e47467 Author: VMware, Inc <> Date: Tue Sep 17 20:26:17 2013 -0700 Switch utf::string from g_utf8_validate to Unicode_IsBufferValid. In the version of glib we currently use g_utf8_validate rejects strings containing the non-characters U+FFFE and U+FFFF. This was marked as a bug and resolved (see https://bugzilla.gnome.org/show_bug.cgi?id=694669) but until that is released we need a workaround. Our internal UTF-8 validation routine accepts these characters as valid so use that instead. Signed-off-by: Dmitry Torokhov commit eb245cb3633d0f4078ea61c8f8ece54bacc4d855 Author: VMware, Inc <> Date: Tue Sep 17 20:26:09 2013 -0700 HGFS: Clean up of server packet send Make packet the send function local to the only file where it is used. Signed-off-by: Dmitry Torokhov commit 3d814b1c8ea9b6c5249c064e47326f37026ff2d6 Author: VMware, Inc <> Date: Tue Sep 17 20:25:21 2013 -0700 Fix VMHSUtilFileMove and clarify comments of File_Replace VMHSUtilFileMove has been broken since 2008 and no one has noticed, so I would be happy to remove the entire mv command from VMHS if no one would miss it. Signed-off-by: Dmitry Torokhov commit 48a12d8ff6d89e2e06f094cdf0c34e29fe338cbc Author: VMware, Inc <> Date: Tue Sep 17 20:25:16 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 811ceb8315512c3146c9f30b926e86538f7734d3 Author: VMware, Inc <> Date: Tue Sep 17 20:25:06 2013 -0700 Change the lspci parameters to avoid crash dangerous and offer more readable information. Currently our WS `vm-support` runs: lspci -H1 -M lspci -H1 -M -vn The -H parameter is dangerous. In better case it will crash your server, in worse case it will corrupt your data. So change them to: runcmd "lspci -M -vvv -nn -xxxx" "/tmp/lspci1.$$.txt" runcmd "lspci -t -v -nn -F /tmp/lspci1.$$.txt" "/tmp/lspci2.$$.txt" runcmd "lspci -vvv -nn" "/tmp/lspci3.$$.txt" Signed-off-by: Dmitry Torokhov commit c2676c087a208e8bca090c741ef34d6ff1a8cc6b Author: VMware, Inc <> Date: Tue Sep 17 20:24:59 2013 -0700 Replace some RpcOut_* API using new RpcChannel API. Signed-off-by: Dmitry Torokhov commit 0bc8730194cd723c32010053a93a580eb336e54c Author: VMware, Inc <> Date: Tue Sep 17 20:24:08 2013 -0700 HGFS: Server packet abstraction part IX Adding in the new fields to indicate the size of the valid data, not the size of the buffer. Previously, the two were combined which meant that the buffer size was ultimately used instead making the data copies very inefficient. Another transitional change to get this stuff moved over to handle the total pack size and valid data sizes separately. Currently, VMCI has to use the total packet sizes only and so maps in 16 pages and copies all the data back and forth because it can't tell how much is actually valid. When I switch the VMCI transport header to support V2 it will have the correct data size and packet ID - asynchronous will then work too. Signed-off-by: Dmitry Torokhov commit 54baff91bb4ee3f1d4bd31e23b1f79ed513a9c81 Author: VMware, Inc <> Date: Tue Sep 17 20:23:19 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 7f20a2f72a0a2314a448fc38a6d76623d0744ce7 Author: VMware, Inc <> Date: Tue Sep 17 20:22:43 2013 -0700 Linux kernel modules: remove pre 2.6 support from makefiles Since pre 2.6.9 support was moved off to legacy branch we do not need it here. Signed-off-by: Dmitry Torokhov commit fd70a7c37fa26eedfa6760606ead6c4bc43a56f6 Author: VMware, Inc <> Date: Tue Sep 17 20:22:25 2013 -0700 Changed a warning log message to debug message. If a tools service is running inside a non-VMware environment, we should not be filling the system logs with our warning messages. Signed-off-by: Dmitry Torokhov commit 2b1a8355548e3d82ad1f3a311dad1c3c8f731c4a Author: VMware, Inc <> Date: Tue Sep 17 20:22:09 2013 -0700 Mac OS Tools: Make system-wide services launchd-compliant Since day 1, the way we have started the tools services has been: at boot, launchd executed the process "services.sh --start", which: 1) Loaded kexts. 2) Started the long-lived vmsvc as a daemon. 3) Exited. According to http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html , launchd sends it a SIGTERM. See "SIGTERM". This change fixes the above two issues, by turning things upside down: since vmsvc is already a long-lived process, let's: o Have launchd start vmsvc directly, without daemonizing it, just like launchd already does with the vmusr process. o Modify vmsvc so that the first thing it does is load the kexts. I kept the "services.sh --stop" interface (I just re-implemented it differently), because it is useful to testers, but more importantly because it is called from two places: The tools preinstall package script (possibly in a tools package older than this change). The tools uninstallation script. Signed-off-by: Dmitry Torokhov commit 4111a70f4527aca6442162e0481cd39abeaa3efe Author: VMware, Inc <> Date: Tue Sep 17 20:21:40 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit d6873aa9d43c6b807057fcd165f2a8547b5ed5a2 Author: VMware, Inc <> Date: Tue Sep 17 20:21:32 2013 -0700 Ignore SIGPIPE for tools. Otherwise tools exits upon socket write error. Found this in guest rabbitmq proxy testing. Signed-off-by: Dmitry Torokhov commit 6f8769f85cf842590867c6ca021cc7d148a59962 Author: VMware, Inc <> Date: Tue Sep 17 20:20:35 2013 -0700 Reactivate guestRpc polling reduction code on the guest side. Reactivate guestRpc polling reduction code on the guest side. The code was disabled completely due to an issue that has been fixed. Signed-off-by: Dmitry Torokhov commit 52cac5493686e9f6da1bc9f67c13e2f656af83a3 Author: VMware, Inc <> Date: Tue Sep 17 20:21:26 2013 -0700 Fix a segfault in RpcChannel_SendOutRaw. Fix a segfault due to null pointer reference in debug code. Signed-off-by: Dmitry Torokhov commit 38756b5b32ca5c8c3b1a17bfc2216c59c6bcf7dc Author: VMware, Inc <> Date: Tue Sep 17 20:20:27 2013 -0700 Use __thread on Linux (and ESX) in vthreadBase.c. This change makes use of __thread on Linux for storing the vthread base pointer and the thread ID. We still also store the value with pthreads_setspecific so that we have consistent behavior on thread destruction (using the pthreads destructor). But this allows the VThread_CurID path to skip loading the pthread key, skip checking if the key is initialized, and skip the call into pthread_getspecific. (With VThread_CurID taking its own fast path, it's not clear there's much benefit at all from optimizing the path for the base pointer, but I did so for consistency's sake.) I tried using my USB bandwidth test to measure the performance impact of this on a Linux host. Unfortunately I found the test to be much more noisy under Linux. The results claimed 1.6% faster overall, but I have almost no faith in that number. Still, having inspected the new code and looked at the contents of pthread_getspecific, I think it's safe to claim that this should be better overall even if its difficult to quantify how much. And though it makes the code slightly more crufty, such ugliness is confined to two functions. Signed-off-by: Dmitry Torokhov commit e996a35e60280a8dd73bb78f9a9ddde06fec7b77 Author: VMware, Inc <> Date: Tue Sep 17 20:20:14 2013 -0700 Internal branch sync. Included in this change: . dnd plugin: various cleanups . asyncsocket: Fix for race conditions with sync operations on a 2nd thread Signed-off-by: Dmitry Torokhov commit c7fbb99626b9ee8e20cc8e12691805d013826fbd Author: VMware, Inc <> Date: Tue Sep 17 20:20:02 2013 -0700 Remove some whitespace from x86cpuid.h. Sometimes when we make preprocessor tables we have to blow past 80 columns. But in x86cpuid.h we had a table with plenty of internal whitespace which was 81 columns long. No reason to have to suffer with that. Signed-off-by: Dmitry Torokhov commit bb80b3337a94be4668be732967ca453ca1b97359 Author: VMware, Inc <> Date: Tue Sep 17 20:19:54 2013 -0700 HGFS: Server packet abstraction part IX The HGFS server sets the packet's ID field as the HGFS protocol request ID. This should not occur and it overloads that the packet ID which should be private to the transport channel which has nothing to do with the HGFS request ID. The HGFS request ID has it's own field in the HGFS header used by the request and reply. Remove the HGFS server modifying the packet ID. This is currently safe, as the clients do not receive any asynchronous replies from any HGFS server where the packet ID in the reply is used. Signed-off-by: Dmitry Torokhov commit 4f860433a9a51fd978f51ed6c9fa1db167909419 Author: VMware, Inc <> Date: Tue Sep 17 20:19:48 2013 -0700 VMCI: Remove VM2VM We're never going to ship it, so let's yank it out. This isn't a straight backout for the following reasons: o Some of the files have diverged so far that backout fails. o Petr added some nice log messages in his original change that we want to retain. So this was mostly manual. I did do a side-by-side with the pre-VM2VM version and it looks good. Note that our 128-bit QP tag code will re-appear in vm_atomic.h at some point. Signed-off-by: Dmitry Torokhov commit ed57ff3cc7d3725cd6ef6ba482608108faa587c6 Author: VMware, Inc <> Date: Tue Sep 17 20:19:40 2013 -0700 Tools: prepare for gcc upgrade Had a few spare cycles, so tried compiling Tools with gcc-4.4.3. This change fixes all compilation errors. (It does NOT do the compiler upgrade, hence the minimal testing.) All changes are mechanical / should be correct at compile-time. appUtilFileTypes.h: hash_map was never a standard, use the standardized (std::tr1) unordered_map. Which removes ifdefs too. most other files: character strings are "const" in C++. Signed-off-by: Dmitry Torokhov commit 7f89ef424c41687763e8a976337fea1a43ed299b Author: VMware, Inc <> Date: Tue Sep 17 20:19:34 2013 -0700 Add Clamped_UAdd64 Signed-off-by: Dmitry Torokhov commit 0910f4ac428e00cad83893f6fbe68e928666466e Author: VMware, Inc <> Date: Tue Sep 17 20:19:27 2013 -0700 Flip the kill-switch on VM2VM VMCI VM2VM VMCI made a reappearance in 5.5 because vHadoop was planning to use it, but it was eventually rejected. We left the code in so as not to disturb stability, and simply disabled it in the UI. But let's make doubly sure by flipping the kill-switch, so that our customers don't accidentally enable it and then complain about it being removed from 5.1, coming back in 5.5 and then disappearing again. Signed-off-by: Dmitry Torokhov commit 3aea23905d5c28cc4e68011fe2e47f1354c66a4e Author: VMware, Inc <> Date: Tue Sep 17 20:19:21 2013 -0700 Bump up tools version to 9.7.0. Signed-off-by: Dmitry Torokhov commit 036172f0cb580ca370a94324f6a465bcb71f2076 Author: VMware, Inc <> Date: Tue Sep 17 20:19:13 2013 -0700 Fix a spurious warning. /dbc/pa-dbc1121/rrugina/rr-vmcore-dbc0/bora/public/vm_basic_defs.h:315:5: warning: "VMKERNEL" is not defined Signed-off-by: Dmitry Torokhov commit 7e6615de5c2f12ff5b1bb7b6ac47c50312fd1d15 Author: VMware, Inc <> Date: Tue Sep 17 20:19:06 2013 -0700 HGFS: Clean up server packet abstraction part VIII Simply make the pointer checks more consistent. Signed-off-by: Dmitry Torokhov commit 0add24c598aa8c863917eda4da97c14f10380671 Author: VMware, Inc <> Date: Tue Sep 17 20:19:00 2013 -0700 HGFS: Clean up server packet abstraction part VI This cleans up some of the inflexibility and inconsistencies in the use of the mappings of the packet buffers for the meta data (Hgfs header and commmand arguments) and the data component. This splits out hanlding the iov mappings into two smaller utility functions (map and unmap) since the code is replicated in multiple places. The copy from and too an allocated buffer into and from an iov array is split out from the map and unmap functionality and also a second routine is created to copy from the iov array to a buffer which was previously missing. To achieve this I have also added a mapped iov count for the meta and data iov components of the HgfsPacket object. This helps track the state of when mappings are available and not. Previously, this was coded by assumption of what the GetBuf call did. In follow up changes the data will have a total buffer size and a data size for each of the meta and data components. This will allow for optimal movement of data between buffer and iov array. Signed-off-by: Dmitry Torokhov commit fb4b3833080ba2ebd1dbafc8334f0cb10e181197 Author: VMware, Inc <> Date: Tue Sep 17 20:18:47 2013 -0700 Avoid a memory dereference when getting the current thread ID. As part of some recent benchmarking and ensuing discussions a couple of overheads in VThread_CurID have been identified. (1) VThread_CurID ultimately gets a pointer to a per thread structure that contains various bits of state including the thread ID. After getting that pointer it must read the thread ID out of memory. This could be avoided if the thread local value we stored was the thread ID itself. (2) Before calling into the host's API for thread local storage, vthreadBase.c must get the host key, check if it is initialized and initialize it if necessary. Then once it gets the thread local value from the host API it must check if that has been initialized. These checks could be avoided if we forced clients to initialize the thread before calling functions like VThread_CurID. (3) On some (all?) Linux pthread implementations pthread_getspecific itself can be heavyweight. Both Windows and Linux offer alternatives to make thread local storage cheaper. (OS X on the other hand provides a very fast implementation of pthread_getspecific: pretty much one instruction plus the function call overhead.) The first two overheads came up in my profiling of USB workloads on OS X while Kevin raised the third issue in the following discussions. This change attempts to eliminate the first overhead, but to do so in a way that helps set up the code for attacking the remaining two. In particular it introduces a second thread local variable to store the thread ID. For the time I left the thread ID in the other structure as well and verify that they stay in sync. We could get rid of it, but it's low cost and I suspect (though I have no proof) that it could be useful in debugging. As part of this I've rearranged some of the initialization code both for the TLS keys as well as for initializing the TLS data. This is useful because I wanted both pieces of state to get set together (and mutated together -- yes our threads change IDs during their life). And, with respect to the pthread keys, it's important to make sure the base key gets allocated before the thread ID key. This ensures it gets destroyed first which allows us to keep an ASSERT to make sure that the two thread IDs stay in sync. This does run into one wrinkle because of the lazy thread initialization. The default value for uninitialized state is NULL which, inconveniently, is a valid vthread ID. So instead of actually storing the thread ID, we store the thread ID incremented by one. This means the default/uninitialized value will show up as -1. We can avoid this after addressing (2) from above, but in the meantime trading a memory read for an ALU operation is still a nice win. Signed-off-by: Dmitry Torokhov commit 447758846b1a1caa09c2aa0dad5757897ad79bc0 Author: VMware, Inc <> Date: Tue Sep 17 20:18:23 2013 -0700 Internal branch sync. Included in this change: . lib/file - add File_MakeSafeTempDir() . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 0758f4374dedac711fd674ec6f0c4ebc346cdb60 Author: VMware, Inc <> Date: Tue Sep 17 20:17:55 2013 -0700 Internationalize disk shrink progress string Disk shrink is a long running operation with progress reporting. The "progress" string is visible to users and therefore needs to be internationalized. Signed-off-by: Dmitry Torokhov commit d0acf1b782efc1477ae216979a6984531f13ce52 Author: VMware, Inc <> Date: Tue Sep 17 20:17:44 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit ffb568be68fae5f318b09fdf4b60da84a180f20e Author: VMware, Inc <> Date: Tue Sep 17 20:17:19 2013 -0700 HGFS: Clean up server packet abstraction part VII Consolidate the HgfsPacket bool fields into a flags field. Make the names of the bool fields more accurate too in some cases. Signed-off-by: Dmitry Torokhov commit 7230cb3017b18946be3e056d47a3a5e3293b8f09 Author: VMware, Inc <> Date: Tue Sep 17 20:17:02 2013 -0700 HGFS: Clean up server transport session usage The transport session is only ever used in the common HGFS server code. The scope should be constrained to that file and beyond that treated as an opaque type. Make some of the transport session functions static to the common HGFS server file and remove the declarations from the common header file. Signed-off-by: Dmitry Torokhov commit 227a637742a06ce2155ed14a60d2d31ce772bc90 Author: VMware, Inc <> Date: Tue Sep 17 20:16:56 2013 -0700 Remove fake pthreads A while ago, we decided to always compile with pthreads; optimizing for single-threaded programs no longer makes sense. Which means vthreadBase.c can get cleaned up. (Notice that this implements the "best thing to do" comment on lines 195-6). Signed-off-by: Dmitry Torokhov commit 039bc01a6547c7306ac9c62c8f62ecd055443e9d Author: VMware, Inc <> Date: Tue Sep 17 20:16:49 2013 -0700 HGFS: Clean up server packet abstraction part V Clean up the packet utility routines to only pass the arguments that are required. This means we only need to use the HGFS server channel callbacks and not the whole HGFS server transport session object. Signed-off-by: Dmitry Torokhov commit df7a9a235364cd9c2f28c72ef1c54f857d0894b9 Author: VMware, Inc <> Date: Tue Sep 17 20:16:10 2013 -0700 HGFS: Fix build on Linux 3.10-rc1 The kernel changes broke the asynchronous read and write HGFS client code which picks out the dentry from within the kiocb struct. Include the header file directly now for newer kernel versions. Signed-off-by: Dmitry Torokhov commit 8e5da80487fa58c637bfe01426383164754283db Author: VMware, Inc <> Date: Tue Sep 17 20:15:46 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit b7ef7d7bc15c8c9a5336f77f96ac4d28dc4c2f68 Author: VMware, Inc <> Date: Tue Sep 17 20:15:38 2013 -0700 HGFS: Make server use of const more consistent In particular we see const void * and void const * intermixed and so now make the server code consisten in its use and stick with the const void * format. Signed-off-by: Dmitry Torokhov commit e8c800081d0339e10641e216e78ad9b47e4d5afa Author: VMware, Inc <> Date: Tue Sep 17 20:15:31 2013 -0700 HGFS: Clean up server packet abstraction part IV Complete some tidy up of the input params created from the HgfsPacket. This can be contained to only the HgfsServer code and not required to be exposed beyond that. So this removes the one usage from the parameter pack and unpack code which was in the unpack write request. As I was modifying up the HGFS server write request I correct a couple of const char * to const void * for the write data. I removed a HSPU_PutPacket declaration as the function did not exist. Signed-off-by: Dmitry Torokhov commit 61bd632f8cac230d9fb06bda67ebd0bfa33b13ff Author: VMware, Inc <> Date: Tue Sep 17 20:15:12 2013 -0700 HGFS: Fix server check for minimum sizes of session requests The HGFS server check for the minimum protocol request sizes for create and destroy session was incorrect. The full request including the reserved fields must be sent by the clients. Currently they all do that, including any shipping versions. Signed-off-by: Dmitry Torokhov commit 5dc550ca73d22d7d3bca6a095c2193b0f98184bd Author: VMware, Inc <> Date: Tue Sep 17 20:15:05 2013 -0700 HGFS: Clean up server packet abstraction part III Now the HGFS server packet abstraction has moved from an invalid const char * pointer for the input parameters set from the HgfsPacket abstraction we make the pack functions correct too. This fixes the packet header which can be of two different types to be a const void * now and not the incorrect const char *. Signed-off-by: Dmitry Torokhov commit 202788ac7df7a74b4f243dd3a6856b0547f7167d Author: VMware, Inc <> Date: Tue Sep 17 20:14:59 2013 -0700 HGFS: Clean up HGFS server packet abstraction part II Clean up the input params object which reuses the packet abstraction field names which are generic because they are opaque outside of the HGFS server. Since the input params are wholly contained within the HGFS server and have specific meaning in the HGFS server context, we give the fields the HGFS meaningful names. Signed-off-by: Dmitry Torokhov commit 147847abf45b67bc20483d1a8a83bff3f039bcfa Author: VMware, Inc <> Date: Tue Sep 17 20:14:46 2013 -0700 HGFS: Clean up server packet abstraction part I The HGFS packet object passed between the transport channel and the HGFS server is in need of some clean up so that it can be made much more efficient. This just closes out some unnecessary public functions and makes them static. Signed-off-by: Dmitry Torokhov commit 65d11e664ca3e3905f2afe102efa52a6122753d4 Author: VMware, Inc <> Date: Tue Sep 17 20:14:19 2013 -0700 HGFS: Fix the server to close sessions being invalidated When the HGFS server running in the tools is left with any sessions open due to the clients not terminating them cleanly they will be marked inactive. The HGFS server callback to invalidate them will periodically be called and after a brief period will terminate those sessions. These sessions are not closed first, thus triggering the assert in the session exit function which checks the session's state. Fix is to close the inactive sessions being terminated in the HGFS server invalidate callback. Signed-off-by: Dmitry Torokhov commit 0c899a265608805ce9962f85e3eb8636ec135b9c Author: VMware, Inc <> Date: Tue Sep 17 20:14:08 2013 -0700 Internal branch sync. Included in this change: . Solaris vmxnet3: log over-fragmented condition only when retry fails . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 4d268b0fff1d7075fc3e17a5c34d194e1809a5da Author: VMware, Inc <> Date: Tue Sep 17 20:13:54 2013 -0700 Replace BackdoorChannel_New with RpcChannel_New. Signed-off-by: Dmitry Torokhov commit f05250e1c8fe0fe64c5497507fa7a7790f41b496 Author: VMware, Inc <> Date: Tue Sep 17 20:13:42 2013 -0700 Fix for not starting RpcIn during fallback on backdoor channel. Signed-off-by: Dmitry Torokhov commit 6068b80208fe0e7b11bd506524cea5e2d73022cb Author: VMware, Inc <> Date: Tue Sep 17 20:13:35 2013 -0700 Bump up the tools version to 9.3.3 for RC 1. Signed-off-by: Dmitry Torokhov commit e6b0b955c2e4e6fc6a53bd1cb32f74bb70ab582c Author: VMware, Inc <> Date: Tue Sep 17 20:13:28 2013 -0700 HGFS: Fix Linux client to work with Perforce versioning The problem is that perforce client uses rename operation upon a temp file which has read-only attributes. The operation then fails with permission denied. The fix removes the read only attribute and retries the rename operation again as per the delete operation. This occurs on Windows HGFS servers as the target of the rename operation to be replaced has the read only attribute set. The prevents a rename even if they want to overwrite the target if it exists. So removing the read only flag is required. Signed-off-by: Dmitry Torokhov commit b34fff0c862b0ba8c6f93fc96a335d3a8e243f9c Author: VMware, Inc <> Date: Tue Sep 17 20:13:16 2013 -0700 Internal branch sync. Included in this change: . Scrub sensitive data in VIX before freeing it . Fix memory leak in VMCISock_GetAFValueFd() . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 35453dc666791c5fa87dbcc442839f0491e31d17 Author: VMware, Inc <> Date: Tue Sep 17 20:13:02 2013 -0700 Secure GuestRPC channels Use VMCI/Vsocket instead of backdoor for GuestRPC RPCI channels. For privileged channels, the guest side can bind port to less than 1024, VMX can then verify the binding and enforce privileged commands can only be ran by privileged users. Signed-off-by: Dmitry Torokhov commit 653df5dffb2ea5f9249dcb097a75f707bb578415 Author: VMware, Inc <> Date: Tue Sep 17 20:12:44 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 737ced1b4fab413f56ac4aa1532191de87a552d8 Author: VMware, Inc <> Date: Tue Sep 17 20:12:08 2013 -0700 Internal branch sync. Included in this change: . Properly handle timezone in TimeUtil_SecondsSinceEpoch() . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 1e9f5c94d0bcc807ac552b19bd5c9a60d96f301a Author: VMware, Inc <> Date: Tue Sep 17 20:11:56 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 4f174540292f0f158543cc0b315cdcaee72e875c Author: VMware, Inc <> Date: Tue Sep 17 20:11:40 2013 -0700 Plumb in a new VIX error code Signed-off-by: Dmitry Torokhov commit 065f236104ab12a89cd4b2e73597aeba203e0e0b Author: VMware, Inc <> Date: Tue Sep 17 20:11:25 2013 -0700 HGFS: Clean up the VMCI transport request and reply headers part I This is the first part of cleaning up the HGFS VMCI transport request and reply headers. This deals with the reply header only which is almost identical to the client request VMCI header but not quite - frustratingly. It really is not ideal to use a reply header that is different from the request header and has fields that require corresponding information from the request header which are missing. Consequently, the request header is going to be ramped up to a version 2 which includes all the information for both request and reply and be extensible. Signed-off-by: Dmitry Torokhov commit 8df8396102ebfdcd71cffaa2d05bee4f286f86f3 Author: VMware, Inc <> Date: Tue Sep 17 20:11:08 2013 -0700 VMCI/VSOCK: Cleanup some files Remove extra whitespace, replace tabs with spaces, fix indentation. Also updated the copyright for any file that I touched. Signed-off-by: Dmitry Torokhov commit c6b8484ee1dd7b53846b5cad4f0d7575b6501517 Author: VMware, Inc <> Date: Tue Sep 17 20:10:58 2013 -0700 Add compiler barriers to Atomic_MFence The MFENCE instruction ensures that all loads and stores that preceed it are "globally visible" before any load or store that follow it. However, we don't have a compiler barrier in Atomic_MFence and so the compiler can move code and defeat this. While this bug has probably been around for quite a while, it only came up recently now that the AtomicEpilogue() is compiled out. That contains a compiler memory barrier, and while it's not technically sufficient (need barrier before the MFENCE too), it was apparently enough to discourage the code motion in practice. Signed-off-by: Dmitry Torokhov commit a29d9d534464b563bedda7b16c1c4863c15ccf00 Author: VMware, Inc <> Date: Tue Sep 17 20:10:54 2013 -0700 HGFS: Fix notification cleanup session tear down Previously, when a transport session was disconnected any notifications for the HGFS session were then removed if notification module was enabled. However, this is grossly inadequate, as an HGFS session can come and go driven by a client's protocol requests. The notifications are per HGFS session which is completely independent from the transport session. The only reason the transport session comes into play is whether it has the transport characteristics to support the bidirectional nature of the notification feature. When an HGFS session is destroyed whether it is from a tranport connection session disconnect or a destroy HGFS session protocol request any folder the outstanding notifications for the session should be removed. Since that currently does not happen, e.g. when an HGFS session is destroyed via the protocol requests from a client and goes on to create a new one, during a Windows VM reboot, then when host updates do occur on an HGFS share the notifications will be generated that hold pointers to invalid sessions. This causes the VMX to crash. The fix is simply to move the notification teardown for a session is at the session teardown function, from the transport session disconnect. Signed-off-by: Dmitry Torokhov commit 6a8d296cc68cf6687f9cb8084669aa585ec8da0a Author: VMware, Inc <> Date: Tue Sep 17 20:10:12 2013 -0700 Internal branch sync. Included in this change: . File locking: tolerate another race in FileUnlockIntrinsic . Add util function for getting the epoch from a TimeUtil_Date . Add LRO defines for VMXNET3 . changes in shared code that don't affect open-vm-tools functionality Signed-off-by: Dmitry Torokhov commit 203ba46d6469894f2e92af3eb2c4edc03f01be09 Author: VMware, Inc <> Date: Tue Sep 17 20:09:38 2013 -0700 Changes in shared code that don't affect open-vm-tools functionality. Signed-off-by: Dmitry Torokhov commit 6a1997ee3179db62f8998f847291cfbaf19bf7c3 Author: VMware, Inc <> Date: Tue Sep 17 20:09:31 2013 -0700 HGFS: Fix Posix server from blocking on pipes The HGFS protocol function to get attributes of a file or folder does a Posix open without the O_NONBLOCK flag. This can cause the open to block if there isn't anyone on the other end of the pipe. Fix is to use the same flags we use for the protocol open to ensure the correct basic flags are used. Also, if the share is not allowed to follow symlinks we get this flag set correctly too now. Signed-off-by: Dmitry Torokhov commit ef2a0f5a022dac45b0e70007a23bce9b0b2a1741 Author: VMware, Inc <> Date: Tue Sep 17 20:09:08 2013 -0700 HGFS: Improve VMCI transport headers part I Begin to consolidate the client to server and server to client VMCI transport headers to be just one common header for both. Currently, there are two one for each direction and they are almost identical. Also the header for the client to the server does not have all information that is required for asynchronous packet sending and replies. Hence the motivation for improving this. The packet headers are poorly defined as they do not have any reserved fields for extending the current version and they are inconsistent with the packet types with each direction. This initial change pulls out the version and packet type into a header node that will be common to the version one and newer versions of the transport header. This involves modifying the server and client sides. The version 1 transport header will remain binary compatible with this change, it just moves the first two fields into a common substructure. Broke out the transport header to return the information from multiple versions of the header. Moved the validate datagram function call to the main receive message callback. Removed the transport header check from this function too, as it is not useful to have it there. It will be done by each of the specific header version handling routines. Signed-off-by: Dmitry Torokhov commit ee7f312e45adeec460f83b3de1ec0c44f88f6e82 Author: VMware, Inc <> Date: Wed Apr 17 14:42:21 2013 -0700 Updating open-vm-tools version for release 2013.04.16-1098359. Signed-off-by: Dmitry Torokhov 2013.04.16 Dmitry Torokhov This release tag contains commits up to the following id: 867ea989d5e6889abcac77b4c7dae7db2651df58 2012.12.26 Dmitry Torokhov This release tag contains commits up to the following id: 530ef7f26ed041ab1b6655f2cdc79f3af97fc50b 2012.10.14 Dmitry Torokhov This release tag contains commits up to the following id: d85408321c66c927bffdb05106a26581244edd4a 2012.05.21 Dmitry Torokhov This release tag contains commits up to the following id: 482332b8d4282df09838df5ea4c58df9cdb4faf3 2012.03.13 Dmitry Torokhov This release tag contains commits up to the following id: 0114aabd54bf2db4556563b7149c4fbbdec3d87b 2011.12.20 Marcelo Vanzin This release tag contains commits up to the following id: dfca5cf9d1c2335c5d001deedd9266c84956b508 2011.11.20 Marcelo Vanzin This release tag contains commits up to the following id: 6c197b8e5eccf32bfee0e2452d8926968182aada 2011.10.26 Marcelo Vanzin This release tag contains commits up to the following id: 6271fde90248a4fd49e38aa61498db9e1dbf37c3 2011.09.23 Marcelo Vanzin This release tag contains commits up to the following id: 05baddbed1c5e47e9789a44d30bb217d7184232a 2011.08.21 Marcelo Vanzin This release tag contains commits up to the following id: 2b3d76ba776f55d06fb5b62499b189ebd6bc1c75 2011.07.19 Marcelo Vanzin This release tag contains commits up to the following id: 5bed6f1369ca6e9c2c7fbaf4205d86e50f219c5f 2011.06.27 Marcelo Vanzin This release tag contains commits up to the following id: 166bbe1d28da4dab763b9568f163c8dca99ced9c 2011.05.27 Marcelo Vanzin This release tag contains commits up to the following id: 3793ddc9c9b5facf376a2625d4c2252aa9bd3daa 2011.04.25 Marcelo Vanzin This release tag contains commits up to the following id: 3112c27981074deb53e86e30e1c168d55e42220c 2011.03.28 Marcelo Vanzin This release tag contains commits up to the following id: ec43520f5f3a50f5a980a73d22ae231380f97555 2011.02.23 Marcelo Vanzin This release tag contains commits up to the following id: 96cf4718ac0aff1743e50a2165599306ba442fe1 2011.01.24 Marcelo Vanzin This release tag contains commits up to the following id: 60c470337c8932a6d9564130dcaf06c7a1a3df53 2010.12.19 Marcelo Vanzin This release tag contains commits up to the following id: 5aef2b20a519788613350752575bcba0ac71df79 2010.11.17 Marcelo Vanzin This release tag contains commits up to the following id: 11c0273ed4269f6f7a92f82f6c822df7da4c8720 2010.10.18 Marcelo Vanzin This release tag contains commits up to the following id: 2162c5d770cdac3b0e275907a1a5d22ece8ce23c 2010.09.19 Marcelo Vanzin This release tag contains commits up to the following id: c92a8bfbb406a906bcd2fb9ef6801f92c5b64d1f 2010.08.24 Marcelo Vanzin This release tag contains commits up to the following id: 94e63742d734b41638d37580602de4232da5ece6 2010.07.25 Marcelo Vanzin This release tag contains commits up to the following id: b15cffc7961b97129d0b77643db42b4d4d8e3da7 2010.06.16 Marcelo Vanzin This release tag contains commits up to the following id: ec87703fccdd0f954a118640c0b097e383994391 2010.04.25 Marcelo Vanzin This release tag contains commits up to the following id: 6fafd672e006208c1e479b297e19618170ff19bd 2010.03.20 Marcelo Vanzin This release tag contains commits up to the following id: 7cdbb623125729b41bf54068568dfbcc2dd58733 2010.02.23 Marcelo Vanzin This release tag contains commits up to the following id: 8baa8588d5fd4cf64efb17164cb70c86c758d0c6 2010.01.19 Marcelo Vanzin This release tag contains commits up to the following id: 8ee82a5774ae7badeb98ecf4dc629c7e9aac7077 2009.12.16 Marcelo Vanzin This release tag contains commits up to the following id: 0d28106da5684dc31ea52ebb5a2dc6a0af5c1d61 2009.11.16 Marcelo Vanzin This release tag contains commits up to the following id: 6f4cdd0f38be020d722f2393c0b78d7cd13f04d2 2009.10.15 Marcelo Vanzin This release tag contains commits up to the following id: d2f1b83daab1d7882fd651ad1cc77c729bbd9760 2009.09.18 Marcelo Vanzin This release tag contains commits up to the following id: 8bb94fbfbdf65b53b87279cf81529756dba7a2ca Other changes not captured in the git logs: * Resync with internal dev branch (2009.08.24) * hgfsmounter/hgfsmounter.c: allow hgfs users to set ttl to 0 at mount time. * lib/guestApp/guestApp.c, lib/include/conf.h, lib/include/netutil.h, lib/include/procMgr.h, lib/include/system.h, lib/vixTools/vixTools.c, lib/vmCheck/vmcheck.c: remove (now unused) Netware checks. * lib/message/*, modules/freebsd/vmhgfs/Makefile, modules/linux/vmhgfs/Makefile.*, modules/solaris/vmhgfs/Makefile: remove unused message transport abstraction. The rpcChannel library is now used to do RPC abstraction. * modules/*/vmmemctl/*: refactor of the vmmemctl module as part of adding support for Mac OS guests. * modules/linux/pvscsi/pvscsi.c: don't clobber RESERVATION_CONFLICT sdstat up from linux pvscsi driver. * modules/linux/shared/*: VMCI changes unrelated to the guest driver. * modules/linux/vmhgfs/fsutil.c, modules/linux/vmhgfs/inode.c: fix the case where two directories refer to the same inode. * scripts/linux/*: support older versions of NetworkManager. 2009-08-24 Marcelo Vanzin * Resync with internal trunk (2009.08.19) * configure.ac: remove support for Linux kernels < 2.6.9. * lib/include/vmtools.h, libvmtools/vmtoolsLog.c, doc/api/services/util.txt: add new log handled that allows appending to existing log files, and fix an issue where old log files would be "rotated" whenever the config file was reloaded. * lib/appUtil/appUtilX11.c, lib/ghIntegration/ghIntegrationX11.c, lib/include/appUtil.h: fix compilation issues on FreeBSD when unity was enabled. * lib/dnd/dndLinux.c, lib/include/vmblock_user.h, tests/testVmblock/*: add vmblock tests and, as part of the change, do some refactoring of vmblock related functions. * lib/guestInfo/guestInfo.c, lib/include/wiper.h, lib/wiper/*, toolbox/toolboxcmd-shrink.c, toolbox/toolboxShrink.c: refactor the wiper structures so that they behave the same on Win32 and other platforms, and also reuse data structures already in use by other parts of the code. This fixes an "use after free" issue that toolbox-cmd had on Win32. * lib/guestInfo/guestInfo.c, lib/guestInfo/guestInfoInt.h, lib/guestInfo/guestInfoPosix.c, lib/guestRpc/nicinfo.x, lib/include/guestInfo.h, lib/include/netutil.h, lib/include/slashProc.h, lib/netutil/netUtilLinux.c, lib/slashProc/*, services/plugins/guestInfo/guestInfoServer.c: add support for sending more network-related information to the host, such as routing tables and name servers. * lib/hgfsBd/hgfsBd.c: don't log RPC errors when HGFS is disabled. * lib/hgfsHelper/*, lib/include/hgfsHelper.h, lib/vixTools/vixTools.c: new library with functions to query information about HGFS; expose some HGFS properties through VIX. * lib/hgfsServer/*, lib/hgfsServerPolicyGuest/hgfsServerPolicyGuest.c, lib/include/hgfsServerPolicy.h: fix checking of whether an object belongs to a particular share; this was causing issues with invalid information being returned in certain cases. * lib/hgfsServer/*, lib/include/hgfsProto.h: changes to support new VIX API calls (mostly affecting Win32 only). * lib/include/guestCaps.h, lib/include/unityCommon.h: add boilerplate for new RPCs for setting windows as sticky / non-sticky (not yet implemented). * lib/include/hgfsProto.h: new definitions for the next version of the HGFS protocol. * lib/include/xdrutil.h: make XDRUTIL_ARRAYAPPEND() more type-safe when using GCC. * lib/misc/codesetOld.c: fix some issues with UTF16 -> UTF8 conversion. * lib/rpcChannel/rpcChannel.c, libvmtools/signalSource.c, libvmtools/vmtools.c, libvmtools/vmtoolsConfig.c: g_assert -> ASSERT. * lib/unityWindowTracker/unityWindowTracker.c: fix issue with z-ordering of modal dialogs. * libvmtools/vmtoolsConfig.c: fix some old config translation issues. * modules/freebsd/shared/*, modules/freebsd/vmblock/*: make vmblock work on FreeBSD 8. * modules/freebsd/vmmemctl/*, modules/linux/vmmemctl/*, modules/solaris/vmmemctl/*, : refactoring and code changes to support the driver on Mac OS X. * modules/linux/vmblock/*, modules/linux/vmci/*, modules/linux/vsock/linux/*: remove compatibility code for older kernels. * modules/linux/vmhgfs/*: fix memory leak in HgfsAccessInt(). * modules/linux/vmxnet3/*: fix kunmap usage in vmxnet3_shm, and reset the shared pages when the char device is closed. * modules/linux/vsock/linux/af_vsock.{c,h}, modules/linux/vsock/linux/util.c: add vsock protocol negotiation for notifyOn ops. This allows the driver to negotiate with the remove end which version of the notification protocol to use. * modules/linux/vsock/linux/notify.c, modules/linux/vsock/linux/notify.h, modules/linux/vsock/linux/notifyQState.c, modules/linux/vsock/linux/vsockPacket.h: add pktOn protocol. This new protocol improves performance by detecting changes in the queue state instead of sending WAITING_READ and WAITING_WRITE packets. * services/plugins/hgfsServer/hgfsPlugin.c, services/plugins/resolutionSet/resolutionSet.c, services/vmtoolsd/mainLoop.c, services/vmtoolsd/pluginMgr.c, services/vmtoolsd/toolsRpc.c: load plugins even when an RPC channel cannot be instantiated (i.e., when running outside of a virtual machine); this allows plugins to perform actions (at load time) also when running outside virtual machines (e.g., to undo some configuration done when the OS was run in a VM). * services/vmtoolsd/mainLoop.c, services/vmtoolsd/mainPosix.c, services/vmtoolsd/toolsCoreInt.h: handle SIGHUP differently; instead of stopping the service, just re-load the config data. This should make it easier to integrate the tools service with other tools such as logrotate. * toolbox/toolbox-cmd.c, toolbox/toolboxcmd-stat.c: remove memory info query, which didn't really return useful information. * vmware-user/copyPasteUI.cpp: if the clipboard/primary with most recent timestamp has no data on it, try the other before giving up during copy/paste. 2009-07-22 Marcelo Vanzin * Resync with internal trunk (2009.07.17) * configure.ac: fix detection of "dot" and its usage in the doxygen config file. * configure.ac, libguestlib/Makefile.am, libguestlib/vmguestlib.pc.in: install vmguestlib headers and add new pkgconfig script. * lib/dndGuest/dnd.{cc,hh}, lib/include/dndBase.h, vmware-user/dndUI.{cpp,h}: fix an issue where the DnD code would prevent drops to other windows in Unity mode, instead of just intercepting drops to the desktop. * lib/dndGuest/dnd.{cc,hh}, lib/dndGuest/dndRpc.hh, lib/dndGuest/dndRpcV3.cc, lib/include/dndBase.h, vmware-user/dndUI.{cpp,h}: fix an issue where the host Unity code would cause an undesired drop event. * lib/dndGuest/dnd.{cc,hh}, lib/dndGuest/dndRpc.hh, lib/dndGuest/dndRpcV3.cc, lib/include/dndBase.h: cleanup mouse simulation code, and fix an issue where a drag would be canceled if the contents were dragged out of a guest and then back in. * lib/dndGuest/dndRpcV3.cc, vmware-user/copyPasteDnDWrapper.cpp, vmware-user/dndUI.cpp, vmware-user/dndUI.h, vmware-user/dragDetWnd.cpp, vmware-user/dragDetWnd.h: several DnD fixes; make the DnD code behave more like other GTK applications (based on analysing the flow of signals on a test widget), and get rid of one of the detection windows, merging both the Unity and non-Unity windows. Also, some code refactoring. * lib/ghIntegration/*, lib/guestRpc/*, lib/include/guestCaps.h, lib/include/unityCommon.h: add stubs for a few new GHI functions (setting window focus, tray icon updates and enhanced app info) - currently only implemented on Win32. * lib/ghIntegration/ghIntegrationX11.c: examine WM_CLASS when determining which DE Tools are running in. The previous code was failing to show a few entries set as "OnlyShowIn=xxx" because checking WM_NAME wasn't enough to properly detect the desktop environment in certain cases. * lib/guestApp/guestAppPosixX11.c: use gconftool-2 to detect the user's browser, since gnome-open fails to open "file://" URLs which contain query strings. Also, use "kde-open" when running under KDE. * lib/guestInfo/guestInfo.c, lib/include/wiper.h, lib/wiper/wiperPosix.c: allow shrinking LVM partitions. * lib/include/appUtil.h: partial refactoring of icon retrieval code. * lib/include/dbllnklst.h, lib/misc/dbllnklst.c: inline linked list functions. * lib/include/guest_os.h, lib/misc/hostinfoPosix.c: add a couple of distros to the known distro list. * lib/include/netutil.h, lib/netUtil/netUtilLinux.c: add Linux interface name, index lookup routines. * lib/include/system.h, lib/system/systemLinux.c, services/plugins/timeSync/timeSync.c: fixes a few bugs in the backwards time sync code, mostly due to unit mismatches. * lib/include/unityWindowTracker.h, lib/unity/unity.c, lib/unity/unityPlatform.h, lib/unity/unityPlatformX11Window.c, lib/unityWindowTracker/unityWindowTracker.c: expose two new properties in the window tracker to save an RPC to retrieve those properties. * lib/include/vmtoolsApp.h, services/vmtoolsd/mainLoop.c, services/vmtoolsd/pluginMgr.c, services/vmtoolsd/toolsCoreInt.h: add support for "application providers", which allow plugins to add support to new kinds of application frameworks through vmtoolsd. * lib/unity/unityPlatformX11.c: only enable GIO channels when Unity is actually active. * lib/unity/*: cleanup old GTK1 code. * libvmtools/vmtoolsConfig.c: don't complain if config file is empty. * modules/linux/dkms.conf, modules/linux/dkms.sh: fix dkms.conf, and provide a script to create a dkms tree from open-vm-tools. * modules/linux/shared/vmci_queue_pair.h, modules/linux/vmci/vmciKernelIf.c: remove two (now) unneeded functions. * modules/linux/vmhgfs/*: code cleanups, properly initialize the list head, and allow receives to timeout so that hibernation works. * modules/linux/vmxnet/vmxnet.c, modules/linux/vmxnet3/vmxnet3_drv.c: fix drivers for kernels 2.6.29+. * modules/linux/vmxnet3/*: add shared memory support for faster communication between user space and the device backend; this doesn't affect the regular driver functionality, but is used by some VMware code not part of Tools. * modules/linux/vsock/*: fix an issue where it was possible for users to send VMCI datagrams directly to the hypervisor. * scripts/common/vmware-user.desktop: work around a bug in KDE where desktop files with "NoDisplay" fail to autostart. * scripts/freebsd/suspend-vm-default: use netif to bring down interfaces, since dhclient doesn't understand "-r" in the default install. * services/plugins/vmbackup/*: add some new code used by enhancements being done in the Win32 version of the plugin. * services/vmtoolsd/mainPosix.c: fix running in background when executing vmtoolsd while relying on PATH. * services/vmtoolsd/Makefile.am: point to the correct plugin install directory. * toolbox/*: better command line handling in the CLI utility, plus some code cleanup. * vmware-user/copyPaste.c, vmware-user/copyPasteDnDWrapper.cpp, vmware-user/copyPasteDnDWrapper.h, vmware-user/dnd.c: properly unregister RPCs to avoid multiple registrations (and the ensuing ASSERT) in certain cases. * vmware-user/copyPasteUI.{cpp,h}: change way data is retrieved from the clipboard, using the gtk+ clipboard wait APIs (which turn out to be more reliable than the previous approach). 2009-06-18 Marcelo Vanzin * Resync with internal trunk (2009.06.15) * docs/api/Makefile.am: replace all variables in the doxygen conf file with the correct values. * lib/appUtil/appUtilX11.c: try alternate file extensions during icon search. Sometimes a package lists its icon as icon-foo.png, but the package didn't include icon-foo.png. Instead, it included icon-foo.xpm. Ex: Ubuntu 8.04's hwtest. * lib/guestApp/guestAppPosixX11.c: change detection of the default browser so that the new help system works; the help files are not yet available in open-vm-tools. * lib/hgfs/*, lib/include/cpName.h, lib/include/cpNameLite.h, lib/include/hgfsUtil.h: avoid compiling certain parts of the source in kernel modules. * lib/hgfsServer/*: return correct error when files / directories don't exist. * lib/include/hgfsChannel.h, modules/linux/vmhgfs/*: added support for vsock channel for HGFS. * lib/include/util.h, lib/misc/utilMem.c: un-inline a bunch of functions to reduce the size of binaries. * lib/include/vm_tools_version.h: bumped Tools version. * lib/resolution/resolutionX11.c: fix for issue where the host would send a "topology set" command with a top-left corner that was not (0, 0) and cause the screen to be reconfigured in the wrong way. * lib/unity/unityPlatformX11Window.c: check for errors in calls to XQueryTree. * lib/wiper/wiperPosix.c: check return of fgets() to avoid compiler warnings. * libvmtools/vmtools.c: fix initialization of wiper library on Win32. * modules/Makefile.am: install vsock header file on Linux. * modules/freebsd/vmhgfs/*, modules/linux/vmci/*, modules/linux/vsock/*: changes related to 64-bit Mac drivers, don't affect either the FreeBSD or Linux drivers. * modules/linux/vmhgfs/hgfs.h: removed duplicate file. * modules/linux/vmhgfs/fsutil.c, modules/linux/vmhgfs/inode.c, modules/linux/vmhgfs/module.h: fix issue where two files would get the same inode number in some situations. * modules/linux/vmxnet/vmxnet.c: re-probe vmxnet2 device features on resume from hibernate, to cover the case where a VM is resumed on a platform with a different version of the device backend (bug #2209565). * scripts/resume-vm-default, scripts/suspend-vm-default: use NetworkManager to handle networking where it is available. * services/plugins/hgfsServer/Makefile.am, services/plugins/vix/Makefile.am: fix installation of vmusr plugins that are shared with vmsvc. * services/plugins/timeSync/timeSync.c: fix backwards time sync. * services/vmtoolsd/cmdLine.c, toolbox/toolbox-cmd.c: print build number as part of "-v" output. * toolbox/toolboxcmd-shrink.c: correctly ignore unsupported partitions when shrinking. * toolbox/toolbox-gtk.c: changes for the new help system, not yet available for open-vm-tools. * toolbox/toolboxInt.{c,h}, toolbox/toolboxScripts.c: some code refactoring. * vmware-user/Makefile.am: fix linking when compiling without gtkmm. 2009-05-22 Marcelo Vanzin * Resync with internal trunk (2009.05.18) * configure.ac, m4/vmtools.m4: check for PAM and enable PAM support when available. * configure.ac, services/plugins/*/Makefile.am, tests/*/Makefile.am: avoid the "-rpath" hack to create plugins, using plugin_LTLIBRARIES instead (and manually fixing things when necessary). Thanks to Dominique Leuenberger for the suggestion (and sample patch). * docs/api/Makefile.am: fix doc target directories. * configure.ac, lib/Makefile.am, lib/deployPkg/*, lib/include/deployPkg.h: remove the deployPkg code, which depends on some VMware code that is not yet open source. * lib/backdoor/*, lib/hgfs/*, lib/hgfsBd/*, lib/include/*, lib/include/compat/*, lib/message/*, lib/misc/dbllnklst.c, lib/rpcOut/rpcout.c: as part of sharing code between user-level code and kernel modules, some files have been tagged with more than one license. * lib/dndGuest/*, lib/include/dndBase.h, lib/include/dndMsg.h, lib/include/unity*, lib/unity/unityPlatformX11.c: implement mouse movement from within the guest; this avoids a dependency on "unofficial" mouse APIs in the VMware host code, making DnD more reliable, and makes a few things (such as cancelling an ongoing DnD operation) easier. * lib/file/filePosix.c: make File_FullPath()'s behavior consistent when the input path starts with a '/'. * lib/ghIntegration/ghIntegration.c: send more info about the "start menu" contents to the host (only usable for Windows guests). * lib/ghIntegration/ghIntegrationX11.c: prettify the category names of menu items. This is a temporary solution before actually reading this information from .desktop files. * lib/guestApp/guestApp.c, libguestlib/vmGuestLib.c, lib/include/guestApp.h, toolbox/toolbox-gtk.c, vmware-user/foreignVM*, vmware-user/vmware-user.cpp, configure.ac, lib/Makefile.am, lib/include/socketMgr.h, lib/socketMgr.*: remove code related to "foreign VM" support, which was never really used. * lib/guestInfo/guestInfo.c, lib/include/wiper.h, lib/wiper/wiperPosix.c: properly report disk info for LVM volumes. * lib/hgfsServer/hgfsDirNotify*, lib/hgfsServer/hgfsServer.c: add support for directory / file monitoring. It's currently only implemented on Mac OS X. * lib/hgfsServer/hgfsServer*: fix issue where it was possible to create a file on a read-only share on Windows hosts. * lib/hgfsServer/hgfsServer*, lib/hgfsServerManagerGuest/*, lib/include/hgfs*.h, services/plugins/hgfsServer/hgfsPlugin.c, services/plugins/vix/foundryToolsDaemon.c: some refactoring caused by the work to make HGFS support pluggable transports. * lib/include/procMgr.h, lib/procMgr/procMgrPosix.c: remove ProcMgr_GetAsyncStatus(). * lib/include/vmsupport.h, scripts/vm-support, xferlogs/xferlogs.c, services/plugins/guestInfo/guestInfoServer.c: new feature to automatically collect support data from the guest from the VMware UI. * lib/panicDefault/*, lib/user/*: change file names to avoid clash with another file (Mac OS linker doesn't really like that). * lib/rpcChannel/rpcChannel.c: try to reinitialize the outbound channel on failure. * lib/vixTools/vixTools.c, lib/include/vixCommands.h, lib/include/vixOpenSource.h: add backend for new VIX API call to list the guest's filesystems. * libvmtools/vmtoolsLog.c: lazily open the log file, instead of opening it during configuration of the log system. This way two processes can use the same conf file and not overwrite each other's log files (assuming the conf data is sane). * modules/Makefile.am, modules/linux/vmci/Makefile.kernel, modules/linux/vsock/Makefile.kernel: don't store VMCI module symbols in /tmp during build; this avoids a possible symlink attack that could cause data to be overwritten when building open-vm-tools. * modules/*/*, vmblock-fuse/*: remove a lot of duplicated files by either moving them to a shared location or reusing files that were already available elsewhere. * modules/freebsd/vmblock/subr.c, modules/freebsd/vmblock/vmblock_k.h, modules/freebsd/vmblock/vnoops.c: fix a possible kernel crash caused by trying to read / write to the mount point (something vmware-user does to detect whether it's using fuse or non-fuse vmblock). * modules/linux/pvscsi/*: adds support for a generic msg framework that is currently used to deliver hot-plug/unplug notifications; get rid of a few divisions; fix a bug where pvscsi_probe could return 0 (aka success) if a call to kmalloc() failed; remove a few unused fields. * modules/linux/shared/vmci*: mostly changes related to the host VMCI drivers (removed user-level queue-pair daemon, added support for trusted VMCI endpoints) to keep binary compatibility between the host and guest VMCI drivers. * modules/linux/hgfs/inode.c: check host's access rights when checking file permissions, so that permissions are correctly checked when the guest's user id is different from the host's user id. * modules/linux/bdhandler.*, modules/linux/filesystem.c; modules/linux/tcp.*, modules/linux/transport.*,: postpone opening the channels so that module can load successfully even if shared folders are disabled on the host; fix a synchronization problem between recv and close/open; allow hibernation to work by timing out the recv thread; correctly handle failures in recv, including injecting a dummy error to the pending requests when the recv thread exits; move the recv code to the channel's implementation so that it can be simpler. * modules/linux/vmxnet3/vmxnet3.c, modules/linux/shared/compat_pci.h: fix Wake-On-LAN for 2.6.27 and newer Linux guests. * modules/linux/vsock/linux/*: changes to support trusted VMCI host apps; pull out notification and stats logging code into their own files. * modules/solaris/vmhgfs/vnode.c: do not substitute errors returned by uiomove() calls with EIO, propagate returned error code (which is EFAULT) up the stack. * services/vmtoolsd/Makefile.am, scripts/common/linux/pam.d/vmtoolsd-x64, scripts/common/linux/pam.d/64/vmtoolsd: install the 64-bit PAM config file with the correct name. * services/plugins/powerOps/powerOps.c: fix running default scripts by making sure the path to the script is absolute. * services/vmtoolsd/Makefile.am, services/vmtoolsd/pluginMgr.c: use info from the configure step to define the plugin path; this avoids requiring a symlink to be placed in /etc/vmware-tools for vmtoolsd to be able to find the plugins. * services/vmtoolsd/toolsRpc.c: send the build information to the host so it's logged in the VM's logs. * toolbox/toolbox-cmd.c, toolbox/toolboxcmd-*, toolbox/toolboxCmdInt.h: make string comparison case-insensitive on Win32. * toolbox/toolboxcmd-shrink.c: properly finish the shrinking process by sending the "disk.shrink" RPC to the host. * toolbox/toolboxScripts.c: fix showing default settings for power ops scripts (should show default script enabled, not script disabled). * vmblock-fuse/Makefile.am: fix compilation on FreeBSD. * vmware-user/copyPasteUI.cpp: disallow copy-paste text of size greater than 4MB, instead of truncating the data. * vmware-user/dndUI.*, lib/dndGuest/dnd.cc, lib/include/dndBase.h: remove drag timeout callback (which was not needed), and add new signal to indicate that a GH DnD was cancelled. * vmware-user/Makefile.am: remove C++ link hack (not needed now since vmware-user has C++ code already). 2009-04-23 Marcelo Vanzin * Resync with internal trunk (2009.04.17) * configure.ac, Makefile.am, docs/*: build API docs for vmtools; the documentation files are provided under a BSD-style license. * configure.ac, Makefile.am, guestd/*, lib/Makefile.am, lib/guestInfo/*, lib/include/vmbackup_def.h, lib/include/vmBackup.h, lib/vmBackupLib/*, libvmtools/Makefile.am, services/plugins/vmbackup/vmbackup_def.h: remove guestd from open-vm-tools, and clean up code in other places that was only there because of guestd. * configure.ac, modules/solaris/vmblock/*, modules/solaris/vmmemctl/*: add Solaris vmblock and vmmemctl driver sources. The vmmemctl module also includes a user-level daemon (vmmemctld.c). * lib/conf/conf.c, lib/include/conf.h, libvmtools/vmtoolsConfig.c: remove unused config options. * lib/deployPkg/toolsDeployPkg.h: code refactoring. * lib/dnd/dndClipboard.c: if size of clipboard exceeds the maximum backdoor packet size, only keep text data (dropping the RTF data). * lib/dnd/dndLinux.c, lib/include/dnd.h, lib/include/vmblock.h, vmware-user/copyPaste.c, vmware-user/dnd.c, vmware-user/vmware-user.cpp, vmware-user/vmwareuserint.h, vmware-user-suid-wrapper/main.c: detect whether plain vmblock or vmblock-fuse is being used, allowing the same executable to be used with either. * lib/dndGuest/*, vmware-user/copyPaseDnDWrapper.{cpp,h}, vmware-user/dndUI.{cpp,h}, vmware-user/dragDetWnd.{cpp,h}: vmware-user/vmware-user.cpp: more DnD V3 protocol work. * lib/ghIntegration/*, lib/include/guestCaps.h, lib/include/unityCommon.h: work related to mapping Outlook folders over HGFS and exposing the Windows Recycle Bin to the host (doesn't really affect open-vm-tools). * lib/ghIntegration/ghIntegrationX11.c: restore the native environment when launching external applications. This doesn't really affect open-vm-tools. * lib/guestRpc/*, vmware-user/copyPasteUI.{cpp,h}: implement RTF and file contents copy & paste. * lib/include/circList.h, lib/include/vm_basic_math.h, lib/include/vm_device_version.h, modules/linux/*, modules/Makefile.am: changes to share files between the user space code and the kernel code, instead of duplicating the same source files in different places. * lib/include/rpcChannel.h, lib/rpcChannel/*, tests/testDebug/testDebug.c, test/vmrpcdbg/debugChannel.c: some code cleanup, and fix crash when dealing with multiple reset messages. * lib/include/system.h, lib/system/systemLinux.c, services/vmtoolsd/mainPosix.c: remove System_Daemon() (replaced with Hostinfo_Daemonize()). * lib/include/unityCommon.h, lib/unity/*: ressurrect UNITY_RPC_WINDOW_SHOW and UNITY_RPC_WINDOW_HIDE RPCs. * lib/procMgr/procMgrPosix.c: fix ProcMgr_IsProcessRunning(). * lib/system/systemLinux.c: fix shutdown / reboot commands on Solaris; fix rebuilding of native environment from variables set by VMware scripts (this last one doesn't really affect open-vm-tools). * lib/unicode/unicodeSimpleTypes.c: speed up UnicodeIANALookup, and fix case where C++ constructors could call UnicodeIANALookup before Unicode_Init() was called by lazily creating the internal cache. * libguestlib/*: link libguestlib against libvmtools. This avoids having two definitions of certain symbols (like Debug()) when an application links to both libraries. * modules/linux/vmblock/linux/control.c: only set directory entry owner when needed. * modules/linux/vmhgfs/bdhandler.{c,h}, modules/linux/vmhgfs/dir.c, modules/linux/vmhgfs/file.c, modules/linux/vmhgfs/filesystem.c, modules/linux/vmhgfs/fsutil.c, modules/linux/vmhgfs/inode.c, modules/linux/vmhgfs/module.{c,h}, modules/linux/vmhgfs/page.c, modules/linux/vmhgfs/request.{c,h}, modules/linux/vmhgfs/super.c, modules/linux/vmhgfs/tcp.{c,h}, modules/linux/vmhgfs/transport.{c,h}: cleanup use of atomic variables in HGFS; add a transport abstraction layer, and add an initial version of a socket-based transport (not yet stable and not yet supported by any released VMware product). * modules/linux/vmxnet3/vmxnet3.c: fix build on kernel 2.6.29. * modules/linux/vsock/af_vsock.c: export more functions to other kernel modules; some changes to statistics gathering code. * modules/solaris/vmhgfs/filesystem.c: make module loadable on Solaris 9. * modules/solaris/vmhgfs/vnode.c: unify mapping of HGFS to Solaris error codes. * scripts/*: restart network before running user scripts in resume scripts. * services/plugin/powerOps/powerOps.c: fix running default power scripts. * services/vmtoolsd/pluginMgr.c: better error logging. * toolbox/toolbox-cmd.c: fix help string. * vmblock-fuse/block.c: fix vmblock-fuse compilation on FreeBSD. 2009-03-18 Marcelo Vanzin * Resync with internal trunk (2009.03.13) * configure.ac: check for FreeBSD kernel tree when building modules; warn about which version of make to use when building kernel modules on FreeBSD and Solaris; add compiler defines for identifying Solaris 9 and 11. * configure.ac, modules/Makefile.am: handle SYSDIR on FreeBSD. * guestd/main.c, modules/solaris/vmhgfs/Makefile: remove HGFS-related that is now obsolete with the recent changes to the HGFS module on Solaris. * guestd/toolsDaemon.c: default to the configuration dir when the power script path is not absolute. * guestd/toolsDaemon.c, lib/include/guestInfo.h, lib/netUtil/netUtilLinux.c: handle case when all network interfaces have been disabled and send an "unknown" IP address to the host. * guestd/toolsDaemon.c, services/vmtoolsd/toolsRpc.c: always send TOOLS_VERSION_UNMANAGED from an open-vm-tools build, so there's no need for a config file option anymore. * hgfsclient/*: make it link to libvmtools to avoid code duplication. * lib/appUtil/appUtil.c: update list of "skippable" apps when figuring out an application's path. * lib/auth/authPosix.c, scripts/linux/pam.d/*, guestd/Makefile.am, services/vmtoolsd/Makefile.am : change the name of the PAM application to "vmtoolsd" to reflect the new service name. * lib/dnd/dndFileContentsUtil.h, lib/dnd/dndInt.h, lib/dndGuest/*.hh, and corresponding files in lib/include: relocate private headers. * lib/ghIntegration/ghIntegration.c, lib/ghIntegration/ghIntegrationInt.h, lib/ghIntegration/ghIntegrationX11.c, lib/include/unityCommon.h: glue code for Outlook mirrored folder, which does not affect open-vm-tools. * lib/guestRpc/guestlibV3.x, lib/include/vmGuestLib.h, libguestlib/vmGuestLib.c: add new guestlib counters. * lib/include/conf.h, toolbox/toolbox-gtk.c: remove the need for the "helpdir" config option; this doesn't really affect open-vm-tools since the help files are not yet included. * lib/include/guest_os.h, lib/misc/hostinfoPosix.c: more guest OS names; fix name used to identify Solaris to match what VMware's host code expects. * lib/include/guestStats.h: documentation changes. * lib/include/hostinfo.h, lib/user/hostinfoPosix.c: add a new function that behaves like daemon(3), but is more Mac OS-friendly. * lib/include/toolsLogger.h, lib/Makefile.am, lib/toolsLogger/*: removed library, which is not used anymore. * lib/include/vm_basic_types.h, lib/misc/timeutil.c: fixes to compile under (Open) Solaris 11. * lib/include/vmtoolsApp.h, services/plugins/vmbackup/stateMachine.c, services/vmtoolsd/mainLoop.c, services/vmtoolsd/mainPosix.c, services/vmtoolsd/serviceObj.c, services/vmtoolsd/toolsCoreInt.h: add new signal handler to gather debugging information from a running vmtoolsd instance. * lib/misc/posixPosix.c: fix off-by-one error. * lib/unity/unity.c, lib/unity/unityPlatform.h, lib/unity/unityPlatformX11.c, lib/unity/unityPlatformX11Settings.c: always send Unity updates using RPCI; this avoids a possible race between replying to an incoming RPC and sending an Unity update from a different thread; also, API documentation updates. * lib/unity/unityPlatformX11.c: verify the DnD detection window was initialized before actually using it. * lib/unity/unityPlatformX11Settings.c, lib/unity/unityPlatformX11Window.c: reset _NET_WM_DESKTOP as necessary before exiting Unity; this could cause guest taskbars to disappear when in Unity mode. * lib/unity/unityPlatformX11.c, lib/unity/unityPlatformX11Window.c, lib/unity/unityX11.h: examine WM_CLIENT_LEADER when gathering application information; certain applications use this property to define the window where the WM_COMMAND property should be. * lib/vixTools/vixTools.c: do not follow symlinks when deleting files in the guest using the VIX API. * libvmtools/vmtools.c, libvmtools/vmtoolsLog.c: allow the logging subsystem to be re-configured, and clean up the logging data when unloading the library; allow ${USER} and ${PID} to be used in log file paths. * modules/freebsd/vmblock/subr.c, modules/freebsd/vmblock/vnops.c: fix kernel panic on FreeBSD 7. * modules/linux/*/Makefile: remove GCC version check. * modules/linux/*/compat_wait.h: fix COMPAT_DEFINE_WAIT for "vanilla" 2.4 kernels. * modules/linux/vmhgfs/Makefile.normal: fix build of HGFS module on 2.4 kernels. * modules/linux/vmxnet/*, modules/linux/vmxnet3/*: avoid using compat functions when they're not needed; add compatibility functions for newer Linux kernels. * modules/linux/vsock/linux/af_vsock.c: fix two races; one when the socket state changed between calls to VSockVmciRecvStreamCB and VSockVmciRecvPktWork, and another when trying to read from the socket after a RST arrived after the socket got a detach notification. * modules/solaris/vmxnet3/*: add Solaris vmxnet3 driver. * rpctool/*: add "rpctool", a simple, stand-alone tool to send RPC commands to the host software. * services/plugins/guestInfo/guestInfoServer.c: don't cache configuration data. * services/plugins/guestInfo/perfMonLinux.c: fix problem with overwriting flags after GuestInfoMonitorReadMeminfo() was called. (Same as fix to lib/guestInfo on previous release.) * services/plugins/powerOps/powerOps.c: handle power ops-related options sent from the host. * services/vmtoolsd/mainLoop.c: handle re-loading the configuration file. * services/vmtoolsd/mainPosix.c: exec after forking on Mac OS, since CoreFoundation classes don't work after a fork. * services/vmtoolsd/pluginMgr.c: allow both 32 and 64 bit plugins to be installed on Solaris by loading them from the appropriate directory; add library loading code that is not really needed (nor used) in open-vm-tools. * services/vmtoolsd/toolsRpc.c: send another "capability" the host expects from Tools. * toolbox/toolbox-gtk.c: add F1 shortcut to invoke help. * toolbox/toolboxScripts.c: fix issue with freeing data that should not be freed. * vmware-user/*: implement the new DnD protocol (V3). 2009-02-18 Marcelo Vanzin * Resync with internal trunk (2009.02.13) * configure.ac, m4/vmtools.m4: clean up a lot of the library detection code. * configure.ac: remove support for gtk+ 1.2 (code already depended on it in any case); enforce need for glib 2.6.0 or later due to new code being added; add detection for gtkmm; check for C++ compiler when it's needed; reorder the include path to avoid clashing with system headers in some situations. * guestd/foundryToolsDaemon.*, vmware-user/foundryToolsDaemon.*, guestd/Makefile.am, vmware-user/Makefile.am: moved shared source files to a new place to avoid duplication. * hgfsmounter/hgfsmounter.c: add support for Solaris. * lib/appUtil/appUtilX11.c: fix loading of icons when the name has a period. * lib/dnd/dndClipboard.c, lib/dnd/dndInt.h, lib/dnd/dndMsg.c, lib/dnd/Makefile.am, lib/dndGuest/*, lib/include/copyPasteBase.h, lib/include/copyPaste.hh, lib/include/copyPasteRpc.hh, lib/include/copyPasteRpcV3.hh, lib/include/dndBase.h, lib/include/dndClipboard.h, lib/include/dndFileContentsUtil.h, lib/include/dndFileList.hh, lib/include/dnd.h, lib/include/dnd.hh, lib/include/dndInt.h, lib/include/dndMsg.h, lib/include/dndRpc.hh, lib/include/dndRpcV3.hh, lib/include/dndTransportGuestRpc.hh, lib/include/dndTransport.hh, lib/include/libExport.hh, vmware-user/copyPaste.cpp, vmware-user/copyPasteUI.{cpp,h}, vmware-user/copyPasteV3.h, vmware-user/copyPasteWrapper.{cpp,h}, vmware-user/dnd.cpp, vmware-user/Makefile.am, vmware-user/vmware-user.{c,cpp}, vmware-user/vmwareuserInt.h, vmware-user/stringxx/string.{cc,hh}, vmware-user/stringxx/ubstr_t.hh: add support for new version of the DnD protocol. * lib/guestInfo/guestInfoPerfMonLinux.c: fix problem with overwriting flags after GuestInfoMonitorReadMeminfo() was called. * lib/guestRpc/guestlibV3.x, lib/include/vmGuestLib.h, libguestlib/vmGuestLib.c: add new host stats. * lib/guestRpc/Makefile.am: fix a few compatibility issues with non-GNU versions of make. * lib/hgfsServer/hgfsServer.c, lib/hgfsServer/hgfsServerInt.h, lib/hgfsServer/hgfsServerLinux.c, */hgfsProto.h, modules/freebsd/vmhgfs/vnops.c, modules/freebsd/vmhgfs/vnopscommon.{c,h}: don't trust the local VFS layer, check the HGFS server to see if an operation would succeed. * lib/include/rpcChannel.h, lib/rpcChannel/*: add new Guest RPC channel abstraction library used by the new "core services" code. * lib/include/vmrpcdbg.h, tests/*: add test code from the "core services" project. * lib/include/vmtoolsApp.h, lib/include/vmtoolsd_version.h, services/vmtoolsd/*: add "vmtoolsd", the new service "shell" used in the "core services" project. * lib/unity/unityPlatformX11Window.c: don't send initial "region" updates for shaped windows. This works around an issue where resizing a shaped window would not work as expected in Unity mode. * lib/wiper/wiperPosix.c: fix major number detection for disks on newer Linux kernels. * libvmtools/Makefile.am: link more libraries needed by vmtoolsd and the new plugins. * modules/linux/pvscsi/pvscsi.c, modules/linux/pvscsi/pvscsi_version.h: use PCI-specific memory allocation functions and update driver version. * modules/linux/vmci/vmciKernelIf.c: disable queue pair support in the host version of the driver on older Linux kernels. This doesn't affect the guest driver. * modules/linux/vmci/vmci_queue_pair.h: implement MSG_PEEK support on Linux driver. * modules/linux/vmhgfs/bdhandler.c, modules/linux/vmhgfs/compat_sched.h, modules/linux/vmmemctl/os.c: fix issue with HGFS module interfering with suspend / hibernation on newer Linux kernels (bug #2523263). * modules/linux/vmhgfs/compat_cred.h, modules/linux/vmhgfs/file.c, modules/linux/vmhgfs/filesystem.c, modules/linux/vmhgfs/inode.c: changes for compatibility with newer Linux kernels, where it's not possible to change fsuid/capabilities directly anymore. * modules/linux/vmhgfs/compat_pagemap.h, modules/linux/vmhgfs/page.c: fix warning, and compatibility changes for newer Linux kernels (2.6.28.1 and newer; bug #2530616). * modules/linux/vmhgfs/inode.c: fix creation of symlinks (bug #2531303). * modules/linux/vmxnet/vmxnet.c: use PCI-specific memory allocation functions. * modules/linux/vmxnet/vmxnet.c, modules/linux/vmxnet3/vmxnet3.c: add option to disable LRO. * modules/linux/vsock/af_inet.{c,h}, modules/linux/vsock/util.{c,h}: add MSG_PEEK support; remove ifdefs that were disabling support for queue pairs on the host kernel module; fix compilation with certain versions of gcc (bug #2531283). * modules/solaris/vmhgfs/*: move backdoor handling code to the HGFS driver; this makes the user-level code to handle the driver (currently in vmware-guestd) obsolete. * modules/solaris/vmxnet/*: add vmxnet driver for Solaris, under the CDDL. * services/plugins/*: add all currently available "core services" plugins. The current set of plugins provide the functionality available in vmware-guestd; there are a few plugins that replace functionality from vmware-user, but not all features are ported yet (and vmtoolsd - with vmware-user plugins - and vmware-user cannot run at the same time). * toolbox/toolboxAbout.c: fix the copyright character. * toolbox/toolbox-cmd.c: reword a few messages, fix typos. * toolbox/toolboxCmdInt.h, toolbox/toolboxcmd-record.c, toolbox/toolbox-gtk.c, toolbox/toolboxRecord.c: remove the "record" functionality from tools (due to internal request). * toolbox/toolboxInt.c, toolbox/toolboxScripts.c, toolbox/toolbox-scripts.c: changes to use the new config file format used by the "core services" code. * */Makefile.am: make sure 'rm' and 'mv' are being used instead of $(RM) and $(MV) (which are not defined by automake; bug #2492040). 2009-01-21 Marcelo Vanzin * Resync with internal trunk (2009.01.19) * configure.ac: detect the presence of FUSE libraries. * configure.ac, Makefile.am: compile kernel modules for Solaris, and vmblock-fuse module if FUSE is available. * lib/ghIntegration/ghIntegrationX11.c: retrieved localized application names. * lib/guestInfo/guestInfo.c, lib/guestInfo/guestInfoPosix.c, lib/include/hostinfo.h, lib/misc/hostinfo_misc.c, lib/misc/hostinfoPosic.c, lib/vixTools/vixTools.c: refactoring to move code shared with other VMware products to a common library. * lib/guestRpc/guestlibV3.x, lib/guestRpc/Makefile.am, lib/include/vmGuestLib.h, libguestlib/*: add new iteration of the "guestlib" protocol. This is a more extensible solution than the current protocol, and should make it easier to add new information when needed. * lib/include/dynarray.h, lib/include/dynbuf.h, lib/misc/dynarray.c, lib/misc/dynbuf.c: make some DynArray/DynBuf functions inline for speed. * lib/include/unityCommon.h: more documentation about the Unity protocol. * lib/unity/unityPlatformX11.c: fix Unity<->guest desktop ID mappings. * libvmtools/vmtoolsLog.c: change the way log domains are configured; now sub-domains inherit the default handler for the app if no handler is specified. * modules/freebsd/vmhgfs/state.c, modules/freebsd/vmhgfs/state.h, modules/freebsd/vmhgfs/vnopscommon.{c,h}: implement support for mmap on the Mac OS driver, which allows running executables from an HGFS share. The FreeBSD module still does not support this functionality. * modules/freebsd/vmhgfs/transport.{c,h}: refactoring for sharing structure definitions. * modules/linux/pvscsi/pvscsi.c, modules/linux/vmblock/linux/module.c, modules/linux/vmci/vmci_drv.c, modules/linux/hgfs/module.c, modules/linux/vmmemctl/os.c, modules/linux/vmsync/sync.c, modules/linux/vmxnet/vmxnet.c, modules/linux/vmxnet3/vmxnet3.c: add support for Novell's proprietary module info tag ("supported"). * modules/linux/vmci/vmciKernelIf.c: add support for VMCI queue pairs on the host. This does not affect the driver when it runs inside virtual machines. * modules/linux/vmci/*.h, modules/linux/vsock/*.h: some changes in the common code to support Mac OS X, and also queue pairs on the Solaris VMCI module. * modules/linux/vsock/af_vsock.{c,h}: add functions for registering with the vsock driver from within the kernel. * modules/linux/*/Makefile: add $(LINUXINCLUDE) to the compiler flags; this allows compiling the modules against recent kernels which removed that from $(KBUILD_CPPFLAGS). * modules/Makefile.am: add support for compiling Solaris kernel modules. * modules/solaris/vmhgfs/*: initial release of the Solaris HGFS driver in open-vm-tools. Driver is licensed under the CDDL 1.0. * vmblock-fuse/*: add the user-level implementation of the vmblock driver, which is build on top of FUSE, to open-vm-tools. vmware-user hasn't yet been modified to use this version of vmblock. * vmware-user/copyPaseV3.h: new header introduced during development of the next version of copy paste / DnD for X11 platforms. 2008-11-23 Marcelo Vanzin * Resync with internal trunk (2008.12.19) * configure.ac, */Makefile.am: standardize on using libtool archives for the libraries. This also means several makefiles were removed, since there's no need to build two archives of the same library anymore. * configure.ac: add logic to detect glib 2.6; this is the minimum version required by the "Core Services" project. Currently it's an optional dependency. * configure.ac: disable Unity when user specifies --disable-multimon. * configure.ac: actually build the pvscsi modules if the detected kernel version supports it. * configure.ac, Makefile.am, lib/guestInfo/Makefile.am, lib/stubs/Makefile.am, libvmtools/*, lib/include/vmtools.h: add the "vmtools" shared library used in the "Core Services" project. The library is a collection of a lot of other libraries used by most VMware Tools programs, and adds some functionality on top of glib that is used in the "Core Services" project. Currently no other components from that project are available as part of open-vm-tools. * lib/deployPkg/deployPkgLog.h, lib/deployPkg/toolsDeployPkg.h: moved private headers out of the public header directory. * lib/guestRpc/Makefile.am, modules/Makefile.am: fix the makefiles so that it's possible to build open-vm-tools from a directory different from the source dir. * lib/hgfsServer/hgfsServer.c: changes to support aliases on Mac OS hosts. * lib/hgfsServer/hgfsServerLinux.c: changes to map Windows attributes to Mac OS FileInfo. * lib/include/circList.h: removed unused file. * lib/include/unityCommon.h, lib/unity/unity.c: changes to add documentation to various application RPCs used in Tools. * lib/misc/posixPosix.c, toolbox/toolboxScripts.c: fix include path for syslimits.h on FreeBSD. * lib/unity/unityPlatformX11.c: better detection of the guest's work area boundaries; fixes a problem when dragging a Window in Unity mode with the host's task bar on the left/right of screen would result in weird behavior. * lib/unity/unityPlatformX11Settings.c, lib/unity/unityPlatformX11Window.c, lib/unity/unityX11.h: preserve the _NET_WM_DESKTOP setting when hiding windows; this fixes a problem where hiding a panel and later restoring it would result in the wrong _NET_WM_DESKTOP property being set for the panel, causing it to only display on the first virtual desktop. * modules/linux/vmci/*: minor changes related to internal development of the Mac OS drivers. * modules/linux/vmhgfs/page.c: fix HGFS driver for kernel 2.6.28. * modules/linux/vsock/linux/af_vsock.c: added code to gather some performance statistics for the driver. * toolbox/toolbox-gtk.c: a few fixes to the help functionality. * vmware-user/vmware-user.c, vmware-user-suid-wrapper/main.c: change the "blockFd" argument to have an extra dash so it follows the convention of common command line parsing libraries. * Other bug fixes and changes in shared code that don't affect open-vm-tools. 2008-11-18 Marcelo Vanzin * Resync with internal trunk (2008.11.14) * lib/include/vm_version.h: Bumped TOOLS_VERSION. * guestd/toolsDaemon.c, lib/include/vm_app.h: changes related to host-side configuration of power operations. * hgfsclient/hgfsclient.c, lib/dnd/dndCommon.c, lib/dnd/dndLinux.c, lib/hgfs/*, lib/hgfsServer/*, lib/include/cpName.h, lib/include/dnd.h, lib/include/hgfsEscape.h, lib/include/staticEscape.h, modules/*/vmhgfs/*, vmware-user/dnd.c: refactor the HGFS character escaping code; escape invalid characters when the sender allows characters in the file name that the receiver does not allow. * lib/hgfsServer/hgfsServerLinux.c: return proper error code when the remote path points to a non-existent directory. * lib/deployPkg/deployPkg.c, lib/deployPkg/deployPkgLog.c, lib/include/deployPkg.h, lib/include/rpcin.h, lib/rpcin/rpcin.c: refactoring for the Tools Core Services project. * lib/dnd/dndCommon.c: don't ASSERT if the staging directory is not actually a directory. * lib/dynxdr/xdrutil.c, lib/include/xdrutil.h: more XDR-related utility functions. * lib/file/file.c, lib/file/fileLockPrimitive.c, lib/include/vm_basic_defs.h: replace use of strtok with strtok_r. * lib/guestApp/guestApp.c, lib/include/guestApp.h: more utility functions. * lib/guestApp/guestApp.c, lib/include/backdoor_def.h, vmware-user/pointer.c: add the ability to detect whether the mouse hardware can be used in absolute mode, which allows for auto grab / auto ungrab to work. * lib/guestInfo/guestInfo.c, lib/guestInfo/guestInfoPosix.c, lib/guestRpc/nicinfo.x: provide the prefix length of an IPv6 address in a separate field of the NicInfo struct. * lib/guestInfo/guestInfoPerfMonLinux.c: reduce log spew. * lib/guestInfo/guestInfoServer.c, lib/include/guestInfo.h: changes related to how the VMware code in the host handles Tools version information. * lib/include/unityCommon.h: changes related to documenting the Unity API. * lib/include/unity.h, lib/unity/*: remove a few unused RPCs, add a new function used to notify the host of the status of Unity. * modules/freebsd/vmhgfs/state.c, modules/vmhgfs/freebsd/vnops.c, modules/vmhgfs/freebsd/vnopscommon.*: support symlinks on FreeBSD and Mac OS. * modules/freebsd/vmhgfs/worker.c: fix mutex not being unlocked in some error paths. * modules/linux/dkms.conf: add rudimentary dkms support. * modules/linux/pvscsi/*: add a driver for VMware's paravirtualized SCSI device. * modules/linux/*/Makefile, modules/linux/vmci/Makefile.kernel, modules/linux/vsock/Makefile.kernel: add support for exporing symbols, needed for dependent modules to load if a kernel >= 2.6.26 is compiled with CONFIG_MODVERSIONS. Make the vsock module reference the vmci module's symbols. * modules/vmmemctl/freebsd/os.c: add sysctl to get driver status. Information can be retrieved with "sysctl vm.vmmemctl". * modules/linux/vmci/vmci_defs.h, modules/linux/vmci/vmci_call_defs.h, modules/linux/vsock/vmciHostKernelAPI.h: changes related to VMCI work on VMware ESX. * modules/linux/vsock/linux/*: improve performance of some applications by improving the poll behavior and sending less packets when waiting for a response. * modules/linux/vmsnc/sync.c: fix panic on kernels < 2.6.20. * modules/linux/vmxnet3/vmxnet3.c, modules/linux/vmxnet3/vmxnet3_int.h, modules/linux/vmxnet3/vmxnet3_version.h: inherit net device features to avoid having the kernel setting the PSH flag on every TCP packet (among other issues). * modules/*/*/*: Reflected changes from elsewhere. * scripts/common/vmware-user.desktop: add missing "Type" information; fixes auto-start of vmware-user on Ubuntu 8.10. * toolbox/*: fix a GTK+ warning caused when trying to unref a dialog instance from a signal callback. * vmware-user/copyPaste.c: work around an issue when OpenOffice's "cut" command is used; it sets the timestamp of both the clipboard and the primary selection, but only puts data in the clipboard. * Other files: minor refactorings, and changes unrelated to open-vm-tools. 2008-10-13 Adar Dembo * Resync with internal trunk (2008.10.09) * configure.ac, modules/Makefile.am: Added a command-line option to skip privileged operations during make install (requested by Dennis Leroy). Integrated new vmxnet3 kernel module. * configure.ac, lib/guestInfo/Makefile.am, lib/guestInfo/guestInfoPerfMonLinux.c, lib/include/vm_procps.h: Removed open-vm-tools dependency on libproc-dev by providing some procps bits and pieces in our own vm_procps.h (Sourceforge bug 1960947). * hgfsmounter/Makefile.am: Removed chown calls. Only call chmod if we're running as root (requested by Dennis Leroy). * */foreignVMToolsDaemon.c, */foundryToolsDaemon.[ch], lib/guestInfo/guestInfo.c, lib/guestInfo/guestInfoServer.c, lib/include/guestInfoServer.h, lib/include/vixTools.h, lib/rpcin/rpcin.c, lib/vixTools/vixTools.c, vmware-user/copyPaste.c, vmware-user/vmware-user.c: More refactoring from the Tools core services project. * */foundryToolsDaemon.c: Changed HGFS mounting behavior such that the global HGFS share is mounted at /mnt/hgfs instead of relying on "mount -a". * guestd/toolsDaemon.[ch], lib/include/backdoor_def.h, lib/include/system.h, lib/include/vm_app.h, lib/system/systemLinux.c: Added backwards time synchronization functionality. Moved Tools scripts checking from VMX to guestd. * hgfsmounter/hgfsmounter.c: Added handling for multiple "-o" flags on the command line. * lib/dynxdr/dynxdr.c: Fixed x_putint32 behavior on 64-bit Solaris. * lib/file/*, lib/include/codeset.h, lib/include/file.h, lib/include/fileIO.h, lib/include/hostinfo.h, lib/include/loglevel_user.h, lib/include/productState.h, lib/include/timeutil.h, lib/include/unicodeTypes.h, lib/include/vixCommands.h, lib/include/vix.h, lib/include/vm_basic_asm.h, lib/include/vm_basic_types.h, lib/include/vm_legal.h, lib/include/vm_product.h, lib/include/win32util.h, lib/include/x86cpuid.h, lib/misc/codeset.c, lib/misc/codesetOld.[ch], lib/misc/posixPosix.c, lib/misc/timeutil.c, lib/region/region.c, lib/string/bsd_vsnprintf.c, lib/unicode/*, lib/user/hostinfoPosix.c, modules/freebsd/vmhgfs/sha1.c, modules/*/*/vm_device_version.h, modules/linux/*/vmci_iocontrols.h, modules/linux/*/vmci_version.h, modules/linux/vmhgfs/hgfsEscape.h: Changes from work unrelated to open-vm-tools on internal trunk. * lib/ghIntegration/ghIntegrationX11.c: Fixed some bugs in menu-spec and desktop-entry-spec support in Linux guests. * lib/guestApp/guestApp.c, lib/include/guestApp.h, lib/include/statelogger_backdoor_def.h, toolbox/Makefile.am, toolbox/toolbox-cmd.c, toolbox/toolbox-gtk.c, toolbox/toolboxCmdInt.h, toolbox/toolboxGtkInt.h, toolbox/toolboxInt.h, toolbox/toolboxRecord.c, toolbox/toolboxcmd-record.c: Patches from Yiwen Zhang to add basic record/replay controls to the gtk and command-line toolbox apps. * lib/guestInfo/guestInfoPosix.c: Fixed a bug where we assumed the primary interface's addresses were all IPv4 addresses. * lib/guestInfo/guestInfoServer.c: Fixed a memory leak. * lib/guestRpc/Makefile.am, lib/guestRpc/unityActive.x, lib/include/guestCaps.h, lib/include/unityCommon.h, lib/unity/unity.c, vmware-user/Makefile.am: Added new unityActive xdr protocol, used for tracking whether Unity is enabled or not. * lib/hgfsServer/hgfsServer.c, lib/hgfsServer/hgfsServerLinux.c, lib/hgfsServerPolicyGuest/hgfsServerPolicyGuest.c, lib/include/hgfsProto.h: Fixed bug where we were invalidating HGFS handles on the share of entire drive ("/"). Added optional symlink following behavior to HGFS server. Fixed a UTF-8 validation issue. Added volume ID field to attribute fields. * lib/include/vm_tools_version.h: Bumped internal Tools backdoor version. * lib/include/vm_version.h: Bumped TOOLS_VERSION. * lib/procMgr/progMgrPosix.c: Fixed impersonation behavior so that uids are passed to setresuid instead of gids. Added alternate way to list processes in situations where a process lacks a command line. * lib/region/region.c: Reforked xorg miregion.c and apply open-vm-tools specific patches. * lib/unity/*, lib/unityWindowTracker/unityWindowTracker.c: Fixed an overflow that lead to a panic when a window title exceeded 1024 bytes. Fixed some initialization assumptions when using virtual desktops. * lib/unity/unityPlatformX11Window.c: Fixed an issue with restacking windows above non-existent windows. Other minor fixes. * modules/*/*/*: Reflected changes from elsewhere. * modules/linux/*/Makefile.kernel: Changed clean target to remove Module.markers and modules.order. * modules/linux/vsock/include/compat_sock.h, modules/linux/vsock/*: Fixed several issues in vsock. 2008-09-03 Adar Dembo * Resync with internal trunk (2008.08.29) * Makefile.am, aclocal.m4, m4/*: Moved macros to 'm4' subdir. * compile, config.guess, config.sub, config/*, depcomp, install-sh, ltmain.sh, missing: Moved auxiliary build tools to 'config' subdir. * configure.ac: Moved macros and auxiliary build tools into separate subdirectories. Added command line option to force the use of gtk1 over gtk2. Cosmetic fixes. Reworked libicu detection. Switched over to libtool-2.2. Added library check for new gdk symbol. Added library check for libnotify. Reworked use of macros from AC_PATH_XTRA and some X11 library checks. * */foundryToolsDaemon.c, toolbox/toolbox-cmd.c, guestd/main.c, lib/guestInfo/guestInfoPerfMonLinux.c, lib/guestInfo/guestInfoPosix.c, lib/misc/posixPosix.c, lib/panic/panic.c, lib/system/systemLinux.c, modules/linux/vsock/linux/util.c, xferlogs/xferlogs.c: Added checks for return codes of certain functions and passed %s to formatted string functions where appropriate (needed to compile on Ubuntu Intrepid). * lib/appUtil/appUtilX11.c: Fixed command line skipping logic and added more icon paths. Removed unnecessary chdir(2) canonicalization logic. * lib/deployPkg/runDeployPkgPosix.c, lib/file/fileIO.c, lib/file/fileIOPosix.c, lib/file/fileLockPrimitive.c, lib/file/filePosix.c, lib/hgfsServer/hgfsServerLinux.c, lib/include/bsdfmt.h, lib/include/file.h, lib/include/fileIO.h, lib/include/iovector.h, lib/include/msgfmt.h, lib/include/str.h, lib/include/vm_basic_defs.h, lib/include/vm_basic_types.h, lib/misc/hostname.c, lib/misc/idLinux.c, lib/misc/posixPosix.c, lib/SLPv2Parser/*.c, lib/wiper/wiperPosix.c, toolbox/toolboxScripts.c: Added FreeBSD compatibility glue. * guestd/toolsDaemon.c, lib/file/file.c, lib/foundryMsg/foundryPropertyListCommon.c, lib/image/imageUtilPng.c, lib/include/appUtil.h, lib/include/backdoor_def.h, lib/include/conf.h, lib/include/cpuid_info.h, lib/include/guest_os.h, lib/include/hostinfo.h, lib/include/imageUtil.h, lib/include/imageUtilTypes.h, lib/include/log.h, lib/include/loglevel_user.h, lib/include/netutil.h, lib/include/posix.h, lib/include/timeutil.h, lib/include/util.h, lib/include/uuid.h, lib/include/vix.h, lib/include/vixOpenSource.h, lib/include/vm_atomic.h, lib/include/vm_legal.h, lib/include/vm_version.h, lib/include/x86cpuid.h, lib/misc/codesetOld.c, lib/misc/timeutil.c, lib/string/bsd_vsnprintf.c, lib/user/util.c, lib/user/utilPosix.c, lib/vixTools/vixTools.c, modules/linux/*/vmci_kernel_if.h, modules/linux/vmxnet/compat_timer.h, toolbox/toolboxCmdInt.h, toolbox/toolboxcmd-*.c: Changes from work unrelated to open-vm-tools on internal trunk. * lib/ghIntegration/ghIntegration.c, lib/guestRpc/ghiGetBinaryHandlers.x: Don't send oversized messages. Increased maximum number of binary handlers. * lib/ghIntegration/ghIntegrationX11.c, lib/guestApp/guestAppPosix.c, lib/include/guestApp.h, lib/include/system.h, lib/system/systemLinux.c, toolbox/toolbox-gtk.c: Improved "run program" functionality by restoring program environment and stripping any VMware wrapper script changes to LD_LIBRARY_PATH. * lib/guestApp/guestAppPosixX11.c: Now using glib to open URLs instead of system(3). Improved gnome and kde session detection. * lib/guestApp/Makefile.am: This library needed GTK_CPPFLAGS too. * lib/guestInfo/guestInfoInt.h, lib/guestInfo/guestInfoPosix.c, lib/guestInfo/guestInfoServer.c: Added logic to optionally convert subnet mask to an ASCII string. * lib/guestRpc/Makefile.am: Cleaned up generated xdr headers better. * lib/hgfsServer/hgfsServer.c, lib/hgfsServer/hgfsServerInt.h, lib/hgfsServer/hgfsServerLinux.c: Fixed problems when packing V3 replies. * lib/hgfsServer/hgfsServerLinux.c: Fixed UTF-8 normal form D/C conversions on the root directory. * lib/include/dndGuest.h: Changed preprocessor usage to allow gtk1 to access UnityDnD. * lib/include/dnd.h, vmware-user/copyPaste.c: Code motion. * lib/include/guestCaps.h: Resort the capabilities table. * lib/include/rpcin.h, lib/rpcIn/rpcin.c, : Beginnings of the Tools core services. This is a full-fledged refactoring of the Tools userlevel apps to a "service" vs. "plugin" programming model. * lib/include/vmblock.h, modules/*/vmblock/block.c, modules/*/vmblock/stubs.c, modules/*/vmblock/stubs.h: Changes needed to support the fuse-based implementation of vmblock (coming soon). * lib/include/vm_tools_version.h: Some Tools version bumps. * modules/*/*/*: Reflected changes from elsewhere. * modules/*/*/compat/compat_stdarg.h: Added compatibility wrappers for stdarg features. * modules/freebsd/vmhgfs/debug.*: Cosmetic fixes. * modules/freebsd/vmhgfs/*: Make driver compliant with HGFSv3. * modules/*/vmmemctl/vmballoon.c: Allow module to yield the processor when allocating many pages. * modules/linux/*/autoconf/cachector1.c, modules/linux/*/include/compat_sched.h, modules/linux/*/include/compat_semaphore.h, modules/linux/*/include/compat_slab.h, modules/linux/vmblock/linux/filesystem.c, modules/linux/*/Makefile.kernel, modules/linux/vmhgfs/bdhandler.c, modules/linux/vmhgfs/filesystem.c, modules/linux/vmhgfs/module.h, modules/linux/vmhgfs/request.c, modules/linux/vmsync/sync.c, modules/linux/vsock/linux/af_vsock.c: Fix modules for 2.6.27 kernels. * modules/linux/*/Makefile: Fixed DRIVER target. * modules/linux/vmci/vmci_drv.c: Moved interrupt registration to be after driver initialization. * modules/linux/vsock/linux/af_vsock.c, modules/linux/vsock/linux/af_vsock.c: Added optimized flow control protocol. * toolbox/toolboxScripts.c, toolbox/toolboxShrink.c: Cosmetic fixes. * vmware-user/copyPaste.c, vmware-user/dnd.c: Fixed edge case behavior with file copy paste and DnD. * vmware-user/modconfig.c, vmware-user/notify.c, vmware-user/vmware-user.c, vmware-user/vmwareuserInt.h: Added stubbed modconfig module out-of-date notification framework. Not useful for open-vm-tools, hence the stubs. 2008-08-08 Adar Dembo * Resync with internal trunk (2008.07.24) * configure.ac, */Makefile.am: Landed support for command line Toolbox, Unity, vsock, and vmci. Refactored and reformatted a few things. Improved portability by using $(SED) and AC_PROG_SED instead of "sed", $(MKDIR_P) and AC_PROG_MKDIR_P instead of "mkdir -p", $(LN_S) and AC_PROG_LN_S instead of "ln -s". Changed icu feature detection and linking to rely on C++ linker instead of C linker. Fixed module compilation checks on FreeBSD. Fixed $(DESTDIR) handling (patch by Mike Auty). Refactored lib/strUtil into lib/misc. Changed hgfsmounter install hook to symlink mount.vmhgfs. Renamed libghIntegrationStub to libGhIntegrationStub. Fixed compilation of lib/guestApp when using --without-x (reported by Martin Preishuber). Renamed libunityStub to libUnityStub. Fix build on FreeBSD by using ":=" instead of "=" when exporting module directories. The vmware-user desktop link now executes vmware-user-suid-wrapper. Properly install vmware-user-suid-wrapper. * */foundryToolsDaemon.c, lib/vixTools/vixTools.c: Use a larger result packet when handling impersonated HGFS requests (since HGFSv3 uses larger packets). * guestd/main.c: Moved foreign VM check. * guestd/toolsDaemon.*: Added plumbing for HGFS usability library calls. * hgfsmounter/hgfsmounter.c: Added support for passing options to the MacOS HGFS driver. * lib/appUtil/*, lib/include/appUtil.h: New library for Unity support. * lib/auth/authPosix.c: Don't try using PAM from the Tools. * lib/dnd/dndCommon.c, lib/dnd/dndLinux.c, lib/file/file.c, lib/file/fileIOPosix.c, lib/file/filePosix.c, lib/include/dnd.h, lib/include/loglevel_user.h, lib/include/panic.h, lib/include/posix.h, lib/include/strutil.h, lib/unicode/unicodeBase.h, lib/include/unicodeOperations.h, lib/include/vix.h, lib/include/vm_app.h, lib/include/vm_assert.h, lib/include/vm_product.h, lib/include/x86cpuid.h, lib/misc/codeset.c, lib/misc/hashTable.c, lib/misc/strutil.c, lib/misc/timeutil.c, lib/panic/panic.c, lib/string/bsd_vsnprintf.c, lib/strUtil/*, lib/unicode/unicodeCommon.c, lib/unicode/unicodeSimpleBase.c, lib/unicode/unicodeStatic.c, lib/user/hostinfoPosix.c, lib/user/util.c, lib/user/utilPosix.c: Changes from work unrelated to open-vm-tools on the internal trunk. * lib/backdoor/backdoorInt.h, lib/deployPkg/runDeployPkgInt.h, lib/dnd/dndInt.h, lib/file/fileInt.h, lib/guestInfo/guestInfoInt.h, lib/hgfs/cpNameInt.h, lib/hgfsServer/hgfsServerInt.h, lib/impersonate/impersonateInt.h, lib/include/backdoorInt.h, lib/include/bsd_output_int.h, lib/include/cpNameInt.h, lib/include/dndInt.h, lib/include/fileInt.h, lib/include/guestInfoInt.h, lib/hgfsServer/hgfsServerInt.h, lib/include/impersonateInt.h, lib/include/runDeployPkgInt.h, lib/include/toolsLoggerInt.h, lib/include/unicodeInt.h, lib/string/bsd_output_int.h, lib/toolsLogger/toolsLoggerInt.h, lib/unicode/unicodeInt.h: Moved some internal header files out of the general include directory and into the appropriate libraries. * lib/ghIntegration/*: New library for Unity support. * lib/guestApp/guestAppPosixX11.c: Reset the value of LD_LIBRARY_PATH before running the web browser. * lib/guestInfo/guestInfoPosix.c, lib/include/guest_os.h: Fixed a typo in Mandriva guest detection. Added Asianux. * lib/guestInfo/guestInfoServer.c: Fixed behavior for sending nicInfo updates to the host (patch by Jason Lunz). * lib/guestRpc/ghi*.*: New xdr protocol for Unity support. * lib/guestRpc/nicinfo.x: Correctly applied LGPL to file. * lib/hgfs/cpNameLinux.c: Allow building for versions of Solaris newer than 10. * lib/hgfsServer/hgfsServer.c, lib/hgfsServerPolicyGuest/hgfsServerPolicyGuest.c, lib/include/hgfsServerPolicy.h: Provide an override setting for disabling case conversion during file lookups. * lib/hgfsServer/hgfsServerLinux.c: Only perform case insensitive file lookups if a case sensitive lookup fails. * lib/image/imageUtilPng.c, lib/include/imageUtil.h, lib/include/imageUtilTypes.h: New library for Unity support. * lib/include/conf.h, toolbox/toolbox-gtk.c: Robustified the help page discovery mechanism. * lib/include/dndGuest.h: Allow inclusion of header into source files without GTK2 support. * lib/unity/*, lib/include/guestCaps.h, lib/include/unityCommon.h: New library for Unity support. * lib/include/hgfsUtil.h: Fixed a precedence issue in a macro. * lib/raster/*, lib/include/rasterConv.h: New library for Unity support. * lib/region/*, lib/include/region.h: New library for Unity support. * lib/include/system.h: Added new OS type for WinXP 64-bit, reformatted enums. * lib/unityWindowTracker/*, lib/include/unityWindowTracker.h: New library for Unity support. * lib/include/vm_version.h: Bumped TOOLS_VERSION. * lib/wiper/wiperPosix.c: Replaced BSD_VERSION with __FreeBSD_version. * modules/*/*/*: Reflected changes from elsewhere. * modules/freebsd/vmhgfs/*: Reflected changes from MacOS HGFS work, and fixed file permissions so that they're not all owned by root. * modules/linux/vmblock/linux/dentry.c: Changed d_revalidate to properly invalidate negative dentries. * modules/linux/vmci/*: Landed the Virtual Machine Communication Interface guest module. * modules/linux/vmmemctl/os.c: Fixed vmmemctl to build on 2.6.26 (reported by Pavol Rusnak). * modules/linux/vmsync/sync.c: Fixed vmsync to build on 2.6.26 (reported by Pavol Rusnak). * modules/linux/vsock/*: Landed the VMCI sockets interface module. * modules/linux/vmxnet/vmxnet.c, modules/linux/vmxnet/vmxnet2_def.h, modules/linux/vmxnet/vmxnetInt.h: Increased rx ring size for enhanced vmxnet2. * toolbox/*: Refactored pieces of GTK Toolbox and landed the command line Toolbox. Fixed mnemonic collisions in the GTK Toolbox. * vmware-user/copyPaste.c: Fixed several bugs with file copy paste behavior. * vmware-user/notify.c, vmware-user/vmware-user.c, vmware-user/vmwareuserInt.h: Added stubs for notification framework. * vmware-user/pointer.c: Reverted fix for bug with clipboard retry behavior. * vmware-user/vmware-user.c: Fixed build with gtk 1.2 (reported by Stephen Duncan). Added signal handlers for SIGUSR1/SIGUSR2 used by VMware Tools installer to reload vmware-user cleanly during a Tools upgrader. Reload vmware-user on a fatal X I/O error. Don't panic if run outside of a VM. Don't leave Unity mode on a Tools reset. 2008-07-01 Adar Dembo * Resync with internal trunk (2008.06.30) * configure.ac, lib/guestApp/*, toolbox/Makefile.am, vmware-user/Makefile.am: Split lib/guestApp into two libraries, one with X11 functionality, and one without. Improved detection of gnome-open. * guestd/*, lib/netUtil/netUtilLinux.c: guestd now compiles for MacOS guests. * guestd/main.c, lib/include/system.h, lib/system/systemLinux.c: Refactored GuestdWritePidfile into System_Daemon. * guestd/toolsDaemon.c: Fixed a backwards time synchronization issue. Thanks to Eric Castan for reporting the bug. * lib/conf/conf.c, lib/include/conf.h: Removed obsolete configuration keys and values. * lib/file/*, lib/dict/*, lib/foundryMsg/*, lib/include/backdoor_def.h, lib/include/codeset.h, lib/include/config.h, lib/include/file_extensions.h, lib/include/fileInt.h, lib/include/loglevel_user.h, lib/include/msg.h, lib/include/msgid.h, lib/include/posix.h, lib/include/preference.h, lib/include/unity.h, lib/include/vixCommands.h, lib/include/vix.h, lib/include/vmbackup_def.h, lib/include/vmBackup.h, lib/include/vm_basic_defs.h, lib/include/vm_basic_types.h, lib/include/vm_product.h, lib/include/win32util.h, lib/include/x86cpuid.h, lib/misc/codeset.c, lib/misc/codesetOld.c, lib/misc/codesetOld.h, lib/misc/posixPosix.c, lib/strUtil/strutil.c, lib/user/hostinfoPosix.c, lib/user/util.c, lib/vmBackupLib/stateMachine.c, modules/*/vmxnet/net.h: Changes from work unrelated to open-vm-tools on the internal trunk. * lib/guestRpc/Makefile.am: Added comment about misuse of CFLAGS. * lib/hgfsServer/hgfsServer.c: Corrected pointer arithmetic so that new node and search allocation works consistently in 64-bit apps. * lib/hgfsServer/hgfsServerLinux.c, lib/include/hgfsProto.h: Added HGFS_ATTR_HIDDEN_FORCED and set it when returning hidden files. * lib/hgfsServer/*, lib/hgfsServerPolicy/hgfsServerPolicyGuest.c, lib/include/hgfsServerInt.h, lib/include/hgfsServerPolicy.h: Refactored and cleaned up some code. * lib/include/resolution.h, lib/resolution/*, vmware-user/vmware-user.c: Refactored some functions. * lib/include/vm_legal.h: Added another patent to the patent string. * lib/include/vm_tools_version.h: Added a pair of Tools version macros. * lib/include/vm_version.h: Bumped Tools product version. * lib/Makefile.am: Included a fix for compilation --without-x. Thanks to Mark Foster for reporting the issue. * lib/misc/Makefile.am, lib/misc/shared/Makefile.am: Realphabetized some sources and added missing source files. * lib/misc/posixWin32.c: Removed unneeded file from tree. * lib/procMgr/procMgrPosix.c: Made safe for -fPIC and for MacOS. * modules/*/*/*: Reflected changes from elsewhere. * modules/freebsd/vmhgfs/*: Added some code to handle codeset conversions between UTF-8 precomposed and decomposed strings. * modules/linux/vmhgfs/*: Refactored string escaping/unescaping code. * toolbox/*: Added mnemonics for some buttons. * vmware-user/pointer.c: Fixed bug in clipboard retry behavior. * vmware-user/vmware-user.c: Added handlers for SIGUSR1 and SIGUSR2 to facilitate smooth vmware-user upgrades with respect to the vmblock kernel module. 2008-06-20 Elliot Lee * Resync with internal trunk (2008.06.13) * FreeBSD 7/8 fixes from Martin Blapp. * Fix getpwnam_r etc. on FreeBSD & Solaris. * configure.ac: Add --without-kernel-modules, --with-linux-release, and --with-linuxdir (gissa). * configure.ac, lib/guestRpc/*, lib/guestInfo/guestInfo.c, lib/guestInfo/guestInfoServer.c, lib/dynxdr/*, {vmware-user,guestd}/foreignVMToolsNetworking.c, guestd/Makefile.am, {vmware-user,guestd}/foundryToolsDaemon.c, lib/include/dynxdr.h, lib/include/guestInfo.h, lib/include/vmxrpc.h, lib/include/xdrutil.h, lib/Makefile.am, lib/netUtil/*, lib/vixTools/Makefile.am: Add support for XDR encoding of RPC values, including the NicInfoV2 structure. * guestd/stub.c, hgfsclient/Makefile.am, hgfsclient/stub.c, hgfsclient/stub-user-util.c, hgfsmounter/Makefile.am, hgfsmounter/stub.c, lib/stubs/*, libguestlib/Makefile.am, libguestlib/stubs.c, toolbox/Makefile.am, toolbox/stub.c, vmware-user/stub.c: Centralize stubs. * lib/guestInfo/guestInfoPerfMonLinux.c: Convert ioInRate and ioOutRate to be in terms of KB instead of pages. * lib/hgfsBd/hgfsBd.c, lib/hgfsServer/hgfsServer.c, lib/hgfsServer/hgfsServerLinux.c: Large packet support, and additional case-insensitivity fixes. * lib/include/hgfsBd.h, lib/include/hgfs.h, lib/include/hgfsProto.h: Add HGFS error code. * lib/hgfs/hgfsUtil.c, lib/guestInfo/Makefile.am, lib/guestInfo/guestInfoPosix.c, lib/guestApp/guestApp.c, lib/foundryMsg/foundryMsg.c, lib/file/fileLockPrimitive.c, lib/file/fileIOPosix.c, lib/file/fileLockPosix.c, guestd/toolsDaemon.c, guestd/debugStdio.c, guestd/main.c, lib/hgfsServerManagerGuest/hgfsServerManagerGuest.c, lib/include/codeset.h, lib/include/cpuid_info.h, lib/include/dnd.h, lib/include/file_extensions.h, lib/include/fileInt.h, lib/include/ghIntegration.h, lib/include/guestApp.h, lib/include/guestStats.h, lib/include/hgfsServerInt.h, lib/include/hgfsUtil.h, lib/include/hostinfo.h, lib/include/loglevel_user.h, lib/include/netutil.h, lib/include/panic.h, lib/include/posix.h, lib/include/unicode*.h, lib/include/util.h, lib/include/vix.h, lib/include/vixTools.h, lib/include/vm_app.h, lib/include/vm_basic_defs.h, lib/include/vm_product.h, lib/include/vm_tools_version.h, lib/include/vm_version.h, lib/include/x86cpuid.h, lib/misc/codeset.c, lib/misc/codesetOld.c, lib/misc/codesetOld.h, lib/misc/hashTable.c, lib/misc/hostname.c, lib/misc/timeutil.c, lib/panic/panic.c, lib/string/str.c, lib/sync/syncMutex.c, lib/system/systemLinux.c, lib/unicode/*.c, lib/unityStub/*, lib/user/hostinfo.c, lib/user/hostinfoPosix.c, lib/vixTools/*, modules/linux/vmxnet/*, toolbox/debugStdio.c, vmware-user/debugStdio.c, vmware-user/dnd.c, vmware-user/main.c: Bug fixes. * modules/linux/vmxnet/*: Remove unused BPF code. Add ethtool callbacks to get & set driver settings. * lib/user/util.c: Add function for getting backtraces. * lib/resolution/*, vmware-user/*, lib/Makefile.am, configure.ac: Move resolution-changing code into separate library. * guestd/main.c, lib/include/tools.h: Allow disabling tools version reporting to the host, via config file. * lib/rpcIn/*, lib/include/rpcin.h, guestd/toolsDaemon.c, toolbox/toolbox-gtk.c: Updated RPC API * lib/include/dndGuest.h: Helper API for DnD code * modules/freebsd/vmhgfs/*, modules/freebsd/vmmemctl/*, modules/freebsd/vmblock/*, modules/linux/vmhgfs/*, modules/linux/vmmemctl/*: Reflect changes from main source tree. * vmware-user/copyPaste.c: Copy/paste cleanup. * vmware-user/vmware-user.c: Updated locking code to use X11 display instead of lockfiles. 2008-06-03 Adar Dembo * Resync with internal trunk (2008.05.28). * configure.ac, Makefile.am, */Makefile.am: Added rudimentary `make install` support. Fixes Sourceforge bug 1839981. * configure.ac, Makefile.am, vmware-user-suid-wrapper/*: Added vmware-user-suid-wrapper to help autostart vmware-user. Added some informational tags to AC_DEFINE macros. * */debugStdio.c: Fixed a format string vulnerability in Debug. Allocate fd on the stack in DebugToFile. * lib/auth/authPosix.c, lib/dnd/dndCommon.c, lib/dnd/dndLinux.c lib/impersonate/impersonate.c: Add inclusion of vmware.h and refactor some include statements. * lib/file/file.c, lib/include/file.h: Added File_UnlinkNoFollow function. * lib/file/fileIO.c, lib/file/fileLockPrimitive.c, lib/include/fileIO.h: Added error case for ENAMETOOLONG to FileIO_Lock. Constified 'buf' in FileIO_Pwrite. * lib/file/fileIOPosix.c: Removed coalescing and decoalescing code. Consolidated some Unicode calls. * lib/file/filePosix.c: Reworked some error handling logic. * lib/foundryMsg/foundryMsg.c: Refactored buffer encoding and decoding logic into a single pair of functions. * lib/foundryMsg/foundryThreads.c, lib/include/foundryThreads.h lib/include/util.h, lib/misc/util_misc.c: Changed generic thread type from uintptr_t to Util_ThreadID. * lib/hgfsServer/*, lib/hgfs/hgfsProto.h, modules/linux/vmhgfs/*: Additional HGFSv3 fixes and refactoring. * lib/include/dbllnklst.h, lib/misc/dbllnklst.c: Constified argument to DblLnkLst_IsLinked. * lib/include/dnd.h: Added support for DnD of RTF. * lib/include/fileInt.h: Removed prototype of FileLockFileSize. * lib/include/hashTable.h, lib/misc/hashTable.c: Cosmetic changes. Added HashTable_ReplaceIfEqual. * lib/include/loglevel_user.h: Added hpet loglevel. * lib/include/msg.h: Removed prototype of MsgSetPostStderrBlock. * lib/include/posix.h: Removed certain includeCheck allowances. * lib/include/productState.h: Added VDM client product. * lib/include/unicode*, lib/unicode/*: Ongoing i18n work. * lib/include/vixCommands.h: Added command to set snapshot information. * lib/include/vix.h: Added more errors and a new flag. * lib/include/vixOpenSource.h: Reworked asserts and added VIX_ASSERT. * lib/include/vm_app.h: Added Tools tray app. * lib/include/vm_product.h: Reworked VMRC product definitions and added VDM client product definitions. * lib/include/vm_tools_version.h: Added WS65 Tools version. * lib/include/vm_version.h: Bumped Tools version. Added logic for VMRC product. * lib/include/x86cpuid.h: Modified a flag and trimmed an unneeded macro. * lib/misc/codesetOld.c: Implement UTF-16 codest conversion to UTF-8 for CURRENT_IS_UTF8. * lib/misc/dynbuf.c: Modified dynbuf growing behavior. * lib/misc/posixDlopen.c, lib/misc/posixInt.h, lib/misc/posixPosix.h: Refactored codeset conversion code into PosixConvertToCurrent. * lib/misc/posixWin32.c: Added some path checks. * lib/misc/timeutil.c: Win32-wrappified TimeUtil_GetTimeFormat. * lib/misc/vmstdio.c: Reduce virtual memory usage and add '\r' as a line ending in StdIO_ReadNextLine. * lib/rpcout/rpcout.c: Added comments. * lib/str/str.c: Cosmetic changes. * lib/vixTools/vixTools.c: Added unlink(2) logic to avoid deleting symlink targets. Cosmetic changes. * modules/*/*/*: Reflect changes from elsewhere in the source tree. * modules/linux/vmhgfs/super.c: Fix vmhgfs to properly report the available space on the host (Sourceforge bug 1924246). * vmware-user/vmware-user.c: Add advisory locking code to help maintain only one vmware-user instance per X session. * xferlogs/xferlogs.c: Fix a formatted string vulnerability. 2008-05-12 Elliot Lee * Resync with internal trunk (2008.05.08). * configure.ac, **/Makefile.am: Use CPPFLAGS instead of CFLAGS to eliminate warning about proc/sysinfo.h. * guestd/foreignVMToolsNetworking.c, vmware-user/foreignVMToolsNetworking.c lib/hgfsServer/hgfsServerLinux.c, lib/include/hgfsServerInt.h, modules/linux/vmhgfs/bdhandler.c, modules/linux/vmhgfs/dir.c, modules/linux/vmhgfs/file.c, modules/linux/vmhgfs/filesystem.h, modules/linux/vmhgfs/fsutil.h, modules/linux/vmhgfs/inode.c, modules/linux/vmhgfs/link.c, modules/linux/vmhgfs/module.h, modules/linux/vmhgfs/page.c, modules/linux/vmhgfs/request.c, modules/linux/vmhgfs/request.h: Whitespace cleanups. * guestd/main.c: Removed "blessed app" code for starting vmware-user. Hooray! * lib/deployPkg/deployPkg.c: Remove unneeded Utf8 conversion for Windows. * lib/file/filePosix.c: Use new Posix_RealPath implementation. * lib/guestApp/guestApp.c, lib/include/guestApp.h: Remove/cleanup UTF-8 related RPC functions. * lib/guestInfo/guestInfoPerfMonLinux.c, lib/guestInfo/guestInfoPosix.c, lib/include/guestInfo.h, lib/include/guestInfoInt.h, lib/include/guestStats.h: Rename structures to GuestMemInfo, GuestNicInfo, and GuestDiskInfo. * lib/guestInfo/guestInfoServer.c, lib/include/guest_msg_def.h: As above, and also GUESTMSG_MAX_IN_SIZE moved to guest_msg_def.h, and misc locking updates. Also add GuestInfoServer_Main(), and cleanup whitespace. * lib/hgfsServer/hgfsServer.c: Cleanup UTF-8 handling. * lib/include/codeset.h: Update defines that indicate whether the current platform is using UTF-8. * lib/include/dnd.h: Add prototypes for a couple of string conversion functions. * lib/include/file_extensions.h: Add OVF and Archived OVF file extensions. * lib/include/file.h: C++ guard thingies. Update a couple of function prototypes to work on file descriptors instead of filenames. * lib/include/hashTable.h, lib/include/guest_os.h, lib/include/loglevel_defs.h, lib/include/stats_user_defs.h, lib/include/stats_user_setup.h, lib/include/str.h, lib/include/unicodeTypes.h, lib/include/util.h: Allow inclusion in kernel modules... * lib/include/loglevel_user.h: As above, and add a couple of loglevel variables. * lib/include/util.h, lib/misc/util_misc.c: Allow inclusion in kernel modules as above, and add some utility functions on Windows for manipulating canonical paths. * lib/include/hgfsProto.h, lib/include/hgfsUtil.h: Move request/reply payload macros to hgfsProto.h. * lib/include/hgfsServerPolicy.h: Add ShareList management prototypes and structure members. * lib/include/msg.h: Add function prototypes for creating and posting lists of messages. * lib/include/system.h: Add types & functions related to desktop switch monitoring on Windows. * lib/include/unicodeOperations.h: Add/update inline unicode operations. * lib/include/vixCommands.h: Add VIX requests and events. * lib/include/vmbackup_def.h, lib/vmBackupLib/stateMachine.c: Move backup status enum to public header. * lib/include/vm_basic_asm_x86_64.h: Div643232 now also works on MSC. * lib/include/vm_basic_defs.h: Add debug output macros for Windows drivers. * lib/include/vm_basic_types.h: Update the FMTPD macro, add SCANF_DECL macro for arg checking on scanf-like functions. * lib/include/x86cpuid.h: Defines for AMD L2/L3 cache separately, and CPUID for Nehalem. * lib/misc/codesetOld.c: Bug fixes and general unicode handling updates. * lib/system/systemLinux.c: Use Posix_Getenv/Posix_Setenv impls. * lib/vixTools/vixTools.c, lib/vmBackupLib/scriptOps.c: Bug fixes. * modules/freebsd/*, modules/linux/*: Updates to correspond to updates of files in main tree. * modules/freebsd/vmhgfs/hgfs_kernel.h: Bug fixes. * modules/freebsd/vmxnet/vm_device_version: Add SCSI_IDE_HOSTED_CHANNEL define, update SCSI_MAX_CHANNELS. * modules/freebsd/vmxnet/vmnet.def: Add capabilities for IPv6 checksumming and TSO, and large packet TSO. * lib/include/vmblock.h, modules/linux/vmblock/linux/control.c, modules/linux/vmblock/linux/vmblockInt.h: Use a macro to better abstract the vmblock mount point & device. * vmware-user/vmware-user.c: Add SIGPIPE to the list of signals that vmware-user handles. 2008-05-02 Adar Dembo * Resync with internal trunk (2008.04.19). * configure.ac, guestd/Makefile.am, hgfsclient/Makefile.am, lib/misc/*/Makefile.am, lib/string/*/Makefile.am, toolbox/Makefile.am, vmware-user/Makefile.am, xferlogs/Makefile.am: Added libicu support for codeset conversions. This includes some makefile logic as well as autoconf arguments for controlling libicu behavior at compile-time. * */foreignVMToolsNetworking.c, lib/vixTools/vixTools.c: Unicode fixes. * */foundryToolsDaemon.c, lib/foundryMsg/vixTranslateErrOpenSource.c, lib/panic/panic.c, lib/printer/printer.c: Added calls to Win32 Unicode wrappers. * guestd/main.c: Cleaned up guestInfo server when guestd shuts down. * guestd/toolsDaemon.c, vmware-user/resolution.c: Disabled multi-mon advertisement for Win2k. * lib/auth/authPosix.c, lib/dnd/dndLinux.c, lib/file/*, lib/impersonate/impersonatePosix.c, lib/include/mntinfo.h, lib/sync/syncWaitQPosix.c, lib/user/hostinfoPosix.c, lib/user/util.c, lib/user/utilPosix.c, lib/wiper/wiperPosix.c: Added calls to POSIX Unicode wrappers. * lib/file/*: Replaced calls to string functions with calls to the "safe" family of string functions. * lib/dict/dictll.c, lib/include/dictll.h: Detect and tolerate UTF-8 dictionary files that contain the UTF-8 BOM. * lib/err/*, lib/include/err.h, lib/include/msgfmt.h, lib/include/msg.h: Added support for localization of error strings. * lib/foundryMsg/foundryThreads.c, lib/include/foundryThreads.h, lib/misc/util_misc.c: Added opaque type for threads/process IDs. * lib/guestInfo/guestInfoServer.c: Removed separate thread context. * lib/hgfsServer/*, lib/include/hgfs*.h: Additional HGFSv3 cleanup. * lib/hgfsServer/hgfsServerLinux.c: Added calls to POSIX Unicode wrappers. Fixed some alias detection code for MacOS. * lib/include/backdoor_def.h: Added backdoor call for debugging events. * lib/include/bsdfmt.h, lib/string/bsd_vsnprintf.c, lib/string/bsd_vsnprintfw.c: Replaced BSDFmt_WCSonv with BSDFmt_WChartoUTF8. * lib/include/codeset.h, lib/include/codesetOld.h, lib/misc/codeset.c, lib/misc/codesetOld.c, lib/string/convertutf.h: Implemented libicu-backed codeset layer. When building without libicu, fallback on codesetOld. * lib/include/guestApp.h: Added wide versions of dictionary functions. * lib/include/loglevel_user.h: Added two new loglevels. * lib/include/posix.h, lib/misc/posixPosix.c: Added new POSIX wrappers. * lib/include/str.h: Clarified the use of some functions. * lib/include/syncMutex.h, lib/include/syncWaitQ.h: Removed unneeded macros. * lib/include/unicode*.h, lib/unicode/*: Ongoing Unicode work. * lib/include/util.h: Added Util_FreeStringList, removed Util_FreeList. * lib/include/uuid.h: Added new UUID creation scheme. * lib/include/vix*.h: Tweaked some VIX commands, errors, and properties. * lib/include/vmBackup.h, lib/vmBackupLib/scriptOps.c, lib/vmBackupLib/stateMachine.c: Moved disabled targets logic from library to Windows VSS provider. * lib/include/vm_basic_asm_x86*.h: Allow emitted FX functions to modify main memory as a side effect. * lib/include/vm_tools_version.h: Bump Tools version. * lib/include/vm_version.h: Added several product versions. * modules/linux/vmhgfs/*: Additional cleanup for HGFSv3. Use new kthread wrapper when possible. Bump module version. * modules/linux/vmmemctl/*: Use new kthread wrapper when possible. Remove dead delayed work code. Bump module version. * modules/linux/*/compat_kthread.c: Added kthread wrapper implementation for modules that use kernel threads. * modules/*/*/*: Reflect header file changes from elsewhere in the source code tree. * vmware-user/copyPaste.c, vmware-user/pointer.c, vmware-user/vmwareuserInt.h: Stop wastefully polling for pointer updates if the VMX is new enough. * xferlogs/xferlogs.c: Fixed a warning in the call to fwrite. (Thanks to Denis Leroy for reporting this bug.) 2008-04-14 Elliot Lee * Resync with internal trunk (2008.04.01). * Fixed legal header on all LGPL-licensed files. * vmware-user/resolution.c: Normalize the display topology that comes in from the host, and report 'global_offset' capability. * toolbox/Makefile.am, vmware-user/Makefile.am, lib/misc/Makefile.am, lib/misc/atomic.c, lib/Makefile.am, lib/atomic/*, hgfsclient/Makefile.am: Move libAtomic stuff into libmisc * vmware-user/foundryToolsDaemon.c, lib/vixTools/vixTools.c, lib/include/hgfsServerInt.h, guestd/toolsDaemon.c, guestd/foundryToolsDaemon.c: Remove WIN9XCOMPAT, and some SOCKET_MGR code. * vmware-user/copyPaste.c: Copy/paste fixes for cross-platform operation. * modules/linux/vmxnet/vmnet_def.h: Add SG_SPAN_PAGES capability. * modules/linux/vmxnet/vm_device_version.h: Update some device limits. * modules/linux/*/compat_sched.h: Add TASK_COMM_LEN define. * modules/linux/*/compat_kernel.h, modules/linux/*/kernelStubsLinux.c: Add vsnprintf define. * modules/linux/*/x86cpuid.h: Add new CPUs. * modules/linux/vmhgfs/vmhgfs_version.h: Bump HGFS version. * modules/linux/*/vm_basic_asm_x86.h, modules/linux/*/vm_basic_asm_x86_64.h, lib/include/vm_basic_asm_x86.h, lib/include/vm_basic_asm_x86_64.h: Formatting fixes, and change asm directives used. * modules/linux/vmhgfs/module.h, modules/linux/vmhgfs/filesystem.c, modules/linux/vmhgfs/bdhandler.c, modules/linux/*/compat_kthread.h: compat_kthread fixes. * modules/freebsd/vmxnet/net_compat.h, modules/freebsd/vmxnet/if_vxn.c: Updates for FreeBSD 7.0. (Thanks to Martin Blapp for contributing to these changes.) * lib/misc/util_misc.c, lib/include/loglevel_user.h, lib/user/hostinfoPosix.c, lib/misc/hostname.c: Bugfix. * lib/unityStub/unityStub.c, lib/include/unity.h: Add stub and enums related to DnD support. * lib/unicode/unicodeSimpleTypes.c, lib/unicode/unicodeSimpleTransforms.c, lib/unicode/unicodeSimpleBase.c, lib/unicode/unicodeCommon.c, lib/include/unicodeTypes.h, lib/include/unicodeTransforms.h, lib/include/unicodeBase.h, lib/include/unicodeCommon.h: Add additional Unicode-related functions. * lib/sync/syncMutex.c, lib/include/syncMutex.h: Add TryLock method. * lib/strUtil/strutil.c: Add int64-related functions. * lib/string/str.c: Compile fix * lib/string/bsd_output_shared.c: Better handling of floating point on Windows. * lib/include/progMgr.h, lib/procMgr/procMgrPosix.c: Clarify that the strings are in UTF-8, do conversion as needed. * lib/include/posix.h, lib/misc/posixPosix.c, lib/misc/posixWin32.c, lib/file/filePosix.c: Add new Posix_ function implementations, and unicodify existing ones. * lib/misc/hashTable.c, lib/include/hashTable.h: Add lock-less hash table functions. * lib/misc/util_misc.c, lib/include/w32util.h: Add a couple of Win32 utility functions. * lib/include/vm_version.h: Add WS5 config version. * lib/include/vm_atomic.h: Add typecasts to atomic operations to make compilers stop complaining, and expand the AtomicUseFence option. * lib/include/vm_app.h: Add a couple of HGFS-related options. * lib/include/vix.h: Update a few errors and other macros. * lib/include/vixCommands.h, lib/foundry/foundryMsg.c: Change a bunch of structure members from int32 to uint32, and add a parsing function. * lib/include/msgfmt.h, lib/include/msg.h: Additional message-handling prototypes. * lib/include/guestInfoInt.h, lib/include/guestInfo.h, lib/guestInfo/Makefile.am, lib/guestInfo/guestInfoServer.c, lib/guestInfo/guestInfoPosix.c, lib/guestInfo/guestInfoPerfMonLinux.c: Add IPv6 support, and the ability to read mem stats on Linux. * lib/include/fileIO.h, lib/file/fileIOPosix.c: Add MacOS function related to Time Machine. * lib/guestApp/guestApp.c: Use Posix_ variants of functions. * lib/ghIntegrationStub/ghIntegrationStub.c: Add GHI capabilities stubs. * lib/dnd/dndCommon.c, lib/file/file.c: Use new Unicode_Format() function, bugfix. * guestd/main.c: Fix a security bug. * configure.ac: Allow calling libdnet 'dumbnet' for Debian systems. Detect libprocps. 2008-03-19 Adar Dembo * Resync with internal trunk (2008.03.13). * vm_version.h: Updated Tools version. * configure.ac: Added dynamic dnet detection and --without-dnet flag. * guestd/debugStdio.c, lib/include/system.h, lib/system/systemLinux.c: Modified debugging to file behavior to prepend debug strings with human readable timestamps. * guestd/main.c, guestd/toolsDaemon.c, lib/conf/conf.c, lib/guestApp/guestApp.c, lib/include/guestApp.h: Internationalized GuestApp_GetInstallPath and GuestApp_GetconfPath. * lib/auth/authPosix.c, lib/dnd/dndLinux.c, lib/file/*, lib/impersonate/impersonatePosix.c, lib/include/fileInt.h, lib/include/posix.h, lib/misc/posix*.c: Refactored, extended, and made use of the set of POSIX internationalization-safe function wrappers. * lib/dnd/dndCommon.c, lib/include/dnd.h, lib/include/dndInt.h, vmware-user/copyPaste.c, vmware-user/dnd.c: Replaced some duplicated UTF-8 formatting code with calls to lib/unicode. * lib/guestInfo/guestInfoPosix.c: Replaced the old syscall-based implementation of nicinfo with a simpler implementation that uses dnet. * lib/guestInfo/guestInfoServer.c, lib/include/guestInfo.h, lib/include/guestInfoInt.h: Added Win32 implementation of meminfo. POSIX implementation to follow. * lib/hgfsServer/hgfsServerLinux.c: Replaced a direct readlink(3) call with a call to the POSIX wrapper for readlink(3). Relax an overeager ASSERT in symlink checking when using the special empty share. * lib/include/codeset.h, lib/string/bsd_vsnprintf.c, lib/string/str.c, lib/unicode/unicodeSimpleOperations.c, lib/unicode/unicodeSimpleUTF16.h: Refactored ICU routines from unicodeSimpleUtf16.h to codeset.h, which is now licensed under the ICU license (BSD variant). * lib/include/file.h, lib/file/file.c: Added function File_StripSlashes. * lib/include/hgfsProto.h: Removed an A acute from a comment to allow the file to be built on Windows systems where the default language isn't English. * lib/include/hostinfo.h, lib/include/util.h, lib/user/hostinfoPosix.c, lib/user/util.c, lib/user/utilPosix.c: More conversions to lib/unicode. Added Util_ZeroFreeStringW function for Windows in util.h. * lib/include/msg.h: Removed obsolete NO_MSGFMT macro. * lib/include/unicodeBase.h, lib/unicode/unicodeCommon.c, lib/unicode/unicodeSimpleBase.c: Added some more encoding functions. * lib/include/vixCommands.h, lib/include/vixOpenSource.h: Added another user credential type, some command flags, some command layouts, some error codes, some properties, and tweaked existing commands. * lib/include/vixTools.h: Added VixToolsUserIsMemberOfAdministratorGroup function. * lib/include/vm_assert.h, lib/include/vm_basic_defs.h: Move IMPLIES to vm_basic_defs.h. Removed some vprobes definitions. * lib/include/vmBackup.h, lib/vmBackupLib/scriptOps.c, lib/vmBackupLib/stateMachine.c: Added infrastructure to disable quiescing targets from a config file. * lib/include/vm_basic_asm.h: Changed __GET_CPUID2 handling for Windows. * lib/include/vm_produt.h: Added VDM product. * lib/include/vm_tools_version.h: Bumped internal Tools version. * lib/include/win32util.h, lib/misc/hostname.c, lib/misc/util_misc: Refactored functions to separate set of Win32 wrappers (next to the POSIX wrappers mentioned earlier). * lib/misc/codeset.c: Made CodeSetGetCurrentCodeSet non-static. * lib/misc/*/Makefile.am: Added POSIX wrappers to build system. * lib/strUtil/strutil.c: Fixed bug in StrUtil_EndsWith function. * lib/include/unicodeTypes.h, lib/unicode/unicodeSimpleTypes.c: Removed ISO-8859-11 encoding. Added cross-reference of IANA character set names, windows code pages, and ICU encodings. * lib/vixTools/vixTools.c: Impersonation tweaks. * modules/*/*/*: Reflect header file changes from elsewhere in the source code tree. 2008-03-11 Adar Dembo * vm_version.h: Updated Tools version. * modules/vmblock/linux/*: Make vmblock build under 2.6.25-rc2. The dentry and mount objects have been moved out of struct nameidata and into the new struct path. Also, path_release() is now path_put(). * modules/vmsync/linux/*: Make vmsync build under 2.6.25-rc2. The same changes were needed here as in vmblock above. 2008-03-10 Adar Dembo * vm_version.h: Updated Tools version. * modules/vmhgfs/linux/*: Make vmhgfs build under 2.6.25-rc1. The iget() function has been removed and filesystems are now expected to implement it themselves using iget_locked(). 2008-02-27 Elliot Lee * configure.ac, guestd/Makefile.am, toolbox/Makefile.am, vmware-user/Makefile.am: Allow passing custom LDFLAGS in to build process (patch by Mike Auty). * Resync with internal trunk (2008.02.27). * guestd/foundryToolsDaemon.c, lib/vixTools/vixTools.c, vmware-user/foundryToolsDaemon.c: Win9x compat changes. * guestd/toolsDaemon.c: Style fixes. * hgfsmounter/hgfsmounter.c: Bug fixes. * lib/dnd/dndLinux.c, lib/dnd/dndCommon.c: Move some code to the platform-independant file, some DnDv3 support. * lib/include/dnd.h, lib/include/dndInt.h: DnDv3 support. * lib/file/file.c, lib/file/fileIO.c, lib/file/fileIOPosix.c, lib/file/fileLockPrimitive.c, lib/file/filePosix.c, lib/include/file_extensions.h, lib/include/fileInt.h, lib/include/fileIO.h: Move functions around, Unicode fixes, misc fixes. * lib/foundryMsg/foundryPropertyListCommon.c: Error handling fixes. * lib/hgfsServer/*.c, lib/include/hgfs*.h, modules/freebsd/vmhgfs/*, modules/linux/vmhgfs/*: HGFS v3 support, updates to improve code re-use between the FreeBSD and MacOS X ports, and updates to make the Linux port build on 2.6.25-rc1 (but not rc2, yet). * lib/include/auth.h, lib/include/codeset.h, lib/include/hostinfo.h, lib/include/str.h, lib/include/unicode*.h, lib/include/vm_basic_types.h, lib/misc/hostname.c, lib/unicode/*.c, lib/user/hostinfoPosix.c: Unicode fixes. * lib/include/backdoor_def.h: Add a new command for use by the BIOS in checking the GuestOS against Darwin. * lib/include/dynarray.h, lib/misc/dynarray.c, lib/misc/Makefile.am, lib/misc/shared/Makefile.am: Add Dynarray implementation. * lib/include/bsdfmt.h, lib/include/bsd_output_int.h, lib/string/bsd_output_shared.c, lib/string/bs_vsnprintf.c, lib/string/bsd_vsnwprintf.c, lib/string/str.c: Rework built-in printf implementation, esp. for Unicode fixes. * lib/include/ghIntegration.h: Shuffle types around. * lib/include/loglevel_user.h, lib/include/unity.h, lib/syncDriver/syncDriverPosix.c, lib/user/util.c, toolbox/toolbox-gtk.c: Misc fixes. * lib/include/vmBackup.h, lib/vmBackupLib/scriptOps.c, lib/vmBackupLib/stateMachine.c, lib/vmBackupLib/vmBackupInt.h: Rework scripts for freeze & thaw operations. * lib/include/vm_product.h, lib/include/vm_version.h: Add new product defs (VMRC). * lib/include/vm_tools_version.h: Add ESX 3.5U1 product. * lib/include/vixCommands.h, lib/include/vix.h: Add new VIX commands and error code. * lib/include/win32util.h: Add misc Win32 utilities. * modules/*/*/*: Reflect header file changes from elsewhere in the source code tree. 2008-02-13 Adar Dembo * Resync with internal trunk (2008.02.12). * configure.ac, lib/unityStub/*, lib/ghIntegrationStub/*, lib/Makefile.am, vmware-user/Makefile.am, vmware-user/vmware-user.c: Added lib/unityStub and lib/ghIntegrationStub. Unity and guest-host integration features for X11 guests are on the way. * configure.ac, guestd/Makefile.am, lib/fileUtf8/*, lib/vixTools/vixTools.c, vmare-user/Makefile.am: lib/file is now fully internationalized. Removed unneeded lib/fileUtf8. * foundryToolsDaemon.c: Fixed a leak of the sync driver handle. * guestd/toolsDaemon.c: Send guestd's "config directory" to the VMX for publishing. * hgfsmounter/hgfsmounter.c: Port to MacOS. * lib/dnd/*, lib/err/err.c, lib/file/*, lib/include/dnd*, lib/include/file*, lib/include/unicode*, lib/include/util.h, lib/unicode/*, lib/user/utilPosix.c: More Unicodification. * lib/file/file.c, lib/include/file.h: Added File_EnsureDirectory. * lib/foundryMsg/foundryMsg.c, lib/guestInfo/guestInfoServer.c, lib/misc/codeset.c, lib/misc/vmstdio.c, lib/SLPv2Parser/SLPv2MsgAssembler.c, lib/user/util.c: Removed some unneeded casts. * lib/foundryMsg/foundryThreads.c, lib/include/foundryThreads.h: Added FoundryThreads_Free. * lib/guestInfo/*, lib/include/guest_os.h, lib/include/guestInfo.h: Refactored GetSystemBitness. Removed osNames.h. * lib/hgfsServer/hgfsServerLinux.c: Modified MacOS alias resolution code so as not to mount volumes. Made HGFS query volume code more resilient to failures. * lib/include/backdoor_def.h: Added commands for VAssert. * lib/include/escape.h, lib/misc/escape.c: Escape_Do is no longer declared inline. * lib/include/hashTable.h, lib/misc/hashTable.c, lib/misc/Makefile.am, lib/misc/shared/Makefile.am: Renamed from hash.[ch]. * lib/include/iovector.h, lib/include/vm_basic_types.h: Added SectorType definition. * lib/include/loglevel_user.h: Added additional log levels. * lib/include/msgfmt.h: Modified for use in VMKERNEL. Added MsgFmt_GetArgswithBuf. * lib/include/msg.h: Added Msg_AppendVob for ESX. * lib/include/stats_user*: Modified some preprocessing steps. Added SETUP_WANT_GETVAL to retrieve named stat counter values. * lib/include/str.h: Modified behavior Str_* family of functions for Windows. * lib/include/strutil.h, lib/strUtil/strutil.c: Removed Split, Grep, GrepFd, and GrepFree. Added EndsWith and DecimalStrToUint. * lib/include/syncWaitQ.h, lib/sync/*: Modified SyncWaitQ_Add and SyncWaitQ_Remove to use PollDevHandle fd types instead of int fd types. * lib/include/timeutil.h, lib/misc/timeutil.c: Added TimeUtil_GetLocalWindowsTimeZoneIndex and some helper functions. * lib/include/util.h, lib/user/utilPosix.c: Added Util_BumpNoFds. * lib/include/vixCommands.h: Added commands for device hotplug and remote debugging. * lib/include/vix.h, lib/include/vixOpenSource.h: Added some new errors and properties. Added more VM manipulation functions. * lib/include/vm_atomic.h: Comment cleanup and added VMKERNEL-specific calls for fencing. * lib/include/vm_basic_asm_x86_64.h: Added inline routines to save and restore ES1. * lib/include/vm_basic_types.h: Added some types and cleaned up a bit. * lib/include/vm_legal.h: Updated COPYRIGHT_YEARS. * lib/include/vm_product.h: Added hostd service name. * lib/include/x86cpuid.h: Cleaned up the file and added some definitions for Penryn processors. * lib/misc/codeset.c: Added new UTF-16 --> UTF-8 conversion routine. * lib/misc/util_misc.c, lib/user/util.c: Moved Util_GetCurrentThreadId and friends to util_misc.c. * lib/procMgr/procMgrPosix.c: Cleaned up some code and reworked asynchronous process execution so as to properly track the grandchild's pid instead of the child's pid. * lib/string/bsd*: Reorganized BSD formatter. * lib/string/str.c: Updated unit tests. Added some Windows corner case behavior for Str_Vsnwprintf. * lib/strUtil/strutil.c: Fixed some corner cases in existing functions that call strtoul. * lib/vixTools/vixTools.c: Changed signature of VixToolsImpersonateUser. Changed error code handling in a few places. * modules/freebsd/vmhgfs/*: Refactored a lot of code so that it can be safely reused within the MacOS vmhgfs module. * modules/*/*/kernelStubs*: Removed dead System_Uptime function. * modules/linux/*/compat_wait.h: Reworked VMW_HAVE_EPOLL macro. Added waitqueue helper macros for older kernels. * modules/linux/vmhgfs/file.c, modules/linux/vmhgfs/fsutil.*, modules/linux/vmhgfs/inode.c: Added HgfsSetUidGid function and used it to preserve uid/gid after creating a directory. * modules/linux/vmhgfs/vmhgfs_version.h: Bumped driver version. * modules/linux/vmsync/compat_workqueue.h: Basic implementation of work queues and delayed work queues (using taskqueues and timers) for older kernels. * modules/linux/vmsync/sync.c: Modified internal state to use new compatible work queue implementation. * modules/linux/vmxnet/compat_ioport.h, modules/linux/vmxnet/compat_netdevice.h, modules/linux/vmxnet/compat_pci.h, modules/linux/vmxnet/compat_skbuff.h, modules/linux/vmxnet/vmxnetInt.h: Added and refactored compatibility macros for use in vmxnet3 and vmci sockets modules. * modules/linux/vmxnet/vmxnet.c: Hide some kernel functions behind compatibility macros. 2008-01-23 Adar Dembo * Resync with internal trunk (2008.01.08). * configure.ac, guestd/Makefile.am, hgfsclient/Makefile.am, lib/Makefile.am, toolbox/Makefile.am, vmware-user/Makefile.am: integrated lib/unicode for internationalizing strings. * guestd/main.c: Stopped using pgrep for finding existing instances of guestd. Removed ancient bandwidth test code. * guestd/toolsDaemon.c: Moved initial send of the guest's uptime from when guestd sends its version to when guestd registers its capabilities. * lib/file/*, lib/include/file*.h : Massive overhaul of lib/file to integrate the new unicode strings that are i18n-safe. Quite a bit of cleanup and refactoring as well. * lib/file/file.c: Addition of File_PrependToPath function. * lib/file/fileIOPosix.c: Addition of FileIO_SetExcludedFromTimeMachine and FileIO_PrivilegedPosixOpen functions. * lib/fileUTF8/fileUTF8Linux.c, lib/include/fileUTF8.h: Removal of some casts and addition of FileUTF8_GetSize function. * lib/foundryMsg/foundryMsg.c, lib/misc/vmstdio.c, lib/SLPv2Parser/SLPv2MsgAssembler.c: Addition of some casts. * lib/foundryMsg/foundryPropertyListCommon.c: Robustified some error cases. * lib/foundryMsg/vixTranslateErrOpenSource.c, lib/include/vixOpenSource.h: Added VIX_E_OUT_OF_MEMORY error code. Added Vix_TranslateCOMError function. ADded VIX_DEBUG macro. * lib/guestInfo/guestInfoServer.c, lib/include/guestInfo.h: Added some casts and refactored some functions. Also fixed a crash that hinders backwards compatibility. * lib/hgfs/cpNameUtil.c, lib/hgfs/cpNameUtilLinux.c, lib/hgfsBd/hgfsBd.c, lib/include/cpName.h, lib/include/cpNameLite.h, lib/include/escBitvector.h, lib/include/hgfsUtil.h, lib/message/messageBackdoor.c, lib/message/message.c, lib/message/messageStub.c, lib/rpcout/rpcout.c, modules/freebsd/vmhgfs/kernelStubs.h: Made safe for inclusion in MacOS kernel module code. * lib/include/backdoor.h: Refactored some type definitions. * lib/include/bsd_output_int.h, lib/include/safetime.h, lib/string/bsd_output_shared.c: Made safe for Win64 builds. * lib/include/dynbuf.h: Added DynBuf_AppendString function. * lib/include/err.h: Assorted cleanup. * lib/include/escape.h, lib/misc/escape.c: Converted Escape_Do to be inline. Some cleanup. * lib/include/guest_os.h: Assorted cleanup. * lib/include/hash.h, lib/misc/hash.c, lib/misc/Makefile.am, lib/misc/shared/Makefile.am: Added basic hash table implementation. * lib/include/hostinfo.h, lib/user/hostinfoPosix.c: Refactored and added several timekeeping functions. * lib/include/localconfig.h, lib/include/util_shared.h: Modified statements for include check. * lib/include/log.h: Changed the value of some macros when debugging. * lib/include/loglevel_defs.h: Refactoed some code, added macros for use in the VMM. * lib/include/loglevel_user.h: Added loglevels for some new components. * lib/include/msgfmt.h: Added new functions. * lib/include/msg.h: Added new Msg_LocalizeList function. * lib/include/netutil.h: Modified prototypes for two Windows-only functions. * lib/include/preference.h: Added new Preference_GetInt64 and Preference_SetFromString functions. * lib/include/strutil.h, lib/strUtil/strutil.c: Cleaned up and added some new functions. * lib/include/su.h: Cleanup. * lib/include/syncMutex.h, lib/sync/syncMutex.c: Added NetWare implementation of some synchronization primitives. * lib/include/unicode*, lib/unicode/*: New library for handling Unicode-aware strings. * lib/include/util.h, lib/user/util.c: Assorted refactoring and addition of some new functions, one related to backtracing. * lib/include/vixCommands.h: New commands for vprobes, replay, message dialogs, and others, plus cleanup of some existing commands. * lib/include/vm_assert.h: Added IMPLIES macro. * lib/include/vm_atomic.h, lib/include/vm_basic_asm.h: Refactored for safe Win64 builds. * lib/include/vm_basic_defs.h: Added compatibility code for __va_copy. * lib/include/vm_basic_types.h: Added FMTH for printing the value of handles. Set a new #pragma to ignore size_t truncation warnings on Windows. Added several other macros, as well as a ssize_t definition for some versions of BSD. * lib/include/vm_legal.h: Added more patents to the patent string. * lib/include/vm_product.h: Added new macros for some products. * lib/include/vm_tools_version.h: Added macros for certain older Tools versions and for PRODUCT_BUILD_NUMBER refactoring. * lib/include/vm_version.h: Tweaked some product expiration dates and versions. Refactored many uses of BUILD_NUMBER to PRODUCT_BUILD_NUMBER. * lib/include/x86cpuid.h: Tweaked definition of RDTSCP flag. Refactored BIT_MASK macro to VMW_BIT_MASK. * lib/misc/base64.c: Modified calling contract for Base64_EasyEncode. * lib/misc/codeset.c: Tweaked casts and preprocessor conditioning. * lib/misc/idLinux.c: Added IdAuthCreateWithFork and reworked several other functions to work around a bug in Apple's detection of GUI processes. * lib/misc/util_misc.c: Moved W32Util_GetLongPathName and W32UTil_LookupSidForAccount elsewhere. * lib/rpcin/rpcin.c: Addition of a ping GuestRPC callback. * lib/string/str.c: Removed a comment. * lib/sync/syncWaitQPosix.c: Added code to disable a workaround for a MacOS bug when appropriate (it was fixed in Leopard). * lib/vixTools/vixTools.c: Refactored some code, added code to modify the guest's networking configuration, added some casts, and added code to prevent renaming a file to itself. * modules/freebsd/*/Makefile, modules/linux/*/Makefile.normal: Set a make variable so the module file will be build in the parent directory. Removed some unused rules. * modules/freebsd/vmhgfs/kernelStubsBSD.c, modules/linux/vmhgfs/kernelStubsLinux.c: Removed unused function. * modules/linux/*/include/driver-config.h: Added check to prevent uintptr_t from being declared twice. * modules/linux/vmblock/linux/filesystem.c, modules/linux/vmblock/Makefile.kernel: Added check for newer kernels where the slab allocator's constructor function expects three arguments. Makes it work with 2.6.25-rc1 (but not rc2, yet). * modules/linux/vmblock/linux/vmblock_version.h: Bumped module version. * modules/linux/vmhgfs/filesystem.c, modules/linux/vmhgfs/inode.c, modules/linux/vmhgfs/module.h, modules/linux/vmhgfs/page.c: Added support for writeback caching in conformant kernels. * modules/linux/vmhgfs/vmhgfs_version.h: Bumped module version. * modules/linux/vmxnet/vmxnetInt.h: Renamed a type and removed the inclusion of unnecessary headers. Pruned said headers from codebase. 2007-11-15 Elliot Lee * Bandsaw release (2007.11.15). * configure.ac: Handle building modules for multiple OS's. Improve X detection to allow building --without-x. Improve Gtk+ detection. Detect libdnet on Solaris. Detect which -Wwarning flags the compiler can handle. * vmware-user/foreignVMToolsNetworking.c, lib/vixTools/vixTools.c, guestd/foreignVMToolsNetworking.c, lib/include/netutil.h, lib/include/guestInfo.h, lib/netUtil/netUtilLinux.c, lib/include/guestInfoInt.h, lib/guestInfo/guestInfoPosix.c, lib/guestInfo/guestInfoServer.c: Move to new NicInfo structures. * vmware-user/foundryToolsDaemon.c, guestd/foundryToolsDaemon.c: Make sure requestMsg is not NULL before looking inside it. * guestd/main.c: Cleanup of HGFS pserver and mounting code. Check for some type of signal when sending an RPC. * guestd/toolsDaemon.c, vmware-user/resolution.c: Have the guest tell the host whether screen resolution changes should be sent, instead of having the host guess it based on the OS type set in the .vmx file. Better timeout checking to avoid problems when host & guest time diverge. * hgfsmounter/hgfsmounter.c: FreeBSD support. Fixes to compile on old systems. * lib/backdoor/backdoor.c: Tweak for FreeBSD kernel modules. * lib/include/mntinfo.h, lib/dnd/dndLinux.c, lib/wiper/wiperPosix.c, lib/syncDriver/syncDriverPosix.c: Fixes to compile on new systems w/gcc 4.2. * lib/err/err.c, lib/err/errPosix.c, lib/err/Makefile.am: Move Err_Errno2String function into POSIX-specific source file. * lib/file/fileIOPosix.c: Handle EDQUOT if applicable. Fixes to compile on new systems where SYS__llseek may not be available. Better reporting of errors, by translating errno into FILEIO_* error codes. * lib/file/fileLockPosix.c: Fixes to compile on old systems. Add a bunch of functions to the FileLock* API. * lib/file/fileLockPrimitive.c, lib/include/fileInt.h: Bunch of file locking cleanups and bug fixes. * lib/file/filePosix.c: Bunch of MacOS-related fixes. Add File_GetTimes(), FilePosixGetParent(), FilePosixGetBlockDevice(), etc. * lib/fileUtf8/fileUTF8Linux.c: Add FileUTF8_GetTimes() function. * lib/foundry/foundryMsg.c, lib/include/vixCommands.h: Add VIX_USER_CREDENTIAL_HOST_CONFIG_HASHED_SECRET credential type, and a bunch of VIX commands relating to record-replay. * lib/foundryMsg/vixTranslateErrOpenSource.c: Translate a couple more error codes. * lib/guestInfo/guestInfoPosix.c, lib/guestInfo/Makefile.am: Use libdnet on Solaris to retrieve networking info. * lib/hgfs/cpNameUtil.c, lib/hgfs/cpNameUtilInt.h, lib/hgfs/cpNameUtilLinux.c: Couple more CPName <-> UTF8 conversion routines. Some MacOS changes as well. * lib/hgfs/hgfsUtil.c, lib/include/hgfs.h, modules/linux/vmhgfs/fsutil.c: Handle ENAMETOOLONG. * lib/hgfs/staticEscape.c, lib/hgfs/hgfsBd.c: Handle FreeBSD as well. * lib/hgfsServer/hgfsServer.c: Tie in the cpNameUtil UTF8 changes on MacOS. * lib/hgfsServer/hgfsServerLinux.c: Make the getdents() wrapper work on a wider range of Linux systems. Add "alias" resolution on MacOS, and tie in the cpNameUtil UTF8 changes on MacOS. * lib/hgfsServer/hgfsServerPolicyGuest.c: Handle FreeBSD. * lib/include/backdoor_def.h: Add BDOOR_CMD_LAZYTIMEREMULATION and BDOOR_CMD_BIOSBBS. * lib/include/str.h, lib/include/bsd_output.h, lib/include/bsd_output_int.h: include compat_stdarg.h, change vsnwprintf prototype, add HAVE_BSD_WPRINTF define, other compat fixups. * lib/include/cpNameUtil.h, lib/include/codeset.h, lib/misc/codeset.c: Changes to correspond to cpNameUtil UTF8 changes. * lib/include/compat/compat_stdarg.h: New header for doing stdarg easily across platforms. * lib/include/cpName.h: FreeBSD fixes. * lib/include/dnd.h: Add Dnd_SetClipboard and Dnd_GetFileList(). * lib/include/escBitvector.h: FreeBSD fixes. * lib/include/file.h, lib/include/fileUTF8.h: Add new MacOS routines and File_GetTimes/FileUTF8_GetTimes. * lib/include/hgfsProto.h: Explanation of the whole cpNameUtil and codeset UTF8 changes and how they tie in with HGFS. * lib/include/hgfsUtil.h: Random compatibility changes. * lib/include/loglevel_user.h: Add a few LOGLEVEL_VAR definitions. * lib/include/msg.h: s/USE_MSGFMT/NO_MSGFMT/ * lib/include/osNames.h: Add Windows 2003 Datacenter Edition, and user-visible 64bit suffix macro. * lib/misc/random.c, lib/include/random.h: Add Random_Quick() and Random_QuickSeed() routines. * lib/misc/idLinux.c, lib/include/su.h: Add Id_AuthGetLocal() and Id_GetAuthExternal() routines, and compat fixes. * lib/misc/timeutil.c, lib/include/timeutil.h: Add TimeUtil_UnixTimeToNtTime() routine. * lib/include/util.h: Add a couple of MacOS routines. * lib/include/vmBackup.h, lib/vmBackupLib/stateMachine.c: add a couple of structure elements for Windows backup fixes. * lib/include/vm_basic_asm.h: fixes for reading TSC on 64-bit platforms. * lib/include/vm_basic_defs.h: Add other va_copy macros. * lib/include/vm_basic_types.h: Fixes for compiling on a wide range of systems. * lib/include/vm_legal.h: Change the PATENTS_STRING * lib/include/vm_product.h: Add "License Infrastructure" product. * lib/include/vm_tools_version.h: Change tools versions listed for various upcoming product releases. * lib/include/vm_version.h: Update the versions. * lib/include/x86cpuid.h: Define more CPU flags & fields, add new CPU models. Fixes for fully writable TSC detection. * lib/message/message.c, lib/message/messageBackdoor.c: Fixes for FreeBSD. * lib/misc/util_misc.c: Handle MacOS. * lib/rpcIn/rpcin.c: Fail a badly-formed RPC instead of ASSERT()'ing into oblivion. * lib/string/bsd_vsnprintf.c: Various fixes to synchronize with bsd_vsnwprintf.c. * lib/string/Makefile.am, lib/string/shared/Makefile.am, lib/string/str.c lib/string/bsd_vsnwprintf.c: New file to implement vsnwprintf() for compat purposes. * lib/vixTools/vixTools.c: New FileUTF8 routines. * Makefile.am, modules/Makefile.am: --without-x fixes, add xferlogs, move kernel module building into separate Makefile.am * modules/freebsd/*: Add FreeBSD kernel modules (vmblock, vmhgfs, vmmemctl, vmxnet). * modules/linux/*/include/compat_*.h, modules/linux/*/autoconf/cachector.c, modules/linux/*/autoconf/cachecreate.c, modules/linux/*/backdoor.c, modules/linux/vmhgfs/filesystem.c, modules/linux/vmhgfs/hgfsBd.c, lib/procMgr/procMgrPosix.c, lib/rpcOut/rpcout.c, lib/user/util.c, lib/vmCheck/vmcheck.c, libguestlib/Makefile.am, lib/deployPkg/runDeployPkgPosix.c, lib/include/vm_atomic.h: Compat fixes. * modules/linux/*/kernelStubs.h: Update for FreeBSD. * modules/linux/*/include/*.h, modules/linux/*/backdoor_def.h, modules/linux/*/cpName.h, modules/linux/*/hgfs.h, modules/linux/*/hgfsProto.h, modules/linux/*/hgfsUtil.[ch], modules/linux/*/kernelStubsLinux.c, modules/linux/*/messageBackdoor.c, modules/linux/*/message.c, modules/linux/*/rpcout.c, modules/linux/*/rpcin.c, modules/linux/*/staticEscape.c, modules/linux/*/vm_basic_asm.h, modules/linux/*/vm_basic_defs.h, modules/linux/*/vm_basic_types.h, modules/linux/*/x86cpuid.h, modules/linux/*/compat_*.h: Pull in updated files from main source tree. * modules/linux/*/Makefile.kernel: Remove CC_WARNINGS/CC_OPTS gunk. * modules/linux/*/README, modules/linux/*/Makefile.normal: Build foo.o driver by default on systems with VM_KBUILD=no. * modules/linux/vmhgfs/vmhgfs_version.h: Updated VMHGFS driver version. * modules/linux/vmmemctl/os.[ch], modules/linux/vmmemctl/vmballoon.c: Implement and use os_yield() to deprioritize the Balloon_Deallocate operation. * modules/linux/vmsync/*: New sync driver to make VM snapshots consistent. * modules/linux/vmxnet/bpf_meta.h: New file. * modules/linux/vmxnet/net_dist.h: Update NET_MAX_IMPL_PKT_OVHD value. * modules/linux/vmxnet/vm_device_version.h: Mention VMXNET3 * modules/linux/vmxnet/vmkapi_status.h: Updated VMK_ERR codes. * modules/linux/vmxnet/vmkapi_types.h: Add VMK_CONST64(U) macros. * modules/linux/vmxnet/vmxnet2_def.h, modules/linux/vmxnet/vmnet_def.h, modules/linux/vmxnet/vmxnet_def.h, modules/linux/vmxnet/vmxnetInt.h, modules/linux/vmxnet/vmxnet.c: Add (optional) BPF support. * modules/linux/vmxnet/vmxnetInt.h, modules/linux/vmxnet/vmxnet.c: Add vmxnet_link_check to propagate device link status to netdev. * common/vm-support: New script to gather support info from a VM. * scripts/*/*-default: New poweron/poweroff/suspend/resume scripts for a VM. Add support for dropping user-provided scripts into a subdirectory. * toolbox/toolboxAbout.c: Eliminate warnings about unused variables. * toolbox/toolboxShrink.c: Update wording of message. * toolbox/copyPaste.c: Try cutting & pasting UTF8 text if we can. * xferlogs/*: New log transfer utility. 2007-10-26 Elliot Lee * Initial import of 2007.09.04-56574 code ("Axe" release). * Import 2007.10.08 snapshot, which includes patches to fix the --without-x flag, and compilation with gcc 4.2. open-vm-tools-stable-10.2.0/open-vm-tools/LICENSE000066400000000000000000001331151321503522500213070ustar00rootroot00000000000000LICENSE Open-vm-tools v10.2.0 The Linux kernel modules are released under the GPL v2, a majority of the user level components are released under the LGPL v2.1, and the SVGA and mouse drivers are released under the X11 license. Copyright © 2007-2017 VMware, Inc. All rights reserved. ========================================================================= GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. ========= GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. ========= X11 License Copyright (c) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ======== Open-vm-tools v10.2.0 includes a number of subcomponents with separate copyright notices and license terms. Your use of the source code for these subcomponents is subject to the terms and conditions of the following licenses. SECTION 1: BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES >>> cvtutf-1.4 >>> freebsd-1.72 >>> freebsd-base64-4.8 >>> unicode-5.0 =================================================== --------------- SECTION 1: BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES ---------- BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES are applicable to the following component(s). >>> cvtutf-1.4 Copyright 2001-2004 Unicode, Inc. Disclaimer This source code is provided as is by Unicode, Inc. No claims are made as to fitness for any particular purpose. No warranties of any kind are expressed or implied. The recipient agrees to determine applicability of information provided. If this file has been purchased on magnetic or optical media from Unicode, Inc., the sole remedy for any claim will be exchange of defective media within 90 days of receipt. Limitations on Rights to Redistribute This Code Unicode, Inc. hereby grants the right to freely use the information supplied in this file in the creation of products supporting the Unicode Standard, and to make copies of this file in any form for internal or external distribution as long as this notice remains attached. >>> freebsd-1.72 Copyright (c) 1990, 1993 The Regents of the University of California. 3 All rights reserved. This code is derived from software contributed to Berkeley by Chris Torek. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 4. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. >>> freebsd-base64-4.8 base64.c -- routines to encode/decode base64 data $OpenLDAP: pkg/ldap/libraries/liblutil/base64.c,v 1.15 2006/01/03 22:12:11 kurt Exp $ / This work is part of OpenLDAP Software . Copyright 1998-2006 The OpenLDAP Foundation. Portions Copyright 1998-2003 Kurt D. Zeilenga. Portions Copyright 1995 IBM Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted only as authorized by the OpenLDAP Public License. A copy of this license is available in the file LICENSE in the top-level directory of the distribution or, alternatively, at . The OpenLDAP Public License Version 2.8, 17 August 2003 Redistribution and use of this software and associated documentation ("Software"), with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source form must retain copyright statements and notices, 2. Redistributions in binary form must reproduce applicable copyright statements and notices, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution, and 3. Redistributions must contain a verbatim copy of this document. The OpenLDAP Foundation may revise this license from time to time. Each revision is distinguished by a version number. You may use this Software under terms of this license revision or under the terms of any subsequent revision of the license. THIS SOFTWARE IS PROVIDED BY THE OPENLDAP FOUNDATION AND ITS CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENLDAP FOUNDATION, ITS CONTRIBUTORS, OR THE AUTHOR(S) OR OWNER(S) OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The names of the authors and copyright holders must not be used in advertising or otherwise to promote the sale, use or other dealing in this Software without specific, written prior permission. Title to copyright in this Software shall at all times remain with copyright holders. OpenLDAP is a registered trademark of the OpenLDAP Foundation. Copyright 1999-2003 The OpenLDAP Foundation, Redwood City, California, USA. All Rights Reserved. Permission to copy and distribute verbatim copies of this document is granted. ADDITIONAL LICENSE INFORMATION: Portions Copyright (c) 1996, 1998 by Internet Software Consortium. Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This work is based upon Base64 routines (developed by IBM) found Berkeley Internet Name Daemon (BIND) as distributed by ISC. They were adapted for inclusion in OpenLDAP Software by Kurt D. Zeilenga. >>> unicode-5.0 Copyright (c) 2008 VMware, Inc. All rights reserved. Copyright (c) 1991-2007 Unicode, Inc. All rights reserved. Distributed under the Terms of Use in http://www.unicode.org/copyright.html. Permission is hereby granted, free of charge, to any person obtaining a copy of the Unicode data files and any associated documentation (the "Data Files") or Unicode software and any associated documentation (the "Software") to deal in the Data Files or Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Data Files or Software, and to permit persons to whom the Data Files or Software are furnished to do so, provided that (a) the above copyright notice(s) and this permission notice appear with all copies of the Data Files or Software, (b) both the above copyright notice(s) and this permission notice appear in associated documentation, and (c) there is clear notice in each modified Data File or in the Software as well as in the documentation associated with the Data File(s) or Software that the data or software has been modified. THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in these Data Files or Software without prior written authorization of the copyright holder. [OPENVMTOOLS1020GANR111717] open-vm-tools-stable-10.2.0/open-vm-tools/Makefile.am000066400000000000000000000042501321503522500223330ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### Top-level Makefile for building the VMware OSS Tools. ### ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ # These flags get passed to aclocal when autoreconf calls it, and tell aclocal # that all of our macros are in the 'm4' subdirectory. ACLOCAL_AMFLAGS = -I m4 SUBDIRS = SUBDIRS += lib SUBDIRS += libvmtools SUBDIRS += libhgfs SUBDIRS += hgfsclient if BUILD_HGFSMOUNTER SUBDIRS += hgfsmounter endif if ENABLE_VGAUTH SUBDIRS += vgauth endif SUBDIRS += checkvm SUBDIRS += libguestlib if ENABLE_DEPLOYPKG SUBDIRS += libDeployPkg endif SUBDIRS += rpctool SUBDIRS += namespacetool if ENABLE_GRABBITMQPROXY SUBDIRS += guestproxycerttool endif SUBDIRS += scripts SUBDIRS += services SUBDIRS += toolbox if HAVE_X11 SUBDIRS += vmware-user-suid-wrapper endif if HAVE_FUSE SUBDIRS += vmblock-fuse SUBDIRS += vmhgfs-fuse endif if !LINUX SUBDIRS += vmblockmounter endif SUBDIRS += xferlogs if ENABLE_TESTS SUBDIRS += tests endif if WITH_KERNEL_MODULES SUBDIRS += modules endif SUBDIRS += docs if ENABLE_CAF SUBDIRS += common-agent/Cpp/Framework SUBDIRS += common-agent/Cpp/ManagementAgent SUBDIRS += common-agent/Cpp/Communication SUBDIRS += common-agent/Cpp/ProviderFx SUBDIRS += common-agent/Cpp/InternalProviders SUBDIRS += common-agent/input SUBDIRS += common-agent/etc endif if HAVE_UDEV SUBDIRS += udev endif open-vm-tools-stable-10.2.0/open-vm-tools/NEWS000066400000000000000000000546361321503522500210130ustar00rootroot00000000000000open-vm-tools 2013.04.16 changes: * VMCI/VMSOCK Linux kernel modules are disabled for kernels 3.9 and above. * HGFS compilation fixes, performance and other improvements. * Disable glib deprecation warnigns on newer Linux distributions. * Configure script will automatically detect procps-ng. * Other fixes and cleanups. open-vm-tools 2012.12.26 changes: * vmsync is not longer being compiled on newer (3.0+) Linux kernels since they support FIFREEZE/FITHAW ioctls. * vmblock is not longer being compiled on newer (3.0+) Linux kernels, such systems should use vmblock-fuse. * The draft SOCK_SEQPACKET code is removed from VSOCK driver. * Fixes for the vmballoon driver. * Other fixes and cleanups. open-vm-tools 2012.10.14 changes: * Changes and cleanups to VMCI driver * Changes to HGFS to allow compiling on newer kernels * Fix MTU handling in vmxnet3 for Solaris driver. * Updates to the vmballon driver to handle new protocol. * Fix for FreeBSD version of vmblock driver to stop kernel panics on unload on FreeBSD 9.0 * Fix to guestinfo plugin causing vmtoolsd to crash when guest had too many NICs. * Other fixes and cleanups. open-vm-tools 2012.05.21 changes: * Updates for newer Linux kernel releases (3.4). * Fix for vmxnet driver and IPV6 * VMCI updates and fixes. * Other fixes and cleanups. open-vm-tools 2012.03.13 changes: * Updates for newer Linux kernel releases (3.3). * Updates for Solaris 11. * Updates for FreeBSD 9.0. * Translation updates. * Other fixes and cleanups. open-vm-tools 2011.12.20 changes: * Updates for new Linux kernel releases, including some fixes for Fedora's re-versioned 3.x kernels. * VMCI sockets has some changes for a new socket type, targeted at replacing the "backdoor" communication used by the tools services. * HGFS has better session support. * Miscelaneous bug fixes and small enhancements in other parts of the code. open-vm-tools 2011.11.20 changes: * Updates for new Linux kernel releases. * Better Unity and DnD compatibility with newer Linux distros. * Other minor fixes and cleanups. open-vm-tools 2011.10.26 changes: * Mostly cleanups and bug fixes. * Code can now compile with uClibc, with some caveats. open-vm-tools 2011.09.23 changes: * open-vm-tools now can use the built in Linux freeze / thaw support for block devices, making the vmsync driver unnecessary in kernels supporting that feature. * The VMCI driver has been simplified, removing VM-to-VM communication support (which is being removed from VMware products). * The Unity team decided to remove the Unity plugin from open-vm-tools, given its partial brokenness due to reliance on internally-modified version of GNOME libraries, among other reasons. * Other bug fixes and code cleanup. open-vm-tools 2011.08.21 changes: * Enabled several VIX APIs on FreeBSD. * Minor bug fixes and code cleanup. open-vm-tools 2011.07.19 changes: * Fix an issue in the HGFS driver that could lead to a kernel panic. * Update some code to support new compiler and kernel versions. * Minor bug fixes and code cleanup. open-vm-tools 2011.06.27 changes: * A few enhancements to Unity: XFCE support, better interaction with "the other" (Ubuntu's) Unity and compositing window managers, better X error handling, and a few bug fixes. * A few bug fixes in HGFS, and minor bug fixes in other components. * Otherwise, mostly code cleanup. open-vm-tools 2011.05.27 changes: * Mostly cleanups and a few bug fixes. open-vm-tools 2011.04.25 changes: * Mostly cleanups and small bug fixes in this release. * Logging is enabled by default in vmtoolsd, writing to syslog. The default log level is not chatty, so few messages should make it to syslog during normal operation. * The GUI version of the toolbox was removed. open-vm-tools 2011.03.28 changes: * HGFS mounter and vmusr's suid wrapper were changed to avoid issues with symlink attacks. A new mount utility for vmblock on Solaris and FreeBSD was added. * The VMCI driver was thoroughly reworked so that it can serve as both the host and guest VMCI driver. This is mostly targeted at supporting nested VMs. * vmusr got better integration with X's session manager, including proper cleanup during session teardown. * Unity has been enhanced to better handle some desktop environments. * Many small bug fixes in other areas, including updates for newer Linux kernels. open-vm-tools 2011.02.23 changes: * Some copy & paste issues with KDE were fixed. * Mostly cleanups and bug fixes, with a few build enhancements. open-vm-tools 2011.01.24 changes: * Mostly cleanups and bug fixes. * Install code fixed to handle translation catalogs correctly. open-vm-tools 2010.12.19 changes: * New version of DnD code lands in open-vm-tools. The host part of the new DnD protocol is not available yet in VMware products, though. * vmtoolsd gets some new functionality to support new features being developed internally. * vmxnet driver for FreeBSD fixed to allow changing the MAC address. * lots of bug fixes and other cleanups in various areas. open-vm-tools 2010.11.17 changes: * Mostly cleanups and bug fixes. * vmxnet3 on Solaris now supports jumbo frames. open-vm-tools 2010.10.18 changes: * The unity plugin has received some refactoring work, and the menu gathering code has been enhanced to be more DE-agnostic and support the new app icon code. It now needs glib 2.24 to compile. * Several bug fixes and enhancements to the VIX plugin. * Bug fixes to the guest info plugin so that it better supports VMs with several network interfaces. * Other minor enhancements and bug fixes in several areas, including vsock, vmmemctl and copy & paste. open-vm-tools 2010.09.19 changes: * Mostly cleanups and minor bug fixes. * VIX plugin has been updated with lots of new commands being added to the next VIX API release. open-vm-tools 2010.08.24 changes: * HGFS and VMCI kernel module bug fixes, and updates to compile in newer Linux kernels. * HGFS server interface refactoring was finished, now supports the transport abstraction available for the kernel interface. * VIX operations are now properly implemented on Solaris, plus new operations added to support features under development. * Other minor cleanups and bug fixes. open-vm-tools 2010.07.25 changes: * Features previously provided by vmware-user are now provided as vmtoolsd plugins. vmware-user has been removed and code that interacted with it changed to start the correct vmtoolsd instance. * Lots of cleanup: removed old compatibility headers not needed anymore, removed dead code, consolidated logging code. * Time synchronization now works more like NTP. * New code for features not yet exposed by VMware host software is being added. open-vm-tools 2010.06.16 changes: * VMCI moves towards unifying the guest and host driver APIs, and gets support for MSI/MSI-X. * More work on new VMCI-backed HGFS protocol. * vmmemctl: Linux driver removed (it's now upstream), plus cleanup and simplification of the FreeBSD and Solaris drivers. * some Linux kernel compatibility fixes. * Cleanup of old kernel support code. * Some cleanup of old VIX features. * toolbox-cmd was updated to use newer APIs, and got some i18n enhancements. * some bug fixes and enhancements to the logging code. * update detection and use of some needed libraries. * More progress in making libraries thread-safe. open-vm-tools 2010.04.25 changes: * VMCI and HGFS get some initial work for new features. * vmbackup support has been extended to more systems, allowing its use even if the system lacks a proper "sync" implementation. * A few bug fixes in different areas: Unity/X11, vmware-user startup on upstart-based systems, and other minor fixes / thread safety fixes. * The pvscsi driver was removed from the open-vm-tools distribution (it is upstream as of Linux 2.6.33). * The vmmemctl driver will be upstream as of Linux 2.6.34, at which point it will be removed from open-vm-tools. open-vm-tools 2010.03.20 changes: * New i18n support for Tools; it is based on VMware's internal tools (instead of gettext). * Logging infrastructure has been enhanced and now supports rotation (without the need for logrotate) and syslog. * Bug fixes in several areas (DnD, backup support, thread safety). * Updates in Linux kernel modules for compatibility with newer kernels. * New functionality in the Unity support code. open-vm-tools 2010.02.23 changes: * Mostly bug fixes, cleanups and code refactoring. open-vm-tools 2010.01.19 changes: * Linux modules have been updated to compile on newer kernels. * Solaris modules now should compile on OpenSolaris (tested on 2009.06). * Other than those, mostly bug fixes and minor refactoring. open-vm-tools 2009.12.16 changes: * Some improvements to vmtoolsd, base libraries and and the plugin interface. * Some library refactoring: use new lock library, changes to support compilation of some code on ARM. * some fixes in configure.ac to try to correctly support newer distros. * vsock/vmci improvements. * bug fixes in the vmxnet / vmxnet3 drivers, and FreeBSD's vmblock driver. * vmxnet3 for Linux is now upstream (as of Linux 2.6.32), and will be removed from later releases of open-vm-tools. * pvscsi will be available upstream starting with Linux 2.6.33 and at that time will be removed from open-vm-tools. open-vm-tools 2009.11.16 changes: * Lots of refactoring and cleanup in the code, mainly targeting the definition of a set of public APIs. * vmblock-fuse can now replace the vmblock kernel module for DnD operations. * Fix some memory leaks in the guestInfo module. Users of the 2009.10.15 release are recommended to upgrade, or at least crossport cid 6a8d4279. open-vm-tools 2009.10.15 changes: * The HGFS module got some performance enhancements. * Minor enhancements to vmtoolsd and the logging system. * Fix for a few issues reported on the sourceforge bug tracker. * Lots of code refactoring, and a few bug fixes. open-vm-tools 2009.09.18 changes: * Mostly bug fixes and minor enhancements. * The pvscsi code was re-factored in preparation for upstreaming. The driver has been sent to the LKML for inclusion in the main Linux tree, and might be removed from open-vm-tools once it's accepted. open-vm-tools 2009.08.24 changes: * Remove support for Linux kernels < 2.6.9. * The vsock now implements a new notification protocol that has better performance than the previous. * New infrastructure for sending more network config-related information about the virtual machine to the host. * Other bug fixes and minor improvements to the code. open-vm-tools 2009.07.22 changes: * Better support for dkms by means of a script to help create a dkms tree. * "make install" now also installs header files for public libraries, plus a few fixes to incorrect install behavior. * Lots of improvements to the new DnD code. * This will be the last release with support for Linux kernels < 2.6.9. open-vm-tools 2009.06.18 changes: * Mostly a bug fix release. * vmhgfs now is able to use vsock as a transport (although backend support for HGFS over vsock is not yet released in VMware products). open-vm-tools 2009.05.22 changes: * Mostly a cleanup and bug fix release. * Fix a build issue where a symlink attack could cause the open-vm-tools build to overwrite data (by placing a symlink in /tmp). * Second (and last?) batch of changes to clean up duplicate files in the source tree, including Solaris and FreeBSD kernel modules and other module-specific shared files. * Plugins now are properly built using plugins_LTLIBRARIES so that "-rpath" doesn't need to be used (this would cause an RPATH entry to be added to the final binary, which some tools didn't like). Thanks to Dominique Leuenberger for the suggestion. * open-vm-tools now properly detects PAM and enables PAM support in the code. open-vm-tools 2009.04.23 changes: * Implemented copy & paste support for RTF data and file contents. * guestd has been removed from open-vm-tools; vmtoolsd is now the only option for the main tools service. * Added vmblock and vmmemctl modules for Solaris (under the CDDL). * vmware-user can now work with both vmblock-fuse and vmblock. * Linux HGFS now has a stream-based (TCP, vsock) transport, still under development. * First batch of changes to cleanup duplicated files in the source tree. Most duplicated files in the Linux kernel modules have been cleaned up. open-vm-tools 2009.03.18 changes: * Mostly a bug fix release. * Solaris vmxnet3 driver was added; open-vm-tools now should also compile on OpenSolaris (tested on 08.11), as long as the --without-gtkmm option is used. * The new DnD V3 protocol is now available in open-vm-tools. * Added "rpctool", a simple, stand-alone tool to send RPC commands to the host software. * vmtoolsd is now preferred in lieu of vmware-guestd; vmware-guestd will most probably be completely removed in the next release. open-vm-tools 2009.02.18 changes: * open-vm-tools now depend on glib 2.6.0 as a minimum requirement. * Added vmxnet module for Solaris, and reworked the HGFS module so it works without help from vmware-guestd. * Added implementation of new DnD protocol, which adds a dependency on a C++ compiler and the gtkmm library to vmware-user. * The code from the "core services" has been added to open-vm-tools, including a few tests. vmtoolsd + plugins are now capable of replacing vmware-guestd (vmware-user still needs to have some features ported over), but this code is still not to be considered as stable as the legacy services, so vmware-guestd is still included. * A few fixes for compatibility with non-GNU toolchains, newer Linux kernels and old gcc compilers. open-vm-tools 2009.01.21 changes: * First open source release of the HGFS module for Solaris, under the CDDL. Other modules are expected to be added in the upcoming releases. * Added an implementation of vmblock on top of FUSE; vmware-user still doesn't use this module even if it is available, though. * Linux modules now add the "supported" tag used by Novell in their SLES 10 SP2 release when loading modules. * Fix compilation of modules in newer Linux kernels which don't include $(LINUXINCLUDE) in the compiler flags anymore. open-vm-tools 2008.12.23 changes: * Lots of makefile cleanup with the switch to using libtool archives. * Automatically disable Unity if multimon support is disabled. * Actually build the pvscsi modules. * First bits of the "Core Service" project are starting to show up; the base "vmtools" library was added to the package. It currently is mostly a collection of the existing libraries already shipped with open-vm-tools, plus some extra functionality build on top of glib. Currently no other code in open-vm-tools uses it, so it's optional. * The HGFS driver was fixed for the Linux 2.6.28 kernel. open-vm-tools 2009.11.18 changes: * The pvscsi Linux kernel module has been added (for kernels >= 2.6.8). It provides access to VMware's new paravirtualized SCSI device. * The HGFS driver and user-level code has seen a lot of refactoring to enable more consistent name escaping. The FreeBSD driver now supports symlinks. * The Linux module makefiles now support exporting symbol version files, allowing modules with dependencies (such as vsock, which depends on vmci) to correctly build and load on Linux >= 2.6.26 with CONFIG_MODVERSIONS. * Rudimentary support for dkms. * Assortment of bug fixes. open-vm-tools 2009.10.13 changes: * The vmxnet3 Linux kernel module has been added. This module provides better network performance for the guest. The corresponding virtual hardware is available beginning with Workstation 6.5, though performance benefits are unlikely to be realized until a later VMware product release. The module should work for all kernels beginning with 2.6. * The open-vm-tools no longer depend on libproc-dev. Several people reported this issue (Sourceforge bug 1960947). * Added a command line argument to skip privileged operations during make install (--without-root-privileges). * Guestd now supports backwards time synchronization, though the corresponding hypervisor-side changes are not yet part of any shipping VMware products. * Assortment of bug fixes. open-vm-tools 2009.09.03 changes: * Fixed an issue where open-vm-tools fails to configure when using --without-icu. Thanks to Timo Gurr for reporting the issue (Sourceforge bug 2046262). * Fixed failed build on Ubuntu Intrepid and Fedora 9. Thanks to Nathan Charles for reporting the issue (Sourceforge bug 2048423). * Fixed kernel module build issues on 2.6.27 pre-release kernels. Thanks to Dominique Leuenberger for reporting the issue (Sourceforge bug 2071170). * ...and other bug fixes. open-vm-tools 2008.08.08 changes: * Unity for X11 guests has been added. Unity is implemented within vmware-user and requires no additional setup beyond setting up the vmware-user application itself. Unity should work with Fusion 1.x releases as well as with the upcoming Workstation 6.5 release. Our in-house testing was with Linux guests, and they should mostly work. There is very little standing in the way of FreeBSD/Solaris support, though we've never built or tested Unity for those platforms. * The VMCI Linux kernel module has been added. This module provides high-speed datagram and socket interfaces for guest<->guest and host<->guest communication. It should work for all kernels beginning with 2.4, and for VMware products beginning with Workstation 6.5. * The VMCI sockets Linux kernel module has been added. It provides both datagram and stream socket interfaces to userlevel for use with VMCI. As with VMCI, it should work for kernels 2.4 or later, and for VMware products beginning with Workstation 6.5. * The command-line Toolbox has been added. This application provides the same functionality as the GTK Toolbox, but with a scriptable command-line interface. It also has some statistic retrieval commands that aren't found in the GTK Toolbox. * Fixed compilation of vmsync and vmmemctl Linux kernel modules on 2.6.26. Thanks to Pavol Rusnak for the report (Sourceforge bug 2032683). * Fixed an issue with guestd's nicInfo updating mechanism. Thanks to Jason Lunz for the patch (not tracked on Sourceforge). * Fixed handling of $(DESTDIR) in automake. Thanks to Mike Auty for the patch (Sourceforge bug 2018802). * Fixed build of vmware-user using gtk 1.2. Thanks to Stephen Duncan for the report (Sourceforge bug 2014338). * Fixed compilation of lib/guestApp when using --without-x. Thanks to Martin Preishuber for the report (Sourceforge bug 2013568). * As usual, other bug fixes. open-vm-tools 2008.07.01 changes: * Fixed a backwards time synchronization issue (not tracked on Sourceforge). Thanks to Eric Castan for reporting it. * Fixed an issue where open-vm-tools configured via --without-x didn't compile (not tracked on Sourceforge). Thanks to Mark Foster for reporting the bug. * Other bug fixes. open-vm-tools 2008.06.20 changes: * Fixed Sourceforge bug 1847750 (FreeBSD 7 & 8 builds) and Sourceforge bug 1981632 (build failure on Solaris). This should get open-vm-tools building and running on FreeBSD 7 & 8 and Solaris. Thanks to Martin Blapp for all the FreeBSD patches, and Jonathan Keatley for reporting the Solaris bug. * Fixed Sourceforge bug 1968416 (packet counting in FreeBSD vmxnet). Thanks to Shunsuke SHINOMIYA for reporting this bug. * Fixed Sourceforge bug 1983375 (Cannot specify kernel constraints). You can now pass --without-kernel-modules, --with-kernel-release, and --with-linuxdir to the ./configure script. Thanks to Craig Phillips for reporting this bug. * Other bug fixes. open-vm-tools 2008.06.03 changes: * Added the vmware-user-suid-wrapper application, with implementations for Linux, FreeBSD, and Solaris. This app is needed to make correct use of vmware-user with the vmblock kernel module. It should have been in the previous code refresh, but we accidentally overlooked it. * Fixed Sourceforge bug 1924246: vmhgfs on Linux properly reports the available space on the host. Thanks to Mikhail Krivtsov for reporting the bug. * Fixed Sourceforge bug 1839981: we now have rudimentary `make install` support. On any platform, it should copy files and kernel modules to the location specified at build-time, and on Linux, it will additionally run `depmod -a` to make the kernel modules accessible to modprobe. This change also adds a "--with-pam-prefix" argument to the configure script, which controls the location of guestd's pam files. * Other bug fixes. open-vm-tools 2008.05.15 changes: * guestd no longer starts vmware-user. Packagers will need to use the XDG autostart spec, Xsession drop-in scripts, or other appropriate mechanisms to make sure that vmware-user is started as part of X session initialization. Please see http://open-vm-tools.wiki.sourceforge.net/Packaging for more details. * Bug fixes as usual. open-vm-tools 2008.05.02 changes: * Continued Unicode support. * open-vm-tools now depends on libicu for codeset conversions. If you wish to build open-vm-tools without libicu, pass "--without--icu" when configuring the package. Without libicu, codeset conversions will be done as before, via calls to iconv. * A few more bug fixes. open-vm-tools 2008.04.14 changes: * Update the license stamp on all LGPL files. * Continued Unicode support. * Handle libdumbnet on Debian. * More bug fixes, including a security fix in guestd. open-vm-tools 2008.03.19 changes: * Continued Unicode support. * A few bug fixes. open-vm-tools 2008.03.03 changes: * Bug fixes (including the ability to specify custom LDFLAGS at build time, thanks to Mike Auty). * First cut of HGFSv3 implementation. * Beginnings of DnDv3 implementation. * Add Unicode support all over the code base. open-vm-tools 2008.02.13 changes: * Some bug fixes. open-vm-tools 2008.01.23 changes: * The Linux HGFS kernel module now supports writeback caching, which should yield better performance. * Added a generic Unicode-aware library to ease i18n and l10n work. * A bunch of bug fixes. open-vm-tools 2007.11.15 "Bandsaw" changes: * Kernel modules for FreeBSD, including an experimental port of HGFS to FreeBSD. * Add the vmsync driver on Linux to make VM snapshots consistent. * Added the xferlogs utility, the *-vm-default scripts, and the vm-support script. * Build on a wider variety of systems. * Lots of smaller bug fixes throughout the code. open-vm-tools 2007.09.04 "Axe" changes: * Initial release of open-vm-tools. open-vm-tools-stable-10.2.0/open-vm-tools/README000066400000000000000000000117531321503522500211650ustar00rootroot00000000000000Project information: open-vm-tools These are the release notes for the open-vm-tools. Read them carefully, as they explain how to build this project for different platforms and various different Linux distributions. ================================================================================ General information: (*)What are the open-vm-tools? The open-vm-tools are a subset of the VMware Tools, currently composed of kernel modules for Linux and user-space programs for all VMware supported Unix like guest operating systems. (*)Where do I find documentation for the open-vm-tools beyond this README? Please refer to the main project web site for all the latest documentation at: (*)How do I build the open-vm-tools? The open-vm-tools uses the GNU Automake tool for generating Makefiles to build all sources. More information about Automake can be found here: For more information on building this project see the "Project build information" section of this document. ================================================================================ Project build information: (*)Getting configure options & help: If you are looking for help or additional settings for the building of this project the following configure command will display a list of help options: "./configure --help" (*)Using configure: When using configure in the steps below it is only necessary to call "./configure" once unless there was a problem after the first invocation. (*)Building Unix user-space programs: 1) "./configure" 2) Run "make" to build Unix userland programs 3) Run "make modules" to build kernel modules (*)Packaging: If you are interested in creating a Tools package, please see for more information. ================================================================================ Build suggestions: Each Linux distribution puts binaries, libraries and development headers in different locations. This leads to having to setup different paths for the compiler and linker for the Automake system. Below is a list of known configurations to build for platforms that do not "just work" out of the box or the tar-ball as the case may be. General Build note: Please make note that the "--disable-multimon" flag should only be used when there are no libXinerama libraries installed, or you do not want to enable multi monitor support. Your operating system version will influence which kernel modules can be built. Here are the minimum OS versions for each module: |------------------------------------------------------------------------------| | vmsync | vmblock | vmxnet | vmmemctl | vmhgfs | |---------------|----------------|--------------|----------------|-------------| | Linux 2.6.6 | Linux 2.4.0 | Linux 2.2.0 | Linux 2.2.0 | Linux 2.4.0 | | FreeBSD N/A | FreeBSD 6.0 | FreeBSD 4.9 | FreeBSD 3.2 | | |------------------------------------------------------------------------------| (*)Suse Enterprise 10.1 (i386 & x86_64): i386: ./configure LDFLAGS="-L/opt/gnome/lib" x86_64: ./configure LDFLAGS="-L/opt/gnome/lib64" (*)OpenSolaris "Nevada" (i386 & x86_64): Before building open-vm-tools on Solaris, you will need to make sure that libdnet (http://libdnet.sourceforge.net/) is installed and that the 'dnet-config' script is on your shell's PATH. Make sure that the GNU tools are in your shell's PATH. The default GNU tools location on OpenSolaris is: "/usr/sfw/bin". Once the PATH is set in your build shell then the following configure command should work: ./configure --disable-multimon (*)FreeBSD 6.2 (i386 & x86_64): ./configure LDFLAGS="-L/usr/local/lib" ================================================================================ Other resources: There are also open-source video & mouse drivers for Xorg/XFree86 that provide better performance and additional features to Linux, Solaris, and BSD derivatives guests running X11. The drivers 'xf86-input-vmmouse' and 'xf86-video-vmware' are included with recent Xorg releases, and it shouldn't be necessary to do anything extra to obtain them. If you want to obtain them separately, they can be downloaded at: ================================================================================ Guest operating systems used to test on this release: (*)Fedora Core 8 (i386 & x86_64) (*)Redhat 9.0 (i386) (*)Redhat Enterprise 4 U5 (i386 & x86_64) (*)Redhat Enterprise 5 (i386 & x86_64) (*)FreeBSD 5.4 (i386 & x86_64) (*)FreeBSD 6.2 (i386 & x86_64) (*)OpenSolaris 10 "Nevada" (i386 & x86_64) (*)Open SuSE 10.3 (i386 & x86_64) (*)Ubuntu 6.04 (i386 & x86_64) (*)Ubuntu 7.10 (i386 & x86_64) =============================================================================== Known issues: =============================================================================== open-vm-tools-stable-10.2.0/open-vm-tools/checkvm/000077500000000000000000000000001321503522500217165ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/checkvm/COPYING000066400000000000000000000634711321503522500227640ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! open-vm-tools-stable-10.2.0/open-vm-tools/checkvm/Makefile.am000066400000000000000000000025731321503522500237610ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ bin_PROGRAMS = vmware-checkvm vmware_checkvm_SOURCES = vmware_checkvm_SOURCES += checkvm.c vmware_checkvm_LDADD = vmware_checkvm_LDADD += @VMTOOLS_LIBS@ if HAVE_ICU vmware_checkvm_LDADD += @ICU_LIBS@ vmware_checkvm_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXX) \ $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ else vmware_checkvm_LINK = $(LINK) endif open-vm-tools-stable-10.2.0/open-vm-tools/checkvm/checkvm.c000066400000000000000000000066471321503522500235170ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * checkvm.c -- * * Check if we are running in a VM or not */ #include #include #if !defined(_WIN32) #include #endif #include "vm_version.h" #include "backdoor.h" #include "backdoor_def.h" #include "vm_basic_types.h" #include "vmcheck.h" #if defined(_WIN32) #include "getoptwin32.h" #endif #include "checkvm_version.h" #include "vm_version.h" #include "embed_version.h" VM_EMBED_VERSION(CHECKVM_VERSION_STRING); /* * getHWVersion - Read VM HW version through backdoor */ void getHWVersion(uint32 *hwVersion) { Backdoor_proto bp; bp.in.cx.halfs.low = BDOOR_CMD_GETHWVERSION; Backdoor(&bp); *hwVersion = bp.out.ax.word; } /* * getScreenSize - Get screen size of the host */ void getScreenSize(uint32 *screensize) { Backdoor_proto bp; bp.in.cx.halfs.low = BDOOR_CMD_GETSCREENSIZE; Backdoor(&bp); *screensize = bp.out.ax.word; } /* * Start of main program. Check if we are in a VM, by reading * a backdoor port. Then process any other commands. */ int main(int argc, char *argv[]) { uint32 version[2]; int opt; int width, height; uint32 screensize = 0; uint32 hwVersion; if (!VmCheck_IsVirtualWorld()) { fprintf(stdout, "Not running in a virtual machine.\n"); return 1; } if (!VmCheck_GetVersion(&version[0], &version[1])) { fprintf(stdout, "Couldn't get version\n"); return 1; } /* * OK, we're in a VM, check if there are any other requests */ while ((opt = getopt(argc, argv, "rph")) != EOF) { switch (opt) { case 'r': getScreenSize(&screensize); width = (screensize >> 16) & 0xffff; height = screensize & 0xffff; if ((width <= 0x7fff) && (height <= 0x7fff)) { printf("%d %d\n", width, height); } else { printf("0 0\n"); } return 0; case 'p': /* * Print out product that we're running on based on code * obtained from getVersion(). */ switch (version[1]) { case VMX_TYPE_SCALABLE_SERVER: printf("ESX Server\n"); break; case VMX_TYPE_WORKSTATION: printf("Workstation\n"); break; default: printf("Unknown\n"); break; } return 0; case 'h': getHWVersion(&hwVersion); printf("VM's hw version is %u\n", hwVersion); break; default: break; } } printf("%s version %d (good)\n", PRODUCT_LINE_NAME, version[0]); return 0; } open-vm-tools-stable-10.2.0/open-vm-tools/checkvm/checkvm_version.h000066400000000000000000000030151321503522500252530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * checkvm_version.h -- * * Version definitions for the VM checking utility. */ #ifndef _CHECKVM_VERSION_H_ #define _CHECKVM_VERSION_H_ /* * This component's version is coupled with Tools versioning. The effect * is that the version increments with each build, and with each Tools * version bump. If and when it becomes necessary to version the component * manually, make sure that the version is bumped any time the component or * its dependencies are changed. */ #include "vm_tools_version.h" #define CHECKVM_VERSION_COMMAS TOOLS_VERSION_EXT_CURRENT_CSV #define CHECKVM_VERSION_STRING TOOLS_VERSION_EXT_CURRENT_STR #endif /* _CHECKVM_VERSION_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/000077500000000000000000000000001321503522500226625ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/000077500000000000000000000000001321503522500234045ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/000077500000000000000000000000001321503522500262115ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Makefile.am000066400000000000000000000402301321503522500302440ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ AUTOMAKE_OPTIONS = subdir-objects subsysdir = @CAF_SUBSYS_DIR@ subsys_LTLIBRARIES = cafbindir = @CAF_PME_BIN_DIR@ cafbin_PROGRAMS = caflibdir = @CAF_PME_LIB_DIR@ caflib_LTLIBRARIES = caflib_LTLIBRARIES += libCommAmqpIntegration.la libCommAmqpIntegration_la_SOURCES= libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AMQChannel.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AMQChannelManager.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AMQCommand.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AMQConnection.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AMQUtil.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/Address.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AmqpAuthPlain.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AmqpChannel.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AmqpCommon.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AmqpConnection.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/AmqpUtil.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/BlockingRpcContinuation.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/CAmqpAuthMechanism.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/CAmqpChannel.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/CAmqpConnection.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/CAmqpFrame.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/CertInfo.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/CommandAssembler.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/ConnectionFactoryImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/ConnectionWeakReference.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/ConsumerDispatcher.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/ConsumerWorkService.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpClient.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/AMQExceptions.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/AMQPImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/AmqpClientImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/AmqpContentHeadersImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicAckMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicCancelMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicCancelOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicConsumeMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicConsumeOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicDeliverMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicGetEmptyMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicGetMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicGetOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicProperties.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicPublishMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicQosMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicQosOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicRecoverMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicRecoverOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicRejectMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/BasicReturnMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/ChannelCloseMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/ChannelCloseOkFromServerMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/ChannelCloseOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/ChannelOpenOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/EnvelopeImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/ExchangeDeclareMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/ExchangeDeclareOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/ExchangeDeleteMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/ExchangeDeleteOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/FieldImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/GetResponseImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueueBindMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueueBindOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueueDeclareMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueueDeclareOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueueDeleteMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueueDeleteOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueuePurgeMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueuePurgeOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueueUnbindMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpClient/amqpImpl/QueueUnbindOkMethod.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/AbstractConnectionFactory.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/AmqpHeaderMapper.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/AmqpIntegrationExceptions.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/AmqpMessageListenerSource.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/AmqpOutboundEndpoint.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/AutoChannelClose.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/BindingImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/BlockingQueueConsumer.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/CachedChannelHandler.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/CachingConnectionFactory.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/ChannelCachingConnectionProxy.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/CompositeConnectionListener.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/DefaultAmqpHeaderMapper.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/ExchangeImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/HeaderUtils.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/QueueImpl.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/RabbitAdmin.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/RabbitTemplate.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/SimpleConnection.cpp libCommAmqpIntegration_la_SOURCES += amqpCore/src/amqpCore/SimpleMessageListenerContainer.cpp libCommAmqpIntegration_la_CPPFLAGS = libCommAmqpIntegration_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libCommAmqpIntegration_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libCommAmqpIntegration_la_CPPFLAGS += @SSL_CPPFLAGS@ libCommAmqpIntegration_la_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ libCommAmqpIntegration_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libCommAmqpIntegration_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/amqpListener/include libCommAmqpIntegration_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/amqpCore/include libCommAmqpIntegration_la_LIBADD = libCommAmqpIntegration_la_LIBADD += @GLIB2_LIBS@ libCommAmqpIntegration_la_LIBADD += @LOG4CPP_LIBS@ libCommAmqpIntegration_la_LIBADD += @SSL_LIBS@ libCommAmqpIntegration_la_LIBADD += -ldl libCommAmqpIntegration_la_LIBADD += @LIBRABBITMQ_LIBS@ libCommAmqpIntegration_la_LIBADD += ../Framework/libFramework.la libCommAmqpIntegration_la_LDFLAGS = -shared subsys_LTLIBRARIES += libCommAmqpIntegrationSubsys.la libCommAmqpIntegrationSubsys_la_LDFLAGS = @CAF_SUBSYS_LDFLAGS@ libCommAmqpIntegrationSubsys_la_SOURCES= libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/AmqpInboundChannelAdapterInstance.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/AmqpOutboundEndpointInstance.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/BindingInstance.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/CachingConnectionFactoryObj.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/ExchangeInstance.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/IntegrationObjects.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/QueueInstance.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/RabbitAdminInstance.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/RabbitTemplateInstance.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/SecureCachingConnectionFactoryObj.cpp libCommAmqpIntegrationSubsys_la_SOURCES += Subsystems/amqpIntegration/src/amqpIntegration.cpp libCommAmqpIntegrationSubsys_la_CPPFLAGS = libCommAmqpIntegrationSubsys_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libCommAmqpIntegrationSubsys_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libCommAmqpIntegrationSubsys_la_CPPFLAGS += @SSL_CPPFLAGS@ libCommAmqpIntegrationSubsys_la_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ libCommAmqpIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libCommAmqpIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/amqpListener/include libCommAmqpIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/amqpCore/include libCommAmqpIntegrationSubsys_la_LIBADD = libCommAmqpIntegrationSubsys_la_LIBADD += @GLIB2_LIBS@ libCommAmqpIntegrationSubsys_la_LIBADD += @LOG4CPP_LIBS@ libCommAmqpIntegrationSubsys_la_LIBADD += @SSL_LIBS@ libCommAmqpIntegrationSubsys_la_LIBADD += -ldl libCommAmqpIntegrationSubsys_la_LIBADD += @LIBRABBITMQ_LIBS@ libCommAmqpIntegrationSubsys_la_LIBADD += ../Framework/libFramework.la libCommAmqpIntegrationSubsys_la_LIBADD += ../Communication/libCommAmqpIntegration.la libCommAmqpIntegrationSubsys_la_LDFLAGS += -shared cafbin_PROGRAMS += CommAmqpListener CommAmqpListener_SOURCES= CommAmqpListener_SOURCES += amqpListener/src/AmqpListenerWorker.cpp CommAmqpListener_SOURCES += amqpListener/src/amqpListenerMain.cpp CommAmqpListener_CPPFLAGS = CommAmqpListener_CPPFLAGS += @GLIB2_CPPFLAGS@ CommAmqpListener_CPPFLAGS += @LOG4CPP_CPPFLAGS@ CommAmqpListener_CPPFLAGS += @SSL_CPPFLAGS@ CommAmqpListener_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ CommAmqpListener_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include CommAmqpListener_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/amqpListener/include CommAmqpListener_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/amqpCore/include CommAmqpListener_LDADD = CommAmqpListener_LDADD += @GLIB2_LIBS@ CommAmqpListener_LDADD += @LOG4CPP_LIBS@ CommAmqpListener_LDADD += @SSL_LIBS@ CommAmqpListener_LDADD += -ldl CommAmqpListener_LDADD += @LIBRABBITMQ_LIBS@ CommAmqpListener_LDADD += ../Framework/libFramework.la CommAmqpListener_LDADD += ../Communication/libCommAmqpIntegration.la subsys_LTLIBRARIES += libCommIntegrationSubsys.la libCommIntegrationSubsys_la_LDFLAGS = @CAF_SUBSYS_LDFLAGS@ libCommIntegrationSubsys_la_SOURCES= libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CCmsMessage.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CCmsMessageAttachments.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CCmsMessageTransformer.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CCmsMessageTransformerInstance.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CCmsMessageUtils.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CEventTopicCalculatorInstance.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CIncomingMessageHandler.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CIncomingMessageHandlerInstance.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CMessageDeliveryRecord.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CMessagePartDescriptor.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CMessagePartDescriptorCalculator.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CMessagePartDescriptorSourceRecord.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CMessagePartRecord.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CMessagePartsBuilder.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CMessagePartsHeader.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CMessagePartsParser.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/COutgoingMessageHandler.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CProtocolHeaderEnricher.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CProtocolHeaderEnricherInstance.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CReplyToCacher.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CReplyToCacherInstance.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/CReplyToResolverInstance.cpp libCommIntegrationSubsys_la_SOURCES += Subsystems/commIntegration/src/commIntegration.cpp libCommIntegrationSubsys_la_CPPFLAGS = libCommIntegrationSubsys_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libCommIntegrationSubsys_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libCommIntegrationSubsys_la_CPPFLAGS += @SSL_CPPFLAGS@ libCommIntegrationSubsys_la_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ libCommIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libCommIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/amqpListener/include libCommIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/amqpCore/include libCommIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Communication/Subsystems/commIntegration/include libCommIntegrationSubsys_la_LIBADD = libCommIntegrationSubsys_la_LIBADD += @GLIB2_LIBS@ libCommIntegrationSubsys_la_LIBADD += @LOG4CPP_LIBS@ libCommIntegrationSubsys_la_LIBADD += @SSL_LIBS@ libCommIntegrationSubsys_la_LIBADD += -ldl libCommIntegrationSubsys_la_LIBADD += @LIBRABBITMQ_LIBS@ libCommIntegrationSubsys_la_LIBADD += ../Framework/libFramework.la libCommIntegrationSubsys_la_LIBADD += ../Communication/libCommAmqpIntegration.la libCommIntegrationSubsys_la_LDFLAGS += -shared open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/000077500000000000000000000000001321503522500303725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/000077500000000000000000000000001321503522500335345ustar00rootroot00000000000000src/000077500000000000000000000000001321503522500342445ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegrationAmqpInboundChannelAdapterInstance.cpp000066400000000000000000000212541321503522500434500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Aug 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CMessageHandler.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/Core/CSourcePollingChannelAdapter.h" #include "Integration/Dependencies/CPollerMetadata.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationAppContext.h" #include "Integration/IIntegrationObject.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpCore/AmqpMessageListenerSource.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/DefaultAmqpHeaderMapper.h" #include "amqpCore/Queue.h" #include "Common/CCafRegex.h" #include "Exception/CCafException.h" #include "AmqpInboundChannelAdapterInstance.h" using namespace Caf::AmqpIntegration; AmqpInboundChannelAdapterInstance::AmqpInboundChannelAdapterInstance() : _isInitialized(false), _isRunning(false), _ackModeProp(ACKNOWLEDGEMODE_AUTO), _connectionFactoryProp("connectionFactory"), _autoStartupProp(true), _phaseProp(G_MAXINT32), _prefetchCountProp(1), _receiveTimeoutProp(1000), _recoveryIntervalProp(5000), _txSizeProp(1), CAF_CM_INIT_LOG("AmqpInboundChannelAdapterInstance") { } AmqpInboundChannelAdapterInstance::~AmqpInboundChannelAdapterInstance() { } void AmqpInboundChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); std::string prop = configSection->findOptionalAttribute("id"); if (prop.length()) { _idProp = prop; } else { _idProp = "AmqpInboundChannelAdapter-"; _idProp += CStringUtils::createRandomUuid(); } _channelProp = configSection->findRequiredAttribute("channel"); _queueProp = configSection->findRequiredAttribute("queue-name"); prop = configSection->findOptionalAttribute("acknowledge-mode"); if (prop.length()) { if (prop == "NONE") { _ackModeProp = ACKNOWLEDGEMODE_NONE; } else if (prop == "AUTO") { _ackModeProp = ACKNOWLEDGEMODE_AUTO; } else if (prop == "MANUAL") { CAF_CM_EXCEPTIONEX_VA0( InvalidArgumentException, 0, "acknowledge-mode MANUAL is not supported"); //_ackModeProp = ACKNOWLEDGEMODE_MANUAL; } else { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "invalid acknowledge-mode '%s'", prop.c_str()); } } prop = configSection->findOptionalAttribute("connection-factory"); if (prop.length()) { _connectionFactoryProp = prop; } _errorChannelProp = configSection->findRequiredAttribute("error-channel"); _mappedRequestHeadersProp = configSection->findOptionalAttribute("mapped-request-headers"); prop = configSection->findOptionalAttribute("auto-startup"); if (prop.length()) { if (prop == "true") { _autoStartupProp = true; } else if (prop == "false") { _autoStartupProp = false; } else { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "invalid auto-startup '%s'", prop.c_str()); } } prop = configSection->findOptionalAttribute("phase"); if (prop.length()) { _phaseProp = CStringConv::fromString(prop); } prop = configSection->findOptionalAttribute("prefetch-count"); if (prop.length()) { _prefetchCountProp = CStringConv::fromString(prop); } prop = configSection->findOptionalAttribute("receive-timeout"); if (prop.length()) { _receiveTimeoutProp = CStringConv::fromString(prop); } prop = configSection->findOptionalAttribute("recovery-interval"); if (prop.length()) { _recoveryIntervalProp = CStringConv::fromString(prop); } prop = configSection->findOptionalAttribute("tx-size"); if (prop.length()) { _txSizeProp = CStringConv::fromString(prop); } _isInitialized = true; } std::string AmqpInboundChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _idProp; } void AmqpInboundChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); CCafRegex qRegEx; qRegEx.initialize("^\\#\\{(?P.+)\\}$"); Cdeqstr matchName = qRegEx.matchName(_queueProp, "name"); if (matchName.size()) { std::string queueRef = matchName.front(); CAF_CM_LOG_DEBUG_VA1("Resolving queue object reference '%s'", queueRef.c_str()); SmartPtrIIntegrationObject obj = _intAppContext->getIntegrationObject(queueRef); SmartPtrQueue queueObj; queueObj.QueryInterface(obj, false); if (queueObj) { _queueProp = queueObj->getName(); CAF_CM_LOG_DEBUG_VA2( "Queue object reference '%s' resolved to AMQP queue name '%s'", queueRef.c_str(), _queueProp.c_str()); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Integration object '%s' is not of type Queue.", queueRef.c_str()); } } SmartPtrAmqpHeaderMapper headerMapper; if (_mappedRequestHeadersProp.length()) { SmartPtrDefaultAmqpHeaderMapper defaultHeaderMapper; defaultHeaderMapper.CreateInstance(); defaultHeaderMapper->init(_mappedRequestHeadersProp); headerMapper = defaultHeaderMapper; } SmartPtrCPollerMetadata pollerMetadata; pollerMetadata.CreateInstance(); pollerMetadata->putMaxMessagesPerPoll(_txSizeProp); pollerMetadata->putFixedRate(50); SmartPtrAmqpMessageListenerSource listenerSource; listenerSource.CreateInstance(); listenerSource->init(headerMapper, pollerMetadata); _listenerContainer.CreateInstance(); _listenerContainer->setAcknowledgeMode(_ackModeProp); SmartPtrIBean bean = appContext->getBean(_connectionFactoryProp); SmartPtrConnectionFactory connectionFactory; connectionFactory.QueryInterface(bean, false); if (!connectionFactory) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Bean '%s' is not a ConnectionFactory", _connectionFactoryProp.c_str()); } _listenerContainer->setConnectionFactory(connectionFactory); _listenerContainer->setPrefetchCount(_prefetchCountProp); _listenerContainer->setQueue(_queueProp); _listenerContainer->setReceiveTimeout(_receiveTimeoutProp); _listenerContainer->setRecoveryInterval(_recoveryIntervalProp); _listenerContainer->setTxSize(_txSizeProp); _listenerContainer->setMessagerListener(listenerSource); _listenerContainer->init(); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize( channelResolver, channelResolver->resolveChannelName(_errorChannelProp)); SmartPtrCMessageHandler messageHandler; messageHandler.CreateInstance(); messageHandler->initialize( _idProp, channelResolver->resolveChannelName(_channelProp), SmartPtrICafObject()); SmartPtrCSourcePollingChannelAdapter sourcePollingChannelAdapter; sourcePollingChannelAdapter.CreateInstance(); sourcePollingChannelAdapter->initialize( messageHandler, listenerSource, errorHandler); SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor; simpleAsyncTaskExecutor.CreateInstance(); simpleAsyncTaskExecutor->initialize( sourcePollingChannelAdapter, errorHandler); _taskExecutor = simpleAsyncTaskExecutor; _intAppContext = NULL; } void AmqpInboundChannelAdapterInstance::setIntegrationAppContext( SmartPtrIIntegrationAppContext context) { CAF_CM_FUNCNAME_VALIDATE("setIntegrationAppContext"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(context); _intAppContext = context; } bool AmqpInboundChannelAdapterInstance::isAutoStartup() const { CAF_CM_FUNCNAME_VALIDATE("isAutoStartup"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _autoStartupProp; } void AmqpInboundChannelAdapterInstance::start(const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _listenerContainer->start(timeoutMs); _taskExecutor->execute(timeoutMs); _isRunning = true; } void AmqpInboundChannelAdapterInstance::stop(const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _listenerContainer->stop(timeoutMs); _taskExecutor->cancel(timeoutMs); } bool AmqpInboundChannelAdapterInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _isRunning; } int32 AmqpInboundChannelAdapterInstance::getPhase() const { CAF_CM_FUNCNAME_VALIDATE("getPhase"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _phaseProp; } AmqpInboundChannelAdapterInstance.h000066400000000000000000000131541321503522500431150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Aug 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AmqpInboundChannelAdapterInstance_h #define AmqpInboundChannelAdapterInstance_h #include "Integration/IIntegrationAppContextAware.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationAppContext.h" #include "Integration/ITaskExecutor.h" #include "amqpCore/SimpleMessageListenerContainer.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/IPhased.h" #include "Integration/ISmartLifecycle.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObj * @brief Adapter that receives messages from an AMQP queue, converts them into * integration messages, and sends the results to a Message Channel. *

*

 * Example context file declaration:
 *
 * 
 *
 * 
 * 
 *
 * 
 *
 *	
*

* XML attribute definitions: * * * * * * * * * * * * * * * *
AttributeDescription
idoptional Unique id for this adapter.
channelrequired The channel to which messages should be sent.
queue-namerequired The AMQP queue from which messaged should be consumed.
acknowledge-modeoptional Acknowledgment mode (NONE, AUTO, MANUAL). Defaults to AUTO.
connection-factoryoptional Bean reference to the RabbitMQ ConnectionFactory. Defaults to 'connectionFactory'
error-channelrequired Message channel to which error messages should be sent.
mapped-request-headersoptional A regular expression indicating which AMQP headers will be mapped into message headers.
auto-startupoptional Specifies if the adapter is to start automatically. If 'false', the adapter must be started programatically. Defaults to 'true'.
phaseoptional Specifies the phase in which the adapter should be started. By default this value is G_MAXINT32 meaning that this adapter will start as late as possible.
prefetch-countoptional Tells the AMQP broker how many messages to send to the the consumer in a single request. Defaults to 1.
receive-timeoutoptional Receive timeout in milliseconds. Defaults to 1000.
recovery-intervaloptional Specifies the interval between broker connection recovery attempts in milliseconds. Defaults to 5000.
tx-sizeoptional Tells the adapter how many messages to process in a single batch. This should be less than or equal to to prefetch-count. Defaults to 1.
*/ class AmqpInboundChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public IIntegrationAppContextAware, public ISmartLifecycle, public IPhased { CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IIntegrationAppContextAware) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(ISmartLifecycle) CAF_QI_ENTRY(IPhased) CAF_END_QI() public: AmqpInboundChannelAdapterInstance(); virtual ~AmqpInboundChannelAdapterInstance(); public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // IIntegrationAppContextAware void setIntegrationAppContext( SmartPtrIIntegrationAppContext context); public: // ISmartLifecycle bool isAutoStartup() const; public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // IPhased int32 getPhase() const; private: bool _isInitialized; bool _isRunning; SmartPtrIIntegrationAppContext _intAppContext; SmartPtrSimpleMessageListenerContainer _listenerContainer; SmartPtrITaskExecutor _taskExecutor; std::string _idProp; std::string _channelProp; std::string _queueProp; AcknowledgeMode _ackModeProp; std::string _connectionFactoryProp; std::string _errorChannelProp; std::string _mappedRequestHeadersProp; bool _autoStartupProp; int32 _phaseProp; uint32 _prefetchCountProp; uint32 _receiveTimeoutProp; uint32 _recoveryIntervalProp; uint32 _txSizeProp; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(AmqpInboundChannelAdapterInstance); }; CAF_DECLARE_SMART_QI_POINTER(AmqpInboundChannelAdapterInstance); }} #endif /* AmqpInboundChannelAdapterInstance_h */ AmqpOutboundEndpointInstance.cpp000066400000000000000000000101321321503522500425510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jul 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpCore/AmqpOutboundEndpoint.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationAppContext.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" #include "amqpCore/AmqpTemplate.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "AmqpOutboundEndpointInstance.h" using namespace Caf::AmqpIntegration; AmqpOutboundEndpointInstance::AmqpOutboundEndpointInstance() : _isInitialized(false), _isRunning(false), CAF_CM_INIT_LOG("AmqpOutboundEndpointInstance") { } AmqpOutboundEndpointInstance::~AmqpOutboundEndpointInstance() { } void AmqpOutboundEndpointInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { _id = configSection->findOptionalAttribute("id"); if (!_id.length()) { _id = CStringUtils::createRandomUuid(); } _configSection = configSection; _isInitialized = true; } std::string AmqpOutboundEndpointInstance::getId() const { return _id; } void AmqpOutboundEndpointInstance::setIntegrationAppContext( SmartPtrIIntegrationAppContext context) { _context = context; } void AmqpOutboundEndpointInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); std::string elementVal = _configSection->findOptionalAttribute("amqp-template"); if (!elementVal.length()) { elementVal = "amqpTemplate"; CAF_CM_LOG_DEBUG_VA0("Using default amqp-template reference value 'amqpTemplate'"); } SmartPtrIIntegrationObject amqpTemplateObj = _context->getIntegrationObject(elementVal); SmartPtrAmqpTemplate amqpTemplate; amqpTemplate.QueryInterface(amqpTemplateObj, false); if (!amqpTemplate) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Bean '%s' is not of type AmqpTemplate", elementVal.c_str()); } SmartPtrIAppConfig appConfig = getAppConfig(); SmartPtrAmqpOutboundEndpoint outboundEndpoint; outboundEndpoint.CreateInstance(); elementVal = _configSection->findOptionalAttribute("exchange-name"); outboundEndpoint->setExchangeName(appConfig->resolveValue(elementVal)); elementVal = _configSection->findOptionalAttribute("exchange-name-expression"); outboundEndpoint->setExchangeNameExpression(elementVal); elementVal = _configSection->findOptionalAttribute("routing-key"); outboundEndpoint->setRoutingKey(appConfig->resolveValue(elementVal)); elementVal = _configSection->findOptionalAttribute("routing-key-expression"); outboundEndpoint->setRoutingKeyExpression(elementVal); elementVal = _configSection->findOptionalAttribute("mapped-request-headers"); outboundEndpoint->setMappedRequestHeadersExpression(appConfig->resolveValue(elementVal)); outboundEndpoint->init( amqpTemplate, appConfig, appContext); elementVal = _configSection->findRequiredAttribute("channel"); SmartPtrIMessageChannel inputChannel = channelResolver->resolveChannelName(elementVal); SmartPtrIIntegrationObject inputChannelObj; inputChannelObj.QueryInterface(inputChannel); _messagingTemplate.CreateInstance(); _messagingTemplate->initialize( channelResolver, inputChannelObj, errorMessageChannel, SmartPtrIMessageChannel(), outboundEndpoint); } void AmqpOutboundEndpointInstance::start(const uint32 timeoutMs) { CAF_CM_FUNCNAME("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(!_isRunning); _isRunning = true; _messagingTemplate->start(0); } void AmqpOutboundEndpointInstance::stop(const uint32 timeoutMs) { CAF_CM_FUNCNAME("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(_isRunning); _isRunning = false; _messagingTemplate->stop(0); } bool AmqpOutboundEndpointInstance::isRunning() const { return _isRunning; } AmqpOutboundEndpointInstance.h000066400000000000000000000075101321503522500422240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jul 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPOUTBOUNDENDPOINTINSTANCE_H_ #define AMQPOUTBOUNDENDPOINTINSTANCE_H_ #include "Integration/IIntegrationAppContextAware.h" #include "Common/IAppContext.h" #include "Integration/Core/CMessagingTemplate.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationAppContext.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObj * @brief An Integration Object implementing Caf::AmqpIntegration::AmqpOutboundEndpoint *

*

 * Example context file declaration:
 *
 * 
 *
 * 
 *
 * 
 *	
*

* XML attribute definitions: * * * * * * * * * *
AttributeDescription
channelrequired The channel supplying messages to be sent.
exchange-nameThe name of the exchange to publish to. * Either exchange-name or exchange-name-expression must be specified.
exchange-name-expressionThe name of the exchange to publish to resolved by calling an IExpressionInvoker object. * Either exchange-name or exchange-name-expression must be specified.
routing-keyThe routing key for the message. * Either routing-key or routing-key-expression must be specified.
routing-key-expressionThe routing key for the message resolved by calling an IExpressionInvoker object. * Either routing-key or routing-key-expression must be specified.
mapped-request-headersoptional A regular expression used to transmit user-defined headers along with the message. *
*/ class AmqpOutboundEndpointInstance : public IIntegrationObject, public IIntegrationComponentInstance, public IIntegrationAppContextAware, public ILifecycle { CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IIntegrationAppContextAware) CAF_QI_ENTRY(ILifecycle) CAF_END_QI() public: AmqpOutboundEndpointInstance(); virtual ~AmqpOutboundEndpointInstance(); public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // IIntegrationAppContextAware void setIntegrationAppContext( SmartPtrIIntegrationAppContext context); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; private: bool _isInitialized; bool _isRunning; std::string _id; SmartPtrIDocument _configSection; SmartPtrCMessagingTemplate _messagingTemplate; SmartPtrIIntegrationAppContext _context; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(AmqpOutboundEndpointInstance); }; CAF_DECLARE_SMART_QI_POINTER(AmqpOutboundEndpointInstance); }} #endif /* AMQPOUTBOUNDENDPOINTINSTANCE_H_ */ BindingInstance.cpp000066400000000000000000000022531321503522500400110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "amqpCore/Binding.h" #include "Exception/CCafException.h" #include "BindingInstance.h" using namespace Caf::AmqpIntegration; BindingInstance::BindingInstance() : CAF_CM_INIT("BindingInstance") { _id = CStringUtils::createRandomUuid(); } BindingInstance::~BindingInstance() { } void BindingInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_EXCEPTIONEX_VA0( UnsupportedOperationException, 0, "Binding init from xml not supported"); } std::string BindingInstance::getId() const { return _id; } void BindingInstance::setBindingInternal(SmartPtrBinding binding) { _binding = binding; } std::string BindingInstance::getQueue() const { return _binding->getQueue(); } std::string BindingInstance::getExchange() const { return _binding->getExchange(); } std::string BindingInstance::getRoutingKey() const { return _binding->getRoutingKey(); } BindingInstance.h000066400000000000000000000027171321503522500374630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BINDINGINSTANCE_H_ #define BINDINGINSTANCE_H_ #include "Integration/IIntegrationObject.h" #include "Integration/IDocument.h" #include "amqpCore/Binding.h" #include "amqpCore/BindingInternal.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObj * @brief An Integration Object implementing Caf::AmqpIntegration::Binding *

* Currently this object is only created indirectly through rabbit-binding * declarations in exchange declarations. */ class BindingInstance : public IIntegrationObject, public BindingInternal, public Binding { CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(BindingInternal) CAF_QI_ENTRY(Binding) CAF_END_QI() public: BindingInstance(); virtual ~BindingInstance(); public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // BindingInternal void setBindingInternal(SmartPtrBinding binding); public: // Binding std::string getQueue() const; std::string getExchange() const; std::string getRoutingKey() const; private: std::string _id; SmartPtrBinding _binding; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BindingInstance); }; CAF_DECLARE_SMART_QI_POINTER(BindingInstance); }} #endif /* BINDINGINSTANCE_H_ */ CachingConnectionFactoryObj.cpp000066400000000000000000000136551321503522500423210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 4, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "amqpCore/CachingConnectionFactory.h" #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionListener.h" #include "Exception/CCafException.h" #include "CachingConnectionFactoryObj.h" using namespace Caf::AmqpIntegration; CachingConnectionFactoryObj::CachingConnectionFactoryObj() : CAF_CM_INIT_LOG("CachingConnectionFactoryObj") { } CachingConnectionFactoryObj::~CachingConnectionFactoryObj() { } void CachingConnectionFactoryObj::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_factory); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); const std::string persistenceDir = AppConfigUtils::getRequiredString( "persistence_dir"); const SmartPtrCPersistenceProtocolDoc persistenceProtocol = CPersistenceUtils::loadPersistenceProtocol(persistenceDir); if (persistenceProtocol.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, ERROR_INVALID_STATE, "Persistence protocol is empty... Comm must be configured - %s", persistenceDir.c_str()); } UriUtils::SUriRecord uri; UriUtils::parseUriString(persistenceProtocol->getUri(), uri); const std::string vhost = UriUtils::findOptParameter(uri, "vhost", AppConfigUtils::getRequiredString("communication_amqp", "vhost")); const std::string connectionTimeout = UriUtils::findOptParameter(uri, "connection_timeout", CStringConv::toString( AppConfigUtils::getRequiredUint32("communication_amqp", "connection_timeout"))); const std::string connectionRetries = UriUtils::findOptParameter(uri, "connection_retries", CStringConv::toString( AppConfigUtils::getRequiredUint32("communication_amqp", "connection_retries"))); const std::string connectionSecondsToWait = UriUtils::findOptParameter(uri, "connection_seconds_to_wait", CStringConv::toString( AppConfigUtils::getRequiredUint32("communication_amqp", "connection_seconds_to_wait"))); const std::string channelCacheSize = UriUtils::findOptParameter(uri, "channel_cache_size", CStringConv::toString( AppConfigUtils::getRequiredUint32("communication_amqp", "channel_cache_size"))); CAF_CM_VALIDATE_STRING(uri.protocol); CAF_CM_VALIDATE_STRING(uri.host); CAF_CM_VALIDATE_STRING(uri.portStr); CAF_CM_VALIDATE_STRING(vhost); SmartPtrCachingConnectionFactory factory; factory.CreateInstance(); factory->init(); factory->setProtocol(uri.protocol); factory->setHost(uri.host); factory->setPort(uri.port); factory->setVirtualHost(vhost); if (!uri.username.empty()) { factory->setUsername(uri.username); } if (!uri.password.empty()) { factory->setPassword(uri.password); } if (!connectionTimeout.empty()) { factory->setConnectionTimeout(CStringConv::fromString(connectionTimeout)); } if (!connectionRetries.empty()) { factory->setRetries(CStringConv::fromString(connectionRetries)); } if (!connectionSecondsToWait.empty()) { factory->setSecondsToWait( CStringConv::fromString(connectionSecondsToWait)); } if (!channelCacheSize.empty()) { factory->setChannelCacheSize(CStringConv::fromString(channelCacheSize)); } _factory = factory; } void CachingConnectionFactoryObj::terminateBean() { CAF_CM_FUNCNAME("terminateBean"); try { if (_factory) { _factory->destroy(); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION ; CAF_CM_CLEAREXCEPTION; } SmartPtrConnection CachingConnectionFactoryObj::createConnection() { CAF_CM_FUNCNAME_VALIDATE("createConnection"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->createConnection(); } std::string CachingConnectionFactoryObj::getProtocol() { CAF_CM_FUNCNAME_VALIDATE("getProtocol"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getProtocol(); } std::string CachingConnectionFactoryObj::getHost() { CAF_CM_FUNCNAME_VALIDATE("getHost"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getHost(); } uint32 CachingConnectionFactoryObj::getPort() { CAF_CM_FUNCNAME_VALIDATE("getPort"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getPort(); } std::string CachingConnectionFactoryObj::getVirtualHost() { CAF_CM_FUNCNAME_VALIDATE("getVirtualHost"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getVirtualHost(); } std::string CachingConnectionFactoryObj::getUsername() { CAF_CM_FUNCNAME_VALIDATE("getUsername"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getUsername(); } std::string CachingConnectionFactoryObj::getPassword() { CAF_CM_FUNCNAME_VALIDATE("getPassword"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getPassword(); } std::string CachingConnectionFactoryObj::getCaCertPath() { CAF_CM_FUNCNAME_VALIDATE("getCaCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getCaCertPath(); } std::string CachingConnectionFactoryObj::getClientCertPath() { CAF_CM_FUNCNAME_VALIDATE("getClientCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getClientCertPath(); } std::string CachingConnectionFactoryObj::getClientKeyPath() { CAF_CM_FUNCNAME_VALIDATE("getClientKeyPath"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getClientKeyPath(); } uint16 CachingConnectionFactoryObj::getRetries() { CAF_CM_FUNCNAME_VALIDATE("getRetries"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getRetries(); } uint16 CachingConnectionFactoryObj::getSecondsToWait() { CAF_CM_FUNCNAME_VALIDATE("getSecondsToWait"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getSecondsToWait(); } void CachingConnectionFactoryObj::addConnectionListener( const SmartPtrConnectionListener& listener) { CAF_CM_FUNCNAME_VALIDATE("addConnectionListener"); CAF_CM_PRECOND_ISINITIALIZED(_factory); _factory->addConnectionListener(listener); } CachingConnectionFactoryObj.h000066400000000000000000000065211321503522500417600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 4, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CACHINGCONNECTIONFACTORYOBJ_H_ #define CACHINGCONNECTIONFACTORYOBJ_H_ #include "IBean.h" #include "amqpCore/CachingConnectionFactory.h" #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionListener.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObj * @brief An implementation of Caf::AmqpIntegration::ConnectionFactory that returns * the same connections from all calls, ignores calls to * Caf::AmqpClient::Connection::close and caches Caf::AmqpClient::Channel. *

* By default, only one channel will be cached, with additional requested channels * being created and disposed on demand. Consider raising the cache size in * high-concurrency environments. *

* NOTE: This factory requires explicit closing of all channels obtained from its * shared connection. Failure to close channels will disable channel reuse. *

* CachingConnectionFactory objects are created by inserting the following into * the application context: *

 *
 * \
 * 	\
 * 	\
 * 	\
 * \
 * 
* Properties: * * * * * * * * * * * * *
PropertyDescription
hostThe broker host. By default the machine's host name (or localhost * if the host name cannot be determined).
portThe broker port. By default AmqpClient::DEFAULT_AMQP_PORT
virtualHostThe virtual host on the broker. By default AmqpClient::DEFAULT_VHOST
connectionTimeoutThe connection timeout in milliseconds. A value of zero means * to wait indefinitely. By default 10 seconds.
channelCacheSizeThe number of channels to cache. By default 1.
*/ class CachingConnectionFactoryObj : public TCafSubSystemObjectRoot, public IBean, public ConnectionFactory { CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdAmqpCachingConnectionFactory) CAF_BEGIN_INTERFACE_MAP(CachingConnectionFactoryObj) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(ConnectionFactory) CAF_END_INTERFACE_MAP() public: CachingConnectionFactoryObj(); virtual ~CachingConnectionFactoryObj(); public: // IBean void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // ConnectionFactory SmartPtrConnection createConnection(); std::string getProtocol(); std::string getHost(); uint32 getPort(); std::string getVirtualHost(); std::string getUsername(); std::string getPassword(); std::string getCaCertPath(); std::string getClientCertPath(); std::string getClientKeyPath(); uint16 getRetries(); uint16 getSecondsToWait(); void addConnectionListener(const SmartPtrConnectionListener& listener); private: SmartPtrCachingConnectionFactory _factory; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CachingConnectionFactoryObj); }; }} #endif /* CACHINGCONNECTIONFACTORYOBJ_H_ */ ExchangeInstance.cpp000066400000000000000000000070241321503522500401620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "amqpCore/Binding.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "ExchangeInstance.h" #include "BindingInstance.h" using namespace Caf::AmqpIntegration; ExchangeInstance::ExchangeInstance() : CAF_CM_INIT_LOG("ExchangeInstance") { } ExchangeInstance::~ExchangeInstance() { } void ExchangeInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); _id = CStringUtils::createRandomUuid(); SmartPtrIAppConfig appConfig = getAppConfig(); const std::string exchange = appConfig->resolveValue(configSection->findRequiredAttribute("name")); const std::string durableStr = configSection->findOptionalAttribute("durable"); if (durableStr.length()) { if ((durableStr != "true") && (durableStr != "false")) { CAF_CM_EXCEPTIONEX_VA3( InvalidArgumentException, 0, "Invalid 'durable' value (%s) for %s '%s'. " "Value must be either 'true' or 'false'.", durableStr.c_str(), configSection->getName().c_str(), exchange.c_str()); } } const bool durable = !durableStr.length() || (durableStr == "true"); if (configSection->getName() == "rabbit-direct-exchange") { _exchange = createDirectExchange(exchange, durable); } else if (configSection->getName() == "rabbit-topic-exchange") { _exchange = createTopicExchange(exchange, durable); } else if (configSection->getName() == "rabbit-headers-exchange") { _exchange = createHeadersExchange(exchange, durable); } else if (configSection->getName() == "rabbit-fanout-exchange") { _exchange = createFanoutExchange(exchange, durable); } else { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "Invalid exchange type (%s)", configSection->getName().c_str()); } SmartPtrIDocument bindingsSection = configSection->findOptionalChild("rabbit-bindings"); if (bindingsSection) { IDocument::SmartPtrCChildCollection bindingSections = bindingsSection->getAllChildren(); for (TSmartConstMapIterator bindingSection(*bindingSections); bindingSection; bindingSection++) { if (bindingSection->getName() != "rabbit-binding") { CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, 0, "Invalid tag (%s) found in bindings section of " "exchange declaration (name=%s)", bindingSection->getName().c_str(), exchange.c_str()); } const std::string queue = appConfig->resolveValue(bindingSection->findRequiredAttribute("queue")); const std::string key = appConfig->resolveValue(bindingSection->findRequiredAttribute("key")); CAF_CM_LOG_DEBUG_VA3( "Adding binding declaration [queue id=%s][exchange name=%s][key=%s]", queue.c_str(), exchange.c_str(), key.c_str()); SmartPtrBindingInstance binding; binding.CreateInstance(); binding->setBindingInternal(createBinding(queue, exchange, key)); _bindings.push_back(binding); } } } std::string ExchangeInstance::getId() const { return _id; } std::string ExchangeInstance::getName() const { return _exchange->getName(); } std::string ExchangeInstance::getType() const { return _exchange->getType(); } bool ExchangeInstance::isDurable() const { return _exchange->isDurable(); } std::deque ExchangeInstance::getEmbeddedBindings() const { return _bindings; } ExchangeInstance.h000066400000000000000000000061021321503522500376230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef EXCHANGEINSTANCE_H_ #define EXCHANGEINSTANCE_H_ #include "Integration/IIntegrationObject.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationAppContext.h" #include "amqpCore/Binding.h" #include "amqpCore/Exchange.h" #include "amqpCore/ExchangeInternal.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObj * @brief An Integration Object implementing Caf::AmqpIntegration::Exchange *

* %Exchange to queue bindings are also declared as part of an exchange declaration. *

* Example context file declarations: *

* Direct exchange: *

 * 
 *    
 *    
 * 
 * 
* Topic exchange: *
 * 
 *    
 *    
 * 
 * 
* Other exchange types are rabbit-headers-exchange and * rabbit-fanout-exchange. *

* %Exchange XML attribute definitions: * * * * * * *
AttributeDescription
namerequired The AMQP name of the exchange. This is the name that * will be sent in the Exchange.Declare AMQP method.
durableoptional true to declare a durable exchange else false.
* %Binding XML attribute definitions: * * * * * * *
AttributeDescription
queuerequired The id of the queue integration object to bind to the exchange.
keyrequired The routing key for the binding. * The format is specific to the type of exchange.
*/ class ExchangeInstance : public IIntegrationObject, public ExchangeInternal, public Exchange { CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(ExchangeInternal) CAF_QI_ENTRY(Exchange) CAF_END_QI() public: ExchangeInstance(); virtual ~ExchangeInstance(); public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // Exchange std::string getName() const; std::string getType() const; bool isDurable() const; public: // ExchangeInternal std::deque getEmbeddedBindings() const; private: std::string _id; SmartPtrIIntegrationAppContext _integrationAppContext; SmartPtrExchange _exchange; std::deque _bindings; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(ExchangeInstance); }; CAF_DECLARE_SMART_QI_POINTER(ExchangeInstance); }} #endif /* EXCHANGEINSTANCE_H_ */ IntegrationObjects.cpp000066400000000000000000000061211321503522500405450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Exception/CCafException.h" #include "IntegrationObjects.h" #include "RabbitTemplateInstance.h" #include "RabbitAdminInstance.h" #include "ExchangeInstance.h" #include "QueueInstance.h" #include "AmqpOutboundEndpointInstance.h" #include "AmqpInboundChannelAdapterInstance.h" using namespace Caf::AmqpIntegration; IntegrationObjects::IntegrationObjects() : CAF_CM_INIT("IntegrationObjects") { } IntegrationObjects::~IntegrationObjects() { } void IntegrationObjects::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; } void IntegrationObjects::terminateBean() { } bool IntegrationObjects::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_VALIDATE_INTERFACE(configSection); const std::string name = configSection->getName(); return (name.compare("rabbit-template") == 0) || (name.compare("rabbit-admin") == 0) || (name.compare("rabbit-direct-exchange") == 0) || (name.compare("rabbit-topic-exchange") == 0) || (name.compare("rabbit-headers-exchange") == 0) || (name.compare("rabbit-fanout-exchange") == 0) || (name.compare("rabbit-queue") == 0) || (name.compare("rabbit-outbound-channel-adapter") == 0) || (name.compare("rabbit-inbound-channel-adapter") == 0); } SmartPtrIIntegrationObject IntegrationObjects::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME("createObject"); CAF_CM_VALIDATE_INTERFACE(configSection); SmartPtrIIntegrationObject rc; const std::string name = configSection->getName(); if (name.compare("rabbit-template") == 0) { SmartPtrRabbitTemplateInstance object; object.CreateInstance(); rc = object; } else if (name.compare("rabbit-admin") == 0) { SmartPtrRabbitAdminInstance object; object.CreateInstance(); rc = object; } else if ((name.compare("rabbit-direct-exchange") == 0) || (name.compare("rabbit-topic-exchange") == 0) || (name.compare("rabbit-headers-exchange") == 0) || (name.compare("rabbit-fanout-exchange") == 0)) { SmartPtrExchangeInstance object; object.CreateInstance(); rc = object; } else if (name.compare("rabbit-queue") == 0) { SmartPtrQueueInstance object; object.CreateInstance(); rc = object; } else if (name.compare("rabbit-outbound-channel-adapter") == 0) { SmartPtrAmqpOutboundEndpointInstance object; object.CreateInstance(); rc = object; } else if (name.compare("rabbit-inbound-channel-adapter") == 0) { SmartPtrAmqpInboundChannelAdapterInstance object; object.CreateInstance(); rc = object; } else { CAF_CM_EXCEPTION_VA1(E_INVALIDARG, "Unknown name - %s", name.c_str()); } rc->initialize(_ctorArgs, _properties, configSection); return rc; } IntegrationObjects.h000066400000000000000000000031701321503522500402130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef INTEGRATIONOBJECTS_H_ #define INTEGRATIONOBJECTS_H_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief The bean responsible for creating all of the AMQP integration objects. *

* All applications using AMQP integration must include this definition in the * application context: *

 * \
 * 
*/ class IntegrationObjects : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdIntegrationObjects) CAF_BEGIN_INTERFACE_MAP(IntegrationObjects) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: IntegrationObjects(); virtual ~IntegrationObjects(); public: // IBean void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(IntegrationObjects); }; }} #endif /* INTEGRATIONOBJECTS_H_ */ QueueInstance.cpp000066400000000000000000000056321321503522500375270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "amqpCore/Queue.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "QueueInstance.h" using namespace Caf::AmqpIntegration; QueueInstance::QueueInstance() : CAF_CM_INIT("QueueInstance") { } QueueInstance::~QueueInstance() { } void QueueInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); _id = configSection->findRequiredAttribute("id"); SmartPtrIAppConfig appConfig = getAppConfig(); const std::string name = appConfig->resolveValue(configSection->findOptionalAttribute("name")); const std::string durable = configSection->findOptionalAttribute("durable"); const std::string exclusive = configSection->findOptionalAttribute("exclusive"); const std::string autoDelete = configSection->findOptionalAttribute("auto-delete"); if (durable.length() && ((durable != "true") && (durable != "false"))) { CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, 0, "queue id (%s): 'durable' must be 'true' or 'false', not '%s'", _id.c_str(), durable.c_str()); } if (exclusive.length() && ((exclusive != "true") && (exclusive != "false"))) { CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, 0, "queue id (%s): 'exclusive' must be 'true' or 'false', not '%s'", _id.c_str(), exclusive.c_str()); } if (autoDelete.length() && ((autoDelete != "true") && (autoDelete != "false"))) { CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, 0, "queue id (%s): 'auto-delete' must be 'true' or 'false', not '%s'", _id.c_str(), autoDelete.c_str()); } if (name.length()) { const bool durableFlag = durable.length() ? durable == "true" : false; const bool exclusiveFlag = exclusive.length() ? exclusive == "true" : false; const bool autoDeleteFlag = autoDelete.length() ? autoDelete == "true" : false; _queue = createQueue(name, durableFlag, exclusiveFlag, autoDeleteFlag); } else { if ((durable == "true") || (exclusive == "false") || (autoDelete == "false")) { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "Anonymous queue (%s) cannot specify durable='true', exclusive='false', " "or auto-delete='false'", _id.c_str()); } _queue = createQueue("", false, true, true); } } std::string QueueInstance::getId() const { return _id; } void QueueInstance::setQueueInternal(SmartPtrQueue queue) { _queue = queue; } std::string QueueInstance::getName() const { return _queue->getName(); } bool QueueInstance::isDurable() const { return _queue->isDurable(); } bool QueueInstance::isExclusive() const { return _queue->isExclusive(); } bool QueueInstance::isAutoDelete() const { return _queue->isAutoDelete(); } QueueInstance.h000066400000000000000000000052561321503522500371760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEINSTANCE_H_ #define QUEUEINSTANCE_H_ #include "Integration/IIntegrationObject.h" #include "Integration/IDocument.h" #include "amqpCore/Queue.h" #include "amqpCore/QueueInternal.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObj * @brief An Integration Object implementing Caf::AmqpIntegration::Queue *

* Example context file declarations: *

* Named queue: *

 * 
 * 
* Anonymous queue: *
 * 
 * 
*

* XML attribute definitions: * * * * * * * * * * * *
AttributeDescription
idrequired The id of the integration object. * All integration objects that reference queues must do so by their id.
nameoptional The AMQP name of the queue. This is the name that * will be sent in the Queue.Declare AMQP method. It does not need to match the * id. To declare an anonymous (server-named) queue, leave this attribute * out of the declaration. Do not set name to blank.
durableoptional true to declare a durable queue else false.
exclusiveoptional true to declare the queue exclusive to the connection * else false.
auto-deleteoptional true to declare that the queue be deleted when it is no * longer in use else false.
* NOTE: Anonymous queues are automatically declared as non-durable, exclusive * and auto-delete. They cannot be declared otherwise. */ class QueueInstance : public IIntegrationObject, public QueueInternal, public Queue { CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(QueueInternal) CAF_QI_ENTRY(Queue) CAF_END_QI() public: QueueInstance(); virtual ~QueueInstance(); public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // QueueInternal void setQueueInternal(SmartPtrQueue queue); public: // Queue std::string getName() const; bool isDurable() const; bool isExclusive() const; bool isAutoDelete() const; private: std::string _id; SmartPtrQueue _queue; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueInstance); }; CAF_DECLARE_SMART_QI_POINTER(QueueInstance); }} #endif /* QUEUEINSTANCE_H_ */ RabbitAdminInstance.cpp000066400000000000000000000154521321503522500406200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationAppContext.h" #include "Integration/IIntegrationObject.h" #include "amqpCore/Binding.h" #include "amqpCore/BindingInternal.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/Exchange.h" #include "amqpCore/ExchangeInternal.h" #include "amqpCore/Queue.h" #include "amqpCore/QueueInternal.h" #include "RabbitAdminInstance.h" using namespace Caf::AmqpIntegration; RabbitAdminInstance::RabbitAdminInstance() : _isRunning(false), CAF_CM_INIT_LOG("RabbitAdminInstance") { } RabbitAdminInstance::~RabbitAdminInstance() { } void RabbitAdminInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { _id = configSection->findOptionalAttribute("id"); if (!_id.length()) { _id = "RabbitAdminInstance-"; _id += CStringUtils::createRandomUuid(); } _connectionFactoryId = configSection->findRequiredAttribute("connection-factory"); _admin.CreateInstance(); } std::string RabbitAdminInstance::getId() const { return _id; } void RabbitAdminInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_VALIDATE_INTERFACE(appContext); _appContext = appContext; } void RabbitAdminInstance::setIntegrationAppContext(SmartPtrIIntegrationAppContext context) { CAF_CM_FUNCNAME_VALIDATE("setIntegrationAppContext"); CAF_CM_VALIDATE_INTERFACE(context); _integrationAppContext = context; } void RabbitAdminInstance::start(const uint32 timeoutMs) { CAF_CM_FUNCNAME("start"); SmartPtrIBean factoryBean = _appContext->getBean(_connectionFactoryId); SmartPtrConnectionFactory connectionFactory; connectionFactory.QueryInterface(factoryBean, true); _admin->init(connectionFactory); try { CAF_CM_VALIDATE_INTERFACE(_integrationAppContext); CAF_CM_LOG_DEBUG_VA0("Initializing exchange/queue/binding declarations"); std::deque queues; IIntegrationAppContext::SmartPtrCObjectCollection objs = _integrationAppContext->getIntegrationObjects(Queue::IIDOF()); CAF_CM_LOG_DEBUG_VA1("Declaring %d queues", objs->size()); if (objs->size()) { for (TSmartConstIterator obj(*objs); obj; obj++) { SmartPtrQueue queue; queue.QueryInterface(*obj); if (queue->getName().length()) { CAF_CM_LOG_DEBUG_VA1("Declaring queue - %s", queue->getName().c_str()); _admin->declareQueue(queue); } else { CAF_CM_LOG_DEBUG_VA0("Declaring anonymous queue"); SmartPtrQueue anonQueue = _admin->declareQueue(); SmartPtrQueueInternal queueInt; queueInt.QueryInterface(queue); queueInt->setQueueInternal(anonQueue); } queues.push_back(queue); } } std::deque exchanges; std::deque bindings; objs = _integrationAppContext->getIntegrationObjects(Exchange::IIDOF()); CAF_CM_LOG_DEBUG_VA1("Declaring %d exchanges", objs->size()); if (objs->size()) { for (TSmartConstIterator obj(*objs); obj; obj++) { SmartPtrExchange exchange; exchange.QueryInterface(*obj); _admin->declareExchange(exchange); exchanges.push_back(exchange); SmartPtrExchangeInternal exchangeInternal; exchangeInternal.QueryInterface(exchange); std::deque embeddedBindings = exchangeInternal->getEmbeddedBindings(); bindings.insert( bindings.end(), embeddedBindings.begin(), embeddedBindings.end()); } } objs = _integrationAppContext->getIntegrationObjects(Binding::IIDOF()); if (objs->size()) { for (TSmartConstIterator obj(*objs); obj; obj++) { SmartPtrBinding binding; binding.QueryInterface(*obj); bindings.push_back(binding); } } CAF_CM_LOG_DEBUG_VA1("Declaring %d bindings", bindings.size()); for (TSmartConstIterator > binding(bindings); binding; binding++) { SmartPtrIIntegrationObject obj = _integrationAppContext->getIntegrationObject(binding->getQueue()); // resolve the queue id to a queue name and replace the binding object SmartPtrQueue queue; queue.QueryInterface(obj); SmartPtrBindingInternal bindingInternal; bindingInternal.QueryInterface(*binding); bindingInternal->setBindingInternal( createBinding( queue->getName(), binding->getExchange(), binding->getRoutingKey())); // declare the binding _admin->declareBinding(*binding); } } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { _admin->term(); _admin = NULL; } CAF_CM_THROWEXCEPTION; _isRunning = true; } void RabbitAdminInstance::stop(const uint32 timeoutMs) { if (_isRunning) { _isRunning = false; _admin->term(); } _admin = NULL; } bool RabbitAdminInstance::isRunning() const { return _isRunning; } void RabbitAdminInstance::declareExchange(SmartPtrExchange exchange) { CAF_CM_FUNCNAME_VALIDATE("declareExchange"); CAF_CM_VALIDATE_BOOL(isRunning()); _admin->declareExchange(exchange); } bool RabbitAdminInstance::deleteExchange(const std::string& exchange) { CAF_CM_FUNCNAME_VALIDATE("deleteExchange"); CAF_CM_VALIDATE_BOOL(isRunning()); return _admin->deleteExchange(exchange); } SmartPtrQueue RabbitAdminInstance::declareQueue() { CAF_CM_FUNCNAME_VALIDATE("declareQueue"); CAF_CM_VALIDATE_BOOL(isRunning()); return _admin->declareQueue(); } void RabbitAdminInstance::declareQueue(SmartPtrQueue queue) { CAF_CM_FUNCNAME_VALIDATE("declareQueue"); CAF_CM_VALIDATE_BOOL(isRunning()); _admin->declareQueue(queue); } bool RabbitAdminInstance::deleteQueue(const std::string& queue) { CAF_CM_FUNCNAME_VALIDATE("deleteQueue"); CAF_CM_VALIDATE_BOOL(isRunning()); return _admin->deleteQueue(queue); } void RabbitAdminInstance::deleteQueue( const std::string& queue, const bool unused, const bool empty) { CAF_CM_FUNCNAME_VALIDATE("deleteQueue"); CAF_CM_VALIDATE_BOOL(isRunning()); return _admin->deleteQueue(queue, unused, empty); } void RabbitAdminInstance::purgeQueue(const std::string& queue) { CAF_CM_FUNCNAME_VALIDATE("purgeQueue"); CAF_CM_VALIDATE_BOOL(isRunning()); return _admin->purgeQueue(queue); } void RabbitAdminInstance::declareBinding(SmartPtrBinding binding) { CAF_CM_FUNCNAME_VALIDATE("declareBinding"); CAF_CM_VALIDATE_BOOL(isRunning()); return _admin->declareBinding(binding); } void RabbitAdminInstance::removeBinding(SmartPtrBinding binding) { CAF_CM_FUNCNAME_VALIDATE("removeBinding"); CAF_CM_VALIDATE_BOOL(isRunning()); return _admin->removeBinding(binding); } RabbitAdminInstance.h000066400000000000000000000061371321503522500402650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef RABBITADMININSTANCE_H_ #define RABBITADMININSTANCE_H_ #include "Integration/IIntegrationAppContextAware.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationAppContext.h" #include "amqpCore/Binding.h" #include "amqpCore/Exchange.h" #include "amqpCore/Queue.h" #include "amqpCore/RabbitAdmin.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObj * @brief An Integration Object implementing Caf::AmqpIntegration::AmqpAdmin *

*

 * Example context file declaration:
 *
 * 
 * 
*

* XML attribute definitions: * * * * * *
AttributeDescription
idoptional The id of the integration object
connection-factoryrequired The id of the ConnectionFactory bean
*/ class RabbitAdminInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle, public IIntegrationAppContextAware, public AmqpAdmin { CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(IIntegrationAppContextAware) CAF_QI_ENTRY(AmqpAdmin) CAF_END_QI() public: RabbitAdminInstance(); virtual ~RabbitAdminInstance(); public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // IIntegrationAppContextAware void setIntegrationAppContext( SmartPtrIIntegrationAppContext context); public: // AmqpAdmin void declareExchange(SmartPtrExchange exchange); bool deleteExchange(const std::string& exchange); SmartPtrQueue declareQueue(); void declareQueue(SmartPtrQueue queue); bool deleteQueue(const std::string& queue); void deleteQueue( const std::string& queue, const bool unused, const bool empty); void purgeQueue(const std::string& queue); void declareBinding(SmartPtrBinding binding); void removeBinding(SmartPtrBinding binding); private: bool _isRunning; std::string _id; std::string _connectionFactoryId; SmartPtrRabbitAdmin _admin; SmartPtrIAppContext _appContext; SmartPtrIIntegrationAppContext _integrationAppContext; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(RabbitAdminInstance); }; CAF_DECLARE_SMART_QI_POINTER(RabbitAdminInstance); }} #endif /* RABBITADMININSTANCE_H_ */ RabbitTemplateInstance.cpp000066400000000000000000000131211321503522500413320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpCore/AmqpTemplate.h" #include "amqpClient/api/ConnectionFactory.h" #include "Common/IAppConfig.h" #include "RabbitTemplateInstance.h" using namespace Caf::AmqpIntegration; RabbitTemplateInstance::RabbitTemplateInstance() : _isWired(false), CAF_CM_INIT_LOG("RabbitTemplateInstance") { } RabbitTemplateInstance::~RabbitTemplateInstance() { } void RabbitTemplateInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { _id = configSection->findOptionalAttribute("id"); if (!_id.length()) { _id = CStringUtils::createRandomUuid(); } _configSection = configSection; } std::string RabbitTemplateInstance::getId() const { return _id; } void RabbitTemplateInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_VALIDATE_INTERFACE(_configSection); const std::string connectionFactoryId = _configSection->findRequiredAttribute("connection-factory"); SmartPtrIBean factoryBean = appContext->getBean(connectionFactoryId); SmartPtrConnectionFactory connectionFactory; connectionFactory.QueryInterface(factoryBean, true); SmartPtrIAppConfig appConfig = getAppConfig(); _template.CreateInstance(); std::string param = _configSection->findOptionalAttribute("exchange"); if (param.length()) { CAF_CM_LOG_DEBUG_VA1("Setting exchange='%s'", param.c_str()); _template->setExchange(appConfig->resolveValue(param)); } param = _configSection->findOptionalAttribute("queue"); if (param.length()) { CAF_CM_LOG_DEBUG_VA1("Setting queue='%s'", param.c_str()); _template->setQueue(appConfig->resolveValue(param)); } param = _configSection->findOptionalAttribute("routing-key"); if (param.length()) { CAF_CM_LOG_DEBUG_VA1("Setting routing-key='%s'", param.c_str()); _template->setRoutingKey(appConfig->resolveValue(param)); } param = _configSection->findOptionalAttribute("reply_timeout"); if (param.length()) { param = appConfig->resolveValue(param); uint32 timeout = CStringConv::fromString(param); CAF_CM_LOG_DEBUG_VA1("Setting reply_timeout=%d", timeout); _template->setReplyTimeout(timeout); } _template->init(connectionFactory); _isWired = true; _configSection = NULL; } void RabbitTemplateInstance::start(const uint32 timeoutMs) { } void RabbitTemplateInstance::stop(const uint32 timeoutMs) { if (_isWired) { _template->term(); } _template = NULL; _isWired = false; } bool RabbitTemplateInstance::isRunning() const { return (_isWired && !_template.IsNull()); } void RabbitTemplateInstance::send( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_VALIDATE_BOOL(isRunning()); _template->send(message, headerMapper); } void RabbitTemplateInstance::send( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_VALIDATE_BOOL(isRunning()); _template->send(routingKey, message, headerMapper); } void RabbitTemplateInstance::send( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_VALIDATE_BOOL(isRunning()); _template->send(exchange, routingKey, message, headerMapper); } SmartPtrIIntMessage RabbitTemplateInstance::receive( SmartPtrAmqpHeaderMapper headerMapper) { CAF_CM_FUNCNAME_VALIDATE("receive"); CAF_CM_VALIDATE_BOOL(isRunning()); return _template->receive(headerMapper); } SmartPtrIIntMessage RabbitTemplateInstance::receive( const std::string& queueName, SmartPtrAmqpHeaderMapper headerMapper) { CAF_CM_FUNCNAME_VALIDATE("receive"); CAF_CM_VALIDATE_BOOL(isRunning()); return _template->receive(queueName, headerMapper); } SmartPtrIIntMessage RabbitTemplateInstance::sendAndReceive( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper, SmartPtrAmqpHeaderMapper responseHeaderMapper) { CAF_CM_FUNCNAME_VALIDATE("sendAndReceive"); CAF_CM_VALIDATE_BOOL(isRunning()); return _template->sendAndReceive( message, requestHeaderMapper, responseHeaderMapper); } SmartPtrIIntMessage RabbitTemplateInstance::sendAndReceive( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper, SmartPtrAmqpHeaderMapper responseHeaderMapper) { CAF_CM_FUNCNAME_VALIDATE("sendAndReceive"); CAF_CM_VALIDATE_BOOL(isRunning()); return _template->sendAndReceive( routingKey, message, requestHeaderMapper, responseHeaderMapper); } SmartPtrIIntMessage RabbitTemplateInstance::sendAndReceive( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper, SmartPtrAmqpHeaderMapper responseHeaderMapper) { CAF_CM_FUNCNAME_VALIDATE("sendAndReceive"); CAF_CM_VALIDATE_BOOL(isRunning()); return _template->sendAndReceive( exchange, routingKey, message, requestHeaderMapper, responseHeaderMapper); } gpointer RabbitTemplateInstance::execute(SmartPtrExecutor executor, gpointer data) { CAF_CM_FUNCNAME_VALIDATE("execute"); CAF_CM_VALIDATE_BOOL(isRunning()); return _template->execute(executor, data); } RabbitTemplateInstance.h000066400000000000000000000106651321503522500410110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef RABBITTEMPLATEINSTANCE_H_ #define RABBITTEMPLATEINSTANCE_H_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpCore/AmqpTemplate.h" #include "amqpCore/RabbitTemplate.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" namespace Caf { namespace AmqpIntegration { CAF_DECLARE_CLASS_AND_IMPQI_POINTER(RabbitTemplateInstance); /** * @ingroup IntObj * @brief An Integration Object implementing Caf::AmqpIntegration::AmqpTemplate *

*

 * Example context file declaration:
 *
 * 
 * 
*

* XML attribute definitions: * * * * * * * * * * * *
AttributeDescription
idoptional The id of the integration object
connection-factoryrequired The id of the ConnectionFactory bean
exchangeoptional The name of the exchange to use by default
queueoptional The id of the queue to use by default. The queue name comes from * the queue object with the given id.
routing-keyoptional The routing-key to use by default
reply_timeoutoptional The number of milliseconds to wait for a response when using * sendAndReceive methods. This is an unsigned value. A value of zero indicates * wait indefinitely.
*/ class RabbitTemplateInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle, public AmqpTemplate { CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(AmqpTemplate) CAF_END_QI() public: RabbitTemplateInstance(); virtual ~RabbitTemplateInstance(); public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // AmqpTemplate void send( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); void send( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); void send( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage receive( SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage receive( const std::string& queueName, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage sendAndReceive( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage sendAndReceive( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage sendAndReceive( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()); gpointer execute(SmartPtrExecutor executor, gpointer data); private: bool _isWired; std::string _id; SmartPtrIDocument _configSection; SmartPtrRabbitTemplate _template; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(RabbitTemplateInstance); }; }} #endif /* RABBITTEMPLATEINSTANCE_H_ */ SecureCachingConnectionFactoryObj.cpp000066400000000000000000000160001321503522500434530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 4, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "amqpCore/CachingConnectionFactory.h" #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionListener.h" #include "SecureCachingConnectionFactoryObj.h" using namespace Caf::AmqpIntegration; SecureCachingConnectionFactoryObj::SecureCachingConnectionFactoryObj() : CAF_CM_INIT_LOG("SecureCachingConnectionFactoryObj") { } SecureCachingConnectionFactoryObj::~SecureCachingConnectionFactoryObj() { } void SecureCachingConnectionFactoryObj::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_factory); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); const std::string persistenceDir = AppConfigUtils::getRequiredString("persistence_dir"); const SmartPtrCPersistenceDoc persistence = CPersistenceUtils::loadPersistence(persistenceDir); CAF_CM_VALIDATE_SMARTPTR(persistence); const SmartPtrCPersistenceProtocolDoc amqpBroker = CPersistenceUtils::loadPersistenceProtocol(persistence->getPersistenceProtocolCollection()); CAF_CM_VALIDATE_SMARTPTR(amqpBroker); const SmartPtrCCertPathCollectionDoc tlsCertPathCollection = amqpBroker->getTlsCertPathCollection(); CAF_CM_VALIDATE_SMARTPTR(tlsCertPathCollection); const SmartPtrCLocalSecurityDoc localSecurity = persistence->getLocalSecurity(); CAF_CM_VALIDATE_SMARTPTR(localSecurity); UriUtils::SUriRecord uri; UriUtils::parseUriString(amqpBroker->getUri(), uri); const std::string vhost = UriUtils::findOptParameter(uri, "vhost", AppConfigUtils::getRequiredString("communication_amqp", "vhost")); const std::string connectionTimeout = UriUtils::findOptParameter(uri, "connection_timeout", CStringConv::toString( AppConfigUtils::getRequiredUint32("communication_amqp", "connection_timeout"))); const std::string connectionRetries = UriUtils::findOptParameter(uri, "connection_retries", CStringConv::toString( AppConfigUtils::getRequiredUint32("communication_amqp", "connection_retries"))); const std::string connectionSecondsToWait = UriUtils::findOptParameter(uri, "connection_seconds_to_wait", CStringConv::toString( AppConfigUtils::getRequiredUint32("communication_amqp", "connection_seconds_to_wait"))); const std::string channelCacheSize = UriUtils::findOptParameter(uri, "channel_cache_size", CStringConv::toString( AppConfigUtils::getRequiredUint32("communication_amqp", "channel_cache_size"))); const std::deque tlsCertPathCollectionInner = tlsCertPathCollection->getCertPath(); CAF_CM_VALIDATE_STL(tlsCertPathCollectionInner); CAF_CM_VALIDATE_BOOL(tlsCertPathCollectionInner.size() == 1); const std::string caCertPath = tlsCertPathCollectionInner.front(); CAF_CM_VALIDATE_STRING(uri.protocol); CAF_CM_VALIDATE_STRING(uri.host); CAF_CM_VALIDATE_STRING(uri.portStr); CAF_CM_VALIDATE_STRING(vhost); CAF_CM_VALIDATE_STRING(caCertPath); CAF_CM_VALIDATE_STRING(localSecurity->getCertPath()); CAF_CM_VALIDATE_STRING(localSecurity->getPrivateKeyPath()); SmartPtrCachingConnectionFactory factory; factory.CreateInstance(); factory->init(); factory->setProtocol(uri.protocol); factory->setHost(uri.host); factory->setPort(uri.port); factory->setVirtualHost(vhost); factory->setCaCertPath(caCertPath); factory->setClientCertPath(localSecurity->getCertPath()); factory->setClientKeyPath(localSecurity->getPrivateKeyPath()); if (! uri.username.empty()) { factory->setUsername(uri.username); } if (! uri.password.empty()) { factory->setPassword(uri.password); } if (! connectionTimeout.empty()) { factory->setConnectionTimeout(CStringConv::fromString(connectionTimeout)); } if (! connectionRetries.empty()) { factory->setRetries(CStringConv::fromString(connectionRetries)); } if (! connectionSecondsToWait.empty()) { factory->setSecondsToWait(CStringConv::fromString(connectionSecondsToWait)); } if (! channelCacheSize.empty()) { factory->setChannelCacheSize(CStringConv::fromString(channelCacheSize)); } _factory = factory; } void SecureCachingConnectionFactoryObj::terminateBean() { CAF_CM_FUNCNAME("terminateBean"); try { if (_factory) { _factory->destroy(); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } SmartPtrConnection SecureCachingConnectionFactoryObj::createConnection() { CAF_CM_FUNCNAME_VALIDATE("createConnection"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->createConnection(); } std::string SecureCachingConnectionFactoryObj::getProtocol() { CAF_CM_FUNCNAME_VALIDATE("getProtocol"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getProtocol(); } std::string SecureCachingConnectionFactoryObj::getHost() { CAF_CM_FUNCNAME_VALIDATE("getHost"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getHost(); } uint32 SecureCachingConnectionFactoryObj::getPort() { CAF_CM_FUNCNAME_VALIDATE("getPort"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getPort(); } std::string SecureCachingConnectionFactoryObj::getVirtualHost() { CAF_CM_FUNCNAME_VALIDATE("getVirtualHost"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getVirtualHost(); } std::string SecureCachingConnectionFactoryObj::getUsername() { CAF_CM_FUNCNAME_VALIDATE("getUsername"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getUsername(); } std::string SecureCachingConnectionFactoryObj::getPassword() { CAF_CM_FUNCNAME_VALIDATE("getPassword"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getPassword(); } std::string SecureCachingConnectionFactoryObj::getCaCertPath() { CAF_CM_FUNCNAME_VALIDATE("getCaCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getCaCertPath(); } std::string SecureCachingConnectionFactoryObj::getClientCertPath() { CAF_CM_FUNCNAME_VALIDATE("getClientCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getClientCertPath(); } std::string SecureCachingConnectionFactoryObj::getClientKeyPath() { CAF_CM_FUNCNAME_VALIDATE("getClientKeyPath"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getClientKeyPath(); } uint16 SecureCachingConnectionFactoryObj::getRetries() { CAF_CM_FUNCNAME_VALIDATE("getRetries"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getRetries(); } uint16 SecureCachingConnectionFactoryObj::getSecondsToWait() { CAF_CM_FUNCNAME_VALIDATE("getSecondsToWait"); CAF_CM_PRECOND_ISINITIALIZED(_factory); return _factory->getSecondsToWait(); } void SecureCachingConnectionFactoryObj::addConnectionListener(const SmartPtrConnectionListener& listener) { CAF_CM_FUNCNAME_VALIDATE("addConnectionListener"); CAF_CM_PRECOND_ISINITIALIZED(_factory); _factory->addConnectionListener(listener); } SecureCachingConnectionFactoryObj.h000066400000000000000000000066461321503522500431370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: Jun 4, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef SECURECACHINGCONNECTIONFACTORYOBJ_H_ #define SECURECACHINGCONNECTIONFACTORYOBJ_H_ #include "IBean.h" #include "amqpCore/CachingConnectionFactory.h" #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionListener.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObj * @brief An implementation of Caf::AmqpIntegration::SecureConnectionFactory that returns * the same connections from all calls, ignores calls to * Caf::AmqpClient::Connection::close and caches Caf::AmqpClient::Channel. *

* By default, only one channel will be cached, with additional requested channels * being created and disposed on demand. Consider raising the cache size in * high-concurrency environments. *

* NOTE: This factory requires explicit closing of all channels obtained from its * shared connection. Failure to close channels will disable channel reuse. *

* SecureCachingConnectionFactory objects are created by inserting the following into * the application context: *

 *
 * \
 * 	\
 * 	\
 * 	\
 * \
 * 
* Properties: * * * * * * * * * * * * *
PropertyDescription
hostThe broker host. By default the machine's host name (or localhost * if the host name cannot be determined).
portThe broker port. By default AmqpClient::DEFAULT_AMQP_PORT
virtualHostThe virtual host on the broker. By default AmqpClient::DEFAULT_VHOST
connectionTimeoutThe connection timeout in milliseconds. A value of zero means * to wait indefinitely. By default 10 seconds.
channelCacheSizeThe number of channels to cache. By default 1.
*/ class SecureCachingConnectionFactoryObj : public TCafSubSystemObjectRoot, public IBean, public ConnectionFactory { CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdAmqpSecureCachingConnectionFactory) CAF_BEGIN_INTERFACE_MAP(SecureCachingConnectionFactoryObj) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(ConnectionFactory) CAF_END_INTERFACE_MAP() public: SecureCachingConnectionFactoryObj(); virtual ~SecureCachingConnectionFactoryObj(); public: // IBean void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // ConnectionFactory SmartPtrConnection createConnection(); std::string getProtocol(); std::string getHost(); uint32 getPort(); std::string getVirtualHost(); std::string getUsername(); std::string getPassword(); std::string getCaCertPath(); std::string getClientCertPath(); std::string getClientKeyPath(); uint16 getRetries(); uint16 getSecondsToWait(); void addConnectionListener(const SmartPtrConnectionListener& listener); private: SmartPtrCachingConnectionFactory _factory; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(SecureCachingConnectionFactoryObj); }; }} #endif /* SECURECACHINGCONNECTIONFACTORYOBJ_H_ */ amqpIntegration.cpp000066400000000000000000000026111321503522500401120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: May 24, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CachingConnectionFactoryObj.h" #include "SecureCachingConnectionFactoryObj.h" #include "IntegrationObjects.h" namespace Caf { /** @brief CAF AMQP Integration */ namespace AmqpIntegration { const char* _sObjIdAmqpCachingConnectionFactory = "com.vmware.caf.comm.integration.amqp.caching.connection.factory"; const char* _sObjIdAmqpSecureCachingConnectionFactory = "com.vmware.caf.comm.integration.amqp.secure.caching.connection.factory"; const char* _sObjIdIntegrationObjects = "com.vmware.caf.comm.integration.objects"; }} CEcmSubSystemModule _Module; using namespace Caf::AmqpIntegration; CAF_BEGIN_OBJECT_MAP(ObjectMap) CAF_OBJECT_ENTRY(CachingConnectionFactoryObj) CAF_OBJECT_ENTRY(SecureCachingConnectionFactoryObj) CAF_OBJECT_ENTRY(IntegrationObjects) CAF_END_OBJECT_MAP() CAF_DECLARE_SUBSYSTEM_EXPORTS() extern "C" BOOL APIENTRY DllMain(HINSTANCE hModule, uint32 dwReason, LPVOID) { try { if (DLL_PROCESS_ATTACH == dwReason) { // initialize the sub-system module _Module.Init(ObjectMap, hModule); } else if (DLL_PROCESS_DETACH == dwReason) { // Terminate the sub-system module _Module.Term(); } } catch (std::runtime_error) { ::exit(2); } catch (...) { ::exit(2); } return TRUE; } amqpIntegrationDefines.h000066400000000000000000000012631321503522500410570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: May 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONDEFINES_H_ #define AMQPINTEGRATIONDEFINES_H_ namespace Caf { /** @brief CAF AMQP Integration */ namespace AmqpIntegration { /** @brief CachingConnectionFactory bean subsystem id */ extern const char* _sObjIdAmqpCachingConnectionFactory; /** @brief CachingConnectionFactory bean subsystem id */ extern const char* _sObjIdAmqpSecureCachingConnectionFactory; /** @brief Integration object aggregator bean subsystem id */ extern const char* _sObjIdIntegrationObjects; }} #endif /* AMQPINTEGRATIONDEFINES_H_ */ stdafx.h000066400000000000000000000026061321503522500357120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/amqpIntegration/src/* * Created on: May 24, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #include #include #include "../../../amqpCore/src/amqpCore/amqpIntegrationCoreLink.h" #include "amqpIntegrationDefines.h" /** * @defgroup IntObj Integration Objects * Documentation for the Integration Objects that can be declare in an * application context file. *

* The #Caf::AmqpIntegration::CachingConnectionFactoryObj bean has it's own bean definition in the * application context: *

 * \
 * 
*

* All other integration objects are accessed through the IntegrationObjects bean: *

 * \
 * 
*/ /** * @defgroup IntObjImpl Integration Object Implementation * Documentation for the implementation of the integration objects. *

* These classes and methods cannot be used directly by application code. */ /** * @mainpage * The CAF AMQP Integration Library provides integration components that enable * AMQP message channels, endpoints and gateways to be wired into integration-enabled * applications. */ #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/000077500000000000000000000000001321503522500335315ustar00rootroot00000000000000include/000077500000000000000000000000001321503522500350755ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegrationCCmsMessage.h000066400000000000000000000134111321503522500374000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCmsMessage_h_ #define CCmsMessage_h_ #include #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { class CCmsMessage { public: CCmsMessage(); virtual ~CCmsMessage(); public: void initialize( const std::string& appId, const std::string& pmeId); public: void signBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const; void verifyBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const; void encryptBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const; void decryptBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const; void compressBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const; void uncompressBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const; public: void signBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const; void verifyBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const; void encryptBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const; void decryptBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const; void compressBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const; void uncompressBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const; public: void signFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const; void verifyFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const; void encryptFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const; void decryptFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const; void compressFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const; void uncompressFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const; public: void signFileToFile( const std::string& inputPath, const std::string& outputPath) const; void verifyFileToFile( const std::string& inputPath, const std::string& outputPath) const; void encryptFileToFile( const std::string& inputPath, const std::string& outputPath) const; void decryptFileToFile( const std::string& inputPath, const std::string& outputPath) const; void compressFileToFile( const std::string& inputPath, const std::string& outputPath) const; void uncompressFileToFile( const std::string& inputPath, const std::string& outputPath) const; private: void sign( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const; void verify( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const; void encrypt( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const; void decrypt( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const; void compress( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const; void uncompress( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const; private: void checkCrlf( const std::string& funcName, const std::string& direction, const SmartPtrCDynamicByteArray& buffer, const std::string& path) const; void checkCrlf( const std::string& funcName, const std::string& direction, const SmartPtrCDynamicByteArray& buffer) const; void checkCrlf( const std::string& funcName, const std::string& direction, const std::string& path) const; private: std::string getReqDirPath( const std::string& directory, const std::string& subdir, const std::string& subdir1 = std::string()) const; std::string getReqFilePath( const std::string& directory, const std::string& filename) const; Cdeqstr getReqFilePaths( const std::string& directory, const std::string& subdir) const; std::string getReqRmtCertsDir( const std::string& appId, const std::string& pmeId) const; void getExistingDir( const std::string& parentDir, const std::string& childDir, std::string& result, std::string& errDirs) const; private: bool _isInitialized; EVP_CIPHER* _cipher; std::string _persistenceDir; std::string _nullPath; SmartPtrCDynamicByteArray _nullBuffer; std::string _encryptPublicKeyPath; std::string _decryptPublicKeyPath; std::string _decryptPrivateKeyPath; std::string _signPublicKeyPath; std::string _signPrivateKeyPath; Cdeqstr _caCertificatePaths; bool _checkCrlf; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CCmsMessage); }; CAF_DECLARE_SMART_POINTER(CCmsMessage); } #endif // #ifndef CCmsMessage_h_ CCmsMessageAttachments.h000066400000000000000000000060061321503522500415760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/include/* * Author: bwilliams * Created: July 3, 2015 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCmsMessageAttachments_h_ #define CCmsMessageAttachments_h_ #include "CCmsMessage.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" namespace Caf { class CCmsMessageAttachments { public: CCmsMessageAttachments(); virtual ~CCmsMessageAttachments(); public: void initialize( const SmartPtrCCmsMessage& cmsMessage); public: void enforceSecurityOnAttachments( const std::deque& attachmentCollection, const bool isSigningEnforced, const bool isEncryptionEnforced) const; std::deque encryptAndSignAttachments( const std::deque& sourceAttachmentCollection) const; SmartPtrCAttachmentDoc encryptAndSignAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters = std::map()) const; std::deque decryptAndVerifyAttachments( const std::deque& sourceAttachmentCollection) const; SmartPtrCAttachmentDoc decryptAndVerifyAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters) const; private: void signAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters, std::string& destAttachmentPath, SmartPtrCAttachmentDoc& destAttachment) const; void verifyAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters, std::string& destAttachmentPath, SmartPtrCAttachmentDoc& destAttachment) const; void encryptAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters, std::string& destAttachmentPath, SmartPtrCAttachmentDoc& destAttachment) const; void decryptAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters, std::string& destAttachmentPath, SmartPtrCAttachmentDoc& destAttachment) const; private: void removeStr( std::string& sourceStr, const std::string& strToRemove) const; void enforceSigning( const bool isSigningEnforced, const SmartPtrCAttachmentDoc& attachment) const; void enforceEncryption( const bool isEncryptionEnforced, const SmartPtrCAttachmentDoc& attachment) const; private: bool _isInitialized; SmartPtrCCmsMessage _cmsMessage; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CCmsMessageAttachments); }; CAF_DECLARE_SMART_POINTER(CCmsMessageAttachments); } #endif // #ifndef CCmsMessageAttachments_h_ CMessageDeliveryRecord.h000066400000000000000000000026071321503522500416050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/include/* * Created on: Nov 26, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessageDeliveryRecord_h #define CMessageDeliveryRecord_h #include "CMessagePartDescriptorSourceRecord.h" #include "Integration/IIntMessage.h" namespace Caf { class CMessageDeliveryRecord { public: CMessageDeliveryRecord(); virtual ~CMessageDeliveryRecord(); public: void initialize( const UUID& correlationId, const uint32 numberOfParts, const uint32 startingPartNumber, const std::deque& messagePartSources, const IIntMessage::SmartPtrCHeaders& messageHeaders); public: UUID getCorrelationId() const; std::string getCorrelationIdStr() const; uint32 getNumberOfParts() const; uint32 getStartingPartNumber() const; std::deque getMessagePartSources() const; IIntMessage::SmartPtrCHeaders getMessageHeaders() const; private: bool _isInitialized; UUID _correlationId; uint32 _numberOfParts; uint32 _startingPartNumber; std::deque _messagePartSources; IIntMessage::SmartPtrCHeaders _messageHeaders; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CMessageDeliveryRecord); }; CAF_DECLARE_SMART_POINTER(CMessageDeliveryRecord); } #endif /* CMessageDeliveryRecord_h */ CMessagePartDescriptor.h000066400000000000000000000044271321503522500416320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/include/* * Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagePartDescriptor_h #define CMessagePartDescriptor_h #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { class CMessagePartDescriptor; CAF_DECLARE_SMART_POINTER(CMessagePartDescriptor); /** * Class that emits and parses message parts header blocks.
*/ class CMessagePartDescriptor { public: /** * Converts the BLOCK_SIZE data in a ByteBuffer into a MessagePartsHeader *

* The incoming ByteBuffer position will be modified. * @param buffer ByteBuffer to convert * @return a MessagePartsHeader */ static SmartPtrCMessagePartDescriptor fromByteBuffer(SmartPtrCDynamicByteArray& buffer); /** * Converts a byte array into a MessagePartsHeader * @param blockData byte array to convert * @return a MessagePartsHeader */ static SmartPtrCMessagePartDescriptor fromArray(SmartPtrCDynamicByteArray& blockData); static SmartPtrCDynamicByteArray toArray(const uint16 attachmentNumber, const uint32 partNumber, const uint32 dataSize, const uint32 dataOffset); public: CMessagePartDescriptor(); virtual ~CMessagePartDescriptor(); public: /** * @param correlationId the correlation id * @param numberOfParts the total number of parts */ void initialize( const uint16 attachmentNumber, const uint32 partNumber, const uint32 dataSize, const uint32 dataOffset); /** * @return the attachmentNumber */ uint16 getAttachmentNumber() const; std::string getAttachmentNumberStr() const; /** * @return the partNumber */ uint32 getPartNumber() const; /** * @return the dataSize */ uint32 getDataSize() const; /** * @return the dataOffset */ uint32 getDataOffset() const; public: /** * The BLOCK_SIZE field stores the size of a MessagePartsHeader in byte array form.
*/ static const uint32 BLOCK_SIZE = 20; static const byte CAF_MSG_VERSION = 1; private: static const byte RESERVED = (byte)0xcd; private: bool _isInitialized; uint16 _attachmentNumber; uint32 _partNumber; uint32 _dataSize; uint32 _dataOffset; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CMessagePartDescriptor); }; } #endif /* CMessagePartDescriptor_h */ CMessagePartDescriptorSourceRecord.h000066400000000000000000000020041321503522500441370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/include/* * Created on: Nov 26, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagePartDescriptorSourceRecord_h #define CMessagePartDescriptorSourceRecord_h namespace Caf { class CMessagePartDescriptorSourceRecord { public: CMessagePartDescriptorSourceRecord(); virtual ~CMessagePartDescriptorSourceRecord(); public: void initialize( const uint16 attachmentNumber, const std::string filePath, const uint32 dataOffset, const uint32 dataLength); public: uint16 getAttachmentNumber() const; std::string getFilePath() const; uint32 getDataOffset() const; uint32 getDataLength() const; private: bool _isInitialized; uint16 _attachmentNumber; std::string _filePath; uint32 _dataOffset; uint32 _dataLength; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CMessagePartDescriptorSourceRecord); }; CAF_DECLARE_SMART_POINTER(CMessagePartDescriptorSourceRecord); } #endif /* CMessagePartDescriptorSourceRecord_h */ CMessagePartRecord.h000066400000000000000000000021221321503522500407200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/include/* * Created on: Nov 26, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagePartRecord_h #define CMessagePartRecord_h namespace Caf { class CMessagePartRecord { public: CMessagePartRecord(); virtual ~CMessagePartRecord(); public: void initialize( const uint16 attachmentNumber, const std::string filePath, const uint64 dataOffset, const uint64 dataLength); public: uint16 getAttachmentNumber() const; std::string getFilePath() const; uint64 getDataOffset() const; uint64 getDataLength() const; void setAttachmentNumber(const uint16 attachmentNumber); void setFilePath(const std::string& filePath); void setDataOffset(const uint64 dataOffset); void setDataLength(const uint64 dataLength); private: bool _isInitialized; uint16 _attachmentNumber; std::string _filePath; uint64 _dataOffset; uint64 _dataLength; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CMessagePartRecord); }; CAF_DECLARE_SMART_POINTER(CMessagePartRecord); } #endif /* CMessagePartRecord_h */ CMessagePartsHeader.h000066400000000000000000000042021321503522500410560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/include/* * Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagePartsHeader_h #define CMessagePartsHeader_h #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { class CMessagePartsHeader; CAF_DECLARE_SMART_POINTER(CMessagePartsHeader); /** * Class that emits and parses message parts header blocks.
*/ class CMessagePartsHeader { public: /** * Converts the BLOCK_SIZE data in a ByteBuffer into a MessagePartsHeader *

* The incoming ByteBuffer position will be modified. * @param buffer ByteBuffer to convert * @return a MessagePartsHeader */ static SmartPtrCMessagePartsHeader fromByteBuffer(SmartPtrCDynamicByteArray& buffer); /** * Converts a byte array into a MessagePartsHeader * @param blockData byte array to convert * @return a MessagePartsHeader */ static SmartPtrCMessagePartsHeader fromArray(SmartPtrCDynamicByteArray& blockData); static SmartPtrCDynamicByteArray toArray(const UUID correlationId, const uint32 numberOfParts); public: CMessagePartsHeader(); virtual ~CMessagePartsHeader(); public: /** * @param correlationId the correlation id * @param numberOfParts the total number of parts */ void initialize( const UUID correlationId, const uint32 numberOfParts); /** * @return the correlationId */ UUID getCorrelationId() const; std::string getCorrelationIdStr() const; /** * @return the numberOfParts */ uint32 getNumberOfParts() const; public: /** * The BLOCK_SIZE field stores the size of a MessagePartsHeader in byte array form.
*/ static const uint32 BLOCK_SIZE = 24; static const byte CAF_MSG_VERSION = 1; private: static const byte RESERVED1 = (byte)0xcd; static const byte RESERVED2 = (byte)0xcd; static const byte RESERVED3 = (byte)0xcd; private: bool _isInitialized; UUID _correlationId; uint32 _numberOfParts; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CMessagePartsHeader); }; } #endif /* CMessagePartsHeader_h */ ReplyToResolver.h000066400000000000000000000012101321503522500403600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/include/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef ReplyToResolver_h #define ReplyToResolver_h #include "ICafObject.h" #include "Integration/IIntMessage.h" namespace Caf { struct __declspec(novtable) ReplyToResolver : public ICafObject { CAF_DECL_UUID("4D306795-4475-4D2C-BEF0-0ADE28843BBC") virtual std::string cacheReplyTo(const SmartPtrIIntMessage& message) = 0; virtual std::string lookupReplyTo(const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ReplyToResolver); } #endif /* ReplyToResolver_h */ src/000077500000000000000000000000001321503522500342415ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegrationCCmsMessage.cpp000066400000000000000000000703441321503522500371070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CCmsMessage.h" #include "Exception/CCafException.h" #include "CCmsMessageUtils.h" #include using namespace Caf; CCmsMessage::CCmsMessage() : _isInitialized(false), _cipher(NULL), _checkCrlf(false), CAF_CM_INIT_LOG("CCmsMessage") { } CCmsMessage::~CCmsMessage() { } void CCmsMessage::initialize( const std::string& appId, const std::string& pmeId) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(appId); CAF_CM_VALIDATE_STRING(pmeId); SSL_library_init(); SSL_load_error_strings(); _persistenceDir = AppConfigUtils::getRequiredString("persistence_dir"); const std::string locDir = getReqDirPath(_persistenceDir, "local"); const std::string locPublicKeyPath = getReqFilePath(locDir, "cert.pem"); const std::string locPrivateKeyPath = getReqFilePath(locDir, "privateKey.pem"); const std::string rmtCertsDir = getReqRmtCertsDir(appId, pmeId); const std::string rmtPublicKeyPath = getReqFilePath(rmtCertsDir, "cmsCert.pem"); const std::string rmtCmsCipherNamePath = getReqFilePath(rmtCertsDir, "cmsCipherName.txt"); const std::string rmtCipherName = FileSystemUtils::loadTextFile(rmtCmsCipherNamePath); _caCertificatePaths = getReqFilePaths(rmtCertsDir, "cmsCertCollection"); _cipher = const_cast(EVP_get_cipherbyname(rmtCipherName.c_str())); CAF_CM_VALIDATE_PTR(_cipher); _encryptPublicKeyPath = rmtPublicKeyPath; _decryptPublicKeyPath = rmtPublicKeyPath; _decryptPrivateKeyPath = locPrivateKeyPath; _signPublicKeyPath = locPublicKeyPath; _signPrivateKeyPath = locPrivateKeyPath; CAF_CM_LOG_DEBUG_VA1("Initializing - rmtCipherName: %s", rmtCipherName.c_str()); CAF_CM_LOG_DEBUG_VA1("Initializing - encryptPublicKeyPath: %s", _encryptPublicKeyPath.c_str()); CAF_CM_LOG_DEBUG_VA1("Initializing - decryptPublicKeyPath: %s", _decryptPublicKeyPath.c_str()); CAF_CM_LOG_DEBUG_VA1("Initializing - decryptPrivateKeyPath: %s", _decryptPrivateKeyPath.c_str()); CAF_CM_LOG_DEBUG_VA1("Initializing - signPublicKeyPath: %s", _signPublicKeyPath.c_str()); CAF_CM_LOG_DEBUG_VA1("Initializing - signPrivateKeyPath: %s", _signPrivateKeyPath.c_str()); CAF_CM_LOG_DEBUG_VA2("Initializing - caCertificatePath: %s, %s", rmtCertsDir.c_str(), "cmsCertCollection"); _checkCrlf = AppConfigUtils::getOptionalBoolean("security", "check_crlf"); _isInitialized = true; } void CCmsMessage::signBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("signBufferToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_LOG_DEBUG_VA1("%s", CAF_CM_GET_FUNCNAME); outputBuffer.CreateInstance(); sign(inputBuffer, _nullPath, outputBuffer, _nullPath); } void CCmsMessage::verifyBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("verifyBufferToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_LOG_DEBUG_VA1("%s", CAF_CM_GET_FUNCNAME); outputBuffer.CreateInstance(); verify(inputBuffer, _nullPath, outputBuffer, _nullPath); } void CCmsMessage::encryptBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("encryptBufferToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_LOG_DEBUG_VA1("%s", CAF_CM_GET_FUNCNAME); outputBuffer.CreateInstance(); encrypt(inputBuffer, _nullPath, outputBuffer, _nullPath); } void CCmsMessage::decryptBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("decryptBufferToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_LOG_DEBUG_VA1("%s", CAF_CM_GET_FUNCNAME); outputBuffer.CreateInstance(); decrypt(inputBuffer, _nullPath, outputBuffer, _nullPath); } void CCmsMessage::compressBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("compressBufferToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_LOG_DEBUG_VA1("%s", CAF_CM_GET_FUNCNAME); outputBuffer.CreateInstance(); compress(inputBuffer, _nullPath, outputBuffer, _nullPath); } void CCmsMessage::uncompressBufferToBuffer( const SmartPtrCDynamicByteArray& inputBuffer, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("uncompressBufferToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_LOG_DEBUG_VA1("%s", CAF_CM_GET_FUNCNAME); outputBuffer.CreateInstance(); uncompress(inputBuffer, _nullPath, outputBuffer, _nullPath); } void CCmsMessage::signBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("signBufferToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; sign(inputBuffer, _nullPath, nullBuffer, outputPath); } void CCmsMessage::verifyBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("verifyBufferToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; verify(inputBuffer, _nullPath, nullBuffer, outputPath); } void CCmsMessage::encryptBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("encryptBufferToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; encrypt(inputBuffer, _nullPath, nullBuffer, outputPath); } void CCmsMessage::decryptBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("decryptBufferToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; decrypt(inputBuffer, _nullPath, nullBuffer, outputPath); } void CCmsMessage::compressBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("compressBufferToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; compress(inputBuffer, _nullPath, nullBuffer, outputPath); } void CCmsMessage::uncompressBufferToFile( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("uncompressBufferToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; uncompress(inputBuffer, _nullPath, nullBuffer, outputPath); } void CCmsMessage::signFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("signFileToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, inputPath.c_str()); outputBuffer.CreateInstance(); sign(_nullBuffer, inputPath, outputBuffer, _nullPath); } void CCmsMessage::verifyFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("verifyFileToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, inputPath.c_str()); outputBuffer.CreateInstance(); verify(_nullBuffer, inputPath, outputBuffer, _nullPath); } void CCmsMessage::encryptFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("encryptFileToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, inputPath.c_str()); outputBuffer.CreateInstance(); encrypt(_nullBuffer, inputPath, outputBuffer, _nullPath); } void CCmsMessage::decryptFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("decryptFileToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, inputPath.c_str()); outputBuffer.CreateInstance(); decrypt(_nullBuffer, inputPath, outputBuffer, _nullPath); } void CCmsMessage::compressFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("compressFileToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, inputPath.c_str()); outputBuffer.CreateInstance(); compress(_nullBuffer, inputPath, outputBuffer, _nullPath); } void CCmsMessage::uncompressFileToBuffer( const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer) const { CAF_CM_FUNCNAME_VALIDATE("uncompressFileToBuffer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_LOG_DEBUG_VA2("%s - %s", CAF_CM_GET_FUNCNAME, inputPath.c_str()); outputBuffer.CreateInstance(); uncompress(_nullBuffer, inputPath, outputBuffer, _nullPath); } void CCmsMessage::signFileToFile( const std::string& inputPath, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("signFileToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA3("%s - %s, %s", CAF_CM_GET_FUNCNAME, inputPath.c_str(), outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; sign(_nullBuffer, inputPath, nullBuffer, outputPath); } void CCmsMessage::verifyFileToFile( const std::string& inputPath, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("verifyFileToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA3("%s - %s, %s", CAF_CM_GET_FUNCNAME, inputPath.c_str(), outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; verify(_nullBuffer, inputPath, nullBuffer, outputPath); } void CCmsMessage::encryptFileToFile( const std::string& inputPath, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("encryptFileToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA3("%s - %s, %s", CAF_CM_GET_FUNCNAME, inputPath.c_str(), outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; encrypt(_nullBuffer, inputPath, nullBuffer, outputPath); } void CCmsMessage::decryptFileToFile( const std::string& inputPath, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("decryptFileToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA3("%s - %s, %s", CAF_CM_GET_FUNCNAME, inputPath.c_str(), outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; decrypt(_nullBuffer, inputPath, nullBuffer, outputPath); } void CCmsMessage::compressFileToFile( const std::string& inputPath, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("compressFileToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA3("%s - %s, %s", CAF_CM_GET_FUNCNAME, inputPath.c_str(), outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; compress(_nullBuffer, inputPath, nullBuffer, outputPath); } void CCmsMessage::uncompressFileToFile( const std::string& inputPath, const std::string& outputPath) const { CAF_CM_FUNCNAME_VALIDATE("uncompressFileToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputPath); CAF_CM_VALIDATE_STRING(outputPath); CAF_CM_LOG_DEBUG_VA3("%s - %s, %s", CAF_CM_GET_FUNCNAME, inputPath.c_str(), outputPath.c_str()); SmartPtrCDynamicByteArray nullBuffer; uncompress(_nullBuffer, inputPath, nullBuffer, outputPath); } void CCmsMessage::sign( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME("sign"); checkCrlf(CAF_CM_GET_FUNCNAME, "input", inputBuffer, inputPath); const uint32 flags = CMS_STREAM | CMS_BINARY; BIO* signPublicKeyBio = NULL; BIO* signPrivateKeyBio = NULL; X509* signPublicKey = NULL; EVP_PKEY* signPrivateKey = NULL; BIO* outputBio = NULL; BIO* inputBufferBio = NULL; CMS_ContentInfo* contentInfo = NULL; try { signPublicKeyBio = CCmsMessageUtils::inputFileToBio(_signPublicKeyPath); signPrivateKeyBio = CCmsMessageUtils::inputFileToBio(_signPrivateKeyPath); signPublicKey = CCmsMessageUtils::bioToX509(signPublicKeyBio); // Casting to void to ignore return value and eliminate compiler warning (void) BIO_reset(signPublicKeyBio); signPrivateKey = CCmsMessageUtils::bioToPrivateKey(signPrivateKeyBio); inputBufferBio = CCmsMessageUtils::inputToBio(inputBuffer, inputPath); contentInfo = CMS_sign(signPublicKey, signPrivateKey, NULL, inputBufferBio, flags); if (! contentInfo) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "CMS_sign Failed"); } outputBio = CCmsMessageUtils::outputToBio(outputBuffer, outputPath); /* Write out S/MIME message */ if (! SMIME_write_CMS(outputBio, contentInfo, inputBufferBio, flags)) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA1(E_FAIL, "SMIME_write_CMS Failed - %s", outputPath.c_str()); } CCmsMessageUtils::bioToOutput(outputBio, outputBuffer, outputPath); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; CCmsMessageUtils::free(contentInfo); CCmsMessageUtils::free(signPublicKey); CCmsMessageUtils::free(signPrivateKey); CCmsMessageUtils::free(inputBufferBio); CCmsMessageUtils::free(outputBio); CCmsMessageUtils::free(signPublicKeyBio); CCmsMessageUtils::free(signPrivateKeyBio); CAF_CM_THROWEXCEPTION; checkCrlf(CAF_CM_GET_FUNCNAME, "output", outputBuffer, outputPath); } void CCmsMessage::verify( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME("verify"); checkCrlf(CAF_CM_GET_FUNCNAME, "input", inputBuffer, inputPath); std::deque caCertBios; std::deque caCertX509s; X509_STORE* caCertStore = NULL; BIO* inputBufferBio = NULL; BIO* inputParsedBio = NULL; BIO* outputBio = NULL; CMS_ContentInfo* contentInfo = NULL; try { caCertBios = CCmsMessageUtils::inputFilesToBio(_caCertificatePaths); caCertX509s = CCmsMessageUtils::biosToX509(caCertBios); caCertStore = CCmsMessageUtils::createX509Store(caCertX509s); /* * X509_STORE_free will free up recipient Store and its contents so set * caCerts to NULL so it isn't freed up twice. */ caCertX509s.clear(); inputBufferBio = CCmsMessageUtils::inputToBio(inputBuffer, inputPath); /* parse message */ contentInfo = SMIME_read_CMS(inputBufferBio, &inputParsedBio); if (! contentInfo) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "SMIME_read_CMS Failed"); } outputBio = CCmsMessageUtils::outputToBio(outputBuffer, outputPath); if (! CMS_verify(contentInfo, NULL, caCertStore, inputParsedBio, outputBio, 0)) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "CMS_verify Failed"); } CCmsMessageUtils::bioToOutput(outputBio, outputBuffer, outputPath); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; CCmsMessageUtils::free(contentInfo); CCmsMessageUtils::free(caCertX509s); CCmsMessageUtils::free(caCertStore); CCmsMessageUtils::free(inputBufferBio); CCmsMessageUtils::free(outputBio); CCmsMessageUtils::free(inputParsedBio); CCmsMessageUtils::free(caCertBios); CAF_CM_THROWEXCEPTION; checkCrlf(CAF_CM_GET_FUNCNAME, "output", outputBuffer, outputPath); } void CCmsMessage::encrypt( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME("encrypt"); checkCrlf(CAF_CM_GET_FUNCNAME, "input", inputBuffer, inputPath); const uint32 flags = CMS_STREAM | CMS_BINARY; BIO* encryptPublicKeyBio = NULL; X509* encryptPublicKey = NULL; STACK_OF(X509)* encryptPublicKeyStack = NULL; BIO* outputBio = NULL; BIO* inputBufferBio = NULL; CMS_ContentInfo* contentInfo = NULL; try { encryptPublicKeyBio = CCmsMessageUtils::inputFileToBio(_encryptPublicKeyPath); encryptPublicKey = CCmsMessageUtils::bioToX509(encryptPublicKeyBio); encryptPublicKeyStack = CCmsMessageUtils::createX509Stack(encryptPublicKey); /* * sk_X509_pop_free will CCmsMessageUtils::free up recipient STACK and its contents so set * encryptPublicKey to NULL so it isn't freed up twice. */ encryptPublicKey = NULL; inputBufferBio = CCmsMessageUtils::inputToBio(inputBuffer, inputPath); /* encrypt content */ contentInfo = CMS_encrypt(encryptPublicKeyStack, inputBufferBio, _cipher, flags); if (! contentInfo) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "CMS_encrypt Failed"); } outputBio = CCmsMessageUtils::outputToBio(outputBuffer, outputPath); /* Write out S/MIME message */ if (! SMIME_write_CMS(outputBio, contentInfo, inputBufferBio, flags)) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "SMIME_write_CMS Failed"); } CCmsMessageUtils::bioToOutput(outputBio, outputBuffer, outputPath); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; CCmsMessageUtils::free(contentInfo); CCmsMessageUtils::free(encryptPublicKey); CCmsMessageUtils::free(encryptPublicKeyStack); CCmsMessageUtils::free(inputBufferBio); CCmsMessageUtils::free(outputBio); CCmsMessageUtils::free(encryptPublicKeyBio); CAF_CM_THROWEXCEPTION; checkCrlf(CAF_CM_GET_FUNCNAME, "output", outputBuffer, outputPath); } void CCmsMessage::decrypt( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME("decrypt"); checkCrlf(CAF_CM_GET_FUNCNAME, "input", inputBuffer, inputPath); BIO* decryptPublicKeyBio = NULL; BIO* decryptPrivateKeyBio = NULL; X509* decryptPublicKey = NULL; EVP_PKEY* decryptPrivateKey = NULL; BIO* outputBio = NULL; BIO* inputBufferBio = NULL; CMS_ContentInfo* contentInfo = NULL; try { decryptPublicKeyBio = CCmsMessageUtils::inputFileToBio(_decryptPublicKeyPath); decryptPrivateKeyBio = CCmsMessageUtils::inputFileToBio(_decryptPrivateKeyPath); decryptPublicKey = CCmsMessageUtils::bioToX509(decryptPublicKeyBio); decryptPrivateKey = CCmsMessageUtils::bioToPrivateKey(decryptPrivateKeyBio); inputBufferBio = CCmsMessageUtils::inputToBio(inputBuffer, inputPath); contentInfo = SMIME_read_CMS(inputBufferBio, NULL); if (! contentInfo) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "SMIME_read_CMS Failed"); } outputBio = CCmsMessageUtils::outputToBio(outputBuffer, outputPath); if (!CMS_decrypt(contentInfo, decryptPrivateKey, decryptPublicKey, NULL, outputBio, 0)) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "CMS_decrypt Failed"); } CCmsMessageUtils::bioToOutput(outputBio, outputBuffer, outputPath); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; CCmsMessageUtils::free(contentInfo); CCmsMessageUtils::free(decryptPublicKey); CCmsMessageUtils::free(decryptPrivateKey); CCmsMessageUtils::free(inputBufferBio); CCmsMessageUtils::free(outputBio); CCmsMessageUtils::free(decryptPublicKeyBio); CCmsMessageUtils::free(decryptPrivateKeyBio); CAF_CM_THROWEXCEPTION; checkCrlf(CAF_CM_GET_FUNCNAME, "output", outputBuffer, outputPath); } void CCmsMessage::compress( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME("compress"); checkCrlf(CAF_CM_GET_FUNCNAME, "input", inputBuffer, inputPath); BIO* inputBufferBio = NULL; BIO* outputBio = NULL; CMS_ContentInfo* contentInfo = NULL; try { inputBufferBio = CCmsMessageUtils::inputToBio(inputBuffer, inputPath); /* parse message */ contentInfo = CMS_compress(inputBufferBio, NID_zlib_compression, CMS_STREAM | CMS_BINARY); if (! contentInfo) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "CMS_compress Failed"); } outputBio = CCmsMessageUtils::outputToBio(outputBuffer, outputPath); /* Write out S/MIME message */ if (! SMIME_write_CMS(outputBio, contentInfo, inputBufferBio, CMS_STREAM)) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "SMIME_write_CMS Failed"); } CCmsMessageUtils::bioToOutput(outputBio, outputBuffer, outputPath); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; CCmsMessageUtils::free(contentInfo); CCmsMessageUtils::free(inputBufferBio); CCmsMessageUtils::free(outputBio); CAF_CM_THROWEXCEPTION; checkCrlf(CAF_CM_GET_FUNCNAME, "output", outputBuffer, outputPath); } void CCmsMessage::uncompress( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) const { CAF_CM_FUNCNAME("uncompress"); checkCrlf(CAF_CM_GET_FUNCNAME, "input", inputBuffer, inputPath); BIO* inputBufferBio = NULL; BIO* outputBio = NULL; CMS_ContentInfo* contentInfo = NULL; try { inputBufferBio = CCmsMessageUtils::inputToBio(inputBuffer, inputPath); /* parse message */ contentInfo = SMIME_read_CMS(inputBufferBio, NULL); if (! contentInfo) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "SMIME_read_CMS Failed"); } outputBio = CCmsMessageUtils::outputToBio(outputBuffer, outputPath); if (! CMS_uncompress(contentInfo, outputBio, NULL, 0)) { CCmsMessageUtils::logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "CMS_uncompress Failed"); } CCmsMessageUtils::bioToOutput(outputBio, outputBuffer, outputPath); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; CCmsMessageUtils::free(contentInfo); CCmsMessageUtils::free(inputBufferBio); CCmsMessageUtils::free(outputBio); CAF_CM_THROWEXCEPTION; checkCrlf(CAF_CM_GET_FUNCNAME, "output", outputBuffer, outputPath); } void CCmsMessage::checkCrlf( const std::string& funcName, const std::string& direction, const SmartPtrCDynamicByteArray& buffer, const std::string& path) const { CAF_CM_FUNCNAME("checkCrlf"); CAF_CM_VALIDATE_STRING(funcName); CAF_CM_VALIDATE_STRING(direction); if (_checkCrlf) { if (! buffer.IsNull()) { checkCrlf(funcName, direction, buffer); } else if (! path.empty()) { checkCrlf(funcName, direction, path); } else { CAF_CM_EXCEPTION_VA0(E_FAIL, "Must provide buffer or path"); } } } void CCmsMessage::checkCrlf( const std::string& funcName, const std::string& direction, const SmartPtrCDynamicByteArray& buffer) const { CAF_CM_FUNCNAME("checkCrlf(buffer)"); CAF_CM_VALIDATE_STRING(funcName); CAF_CM_VALIDATE_STRING(direction); CAF_CM_VALIDATE_SMARTPTR(buffer); bool isFnd = false; for (uint32 i = 0; ! isFnd && (i < buffer->getElementCount()); i++) { if (buffer->getAt(i) == '\r') { CAF_CM_EXCEPTION_VA2(E_FAIL, "Found CRLF - func: %s, dir: %s", funcName.c_str(), direction.c_str()); } } } void CCmsMessage::checkCrlf( const std::string& funcName, const std::string& direction, const std::string& path) const { CAF_CM_FUNCNAME("checkCrlf(path)"); CAF_CM_VALIDATE_STRING(funcName); CAF_CM_VALIDATE_STRING(direction); CAF_CM_VALIDATE_STRING(path); std::ifstream ifs(path.c_str()); if(!ifs) { CAF_CM_EXCEPTION_VA1(E_FAIL, "Failed to open file - %s", path.c_str()); } std::istream::sentry se(ifs, true); std::streambuf* sb = ifs.rdbuf(); char c = '\0'; bool isFnd = false; while (! isFnd && ! ifs.eof() && (c != EOF)) { c = sb->sbumpc(); if (c == '\r') { CAF_CM_EXCEPTION_VA3(E_FAIL, "Found CRLF - func: %s, dir: %s, path: %s", funcName.c_str(), direction.c_str(), path.c_str()); } } } std::string CCmsMessage::getReqDirPath( const std::string& directory, const std::string& subdir, const std::string& subdir1) const { CAF_CM_FUNCNAME("getReqFilePath"); CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(subdir); std::string rc; if (subdir1.empty()) { rc = FileSystemUtils::buildPath(directory, subdir); } else { rc = FileSystemUtils::buildPath(directory, subdir, subdir1); } if (! FileSystemUtils::doesDirectoryExist(rc)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "Directory does not exist - %s", rc.c_str()); } return rc; } std::string CCmsMessage::getReqFilePath( const std::string& directory, const std::string& filename) const { CAF_CM_FUNCNAME("getReqFilePath"); CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(filename); const std::string rc = FileSystemUtils::buildPath(directory, filename); if (! FileSystemUtils::doesFileExist(rc)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "File does not exist - %s", rc.c_str()); } return rc; } Cdeqstr CCmsMessage::getReqFilePaths( const std::string& directory, const std::string& subdir) const { CAF_CM_FUNCNAME_VALIDATE("getReqFilePaths"); CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(subdir); const std::string dirPath = getReqDirPath(directory, subdir); FileSystemUtils::DirectoryItems dirItems = FileSystemUtils::itemsInDirectory( dirPath, FileSystemUtils::REGEX_MATCH_ALL); Cdeqstr rc; const FileSystemUtils::Files files = dirItems.files; for (TConstIterator fileIter(files); fileIter; fileIter++) { const std::string filename = *fileIter; const std::string filePath = FileSystemUtils::buildPath( dirPath, filename); rc.push_back(filePath); } return rc; } std::string CCmsMessage::getReqRmtCertsDir( const std::string& appId, const std::string& pmeId) const { CAF_CM_FUNCNAME("getReqRmtCertsDir"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(appId); CAF_CM_VALIDATE_STRING(pmeId); const std::string rmtCertsDir = getReqDirPath(_persistenceDir, "remote"); const std::string pmeIdLower = CStringUtils::toLower(pmeId); const std::string appIdLower = CStringUtils::toLower(appId); const std::string pmeIdUpper = CStringUtils::toUpper(pmeId); const std::string appIdUpper = CStringUtils::toUpper(appId); std::string rc; std::string errDirs; getExistingDir(rmtCertsDir, pmeIdLower, rc, errDirs); getExistingDir(rmtCertsDir, appIdLower, rc, errDirs); getExistingDir(rmtCertsDir, pmeIdUpper, rc, errDirs); getExistingDir(rmtCertsDir, appIdUpper, rc, errDirs); getExistingDir(rmtCertsDir, "remote_default", rc, errDirs); if (rc.empty()) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "Remote directories do not exist - %s", errDirs.c_str()); } return rc; } void CCmsMessage::getExistingDir( const std::string& parentDir, const std::string& childDir, std::string& result, std::string& errDirs) const { CAF_CM_FUNCNAME_VALIDATE("getExistingDir"); CAF_CM_VALIDATE_STRING(parentDir); CAF_CM_VALIDATE_STRING(childDir); if (result.empty()) { const std::string finalDir = FileSystemUtils::buildPath(parentDir, childDir); errDirs += finalDir + ", "; if (FileSystemUtils::doesDirectoryExist(finalDir)) { result = finalDir; } } } CCmsMessageAttachments.cpp000066400000000000000000000322111321503522500412720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: July 3, 2015 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "CCmsMessage.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "CCmsMessageAttachments.h" #include "Exception/CCafException.h" using namespace Caf; CCmsMessageAttachments::CCmsMessageAttachments() : _isInitialized(false), CAF_CM_INIT_LOG("CCmsMessageAttachments") { } CCmsMessageAttachments::~CCmsMessageAttachments() { } void CCmsMessageAttachments::initialize( const SmartPtrCCmsMessage& cmsMessage) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(cmsMessage); _cmsMessage = cmsMessage; _isInitialized = true; } std::deque CCmsMessageAttachments::encryptAndSignAttachments( const std::deque& sourceAttachmentCollection) const { CAF_CM_FUNCNAME("encryptAndSignAttachments"); // sourceAttachmentCollection is optional std::deque rc; for (TConstIterator > sourceAttachmentIter(sourceAttachmentCollection); sourceAttachmentIter; sourceAttachmentIter++) { const SmartPtrCAttachmentDoc sourceAttachment = *sourceAttachmentIter; UriUtils::SUriRecord sourceUriRecord; UriUtils::parseUriString(sourceAttachment->getUri(), sourceUriRecord); if ((sourceUriRecord.protocol.compare("file") == 0) && !sourceAttachment->getIsReference()) { UriUtils::SFileUriRecord sourceFileUriRecord; UriUtils::parseFileAddress(sourceUriRecord.address, sourceFileUriRecord); const std::string sourceAttachmentPath = sourceFileUriRecord.path; if (!FileSystemUtils::doesFileExist(sourceAttachmentPath)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "File not found - %s", sourceAttachmentPath.c_str()); } const SmartPtrCAttachmentDoc destAttachment = encryptAndSignAttachment( sourceAttachmentPath, sourceAttachment, sourceUriRecord.parameters); rc.push_back(destAttachment); } else { rc.push_back(sourceAttachment); } } return rc; } void CCmsMessageAttachments::enforceSecurityOnAttachments( const std::deque& attachmentCollection, const bool isSigningEnforced, const bool isEncryptionEnforced) const { CAF_CM_FUNCNAME("enforceSecurityOnAttachments"); for (TConstIterator > attachmentIter(attachmentCollection); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; const CMS_POLICY cmsPolicy = attachment->getCmsPolicy(); switch(cmsPolicy) { case CMS_POLICY_NONE: enforceSigning(isSigningEnforced, attachment); enforceEncryption(isEncryptionEnforced, attachment); break; case CMS_POLICY_CAF_ENCRYPTED: enforceSigning(isSigningEnforced, attachment); break; case CMS_POLICY_CAF_SIGNED: enforceEncryption(isEncryptionEnforced, attachment); break; case CMS_POLICY_APP_ENCRYPTED: enforceSigning(isSigningEnforced, attachment); break; case CMS_POLICY_APP_SIGNED: enforceEncryption(isEncryptionEnforced, attachment); break; case CMS_POLICY_CAF_ENCRYPTED_AND_SIGNED: case CMS_POLICY_APP_ENCRYPTED_AND_SIGNED: break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown CMS Policy - %d", static_cast(cmsPolicy)); } } } SmartPtrCAttachmentDoc CCmsMessageAttachments::encryptAndSignAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters) const { CAF_CM_FUNCNAME("encryptAndSignAttachment"); CAF_CM_VALIDATE_STRING(sourceAttachmentPath); CAF_CM_VALIDATE_SMARTPTR(sourceAttachment); SmartPtrCAttachmentDoc destAttachment = sourceAttachment; std::string destAttachmentPath; std::string sourceAttachmentPathTmp = sourceAttachmentPath; SmartPtrCAttachmentDoc sourceAttachmentTmp = sourceAttachment; const CMS_POLICY cmsPolicy = sourceAttachmentTmp->getCmsPolicy(); switch(cmsPolicy) { case CMS_POLICY_CAF_ENCRYPTED: encryptAttachment(sourceAttachmentPathTmp, sourceAttachmentTmp, uriParameters, destAttachmentPath, destAttachment); break; case CMS_POLICY_CAF_SIGNED: signAttachment(sourceAttachmentPathTmp, sourceAttachmentTmp, uriParameters, destAttachmentPath, destAttachment); break; case CMS_POLICY_CAF_ENCRYPTED_AND_SIGNED: encryptAttachment(sourceAttachmentPathTmp, sourceAttachmentTmp, uriParameters, destAttachmentPath, destAttachment); sourceAttachmentPathTmp = destAttachmentPath; sourceAttachmentTmp = destAttachment; signAttachment(sourceAttachmentPathTmp, sourceAttachmentTmp, uriParameters, destAttachmentPath, destAttachment); break; case CMS_POLICY_NONE: case CMS_POLICY_APP_ENCRYPTED: case CMS_POLICY_APP_SIGNED: case CMS_POLICY_APP_ENCRYPTED_AND_SIGNED: CAF_CM_LOG_DEBUG_VA1("Passthrough CMS Policy - %s", EnumConvertersXml::convertCmsPolicyToString(cmsPolicy).c_str()) break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown CMS Policy - %d", static_cast(cmsPolicy)); } return destAttachment; } std::deque CCmsMessageAttachments::decryptAndVerifyAttachments( const std::deque& sourceAttachmentCollection) const { CAF_CM_FUNCNAME("decryptAndVerifyAttachments"); // sourceAttachmentCollection is optional std::deque rc; for (TConstIterator > sourceAttachmentIter(sourceAttachmentCollection); sourceAttachmentIter; sourceAttachmentIter++) { const SmartPtrCAttachmentDoc sourceAttachment = *sourceAttachmentIter; UriUtils::SUriRecord sourceUriRecord; UriUtils::parseUriString(sourceAttachment->getUri(), sourceUriRecord); if ((sourceUriRecord.protocol.compare("file") == 0) && !sourceAttachment->getIsReference()) { UriUtils::SFileUriRecord sourceFileUriRecord; UriUtils::parseFileAddress(sourceUriRecord.address, sourceFileUriRecord); const std::string sourceAttachmentPath = sourceFileUriRecord.path; if (!FileSystemUtils::doesFileExist(sourceAttachmentPath)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "File not found - %s", sourceAttachmentPath.c_str()); } const SmartPtrCAttachmentDoc destAttachment = decryptAndVerifyAttachment( sourceAttachmentPath, sourceAttachment, sourceUriRecord.parameters); rc.push_back(destAttachment); } else { rc.push_back(sourceAttachment); } } return rc; } SmartPtrCAttachmentDoc CCmsMessageAttachments::decryptAndVerifyAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters) const { CAF_CM_FUNCNAME("decryptAndVerifyAttachment"); CAF_CM_VALIDATE_STRING(sourceAttachmentPath); CAF_CM_VALIDATE_SMARTPTR(sourceAttachment); SmartPtrCAttachmentDoc destAttachment = sourceAttachment; std::string destAttachmentPath; std::string sourceAttachmentPathTmp = sourceAttachmentPath; SmartPtrCAttachmentDoc sourceAttachmentTmp = sourceAttachment; const CMS_POLICY cmsPolicy = sourceAttachmentTmp->getCmsPolicy(); switch(cmsPolicy) { case CMS_POLICY_CAF_ENCRYPTED: decryptAttachment(sourceAttachmentPathTmp, sourceAttachmentTmp, uriParameters, destAttachmentPath, destAttachment); break; case CMS_POLICY_CAF_SIGNED: verifyAttachment(sourceAttachmentPathTmp, sourceAttachmentTmp, uriParameters, destAttachmentPath, destAttachment); break; case CMS_POLICY_CAF_ENCRYPTED_AND_SIGNED: verifyAttachment(sourceAttachmentPathTmp, sourceAttachmentTmp, uriParameters, destAttachmentPath, destAttachment); sourceAttachmentPathTmp = destAttachmentPath; sourceAttachmentTmp = destAttachment; decryptAttachment(sourceAttachmentPathTmp, sourceAttachmentTmp, uriParameters, destAttachmentPath, destAttachment); break; case CMS_POLICY_NONE: case CMS_POLICY_APP_ENCRYPTED: case CMS_POLICY_APP_SIGNED: case CMS_POLICY_APP_ENCRYPTED_AND_SIGNED: CAF_CM_LOG_DEBUG_VA1("Passthrough CMS Policy - %s", EnumConvertersXml::convertCmsPolicyToString(cmsPolicy).c_str()) break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown CMS Policy - %d", static_cast(cmsPolicy)); } return destAttachment; } void CCmsMessageAttachments::signAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters, std::string& destAttachmentPath, SmartPtrCAttachmentDoc& destAttachment) const { CAF_CM_FUNCNAME_VALIDATE("signAttachment"); CAF_CM_VALIDATE_STRING(sourceAttachmentPath); CAF_CM_VALIDATE_SMARTPTR(sourceAttachment); destAttachmentPath = sourceAttachmentPath + "_signed"; _cmsMessage->signFileToFile(sourceAttachmentPath, destAttachmentPath); const std::string attachmentUri = UriUtils::appendParameters( destAttachmentPath, uriParameters); destAttachment.CreateInstance(); destAttachment->initialize(sourceAttachment->getName(), sourceAttachment->getType(), "file:///" + attachmentUri, sourceAttachment->getIsReference(), sourceAttachment->getCmsPolicy()); } void CCmsMessageAttachments::verifyAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters, std::string& destAttachmentPath, SmartPtrCAttachmentDoc& destAttachment) const { CAF_CM_FUNCNAME_VALIDATE("verifyAttachment"); CAF_CM_VALIDATE_STRING(sourceAttachmentPath); CAF_CM_VALIDATE_SMARTPTR(sourceAttachment); destAttachmentPath = sourceAttachmentPath + "_verified"; removeStr(destAttachmentPath, "_signed"); _cmsMessage->verifyFileToFile(sourceAttachmentPath, destAttachmentPath); const std::string attachmentUri = UriUtils::appendParameters( destAttachmentPath, uriParameters); destAttachment.CreateInstance(); destAttachment->initialize(sourceAttachment->getName(), sourceAttachment->getType(), "file:///" + attachmentUri, sourceAttachment->getIsReference(), sourceAttachment->getCmsPolicy()); } void CCmsMessageAttachments::encryptAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters, std::string& destAttachmentPath, SmartPtrCAttachmentDoc& destAttachment) const { CAF_CM_FUNCNAME_VALIDATE("encryptAttachment"); CAF_CM_VALIDATE_STRING(sourceAttachmentPath); CAF_CM_VALIDATE_SMARTPTR(sourceAttachment); destAttachmentPath = sourceAttachmentPath + "_encrypted"; _cmsMessage->encryptFileToFile(sourceAttachmentPath, destAttachmentPath); const std::string attachmentUri = UriUtils::appendParameters( destAttachmentPath, uriParameters); destAttachment.CreateInstance(); destAttachment->initialize(sourceAttachment->getName(), sourceAttachment->getType(), "file:///" + attachmentUri, sourceAttachment->getIsReference(), sourceAttachment->getCmsPolicy()); } void CCmsMessageAttachments::decryptAttachment( const std::string& sourceAttachmentPath, const SmartPtrCAttachmentDoc& sourceAttachment, const std::map& uriParameters, std::string& destAttachmentPath, SmartPtrCAttachmentDoc& destAttachment) const { CAF_CM_FUNCNAME_VALIDATE("decryptAttachment"); CAF_CM_VALIDATE_STRING(sourceAttachmentPath); CAF_CM_VALIDATE_SMARTPTR(sourceAttachment); destAttachmentPath = sourceAttachmentPath + "_decrypted"; removeStr(destAttachmentPath, "_encrypted"); _cmsMessage->decryptFileToFile(sourceAttachmentPath, destAttachmentPath); const std::string attachmentUri = UriUtils::appendParameters( destAttachmentPath, uriParameters); destAttachment.CreateInstance(); destAttachment->initialize(sourceAttachment->getName(), sourceAttachment->getType(), "file:///" + attachmentUri, sourceAttachment->getIsReference(), sourceAttachment->getCmsPolicy()); } void CCmsMessageAttachments::removeStr( std::string& sourceStr, const std::string& strToRemove) const { CAF_CM_FUNCNAME_VALIDATE("removeStr"); CAF_CM_VALIDATE_STRING(sourceStr); CAF_CM_VALIDATE_STRING(strToRemove); const size_t index = sourceStr.find(strToRemove); if (index != std::string::npos) { sourceStr.erase(index, strToRemove.length()); } } void CCmsMessageAttachments::enforceSigning( const bool isSigningEnforced, const SmartPtrCAttachmentDoc& attachment) const { CAF_CM_FUNCNAME("enforceSigning"); CAF_CM_VALIDATE_SMARTPTR(attachment); if (isSigningEnforced) { CAF_CM_EXCEPTION_VA2(E_FAIL, "Attachment must be signed - name: %s, uri: %s", attachment->getName().c_str(), attachment->getUri().c_str()); } } void CCmsMessageAttachments::enforceEncryption( const bool isEncryptionEnforced, const SmartPtrCAttachmentDoc& attachment) const { CAF_CM_FUNCNAME("enforceEncryption"); CAF_CM_VALIDATE_SMARTPTR(attachment); if (isEncryptionEnforced) { CAF_CM_EXCEPTION_VA2(E_FAIL, "Attachment must be encrypted - name: %s, uri: %s", attachment->getName().c_str(), attachment->getUri().c_str()); } } CCmsMessageTransformer.cpp000066400000000000000000000032131321503522500413210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CCmsMessageTransformer.h" using namespace Caf; CCmsMessageTransformer::CCmsMessageTransformer() : _isInitialized(false), CAF_CM_INIT("CCmsMessageTransformer") { } CCmsMessageTransformer::~CCmsMessageTransformer() { } void CCmsMessageTransformer::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); _ctorArgs = ctorArgs; _properties = properties; initialize(); } void CCmsMessageTransformer::terminateBean() { } void CCmsMessageTransformer::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } bool CCmsMessageTransformer::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); return false; } SmartPtrIIntegrationObject CCmsMessageTransformer::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); SmartPtrIIntegrationObject rc; rc.CreateInstance(_sObjIdCommIntegrationCmsMessageTransformerInstance); rc->initialize(_ctorArgs, _properties, configSection); return rc; } CCmsMessageTransformer.h000066400000000000000000000026431321503522500407740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCmsMessageTransformer_h_ #define CCmsMessageTransformer_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CCmsMessageTransformer : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CCmsMessageTransformer(); virtual ~CCmsMessageTransformer(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationCmsMessageTransformer) CAF_BEGIN_INTERFACE_MAP(CCmsMessageTransformer) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CCmsMessageTransformer); }; } #endif // #ifndef CCmsMessageTransformer_h_ CCmsMessageTransformerInstance.cpp000066400000000000000000000126221321503522500430120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Caf/CBeanPropertiesHelper.h" #include "Integration/Caf/CCafMessageHeaders.h" #include "CCmsMessage.h" #include "CCmsMessageAttachments.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "CCmsMessageTransformerInstance.h" #include "Integration/Caf/CCafMessageCreator.h" #include "Integration/Caf/CCafMessagePayloadParser.h" using namespace Caf; CCmsMessageTransformerInstance::CCmsMessageTransformerInstance() : _isInitialized(false), _isSigningEnforced(true), _isEncryptionEnforced(true), CAF_CM_INIT("CCmsMessageTransformerInstance") { } CCmsMessageTransformerInstance::~CCmsMessageTransformerInstance() { } void CCmsMessageTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); const SmartPtrCBeanPropertiesHelper beanProperties = CBeanPropertiesHelper::create(properties); _id = configSection->findRequiredAttribute("id"); const std::string cmsPolicyStr = beanProperties->getRequiredString("cmsPolicy"); _isSigningEnforced = beanProperties->getRequiredBool("isSigningEnforced"); _isEncryptionEnforced = beanProperties->getRequiredBool("isEncryptionEnforced"); _workingDirectory = AppConfigUtils::getRequiredString("communication_amqp", _sConfigWorkingDir); _isInitialized = true; } std::string CCmsMessageTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CCmsMessageTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } SmartPtrIIntMessage CCmsMessageTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(message); SmartPtrCCafMessageHeaders cafMessageHeaders = CCafMessageHeaders::create(message->getHeaders()); const std::string msgFlow = cafMessageHeaders->getFlowDirection(); const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); SmartPtrCCmsMessage cmsMessage; cmsMessage.CreateInstance(); cmsMessage->initialize( BasePlatform::UuidToString(payloadEnvelope->getClientId()), payloadEnvelope->getPmeId()); SmartPtrCCmsMessageAttachments cmsMessageAttachments; cmsMessageAttachments.CreateInstance(); cmsMessageAttachments->initialize(cmsMessage); SmartPtrIIntMessage rc; if (msgFlow.compare("OUTGOING") == 0) { rc = createOutgoingPayload(message->getHeaders(), payloadEnvelope, cmsMessageAttachments); } else if (msgFlow.compare("INCOMING") == 0) { rc = createIncomingPayload(message->getHeaders(), payloadEnvelope, cmsMessageAttachments); } else { CAF_CM_EXCEPTION_VA1(E_FAIL, "Invalid msgflow header value: %s", msgFlow.c_str()); } return rc; } SmartPtrIIntMessage CCmsMessageTransformerInstance::createOutgoingPayload( const IIntMessage::SmartPtrCHeaders& headers, const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const SmartPtrCCmsMessageAttachments& cmsMessageAttachments) const { CAF_CM_FUNCNAME_VALIDATE("createOutgoingPayload"); CAF_CM_VALIDATE_SMARTPTR(headers); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelope); CAF_CM_VALIDATE_SMARTPTR(cmsMessageAttachments); const std::deque attachmentCollection = payloadEnvelope->getAttachmentCollection()->getAttachment(); const std::deque attachmentCollectionCms = cmsMessageAttachments->encryptAndSignAttachments(attachmentCollection); return CCafMessageCreator::createPayloadEnvelope( payloadEnvelope, attachmentCollectionCms, headers); } SmartPtrIIntMessage CCmsMessageTransformerInstance::createIncomingPayload( const IIntMessage::SmartPtrCHeaders& headers, const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const SmartPtrCCmsMessageAttachments& cmsMessageAttachments) const { CAF_CM_FUNCNAME_VALIDATE("createIncomingPayload"); CAF_CM_VALIDATE_SMARTPTR(headers); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelope); CAF_CM_VALIDATE_SMARTPTR(cmsMessageAttachments); // Get the attachment collection out of the payload. const std::deque attachmentCollectionCms = payloadEnvelope->getAttachmentCollection()->getAttachment(); // Make sure the attachments meet the minimum security bar. cmsMessageAttachments->enforceSecurityOnAttachments(attachmentCollectionCms, _isSigningEnforced, _isEncryptionEnforced); // Decrypt/verify the attachments. const std::deque attachmentCollection = cmsMessageAttachments->decryptAndVerifyAttachments(attachmentCollectionCms); return CCafMessageCreator::createPayloadEnvelope( payloadEnvelope, attachmentCollection, headers); } CCmsMessageTransformerInstance.h000066400000000000000000000045341321503522500424620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCmsMessageTransformerInstance_h_ #define CCmsMessageTransformerInstance_h_ #include #include "CCmsMessageAttachments.h" #include "Common/IAppContext.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CCmsMessageTransformerInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CCmsMessageTransformerInstance(); virtual ~CCmsMessageTransformerInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationCmsMessageTransformerInstance) CAF_BEGIN_INTERFACE_MAP(CCmsMessageTransformerInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: SmartPtrIIntMessage createOutgoingPayload( const IIntMessage::SmartPtrCHeaders& headers, const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const SmartPtrCCmsMessageAttachments& cmsMessageAttachments) const; SmartPtrIIntMessage createIncomingPayload( const IIntMessage::SmartPtrCHeaders& headers, const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const SmartPtrCCmsMessageAttachments& cmsMessageAttachments) const; private: bool _isInitialized; std::string _id; std::string _workingDirectory; bool _isSigningEnforced; bool _isEncryptionEnforced; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CCmsMessageTransformerInstance); }; } #endif // #ifndef CCmsMessageTransformerInstance_h_ CCmsMessageUtils.cpp000066400000000000000000000207441321503522500401270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Exception/CCafException.h" #include "CCmsMessageUtils.h" using namespace Caf; BIO* CCmsMessageUtils::inputBufferToBio( const SmartPtrCDynamicByteArray& inputBuffer) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "inputBufferToBio"); CAF_CM_VALIDATE_SMARTPTR(inputBuffer); BIO* rc = BIO_new_mem_buf( inputBuffer->getNonConstPtr(), static_cast(inputBuffer->getByteCount())); if (! rc) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "BIO_new_mem_buf Failed"); } return rc; } std::deque CCmsMessageUtils::inputFilesToBio( const Cdeqstr& inputFileCollection) { CAF_CM_STATIC_FUNC_VALIDATE("CCmsMessageUtils", "inputFilesToBio"); CAF_CM_VALIDATE_STL(inputFileCollection); std::deque rc; for (TConstIterator elemIter(inputFileCollection); elemIter; elemIter++) { const std::string elem = *elemIter; rc.push_back(inputFileToBio(elem)); } return rc; } BIO* CCmsMessageUtils::inputFileToBio( const std::string& inputFile) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "inputFileToBio"); CAF_CM_VALIDATE_STRING(inputFile); BIO* rc = BIO_new_file(inputFile.c_str(), "r"); if (! rc) { logSslErrors(); CAF_CM_EXCEPTION_VA1(E_FAIL, "BIO_new_file Failed - %s", inputFile.c_str()); } return rc; } BIO* CCmsMessageUtils::inputToBio( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "inputToBio"); BIO* rc = NULL; if (! inputBuffer.IsNull()) { rc = inputBufferToBio(inputBuffer); } else if (! inputPath.empty()) { rc = inputFileToBio(inputPath); } else { CAF_CM_EXCEPTION_VA0(E_FAIL, "Must provide buffer or filename"); } return rc; } BIO* CCmsMessageUtils::outputPathToBio( const std::string& outputPath) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "outputPathToBio"); CAF_CM_VALIDATE_STRING(outputPath); BIO* rc = BIO_new_file(outputPath.c_str(), "w"); if (! rc) { logSslErrors(); CAF_CM_EXCEPTION_VA1(E_FAIL, "BIO_new_file Failed - %s", outputPath.c_str()); } return rc; } BIO* CCmsMessageUtils::outputToBio( const SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "outputToBio"); BIO* rc = NULL; if (! outputBuffer.IsNull()) { rc = createWriteBio(); } else if (! outputPath.empty()) { rc = outputPathToBio(outputPath); } else { CAF_CM_EXCEPTION_VA0(E_FAIL, "Must provide buffer or filename"); } return rc; } void CCmsMessageUtils::bioToOutput( BIO* bio, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "bioToOutput"); CAF_CM_VALIDATE_PTR(bio); if (! outputBuffer.IsNull()) { bioToOutputBuffer(bio, outputBuffer); } else if (! outputPath.empty()) { bioToOutputFile(bio, outputPath); } else { CAF_CM_EXCEPTION_VA0(E_FAIL, "Must provide buffer or filename"); } } void CCmsMessageUtils::bioToOutputBuffer( BIO* bio, SmartPtrCDynamicByteArray& outputBuffer) { CAF_CM_STATIC_FUNC_VALIDATE("CCmsMessageUtils", "bioToOutputBuffer"); CAF_CM_VALIDATE_PTR(bio); BUF_MEM* bptr = NULL; BIO_get_mem_ptr(bio, &bptr); // Casting to void to ignore return value and eliminate compiler warning (void) BIO_set_close(bio, BIO_NOCLOSE); /* So BIO_free() leaves BUF_MEM alone */ outputBuffer.CreateInstance(); outputBuffer->allocateBytes(bptr->length); outputBuffer->memCpy(bptr->data, bptr->length); } void CCmsMessageUtils::bioToOutputFile( BIO* bio, const std::string& outputPath) { CAF_CM_STATIC_FUNC_VALIDATE("CCmsMessageUtils", "bioToOutputFile"); CAF_CM_VALIDATE_PTR(bio); CAF_CM_VALIDATE_STRING(outputPath); } std::deque CCmsMessageUtils::biosToX509( std::deque bioCollection) { CAF_CM_STATIC_FUNC_VALIDATE("CCmsMessageUtils", "biosToX509"); CAF_CM_VALIDATE_STL(bioCollection); std::deque rc; for (TConstIterator > elemIter(bioCollection); elemIter; elemIter++) { BIO* elem = *elemIter; rc.push_back(bioToX509(elem)); } return rc; } X509* CCmsMessageUtils::bioToX509( BIO* bio) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "bioToX509"); CAF_CM_VALIDATE_PTR(bio); X509* rc = PEM_read_bio_X509(bio, NULL, 0, NULL); if (! rc) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "PEM_read_bio_X509 Failed"); } return rc; } EVP_PKEY* CCmsMessageUtils::bioToPrivateKey( BIO* bio) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "bioToPrivateKey"); CAF_CM_VALIDATE_PTR(bio); EVP_PKEY* rc = PEM_read_bio_PrivateKey(bio, NULL, 0, NULL); if (! rc) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "PEM_read_bio_PrivateKey Failed"); } return rc; } const SSL_METHOD* CCmsMessageUtils::protocolToSslMethod( const std::string& protocol) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "protocolToSslMethod"); CAF_CM_VALIDATE_STRING(protocol); const SSL_METHOD* rc; if (protocol.compare("TLSv1_2") == 0) { rc = TLSv1_2_method(); } else { CAF_CM_EXCEPTION_VA1(E_FAIL, "Unknown protocol - %s", protocol.c_str()); } return rc; } BIO* CCmsMessageUtils::createWriteBio() { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "createWriteBio"); BIO* rc = BIO_new(BIO_s_mem()); if (! rc) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "BIO_new Failed"); } return rc; } STACK_OF(X509)* CCmsMessageUtils::createX509Stack( X509* x509, X509* x5091, X509* x5092) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "createX509Stack"); CAF_CM_VALIDATE_PTR(x509); /* Create recipient STACK and add recipient cert to it */ STACK_OF(X509)* rc = sk_X509_new_null(); if (! rc) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "sk_X509_new_nuss Failed"); } if (!sk_X509_push(rc, x509)) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "sk_X509_push Failed"); } if (x5091) { if (!sk_X509_push(rc, x5091)) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "sk_X509_push Failed"); } } if (x5092) { if (!sk_X509_push(rc, x5092)) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "sk_X509_push Failed"); } } return rc; } X509_STORE* CCmsMessageUtils::createX509Store( std::deque x509Collection) { CAF_CM_STATIC_FUNC("CCmsMessageUtils", "createX509Store"); CAF_CM_VALIDATE_STL(x509Collection); X509_STORE* rc = X509_STORE_new(); if (! rc) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "X509_STORE_new Failed"); } for (TConstIterator > elemIter(x509Collection); elemIter; elemIter++) { X509* elem = *elemIter; if (!X509_STORE_add_cert(rc, elem)) { logSslErrors(); CAF_CM_EXCEPTION_VA0(E_FAIL, "X509_STORE_add_cert Failed"); } } return rc; } void CCmsMessageUtils::free( CMS_ContentInfo* contentInfo) { if (contentInfo) { CMS_ContentInfo_free(contentInfo); } } void CCmsMessageUtils::free( std::deque x509Collection) { for (TConstIterator > elemIter(x509Collection); elemIter; elemIter++) { X509* elem = *elemIter; free(elem); } } void CCmsMessageUtils::free( X509* x509) { if (x509) { X509_free(x509); } } void CCmsMessageUtils::free( STACK_OF(X509)* x509Stack) { if (x509Stack) { sk_X509_pop_free(x509Stack, X509_free); } } void CCmsMessageUtils::free( std::deque bioCollection) { for (TConstIterator > elemIter(bioCollection); elemIter; elemIter++) { BIO* elem = *elemIter; free(elem); } } void CCmsMessageUtils::free( BIO* bio) { if (bio) { BIO_vfree(bio); } } void CCmsMessageUtils::free( X509_STORE* x509Store) { if (x509Store) { X509_STORE_free(x509Store); } } void CCmsMessageUtils::free( EVP_PKEY* privateKey) { if (privateKey) { EVP_PKEY_free(privateKey); } } void CCmsMessageUtils::logSslErrors() { CAF_CM_STATIC_FUNC_LOG_ONLY("CCmsMessageUtils", "logSslErrors"); int32 sslErrorCode = ERR_get_error(); while (sslErrorCode != 0) { const char* sslErrorStr = ERR_error_string(sslErrorCode, NULL); CAF_CM_LOG_WARN_VA2("SSL Error - code: %d, str: %s", sslErrorCode, sslErrorStr); sslErrorCode = ERR_get_error(); } } void CCmsMessageUtils::logCiphers( const std::string& prefix, const SSL* ssl) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CCmsMessageUtils", "logCiphers"); CAF_CM_VALIDATE_STRING(prefix); CAF_CM_VALIDATE_PTR(ssl); int32 index = 0; const char* cipher = SSL_get_cipher_list(ssl, index); while (cipher != NULL) { CAF_CM_LOG_DEBUG_VA3( "%s - index: %d, str: %s", prefix.c_str(), index, cipher); cipher = SSL_get_cipher_list(ssl, index++); } } CCmsMessageUtils.h000066400000000000000000000045551321503522500375760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCmsMessageUtil_h_ #define CCmsMessageUtil_h_ #include #include "Memory/DynamicArray/DynamicArrayInc.h" #include #include #include #include #include #include #include namespace Caf { class CCmsMessageUtils { public: // Convert static BIO* inputBufferToBio( const SmartPtrCDynamicByteArray& inputBuffer); static std::deque inputFilesToBio( const Cdeqstr& inputFileCollection); static BIO* inputFileToBio( const std::string& inputFile); static BIO* inputToBio( const SmartPtrCDynamicByteArray& inputBuffer, const std::string& inputPath); static BIO* outputPathToBio( const std::string& outputPath); static BIO* outputToBio( const SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath); static void bioToOutput( BIO* bio, SmartPtrCDynamicByteArray& outputBuffer, const std::string& outputPath); static void bioToOutputBuffer( BIO* bio, SmartPtrCDynamicByteArray& outputBuffer); static void bioToOutputFile( BIO* bio, const std::string& outputPath); static std::deque biosToX509( std::deque bioCollection); static X509* bioToX509( BIO* bio); static EVP_PKEY* bioToPrivateKey( BIO* bio); static const SSL_METHOD* protocolToSslMethod( const std::string& protocol); public: // Create static BIO* createWriteBio(); static STACK_OF(X509)* createX509Stack( X509* x509, X509* x5091 = NULL, X509* x5092 = NULL); static X509_STORE* createX509Store( std::deque x509Collection); public: // Free static void free( CMS_ContentInfo* contentInfo); static void free( X509* x509); static void free( std::deque x509Collection); static void free( STACK_OF(X509)* x509Stack); static void free( BIO* bio); static void free( std::deque bioCollection); static void free( X509_STORE* x509Store); static void free( EVP_PKEY* privateKey); public: // Log static void logSslErrors(); static void logCiphers( const std::string& prefix, const SSL* ssl); private: CAF_CM_DECLARE_NOCREATE(CCmsMessageUtils); }; } #endif // #ifndef CCmsMessageUtil_h_ CEventTopicCalculatorInstance.cpp000066400000000000000000000051411321503522500426300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Caf/CCafMessagePayload.h" #include "Doc/ResponseDoc/CEventKeyDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "IVariant.h" #include "Integration/IIntMessage.h" #include "Common/CCafRegex.h" #include "Exception/CCafException.h" #include "CEventTopicCalculatorInstance.h" using namespace Caf; CEventTopicCalculatorInstance::CEventTopicCalculatorInstance() : _isInitialized(false), CAF_CM_INIT("CEventTopicCalculatorInstance") { CAF_CM_INIT_THREADSAFE; } CEventTopicCalculatorInstance::~CEventTopicCalculatorInstance() { } void CEventTopicCalculatorInstance::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } void CEventTopicCalculatorInstance::terminateBean() { } SmartPtrIVariant CEventTopicCalculatorInstance::invokeExpression( const std::string& methodName, const Cdeqstr& methodParams, const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("invokeEspression"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(!methodParams.size()); SmartPtrIVariant result; if (methodName == "getTopic") { result = getTopic(message); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchMethodException, 0, "Method '%s' is not supported by this invoker", methodName.c_str()); } return result; } SmartPtrIVariant CEventTopicCalculatorInstance::getTopic( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("getTopic"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCCafMessagePayload cafMessagePayload = CCafMessagePayload::create(message->getPayload()); const SmartPtrCManifestDoc manifest = cafMessagePayload->getManifest(); const std::deque eventKeyCollection = cafMessagePayload->getEventKeyCollection(); CCafRegex replaceDots; replaceDots.initialize("\\."); std::stringstream topicBld; topicBld << "caf.event." << replaceDots.replaceLiteral(manifest->getClassName(), "_") << '.' << replaceDots.replaceLiteral(manifest->getClassNamespace(), "_") << '.' << replaceDots.replaceLiteral(manifest->getClassVersion(), "_"); for (TConstIterator > key(eventKeyCollection); key; key++) { const SmartPtrCEventKeyDoc eventKey = *key; topicBld << '.' << replaceDots.replaceLiteral(eventKey->getValue(), "_"); } return CVariant::createString(topicBld.str()); } CEventTopicCalculatorInstance.h000066400000000000000000000025671321503522500423060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CEventTopicCalculatorInstance_h #define CEventTopicCalculatorInstance_h #include "IBean.h" #include "IVariant.h" #include "Integration/IIntMessage.h" #include "Integration/IExpressionInvoker.h" namespace Caf { class CEventTopicCalculatorInstance : public TCafSubSystemObjectRoot, public IBean, public IExpressionInvoker { public: CEventTopicCalculatorInstance(); virtual ~CEventTopicCalculatorInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationEventTopicCalculator) CAF_BEGIN_INTERFACE_MAP(CEventTopicCalculatorInstance) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IExpressionInvoker) CAF_END_INTERFACE_MAP() public: // IBean void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // IExpressionInvoker SmartPtrIVariant invokeExpression( const std::string& methodName, const Cdeqstr& methodParams, const SmartPtrIIntMessage& message); private: SmartPtrIVariant getTopic( const SmartPtrIIntMessage& message); private: bool _isInitialized; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CEventTopicCalculatorInstance); }; } #endif /* CEventTopicCalculatorInstance_h */ CIncomingMessageHandler.cpp000066400000000000000000000032771321503522500414270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CIncomingMessageHandler.h" using namespace Caf; CIncomingMessageHandler::CIncomingMessageHandler() : _isInitialized(false), CAF_CM_INIT("CIncomingMessageHandler") { } CIncomingMessageHandler::~CIncomingMessageHandler() { } void CIncomingMessageHandler::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } void CIncomingMessageHandler::terminateBean() { } void CIncomingMessageHandler::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } bool CIncomingMessageHandler::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); return false; } SmartPtrIIntegrationObject CIncomingMessageHandler::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); SmartPtrIIntegrationObject rc; rc.CreateInstance(_sObjIdCommIntegrationIncomingMessageHandlerInstance); rc->initialize(_ctorArgs, _properties, configSection); return rc; } CIncomingMessageHandler.h000066400000000000000000000026551321503522500410730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CIncomingMessageHandler_h_ #define CIncomingMessageHandler_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CIncomingMessageHandler : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CIncomingMessageHandler(); virtual ~CIncomingMessageHandler(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationIncomingMessageHandler) CAF_BEGIN_INTERFACE_MAP(CIncomingMessageHandler) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CIncomingMessageHandler); }; } #endif // #ifndef CIncomingMessageHandler_h_ CIncomingMessageHandlerInstance.cpp000066400000000000000000000233401321503522500431050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Caf/CCafMessageHeadersWriter.h" #include "CMessagePartDescriptor.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CIncomingMessageHandlerInstance.h" #include "CMessagePartsHeader.h" #include "Integration/Core/MessageHeaders.h" #include "Integration/Caf/CCafMessageCreator.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Caf/CCafMessagePayload.h" #include "Integration/Core/CMessageHeaderUtils.h" using namespace Caf; CIncomingMessageHandlerInstance::CIncomingMessageHandlerInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CIncomingMessageHandlerInstance") { } CIncomingMessageHandlerInstance::~CIncomingMessageHandlerInstance() { } void CIncomingMessageHandlerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CIncomingMessageHandlerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CIncomingMessageHandlerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); } SmartPtrIIntMessage CIncomingMessageHandlerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); SmartPtrIIntMessage newMessage = handleMessage(message); return newMessage; } /** * Processes an incoming message *

* Pre-processes an incoming message and:
* (1) determines if it is a duplicate message
* (2) determines if it is a stand-alone message or part of a larger message * (chunking)
* (3) enhances the message headers with internal information
* (4) caches the message's replyTo information
*

* This method will return null if the message cannot be processed as * is. This is the case if the message is a chunk of a larger message. When * all of the chunks are assembled then the assembled message will be * returned. *

* This component interacts with the MessageDeliveryStateRecorder in the * case of message receipts. If a message receipt needs to be generated, a * record will be added to the MessageDeliveryStateRecorder which will * produce and send the receipt. *

* If the message is a duplicate it will be marked as such and returned so * that logic in the context file can do something with it if desired. * * @param message incoming message * @return the incoming message if it can be processed on its own or null if * not */ SmartPtrIIntMessage CIncomingMessageHandlerInstance::handleMessage( const SmartPtrIIntMessage& message) { CAF_CM_STATIC_FUNC_VALIDATE("CIncomingMessageHandlerInstance", "handleMessage"); CAF_CM_VALIDATE_INTERFACE(message); const std::string workingDir = AppConfigUtils::getRequiredString("communication_amqp", _sConfigWorkingDir); CMessageHeaderUtils::log(message->getHeaders()); SmartPtrIIntMessage rc; if (CMessageHeaderUtils::getBoolOpt( message->getHeaders(), MessageHeaders::_sMULTIPART)) { rc = getAssembledMessage(message, workingDir); } else { rc = message; } return rc; } SmartPtrIIntMessage CIncomingMessageHandlerInstance::getAssembledMessage( const SmartPtrIIntMessage& message, const std::string& workingDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CIncomingMessageHandlerInstance", "getAssembledMessage"); CAF_CM_VALIDATE_INTERFACE(message); CAF_CM_VALIDATE_STRING(workingDir); const std::string correlationId = processMessage(message, workingDir); const std::string messageDir = FileSystemUtils::buildPath( workingDir, correlationId); const std::string manifestFile = FileSystemUtils::buildPath(messageDir, "0.part"); CAF_CM_LOG_DEBUG_VA1("Reconstructing manifest - %s", manifestFile.c_str()); const SmartPtrCDynamicByteArray payload = CCafMessagePayload::createBufferFromFile(manifestFile); const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(payload); const std::deque attachmentDocs = payloadEnvelope->getAttachmentCollection()->getAttachment(); // refactor the local attachments to point to the transferred // attachments std::deque refactoredAttachments; if (!attachmentDocs.empty()) { if (!attachmentDocs.empty()) { CAF_CM_LOG_DEBUG_VA2( "Refactoring attachments - correlationId: %s, numAttachments: %d", correlationId.c_str(), attachmentDocs.size()); for (TConstIterator > attachmentIter(attachmentDocs); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; const std::string attachmentName = attachment->getName(); const std::string attachmentUri = attachment->getUri(); UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(attachmentUri, uriRecord); CAF_CM_LOG_DEBUG_VA3("Parsed URI - Uri: %s, protocol: %s, address: %s", attachmentUri.c_str(), uriRecord.protocol.c_str(), uriRecord.address.c_str()); if(uriRecord.protocol.compare("attachment") == 0) { const std::string uriPath = uriRecord.address; const std::string::size_type slashPos = uriPath.find('/'); const std::string attNumStr = uriPath.substr(slashPos + 1); const std::string attFile = FileSystemUtils::buildPath( messageDir, attNumStr + ".part"); const std::string attUri = UriUtils::appendParameters( attFile, uriRecord.parameters); SmartPtrCAttachmentDoc refactoredAttachment; refactoredAttachment.CreateInstance(); refactoredAttachment->initialize(attachment->getName(), attachment->getType(), "file:///" + attUri, false, attachment->getCmsPolicy()); refactoredAttachments.push_back(refactoredAttachment); CAF_CM_LOG_DEBUG_VA3( "Adding refactored attachment - name: %s, type: %s, uri: %s", refactoredAttachment->getName().c_str(), refactoredAttachment->getType().c_str(), refactoredAttachment->getUri().c_str()); } else { refactoredAttachments.push_back(attachment); } } } } SmartPtrIIntMessage newMessage; if (refactoredAttachments.empty()) { newMessage = CCafMessageCreator::create( payload, refactoredAttachments, message->getHeaders()); } else { const SmartPtrCCafMessageHeadersWriter cafMessageHeadersWriter = CCafMessageHeadersWriter::create(); cafMessageHeadersWriter->insertString( MessageHeaders::_sMULTIPART_WORKING_DIR, messageDir); newMessage = CCafMessageCreator::createPayloadEnvelope( payloadEnvelope, refactoredAttachments, cafMessageHeadersWriter->getHeaders(), message->getHeaders()); } return newMessage; } std::string CIncomingMessageHandlerInstance::processMessage( const SmartPtrIIntMessage& message, const std::string& workingDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CIncomingMessageHandlerInstance", "processMessage"); CAF_CM_VALIDATE_INTERFACE(message); CAF_CM_VALIDATE_STRING(workingDir); SmartPtrCDynamicByteArray payload = message->getPayload(); payload->resetCurrentPos(); CAF_CM_LOG_DEBUG_VA1("Processing payload - byteCount: %d", payload->getByteCount()); const std::string payloadPath = FileSystemUtils::buildPath(FileSystemUtils::getTmpDir(), "payload.out"); FileSystemUtils::saveByteFile(payloadPath, payload->getPtr(), payload->getByteCount()); SmartPtrCMessagePartsHeader header = CMessagePartsHeader::fromByteBuffer(payload); CAF_CM_LOG_DEBUG_VA3( "Processing message parts - version: %d, correlationId: %s, numberOfParts: %d", CMessagePartsHeader::CAF_MSG_VERSION, header->getCorrelationIdStr().c_str(), header->getNumberOfParts()); const std::string messageDir = FileSystemUtils::buildPath( workingDir, header->getCorrelationIdStr()); if (!FileSystemUtils::doesFileExist(messageDir)) { CAF_CM_LOG_DEBUG_VA1("Creating directory - %s", messageDir.c_str()); FileSystemUtils::createDirectory(messageDir); } while (payload->getByteCountFromCurrentPos() > 0) { SmartPtrCMessagePartDescriptor partDescriptor = CMessagePartDescriptor::fromByteBuffer(payload); CAF_CM_LOG_DEBUG_VA5( "Processing message parts descriptor - version: %d, attachmentNumber: %d, partNumber: %d, dataSize: %d, dataOffset: %d", CMessagePartDescriptor::CAF_MSG_VERSION, partDescriptor->getAttachmentNumber(), partDescriptor->getPartNumber(), partDescriptor->getDataSize(), partDescriptor->getDataOffset()); const std::string attachmentFile = FileSystemUtils::buildPath( messageDir, partDescriptor->getAttachmentNumberStr() + ".part"); SmartPtrCDynamicByteArray partBuffer; partBuffer.CreateInstance(); partBuffer->allocateBytes(partDescriptor->getDataSize()); partBuffer->memCpy(payload->getPtrAtCurrentPos(), partDescriptor->getDataSize()); partBuffer->incrementCurrentPos(static_cast(partDescriptor->getDataOffset())); payload->incrementCurrentPos(partDescriptor->getDataSize()); FileSystemUtils::saveByteFile(attachmentFile, partBuffer->getPtrAtCurrentPos(), partBuffer->getByteCountFromCurrentPos()); } return header->getCorrelationIdStr(); } CIncomingMessageHandlerInstance.h000066400000000000000000000041541321503522500425540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CIncomingMessageHandlerInstance_h #define CIncomingMessageHandlerInstance_h #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CIncomingMessageHandlerInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CIncomingMessageHandlerInstance(); virtual ~CIncomingMessageHandlerInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationIncomingMessageHandlerInstance) CAF_BEGIN_INTERFACE_MAP(CIncomingMessageHandlerInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: static SmartPtrIIntMessage handleMessage( const SmartPtrIIntMessage& message); static SmartPtrIIntMessage getAssembledMessage( const SmartPtrIIntMessage& message, const std::string& workingDir); static std::string processMessage( const SmartPtrIIntMessage& message, const std::string& workingDir); private: bool _isInitialized; std::string _id; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CIncomingMessageHandlerInstance); }; CAF_DECLARE_SMART_QI_POINTER(CIncomingMessageHandlerInstance); } #endif /* CIncomingMessageHandlerInstance_h */ CMessageDeliveryRecord.cpp000066400000000000000000000045251321503522500413050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 26, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CMessagePartDescriptorSourceRecord.h" #include "Integration/IIntMessage.h" #include "CMessageDeliveryRecord.h" using namespace Caf; CMessageDeliveryRecord::CMessageDeliveryRecord() : _isInitialized(false), _correlationId(CAFCOMMON_GUID_NULL), _numberOfParts(0), _startingPartNumber(0), CAF_CM_INIT("CMessageDeliveryRecord") { } CMessageDeliveryRecord::~CMessageDeliveryRecord() { } void CMessageDeliveryRecord::initialize( const UUID& correlationId, const uint32 numberOfParts, const uint32 startingPartNumber, const std::deque& messagePartSources, const IIntMessage::SmartPtrCHeaders& messageHeaders) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _correlationId = correlationId; _numberOfParts = numberOfParts; _startingPartNumber = startingPartNumber; _messagePartSources = messagePartSources; _messageHeaders = messageHeaders; _isInitialized = true; } UUID CMessageDeliveryRecord::getCorrelationId() const { CAF_CM_FUNCNAME_VALIDATE("getCorrelationId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _correlationId; } std::string CMessageDeliveryRecord::getCorrelationIdStr() const { CAF_CM_FUNCNAME_VALIDATE("getCorrelationId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return BasePlatform::UuidToString(_correlationId); } uint32 CMessageDeliveryRecord::getNumberOfParts() const { CAF_CM_FUNCNAME_VALIDATE("getNumberOfParts"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _numberOfParts; } uint32 CMessageDeliveryRecord::getStartingPartNumber() const { CAF_CM_FUNCNAME_VALIDATE("getStartingPartNumber"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _startingPartNumber; } std::deque CMessageDeliveryRecord::getMessagePartSources() const { CAF_CM_FUNCNAME_VALIDATE("getMessagePartSources"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _messagePartSources; } IIntMessage::SmartPtrCHeaders CMessageDeliveryRecord::getMessageHeaders() const { CAF_CM_FUNCNAME_VALIDATE("getMessageHeaders"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _messageHeaders; } CMessagePartDescriptor.cpp000066400000000000000000000113511321503522500413230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CMessagePartDescriptor.h" #include "Exception/CCafException.h" using namespace Caf; /** * Converts the BLOCK_SIZE data in a ByteBuffer into a MessagePartsDescriptor *

* The incoming ByteBuffer position will be modified. * @param buffer ByteBuffer to convert * @return a MessagePartsDescriptor */ SmartPtrCMessagePartDescriptor CMessagePartDescriptor::fromByteBuffer( SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC("CMessagePartDescriptor", "fromByteBuffer"); CAF_CM_VALIDATE_SMARTPTR(buffer); if (buffer->getByteCountFromCurrentPos() < BLOCK_SIZE) { CAF_CM_EXCEPTION_VA2(E_INVALIDARG, "Input data block is too small - rem: %d, tot: %d", buffer->getByteCountFromCurrentPos(), buffer->getByteCount()); } SmartPtrCDynamicByteArray data; data.CreateInstance(); data->allocateBytes(BLOCK_SIZE); data->memCpy(buffer->getPtrAtCurrentPos(), BLOCK_SIZE); buffer->incrementCurrentPos(BLOCK_SIZE); return fromArray(data); } /** * Converts a byte array into a MessagePartsDescriptor * @param blockData byte array to convert * @return a MessagePartsDescriptor */ SmartPtrCMessagePartDescriptor CMessagePartDescriptor::fromArray( SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC("CMessagePartDescriptor", "fromArray"); CAF_CM_VALIDATE_SMARTPTR(buffer); if (buffer->getByteCount() < BLOCK_SIZE) { CAF_CM_EXCEPTION_VA1(E_INVALIDARG, "Input data block is too small - %d", buffer->getByteCount()); } if (CMessagePartsParser::getByte(buffer) != CAF_MSG_VERSION) { CAF_CM_EXCEPTION_VA0(E_INVALIDARG, "Input data block version is incorrect"); } const byte resvd = CMessagePartsParser::getByte(buffer); if (resvd != RESERVED) { CAF_CM_EXCEPTION_VA0(E_INVALIDARG, "Input data block reserved bits are incorrect"); } const uint16 attachmentNumber = CMessagePartsParser::getUint16(buffer); const uint32 partNumber = CMessagePartsParser::getUint32(buffer); const uint32 dataSize = CMessagePartsParser::getUint32(buffer); const uint32 dataOffset = CMessagePartsParser::getUint32(buffer); buffer->verify(); SmartPtrCMessagePartDescriptor messagePartsDescriptor; messagePartsDescriptor.CreateInstance(); messagePartsDescriptor->initialize( attachmentNumber, partNumber, dataSize, dataOffset); return messagePartsDescriptor; } SmartPtrCDynamicByteArray CMessagePartDescriptor::toArray( const uint16 attachmentNumber, const uint32 partNumber, const uint32 dataSize, const uint32 dataOffset) { SmartPtrCDynamicByteArray buffer; buffer.CreateInstance(); buffer->allocateBytes(BLOCK_SIZE); CMessagePartsBuilder::put(CAF_MSG_VERSION, buffer); CMessagePartsBuilder::put(RESERVED, buffer); CMessagePartsBuilder::put(attachmentNumber, buffer); CMessagePartsBuilder::put(partNumber, buffer); CMessagePartsBuilder::put(dataSize, buffer); CMessagePartsBuilder::put(dataOffset, buffer); buffer->verify(); return buffer; } CMessagePartDescriptor::CMessagePartDescriptor() : _isInitialized(false), _attachmentNumber(0), _partNumber(0), _dataSize(0), _dataOffset(0), CAF_CM_INIT("CMessagePartDescriptor") { } CMessagePartDescriptor::~CMessagePartDescriptor() { } void CMessagePartDescriptor::initialize( const uint16 attachmentNumber, const uint32 partNumber, const uint32 dataSize, const uint32 dataOffset) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); this->_attachmentNumber = attachmentNumber; this->_partNumber = partNumber; this->_dataSize = dataSize; this->_dataOffset = dataOffset; _isInitialized = true; } /** * @return the attachmentNumber */ uint16 CMessagePartDescriptor::getAttachmentNumber() const { CAF_CM_FUNCNAME_VALIDATE("getAttachmentNumber"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _attachmentNumber; } std::string CMessagePartDescriptor::getAttachmentNumberStr() const { CAF_CM_FUNCNAME_VALIDATE("getAttachmentNumber"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return CStringConv::toString(_attachmentNumber); } /** * @return the partNumber */ uint32 CMessagePartDescriptor::getPartNumber() const { CAF_CM_FUNCNAME_VALIDATE("getPartNumber"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _partNumber; } /** * @return the dataSize */ uint32 CMessagePartDescriptor::getDataSize() const { CAF_CM_FUNCNAME_VALIDATE("getDataSize"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _dataSize; } /** * @return the dataOffset */ uint32 CMessagePartDescriptor::getDataOffset() const { CAF_CM_FUNCNAME_VALIDATE("getDataOffset"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _dataOffset; } CMessagePartDescriptorCalculator.cpp000066400000000000000000000207151321503522500433410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CMessagePartDescriptorSourceRecord.h" #include "CMessagePartRecord.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Exception/CCafException.h" #include "CMessagePartDescriptorCalculator.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Caf/CCafMessagePayload.h" #include "Integration/Caf/CCafMessageCreator.h" using namespace Caf; uint32 CMessagePartDescriptorCalculator::getMaxPartSize() { return AppConfigUtils::getRequiredUint32("communication_amqp", "max_part_size"); } std::deque CMessagePartDescriptorCalculator::calculateSourcePartRecords( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CMessagePartDescriptorCalculator", "calculateSourcePartRecords"); CAF_CM_VALIDATE_SMARTPTR(payload); const std::string workingDirectory = AppConfigUtils::getRequiredString("communication_amqp", _sConfigWorkingDir); return refactorMessageIntoPartRecords(workingDirectory, payload); } /* * Parse the local file attachments and message body into records * reflecting the full size of each part. */ std::deque CMessagePartDescriptorCalculator::refactorMessageIntoPartRecords( const std::string& workingDirectory, const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_LOG("CMessagePartDescriptorCalculator", "refactorMessageIntoPartRecords"); CAF_CM_VALIDATE_STRING(workingDirectory); CAF_CM_VALIDATE_SMARTPTR(payload); // attachmentCollectionDoc is optional const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(payload); const std::deque sourceAttachments = payloadEnvelope->getAttachmentCollection()->getAttachment(); // Scan the attachment collection and create part records for // any local file attachments that need to be transmitted. std::deque messageParts; std::deque refactoredAttachments; if (!sourceAttachments.empty()) { int16 attachmentNumber = 1; for (TConstIterator > sourceAttachmentIter(sourceAttachments); sourceAttachmentIter; sourceAttachmentIter++) { const SmartPtrCAttachmentDoc attachment = *sourceAttachmentIter; UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(attachment->getUri(), uriRecord); if ((uriRecord.protocol.compare("file") == 0) && !attachment->getIsReference()) { CAF_CM_LOG_DEBUG_VA1("Processing local file attachment - uri: %s", attachment->getUri().c_str()); UriUtils::SFileUriRecord fileUriRecord; UriUtils::parseFileAddress(uriRecord.address, fileUriRecord); const std::string attachmentPath = fileUriRecord.path; if (!FileSystemUtils::doesFileExist(attachmentPath)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "File not found - %s", attachmentPath.c_str()); } const int64 fileSize = FileSystemUtils::getFileSize(attachmentPath); CAF_CM_LOG_DEBUG_VA2("Processing local file attachment - file: %s, size: %d", attachmentPath.c_str(), fileSize); SmartPtrCMessagePartRecord messagePart; messagePart.CreateInstance(); messagePart->initialize(attachmentNumber, attachmentPath, 0, fileSize); messageParts.push_back(messagePart); const std::string newAttachmentUri = UriUtils::appendParameters( "attachment:/" + CStringConv::toString(attachmentNumber), uriRecord.parameters); CAF_CM_LOG_DEBUG_VA1("New attachment URI - %s", newAttachmentUri.c_str()); SmartPtrCAttachmentDoc attachmentNew; attachmentNew.CreateInstance(); attachmentNew->initialize(attachment->getName(), attachment->getType(), newAttachmentUri, attachment->getIsReference(), attachment->getCmsPolicy()); refactoredAttachments.push_back(attachmentNew); ++attachmentNumber; } else { refactoredAttachments.push_back(attachment); } } } // If there are local file attachments to send then rebuild the message // with the refactored attribute collection. SmartPtrCDynamicByteArray payloadNew = payload; if (!messageParts.empty()) { payloadNew = CCafMessageCreator::createPayloadEnvelope( payloadEnvelope, refactoredAttachments)->getPayload(); } // Does the payload itself need to be split? // If it is larger than max_part_size OR if there are transmitted attachments then 'yes' const std::string newPayload = CStringUtils::trim(CCafMessagePayload::saveToStr(payloadNew)); if ((newPayload.length() > getMaxPartSize()) || ! messageParts.empty()) { // Save the new payload to a file const std::string requestIdStr = BasePlatform::UuidToString(payloadEnvelope->getRequestId()); const std::string payloadFileName = requestIdStr + "-payload.xml"; const std::string payloadFile = FileSystemUtils::buildPath( workingDirectory, payloadFileName); FileSystemUtils::saveTextFile(payloadFile, newPayload); SmartPtrCMessagePartRecord messagePart; messagePart.CreateInstance(); messagePart->initialize(0, payloadFile, 0, newPayload.length()); messageParts.push_back(messagePart); } // If there are MessagePartRecords then split them apart into // MessagePartSourceRecords and return them else there is no // splitting required. if (!messageParts.empty()) { return splitMessagePartRecords(messageParts); } else { return std::deque(); } } /* * Split the message part records such that all parts will contain * at most max_part_size bytes. */ std::deque CMessagePartDescriptorCalculator::splitMessagePartRecords( std::deque& messageParts) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CMessagePartDescriptorCalculator", "splitMessagePartRecords"); CAF_CM_VALIDATE_STL(messageParts); if (CAF_CM_IS_LOG_DEBUG_ENABLED) { CAF_CM_LOG_DEBUG_VA0("Message part records"); for (TConstIterator > messagePartIter(messageParts); messagePartIter; messagePartIter++) { const SmartPtrCMessagePartRecord messagePart = *messagePartIter; CAF_CM_LOG_DEBUG_VA4( "Message part - attachmentNumber: %d, filePath: %s, dataLength: %d, dataOffset: %d", messagePart->getAttachmentNumber(), messagePart->getFilePath().c_str(), messagePart->getDataLength(), messagePart->getDataOffset()); } } std::deque packedSourceRecords; uint64 currentPartSize = 0; std::deque::iterator messagePartIter = messageParts.begin(); while (messagePartIter != messageParts.end()) { const SmartPtrCMessagePartRecord messagePart = *messagePartIter; const uint64 availablePartBytes = messagePart->getDataLength() > LONG_MAX ? LONG_MAX : messagePart->getDataLength(); const uint64 fillBytes = MIN(getMaxPartSize() - currentPartSize, availablePartBytes); SmartPtrCMessagePartDescriptorSourceRecord sourceRecord; sourceRecord.CreateInstance(); sourceRecord->initialize(messagePart->getAttachmentNumber(), messagePart->getFilePath(), static_cast(messagePart->getDataOffset()), static_cast(fillBytes)); packedSourceRecords.push_back(sourceRecord); currentPartSize += fillBytes; messagePart->setDataOffset(messagePart->getDataOffset() + fillBytes); messagePart->setDataLength(messagePart->getDataLength() - fillBytes); if (messagePart->getDataLength() == 0) { messagePartIter = messageParts.erase(messagePartIter); } else { ++messagePartIter; } if (currentPartSize == getMaxPartSize()) { currentPartSize = 0; } } if (CAF_CM_IS_LOG_DEBUG_ENABLED) { CAF_CM_LOG_DEBUG_VA0("Split message part descriptor source records"); for (TConstIterator > packedSourceRecordIter(packedSourceRecords); packedSourceRecordIter; packedSourceRecordIter++) { const SmartPtrCMessagePartDescriptorSourceRecord packedSourceRecord = *packedSourceRecordIter; CAF_CM_LOG_DEBUG_VA4( "Packed source - attachmentNumber: %d, filePath: %s, dataLength: %d, dataOffset: %d", packedSourceRecord->getAttachmentNumber(), packedSourceRecord->getFilePath().c_str(), packedSourceRecord->getDataLength(), packedSourceRecord->getDataOffset()); } } return packedSourceRecords; } CMessagePartDescriptorCalculator.h000066400000000000000000000020551321503522500430030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagePartDescriptorCalculator_h #define CMessagePartDescriptorCalculator_h #include "CMessagePartDescriptorSourceRecord.h" #include "CMessagePartRecord.h" #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { class CMessagePartDescriptorCalculator { public: static uint32 getMaxPartSize(); static std::deque calculateSourcePartRecords( const SmartPtrCDynamicByteArray& payload); private: static std::deque refactorMessageIntoPartRecords( const std::string& workingDirectory, const SmartPtrCDynamicByteArray& payload); static std::deque splitMessagePartRecords( std::deque& messageParts); private: CAF_CM_DECLARE_NOCREATE(CMessagePartDescriptorCalculator); }; } #endif /* CMessagePartDescriptorCalculator_h */ CMessagePartDescriptorSourceRecord.cpp000066400000000000000000000032311321503522500436410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 26, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CMessagePartDescriptorSourceRecord.h" using namespace Caf; CMessagePartDescriptorSourceRecord::CMessagePartDescriptorSourceRecord() : _isInitialized(false), _attachmentNumber(0), _dataOffset(0), _dataLength(0), CAF_CM_INIT("CMessagePartDescriptorSourceRecord") { } CMessagePartDescriptorSourceRecord::~CMessagePartDescriptorSourceRecord() { } void CMessagePartDescriptorSourceRecord::initialize( const uint16 attachmentNumber, const std::string filePath, const uint32 dataOffset, const uint32 dataLength) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _attachmentNumber = attachmentNumber; _filePath = filePath; _dataOffset = dataOffset; _dataLength = dataLength; _isInitialized = true; } uint16 CMessagePartDescriptorSourceRecord::getAttachmentNumber() const { CAF_CM_FUNCNAME_VALIDATE("getAttachmentNumber"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _attachmentNumber; } std::string CMessagePartDescriptorSourceRecord::getFilePath() const { CAF_CM_FUNCNAME_VALIDATE("getFilePath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _filePath; } uint32 CMessagePartDescriptorSourceRecord::getDataOffset() const { CAF_CM_FUNCNAME_VALIDATE("getDataOffset"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _dataOffset; } uint32 CMessagePartDescriptorSourceRecord::getDataLength() const { CAF_CM_FUNCNAME_VALIDATE("getDataLength"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _dataLength; } CMessagePartRecord.cpp000066400000000000000000000043731321503522500404310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 26, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CMessagePartRecord.h" using namespace Caf; CMessagePartRecord::CMessagePartRecord() : _isInitialized(false), _attachmentNumber(0), _dataOffset(0), _dataLength(0), CAF_CM_INIT("CMessagePartRecord") { } CMessagePartRecord::~CMessagePartRecord() { } void CMessagePartRecord::initialize( const uint16 attachmentNumber, const std::string filePath, const uint64 dataOffset, const uint64 dataLength) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _attachmentNumber = attachmentNumber; _filePath = filePath; _dataOffset = dataOffset; _dataLength = dataLength; _isInitialized = true; } uint16 CMessagePartRecord::getAttachmentNumber() const { CAF_CM_FUNCNAME_VALIDATE("getAttachmentNumber"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _attachmentNumber; } std::string CMessagePartRecord::getFilePath() const { CAF_CM_FUNCNAME_VALIDATE("getFilePath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _filePath; } uint64 CMessagePartRecord::getDataOffset() const { CAF_CM_FUNCNAME_VALIDATE("getDataOffset"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _dataOffset; } uint64 CMessagePartRecord::getDataLength() const { CAF_CM_FUNCNAME_VALIDATE("getDataLength"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _dataLength; } void CMessagePartRecord::setAttachmentNumber(const uint16 attachmentNumber) { CAF_CM_FUNCNAME_VALIDATE("setAttachmentNumber"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _attachmentNumber = attachmentNumber; } void CMessagePartRecord::setFilePath(const std::string& filePath) { CAF_CM_FUNCNAME_VALIDATE("setFilePath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _filePath = filePath; } void CMessagePartRecord::setDataOffset(const uint64 dataOffset) { CAF_CM_FUNCNAME_VALIDATE("setDataOffset"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _dataOffset = dataOffset; } void CMessagePartRecord::setDataLength(const uint64 dataLength) { CAF_CM_FUNCNAME_VALIDATE("setDataLength"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _dataLength = dataLength; } CMessagePartsBuilder.cpp000066400000000000000000000064571321503522500407710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CMessagePartsBuilder.h" using namespace Caf; void CMessagePartsBuilder::put( const byte value, SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CMessagePartsBuilder", "put(byte)"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); buffer->memAppend(&value, sizeof(value)); // CAF_CM_LOG_DEBUG_VA2("buffer - pos: %d, val: %02x", currentPos, value); } void CMessagePartsBuilder::put( const uint16 value, SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CMessagePartsBuilder", "put(uint16)"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); byte buf[2]; buf[0] = value >> 8; buf[1] = value >> 0; putBytes(buf, 2, buffer); // CAF_CM_LOG_DEBUG_VA4("buffer - pos: %d, val: %04x, buf: %02x %02x", currentPos, value, buf[0], buf[1]); } void CMessagePartsBuilder::put( const uint32 value, SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CMessagePartsBuilder", "put(uint32)"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); byte buf[4]; buf[0] = value >> 24; buf[1] = value >> 16; buf[2] = value >> 8; buf[3] = value >> 0; putBytes(buf, 4, buffer); // CAF_CM_LOG_DEBUG_VA6("buffer - pos: %d, val: %08x, buf: %02x %02x %02x %02x", currentPos, value, buf[0], buf[1], buf[2], buf[3]); } void CMessagePartsBuilder::put( const uint64 value, SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CMessagePartsBuilder", "put(uint64)"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); byte buf[8]; #ifdef WIN32 #pragma warning(push) #pragma warning(disable: 4244) #endif buf[0] = value >> 56; buf[1] = value >> 48; buf[2] = value >> 40; buf[3] = value >> 32; buf[4] = value >> 24; buf[5] = value >> 16; buf[6] = value >> 8; buf[7] = value >> 0; #ifdef WIN32 #pragma warning(pop) #endif putBytes(buf, 8, buffer); // CAF_CM_LOG_DEBUG_VA6("buffer - pos: %d, val: %016x, buf: %02x %02x %02x %02x", currentPos, value, buf[0], buf[1], buf[2], buf[3]); // CAF_CM_LOG_DEBUG_VA6("buffer - pos: %d, val: %016x, buf: %02x %02x %02x %02x", currentPos, value, buf[4], buf[5], buf[6], buf[7]); } void CMessagePartsBuilder::put( const UUID value, SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CMessagePartsBuilder", "put(UUID)"); CAF_CM_VALIDATE_SMARTPTR(buffer); put(static_cast(value.Data1), buffer); put(static_cast(value.Data2), buffer); put(static_cast(value.Data3), buffer); putBytes(value.Data4, 8, buffer); } void CMessagePartsBuilder::putBytes( const byte* buf, const uint32 bufLen, SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CMessagePartsBuilder", "putBytes"); CAF_CM_VALIDATE_PTR(buf); CAF_CM_VALIDATE_SMARTPTR(buffer); for (uint32 index = 0; index < bufLen; index++) { buffer->memAppend(&buf[index], sizeof(buf[index])); } } CMessagePartsBuilder.h000066400000000000000000000017021321503522500404220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagePartsBuilder_h #define CMessagePartsBuilder_h #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { /** * Class that emits and parses message parts header blocks.
*/ class CMessagePartsBuilder { public: static void put(const byte value, SmartPtrCDynamicByteArray& buffer); static void put(const uint16 value, SmartPtrCDynamicByteArray& buffer); static void put(const uint32 value, SmartPtrCDynamicByteArray& buffer); static void put(const uint64 value, SmartPtrCDynamicByteArray& buffer); static void put(const GUID value, SmartPtrCDynamicByteArray& buffer); private: static void putBytes(const byte* buf, const uint32 bufLen, SmartPtrCDynamicByteArray& buffer); private: CAF_CM_DECLARE_NOCREATE(CMessagePartsBuilder); }; } #endif /* CMessagePartsBuilder_h */ CMessagePartsHeader.cpp000066400000000000000000000106151321503522500405620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CMessagePartsHeader.h" #include "Exception/CCafException.h" using namespace Caf; /** * Converts the BLOCK_SIZE data in a ByteBuffer into a MessagePartsHeader *

* The incoming ByteBuffer position will be modified. * @param buffer ByteBuffer to convert * @return a MessagePartsHeader */ SmartPtrCMessagePartsHeader CMessagePartsHeader::fromByteBuffer( SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG("CMessagePartsHeader", "fromByteBuffer"); CAF_CM_VALIDATE_SMARTPTR(buffer); if (buffer->getByteCountFromCurrentPos() < BLOCK_SIZE) { CAF_CM_EXCEPTION_VA2(E_INVALIDARG, "Input data block is too small - rem: %d, tot: %d", buffer->getByteCountFromCurrentPos(), buffer->getByteCount()); } SmartPtrCDynamicByteArray data; data.CreateInstance(); data->allocateBytes(BLOCK_SIZE); data->memCpy(buffer->getPtrAtCurrentPos(), BLOCK_SIZE); buffer->incrementCurrentPos(BLOCK_SIZE); return fromArray(data); } /** * Converts a byte array into a MessagePartsHeader * @param blockData byte array to convert * @return a MessagePartsHeader */ SmartPtrCMessagePartsHeader CMessagePartsHeader::fromArray( SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG("CMessagePartsHeader", "fromArray"); CAF_CM_VALIDATE_SMARTPTR(buffer); if (buffer->getByteCount() < BLOCK_SIZE) { CAF_CM_EXCEPTION_VA1(E_INVALIDARG, "Input data block is too small - %d", buffer->getByteCount()); } const int32 version = CMessagePartsParser::getByte(buffer); if (version != CAF_MSG_VERSION) { CAF_CM_EXCEPTION_VA2(E_INVALIDARG, "Input data block version is incorrect: %d != %d", version, CAF_MSG_VERSION); } const byte resvd1 = CMessagePartsParser::getByte(buffer); const byte resvd2 = CMessagePartsParser::getByte(buffer); const byte resvd3 = CMessagePartsParser::getByte(buffer); if (resvd1 != RESERVED1 || resvd2 != RESERVED2 || resvd3 != RESERVED3) { CAF_CM_EXCEPTION_VA0(E_INVALIDARG, "Input data block reserved bits are incorrect"); } const UUID correlationId = CMessagePartsParser::getGuid(buffer); const uint32 numberOfParts = CMessagePartsParser::getUint32(buffer); buffer->verify(); SmartPtrCMessagePartsHeader messagePartsHeader; messagePartsHeader.CreateInstance(); messagePartsHeader->initialize(correlationId, numberOfParts); return messagePartsHeader; } /** * Create a byte array representation of a descriptor block * @param correlationId the correlation id * @param numberOfParts the number of message parts * @return the byte array containing the encoded data */ SmartPtrCDynamicByteArray CMessagePartsHeader::toArray( const UUID correlationId, const uint32 numberOfParts) { SmartPtrCDynamicByteArray buffer; buffer.CreateInstance(); buffer->allocateBytes(BLOCK_SIZE); CMessagePartsBuilder::put(CAF_MSG_VERSION, buffer); CMessagePartsBuilder::put(RESERVED1, buffer); CMessagePartsBuilder::put(RESERVED2, buffer); CMessagePartsBuilder::put(RESERVED3, buffer); CMessagePartsBuilder::put(correlationId, buffer); CMessagePartsBuilder::put(numberOfParts, buffer); buffer->verify(); return buffer; } CMessagePartsHeader::CMessagePartsHeader() : _isInitialized(false), _correlationId(CAFCOMMON_GUID_NULL), _numberOfParts(0), CAF_CM_INIT("CMessagePartsHeader") { } CMessagePartsHeader::~CMessagePartsHeader() { } void CMessagePartsHeader::initialize( const UUID correlationId, const uint32 numberOfParts) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); this->_correlationId = correlationId; this->_numberOfParts = numberOfParts; _isInitialized = true; } /** * @return the correlationId */ UUID CMessagePartsHeader::getCorrelationId() const { CAF_CM_FUNCNAME_VALIDATE("getCorrelationId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _correlationId; } /** * @return the correlationId */ std::string CMessagePartsHeader::getCorrelationIdStr() const { CAF_CM_FUNCNAME_VALIDATE("getCorrelationId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return BasePlatform::UuidToString(_correlationId); } /** * @return the numberOfParts */ uint32 CMessagePartsHeader::getNumberOfParts() const { CAF_CM_FUNCNAME_VALIDATE("getNumberOfParts"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _numberOfParts; } CMessagePartsParser.cpp000066400000000000000000000124331321503522500406260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CMessagePartsParser.h" using namespace Caf; byte CMessagePartsParser::getByte(SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_VALIDATE("CMessagePartsParser", "getByte"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); const byte rc = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); // CAF_CM_LOG_DEBUG_VA2("buffer - pos: %d, val: %02x", currentPos, rc); return rc; } uint16 CMessagePartsParser::getUint16(SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_VALIDATE("CMessagePartsParser", "getUint16"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); byte buf[2]; buf[0] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[1] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); // Little and Big Endian //const uint16 val = (buf[0]<<0) | (buf[1]<<8); const uint16 val = (buf[0]<<8) | (buf[1]<<0); // CAF_CM_LOG_DEBUG_VA4("buffer - pos: %d, val: %04x, buf: %02x %02x", currentPos, val, buf[0], buf[1]); return val; } uint32 CMessagePartsParser::getUint32(SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_VALIDATE("CMessagePartsParser", "getUint32"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); byte buf[4]; buf[0] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[1] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[2] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[3] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); // Little and Big Endian //const uint32 val = (buf[0]<<0) | (buf[1]<<8) | (buf[2]<<16) | (buf[3]<<24); const uint32 val = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | (buf[3]<<0); // CAF_CM_LOG_DEBUG_VA6("buffer - pos: %d, val: %08x, buf: %02x %02x %02x %02x", currentPos, val, buf[0], buf[1], buf[2], buf[3]); return val; } uint64 CMessagePartsParser::getUint64(SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_VALIDATE("CMessagePartsParser", "getUint64"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); byte buf[8]; buf[0] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[1] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[2] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[3] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[4] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[5] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[6] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[7] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); // Little and Big Endian // const uint64 val = // (buf[0]<<0) // | (buf[1]<<8) // | (buf[2]<<16) // | (buf[3]<<24) // | (static_cast(buf[4])<<32) // | (static_cast(buf[5])<<40) // | (static_cast(buf[6])<<48) // | (static_cast(buf[7])<<56); const uint64 val = (static_cast(buf[0])<<56) | (static_cast(buf[1])<<48) | (static_cast(buf[2])<<40) | (static_cast(buf[3])<<32) | (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | (buf[7]<<0); // CAF_CM_LOG_DEBUG_VA6("buffer - pos: %d, val: %016x, buf: %02x %02x %02x %02x", currentPos, val, buf[0], buf[1], buf[2], buf[3]); // CAF_CM_LOG_DEBUG_VA6("buffer - pos: %d, val: %016x, buf: %02x %02x %02x %02x", currentPos, val, buf[4], buf[5], buf[6], buf[7]); return val; } UUID CMessagePartsParser::getGuid(SmartPtrCDynamicByteArray& buffer) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CMessagePartsParser", "getGuid"); CAF_CM_VALIDATE_SMARTPTR(buffer); UUID guid; guid.Data1 = getUint32(buffer); guid.Data2 = getUint16(buffer); guid.Data3 = getUint16(buffer); get8Bytes(buffer, guid.Data4); CAF_CM_LOG_DEBUG_VA1("guid - %s", BasePlatform::UuidToString(guid).c_str()); return guid; } void CMessagePartsParser::get8Bytes(SmartPtrCDynamicByteArray& buffer, byte* buf) { CAF_CM_STATIC_FUNC_VALIDATE("CMessagePartsParser", "get8Bytes"); CAF_CM_VALIDATE_SMARTPTR(buffer); // const size_t currentPos = buffer->getByteCount() - buffer->getByteCountFromCurrentPos(); buf[0] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[1] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[2] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[3] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[4] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[5] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[6] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); buf[7] = buffer->getAtCurrentPos(); buffer->incrementCurrentPos(1); // CAF_CM_LOG_DEBUG_VA5("buffer - pos: %d, buf: %02x %02x %02x %02x", currentPos, buf[0], buf[1], buf[2], buf[3]); // CAF_CM_LOG_DEBUG_VA5("buffer - pos: %d, buf: %02x %02x %02x %02x", currentPos, buf[4], buf[5], buf[6], buf[7]); } CMessagePartsParser.h000066400000000000000000000015421321503522500402720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagePartsParser_h #define CMessagePartsParser_h #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { /** * Class that emits and parses message parts header blocks.
*/ class CMessagePartsParser { public: static byte getByte(SmartPtrCDynamicByteArray& buffer); static uint16 getUint16(SmartPtrCDynamicByteArray& buffer); static uint32 getUint32(SmartPtrCDynamicByteArray& buffer); static uint64 getUint64(SmartPtrCDynamicByteArray& buffer); static UUID getGuid(SmartPtrCDynamicByteArray& buffer); static void get8Bytes(SmartPtrCDynamicByteArray& buffer, byte* data); private: CAF_CM_DECLARE_NOCREATE(CMessagePartsParser); }; } #endif /* CMessagePartsParser_h */ COutgoingMessageHandler.cpp000066400000000000000000000230751321503522500414550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 25, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CMessageDeliveryRecord.h" #include "CMessagePartDescriptorSourceRecord.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Integration/Core/CIntMessageHeaders.h" #include "Exception/CCafException.h" #include "COutgoingMessageHandler.h" #include "CMessagePartsHeader.h" #include "CMessagePartDescriptor.h" #include "amqpCore/DefaultAmqpHeaderMapper.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Core/CMessageHeaderUtils.h" #include "Integration/Core/MessageHeaders.h" #include "Integration/Core/CMessageHeaderUtils.h" #include using namespace Caf; COutgoingMessageHandler::COutgoingMessageHandler() : _isInitialized(false), CAF_CM_INIT_LOG("COutgoingMessageHandler") { } COutgoingMessageHandler::~COutgoingMessageHandler() { } void COutgoingMessageHandler::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _isInitialized = true; } void COutgoingMessageHandler::terminateBean() { } /** * Handles the incoming management request message *

* Incoming messages are checked for local attachments that need to be transmitted. * If the resulting message would be too large to transmit then multiple message * records are created and stored for the {@link OutgoingMessageProducer} to handle. If the * message is small enough to fit in a single transmission then it will be returned * from this handler if a message receipt is not requested. * * @param message the incoming management request message * @return null if the message must be transmitted as multiple parts or the message itself if it can be transmitted as is */ SmartPtrIIntMessage COutgoingMessageHandler::processMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("processMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); SmartPtrIIntMessage rc; const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); // Touch up the outgoing message headers first so that they are // preserved through the rest of the system. IIntMessage::SmartPtrCHeaders headers = message->getHeaders(); std::deque messagePartSourceRecords = CMessagePartDescriptorCalculator::calculateSourcePartRecords(message->getPayload()); if (messagePartSourceRecords.empty()) { rc = augmentHeaders(false, message); } else { // Message splitting required. Iterate the message parts and group them // such that each group of parts will fill maxPartSize bytes when transmitted. std::deque deliveryRecords; const uint32 maxPartSize = CMessagePartDescriptorCalculator::getMaxPartSize(); const std::string correlationIdStr = CStringUtils::createRandomUuid(); UUID correlationId; BasePlatform::UuidFromString(correlationIdStr.c_str(), correlationId); uint32 startPartNumber = 1; uint32 currentPartSize = 0; std::deque deliveryParts; for (TConstIterator > sourceRecordIter(messagePartSourceRecords); sourceRecordIter; sourceRecordIter++) { const SmartPtrCMessagePartDescriptorSourceRecord sourceRecord = *sourceRecordIter; deliveryParts.push_back(sourceRecord); currentPartSize += sourceRecord->getDataLength(); if (currentPartSize == maxPartSize) { if (CAF_CM_IS_LOG_DEBUG_ENABLED) { CAF_CM_LOG_DEBUG_VA5( "Adding message delivery record [size=%d][totalNumParts=%d][startPartNum=%d][parts=%d][correlationId=%s]", currentPartSize, messagePartSourceRecords.size(), startPartNumber, deliveryParts.size(), correlationIdStr.c_str()); } SmartPtrCMessageDeliveryRecord deliveryRecord; deliveryRecord.CreateInstance(); deliveryRecord->initialize(correlationId, static_cast(messagePartSourceRecords.size()), startPartNumber, deliveryParts, message->getHeaders()); deliveryRecords.push_back(deliveryRecord); startPartNumber += static_cast(deliveryParts.size()); deliveryParts.clear(); currentPartSize = 0; } else if (currentPartSize > maxPartSize) { CAF_CM_EXCEPTION_VA2(ERROR_BUFFER_OVERFLOW, "Buffer overflow - currentPartSize: %d, maxPartSize: %d", currentPartSize, maxPartSize); } } if (currentPartSize > 0) { if (CAF_CM_IS_LOG_DEBUG_ENABLED) { CAF_CM_LOG_DEBUG_VA5( "Adding message delivery record [size=%d][totalNumParts=%d][startPartNum=%d][parts=%d][correlationId=%s]", currentPartSize, messagePartSourceRecords.size(), startPartNumber, deliveryParts.size(), correlationIdStr.c_str()); } SmartPtrCMessageDeliveryRecord deliveryRecord; deliveryRecord.CreateInstance(); deliveryRecord->initialize(correlationId, static_cast(messagePartSourceRecords.size()), startPartNumber, deliveryParts, message->getHeaders()); deliveryRecords.push_back(deliveryRecord); } if (deliveryRecords.size() != 1) { CAF_CM_EXCEPTION_VA1(ERROR_NOT_SUPPORTED, "Currently supports only one delivery record (i.e. no chunking) - size: %d", deliveryRecords.size()); } const SmartPtrIIntMessage newMessage = rehydrateMultiPartMessage( deliveryRecords.back(), IIntMessage::SmartPtrCHeaders()); rc = augmentHeaders(true, newMessage); } CMessageHeaderUtils::log(rc->getHeaders()); return rc; } SmartPtrIIntMessage COutgoingMessageHandler::rehydrateMultiPartMessage( const SmartPtrCMessageDeliveryRecord& deliveryRecord, const IIntMessage::SmartPtrCHeaders& addlHeaders) { CAF_CM_STATIC_FUNC_LOG("COutgoingMessageHandler", "rehydrateMultiPartMessage"); CAF_CM_VALIDATE_SMARTPTR(deliveryRecord); // addlHeaders are optional uint32 payloadSize = CMessagePartsHeader::BLOCK_SIZE; const std::deque sourceRecords = deliveryRecord->getMessagePartSources(); for (TConstIterator > sourceRecordIter(sourceRecords); sourceRecordIter; sourceRecordIter++) { const SmartPtrCMessagePartDescriptorSourceRecord sourceRecord = *sourceRecordIter; payloadSize += CMessagePartDescriptor::BLOCK_SIZE + sourceRecord->getDataLength(); } SmartPtrCDynamicByteArray payload; payload.CreateInstance(); payload->allocateBytes(payloadSize); const SmartPtrCDynamicByteArray partsHeader = CMessagePartsHeader::toArray( deliveryRecord->getCorrelationId(), deliveryRecord->getNumberOfParts()); payload->memAppend(partsHeader->getPtr(), partsHeader->getByteCount()); uint32 partNumber = deliveryRecord->getStartingPartNumber(); if (CAF_CM_IS_LOG_DEBUG_ENABLED) { CAF_CM_LOG_DEBUG_VA3("[# sourceRecords=%d][payloadSize=%d][startingPartNumber=%d]", sourceRecords.size(), payloadSize, partNumber); } for (TConstIterator > sourceRecordIter(sourceRecords); sourceRecordIter; sourceRecordIter++) { const SmartPtrCMessagePartDescriptorSourceRecord sourceRecord = *sourceRecordIter; const SmartPtrCDynamicByteArray partDescriptor = CMessagePartDescriptor::toArray( sourceRecord->getAttachmentNumber(), partNumber++, sourceRecord->getDataLength(), sourceRecord->getDataOffset()); payload->memAppend(partDescriptor->getPtr(), partDescriptor->getByteCount()); CAF_CM_LOG_DEBUG_VA3("Reading from file - file: %s, len: %d, offset: %d", sourceRecord->getFilePath().c_str(), sourceRecord->getDataLength(), sourceRecord->getDataOffset()); std::ifstream file(sourceRecord->getFilePath().c_str(), std::ios::binary); try { if (!file.is_open()) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "Could not open binary file - %s", sourceRecord->getFilePath().c_str()); } file.seekg(sourceRecord->getDataOffset(), std::ios::beg); file.read(reinterpret_cast(payload->getNonConstPtrAtCurrentPos()), sourceRecord->getDataLength()); payload->verify(); if (! file) { CAF_CM_EXCEPTION_VA3(ERROR_BUFFER_OVERFLOW, "Did not read full contents - file: %s, requested: %d, read: %d", sourceRecord->getFilePath().c_str(), sourceRecord->getDataLength(), file.gcount()); } payload->incrementCurrentPos(sourceRecord->getDataLength()); } CAF_CM_CATCH_ALL; file.close(); CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } SmartPtrCIntMessage rc; rc.CreateInstance(); rc->initialize(payload, deliveryRecord->getMessageHeaders(), addlHeaders); return rc; } SmartPtrIIntMessage COutgoingMessageHandler::augmentHeaders( const bool isMultiPart, const SmartPtrIIntMessage& message) { CAF_CM_STATIC_FUNC_VALIDATE("COutgoingMessageHandler", "augmentHeaders"); CAF_CM_VALIDATE_INTERFACE(message); std::string contentType; if (isMultiPart) { contentType = "application/octet-stream"; } else { contentType = "text/plain"; } CIntMessageHeaders messageHeaders; messageHeaders.insertBool(MessageHeaders::_sMULTIPART, isMultiPart); messageHeaders.insertString(AmqpIntegration::DefaultAmqpHeaderMapper::CONTENT_TYPE, contentType); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initialize(message->getPayload(), messageHeaders.getHeaders(), message->getHeaders()); return messageImpl; } COutgoingMessageHandler.h000066400000000000000000000027601321503522500411200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Nov 25, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef COutgoingMessageHandler_h #define COutgoingMessageHandler_h #include "IBean.h" #include "CMessageDeliveryRecord.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageProcessor.h" using namespace Caf; class COutgoingMessageHandler : public TCafSubSystemObjectRoot, public IBean, public IMessageProcessor { public: COutgoingMessageHandler(); virtual ~COutgoingMessageHandler(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationOutgoingMessageHandler) CAF_BEGIN_INTERFACE_MAP(COutgoingMessageHandler) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IMessageProcessor) CAF_END_INTERFACE_MAP() public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IMessageProcessor SmartPtrIIntMessage processMessage( const SmartPtrIIntMessage& message); private: static SmartPtrIIntMessage rehydrateMultiPartMessage( const SmartPtrCMessageDeliveryRecord& deliveryRecord, const IIntMessage::SmartPtrCHeaders& addlHeaders); static SmartPtrIIntMessage augmentHeaders( const bool isMultiPart, const SmartPtrIIntMessage& message); private: bool _isInitialized; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(COutgoingMessageHandler); }; #endif /* COutgoingMessageHandler_h */ CProtocolHeaderEnricher.cpp000066400000000000000000000032271321503522500414460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CProtocolHeaderEnricher.h" using namespace Caf; CProtocolHeaderEnricher::CProtocolHeaderEnricher() : _isInitialized(false), CAF_CM_INIT("CProtocolHeaderEnricher") { } CProtocolHeaderEnricher::~CProtocolHeaderEnricher() { } void CProtocolHeaderEnricher::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); _ctorArgs = ctorArgs; _properties = properties; initialize(); } void CProtocolHeaderEnricher::terminateBean() { } void CProtocolHeaderEnricher::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } bool CProtocolHeaderEnricher::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); return false; } SmartPtrIIntegrationObject CProtocolHeaderEnricher::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); SmartPtrIIntegrationObject rc; rc.CreateInstance(_sObjIdCommIntegrationProtocolHeaderEnricherInstance); rc->initialize(_ctorArgs, _properties, configSection); return rc; } CProtocolHeaderEnricher.h000066400000000000000000000026551321503522500411170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProtocolHeaderEnricher_h_ #define CProtocolHeaderEnricher_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CProtocolHeaderEnricher : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CProtocolHeaderEnricher(); virtual ~CProtocolHeaderEnricher(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationProtocolHeaderEnricher) CAF_BEGIN_INTERFACE_MAP(CProtocolHeaderEnricher) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CProtocolHeaderEnricher); }; } #endif // #ifndef CProtocolHeaderEnricher_h_ CProtocolHeaderEnricherInstance.cpp000066400000000000000000000067021321503522500431340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Caf/CCafMessageHeadersWriter.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "CProtocolHeaderEnricherInstance.h" #include "Integration/Caf/CCafMessagePayloadParser.h" using namespace Caf; CProtocolHeaderEnricherInstance::CProtocolHeaderEnricherInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CProtocolHeaderEnricherInstance") { } CProtocolHeaderEnricherInstance::~CProtocolHeaderEnricherInstance() { } void CProtocolHeaderEnricherInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CProtocolHeaderEnricherInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CProtocolHeaderEnricherInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); } SmartPtrIIntMessage CProtocolHeaderEnricherInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); const SmartPtrCProtocolDoc protocol = findProtocol(payloadEnvelope); UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(protocol->getUri(), uriRecord); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setProtocol(uriRecord.protocol); messageHeadersWriter->setProtocolAddress(uriRecord.address); CAF_CM_LOG_DEBUG_VA2( "Enhanced the headers - protocol: \"%s\", connStr: \"%s\"", uriRecord.protocol.c_str(), uriRecord.address.c_str()); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initialize(message->getPayload(), messageHeadersWriter->getHeaders(), message->getHeaders()); return messageImpl; } SmartPtrCProtocolDoc CProtocolHeaderEnricherInstance::findProtocol( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope) const { CAF_CM_FUNCNAME("findProtocol"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelope); const SmartPtrCProtocolCollectionDoc protocolCollectionDoc = payloadEnvelope->getProtocolCollection(); CAF_CM_VALIDATE_SMARTPTR(protocolCollectionDoc); const std::deque protocolCollection = protocolCollectionDoc->getProtocol(); if (protocolCollection.size() != 1) { CAF_CM_EXCEPTION_VA1(E_NOTIMPL, "Multiple protocols are not yet supported - %d", protocolCollection.size()); } return *(protocolCollection.begin()); } CProtocolHeaderEnricherInstance.h000066400000000000000000000036751321503522500426070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProtocolHeaderEnricherInstance_h #define CProtocolHeaderEnricherInstance_h #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CProtocolDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CProtocolHeaderEnricherInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CProtocolHeaderEnricherInstance(); virtual ~CProtocolHeaderEnricherInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationProtocolHeaderEnricherInstance) CAF_BEGIN_INTERFACE_MAP(CProtocolHeaderEnricherInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: SmartPtrCProtocolDoc findProtocol( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope) const; private: bool _isInitialized; std::string _id; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CProtocolHeaderEnricherInstance); }; } #endif /* CProtocolHeaderEnricherInstance_h */ CReplyToCacher.cpp000066400000000000000000000031231321503522500375530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CReplyToCacher.h" using namespace Caf; CReplyToCacher::CReplyToCacher() : _isInitialized(false), CAF_CM_INIT("CReplyToCacher") { } CReplyToCacher::~CReplyToCacher() { } void CReplyToCacher::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } void CReplyToCacher::terminateBean() { } void CReplyToCacher::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } bool CReplyToCacher::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); return false; } SmartPtrIIntegrationObject CReplyToCacher::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); SmartPtrIIntegrationObject rc; rc.CreateInstance(_sObjIdCommIntegrationReplyToCacherInstance); rc->initialize(_ctorArgs, _properties, configSection); return rc; } CReplyToCacher.h000066400000000000000000000025231321503522500372230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CReplyToCacher_h_ #define CReplyToCacher_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CReplyToCacher : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CReplyToCacher(); virtual ~CReplyToCacher(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationReplyToCacher) CAF_BEGIN_INTERFACE_MAP(CReplyToCacher) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CReplyToCacher); }; } #endif // #ifndef CReplyToCacher_h_ CReplyToCacherInstance.cpp000066400000000000000000000037571321503522500412550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "CReplyToCacherInstance.h" using namespace Caf; CReplyToCacherInstance::CReplyToCacherInstance() : _isInitialized(false), CAF_CM_INIT("CReplyToCacherInstance") { } CReplyToCacherInstance::~CReplyToCacherInstance() { } void CReplyToCacherInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _replyToResolverId = configSection->findRequiredAttribute("reply-to-resolver"); _isInitialized = true; } std::string CReplyToCacherInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CReplyToCacherInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); SmartPtrIBean replyToResolverBean = appContext->getBean(_replyToResolverId); _replyToResolver.QueryInterface(replyToResolverBean, false); if (!_replyToResolver) { CAF_CM_EXCEPTIONEX_VA1(NoSuchInterfaceException, 0, "Bean '%s' is not a ReplyToResolver", _replyToResolverId.c_str()); } } SmartPtrIIntMessage CReplyToCacherInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _replyToResolver->cacheReplyTo(message); return message; } CReplyToCacherInstance.h000066400000000000000000000033461321503522500407140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CReplyToCacherInstance_h #define CReplyToCacherInstance_h #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "ReplyToResolver.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CReplyToCacherInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CReplyToCacherInstance(); virtual ~CReplyToCacherInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationReplyToCacherInstance) CAF_BEGIN_INTERFACE_MAP(CReplyToCacherInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; std::string _replyToResolverId; SmartPtrReplyToResolver _replyToResolver; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CReplyToCacherInstance); }; } #endif /* CReplyToCacherInstance_h */ CReplyToResolverInstance.cpp000066400000000000000000000141421321503522500416570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Caf/CCafMessageHeaders.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "IVariant.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "CReplyToResolverInstance.h" #include "amqpCore/DefaultAmqpHeaderMapper.h" #include "Integration/Caf/CCafMessagePayloadParser.h" using namespace Caf; CReplyToResolverInstance::CReplyToResolverInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CReplyToResolverInstance") { CAF_CM_INIT_THREADSAFE; } CReplyToResolverInstance::~CReplyToResolverInstance() { } void CReplyToResolverInstance::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); // Read cache map into memory loadCache(); _isInitialized = true; } void CReplyToResolverInstance::terminateBean() { persistCache(); } std::string CReplyToResolverInstance::cacheReplyTo( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("cacheReplyTo"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); const SmartPtrCCafMessageHeaders cafMessageHeaders = CCafMessageHeaders::create(message->getHeaders()); const std::string replyTo = cafMessageHeaders->getOptionalStr( AmqpIntegration::DefaultAmqpHeaderMapper::REPLY_TO); if (! replyTo.empty()) { const UUID requestId = payloadEnvelope->getRequestId(); const std::string requestIdStr = BasePlatform::UuidToString(requestId); CAF_CM_LOG_DEBUG_VA2( "Caching replyTo: [reqId=%s][replyTo=%s]", requestIdStr.c_str(), replyTo.c_str()); _replyToAddresses.insert(std::make_pair(requestId, replyTo)); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Message does not have a '%s' header.", AmqpIntegration::DefaultAmqpHeaderMapper::REPLY_TO.c_str()); } return replyTo; } std::string CReplyToResolverInstance::lookupReplyTo( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("lookupReplyTo"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string replyTo; const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); const SmartPtrCCafMessageHeaders cafMessageHeaders = CCafMessageHeaders::create(message->getHeaders()); const UUID requestId = payloadEnvelope->getRequestId(); AddressMap::iterator replyToIter = _replyToAddresses.find(requestId); if (replyToIter != _replyToAddresses.end()) { replyTo = replyToIter->second; _replyToAddresses.erase(replyToIter); } else { const std::string requestIdStr = BasePlatform::UuidToString(requestId); CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Request id %s was not found in the address collection.", requestIdStr.c_str()); } return replyTo; } SmartPtrIVariant CReplyToResolverInstance::invokeExpression( const std::string& methodName, const Cdeqstr& methodParams, const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("invokeExpression"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(!methodParams.size()); SmartPtrIVariant result; if (methodName == "lookupReplyTo") { result = CVariant::createString(lookupReplyTo(message)); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchMethodException, 0, "Method '%s' is not supported by this invoker", methodName.c_str()); } return result; } inline std::string CReplyToResolverInstance::getResolverCacheFilePath() { return AppConfigUtils::getRequiredString("communication_amqp", "resolver_cache_file"); } /* * private methods * */ void CReplyToResolverInstance::loadCache() { CAF_CM_FUNCNAME_VALIDATE("loadCache"); CAF_CM_LOCK_UNLOCK; //const std::string cacheFilePath = AppConfigUtils::getRequiredString("communication_amqp", "resolver_cache_file"); const std::string cacheFilePath = getResolverCacheFilePath(); const std::string cacheDirPath = FileSystemUtils::getDirname(cacheFilePath); if (! FileSystemUtils::doesDirectoryExist(cacheDirPath)) { FileSystemUtils::createDirectory(cacheDirPath); } if (FileSystemUtils::doesFileExist(cacheFilePath)) { const std::deque fileContents = FileSystemUtils::loadTextFileIntoColl(cacheFilePath); for(TConstIterator > fileLineIter(fileContents); fileLineIter; fileLineIter++) { //const std::string fileLine = *fileLineIter; const Cdeqstr fileLineTokens = CStringUtils::split(*fileLineIter, ' '); CAF_CM_LOG_DEBUG_VA2("cache entry - reqId: %s, addr: %s", fileLineTokens[0].c_str(), fileLineTokens[1].c_str()); if (fileLineTokens.size() == 2) { UUID reqId; BasePlatform::UuidFromString(fileLineTokens[0].c_str(), reqId); _replyToAddresses.insert(std::make_pair(reqId, fileLineTokens[1])); } } } else { CAF_CM_LOG_DEBUG_VA1("resolver cache is not available - resolverCache: %s", cacheFilePath.c_str()); } } void CReplyToResolverInstance::persistCache() { CAF_CM_FUNCNAME_VALIDATE("persistCache"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); //const std::string cacheFilePath = AppConfigUtils::getRequiredString("communication_amqp", "resolver_cache_file"); const std::string cacheFilePath = getResolverCacheFilePath(); std::stringstream contents; //contents.str(""); for (AddressMap::const_iterator replyToIter = _replyToAddresses.begin(); replyToIter != _replyToAddresses.end(); ++replyToIter) { std::string reqIdStr = BasePlatform::UuidToString(replyToIter->first); contents << reqIdStr << " " << replyToIter->second << std::endl; CAF_CM_LOG_DEBUG_VA2("caching entry - reqId: %s, addr: %s", reqIdStr.c_str(), replyToIter->second.c_str()); } if (contents.str().length() > 0) { CAF_CM_LOG_DEBUG_VA0("Caching resolver map."); FileSystemUtils::saveTextFile(cacheFilePath, contents.str()); } } CReplyToResolverInstance.h000066400000000000000000000033271321503522500413270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CReplyToResolverInstance_h #define CReplyToResolverInstance_h #include "IBean.h" #include "IVariant.h" #include "ReplyToResolver.h" #include "Integration/IIntMessage.h" #include "Integration/IExpressionInvoker.h" namespace Caf { class CReplyToResolverInstance : public TCafSubSystemObjectRoot, public IBean, public ReplyToResolver, public IExpressionInvoker { public: CReplyToResolverInstance(); virtual ~CReplyToResolverInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCommIntegrationReplyToResolver) CAF_BEGIN_INTERFACE_MAP(CReplyToResolverInstance) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(ReplyToResolver) CAF_INTERFACE_ENTRY(IExpressionInvoker) CAF_END_INTERFACE_MAP() public: // IBean void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // ReplyToResolver std::string cacheReplyTo(const SmartPtrIIntMessage& message); std::string lookupReplyTo(const SmartPtrIIntMessage& message); static std::string getResolverCacheFilePath(); private: // ReplyToResolver void loadCache(); void persistCache(); public: // IExpressionInvoker SmartPtrIVariant invokeExpression( const std::string& methodName, const Cdeqstr& methodParams, const SmartPtrIIntMessage& message); private: bool _isInitialized; typedef std::map AddressMap; AddressMap _replyToAddresses; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CReplyToResolverInstance); }; } #endif /* CReplyToResolverInstance_h */ commIntegration.cpp000066400000000000000000000056241321503522500401130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CCmsMessageTransformer.h" #include "CCmsMessageTransformerInstance.h" #include "CEventTopicCalculatorInstance.h" #include "CIncomingMessageHandler.h" #include "CIncomingMessageHandlerInstance.h" #include "COutgoingMessageHandler.h" #include "CProtocolHeaderEnricher.h" #include "CProtocolHeaderEnricherInstance.h" #include "CReplyToCacher.h" #include "CReplyToCacherInstance.h" #include "CReplyToResolverInstance.h" namespace Caf { const char* _sObjIdCommIntegrationCmsMessageTransformer = "com.vmware.caf.comm.integration.cmsmessagetransformer"; const char* _sObjIdCommIntegrationCmsMessageTransformerInstance = "com.vmware.caf.comm.integration.cmsmessagetransformerinstance"; const char* _sObjIdCommIntegrationEventTopicCalculator = "com.vmware.caf.comm.integration.eventtopiccalculator"; const char* _sObjIdCommIntegrationIncomingMessageHandler = "com.vmware.caf.comm.integration.incomingmessagehandler"; const char* _sObjIdCommIntegrationIncomingMessageHandlerInstance = "com.vmware.caf.comm.integration.incomingmessagehandlerinstance"; const char* _sObjIdCommIntegrationOutgoingMessageHandler = "com.vmware.caf.comm.integration.outgoingmessagehandler"; const char* _sObjIdCommIntegrationProtocolHeaderEnricher = "com.vmware.caf.comm.integration.protocolheaderenricher"; const char* _sObjIdCommIntegrationProtocolHeaderEnricherInstance = "com.vmware.caf.comm.integration.protocolheaderenricherinstance"; const char* _sObjIdCommIntegrationReplyToCacher = "com.vmware.caf.comm.integration.replytocacher"; const char* _sObjIdCommIntegrationReplyToCacherInstance = "com.vmware.caf.comm.integration.replytocacherinstance"; const char* _sObjIdCommIntegrationReplyToResolver = "com.vmware.caf.comm.integration.replytoresolver"; } CEcmSubSystemModule _Module; using namespace Caf; CAF_BEGIN_OBJECT_MAP(ObjectMap) CAF_OBJECT_ENTRY(CCmsMessageTransformer) CAF_OBJECT_ENTRY(CCmsMessageTransformerInstance) CAF_OBJECT_ENTRY(CEventTopicCalculatorInstance) CAF_OBJECT_ENTRY(CIncomingMessageHandler) CAF_OBJECT_ENTRY(CIncomingMessageHandlerInstance) CAF_OBJECT_ENTRY(COutgoingMessageHandler) CAF_OBJECT_ENTRY(CProtocolHeaderEnricher) CAF_OBJECT_ENTRY(CProtocolHeaderEnricherInstance) CAF_OBJECT_ENTRY(CReplyToCacher) CAF_OBJECT_ENTRY(CReplyToCacherInstance) CAF_OBJECT_ENTRY(CReplyToResolverInstance) CAF_END_OBJECT_MAP() CAF_DECLARE_SUBSYSTEM_EXPORTS() extern "C" BOOL APIENTRY DllMain(HINSTANCE hModule, uint32 dwReason, LPVOID) { try { if (DLL_PROCESS_ATTACH == dwReason) { // initialize the sub-system module _Module.Init(ObjectMap, hModule); } else if (DLL_PROCESS_DETACH == dwReason) { // Terminate the sub-system module _Module.Term(); } } catch (std::runtime_error) { ::exit(2); } catch (...) { ::exit(2); } return TRUE; } commIntegrationDefines.h000066400000000000000000000017551321503522500410570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef commIntegrationDefines_h #define commIntegrationDefines_h namespace Caf { extern const char* _sObjIdCommIntegrationCmsMessageTransformer; extern const char* _sObjIdCommIntegrationCmsMessageTransformerInstance; extern const char* _sObjIdCommIntegrationEventTopicCalculator; extern const char* _sObjIdCommIntegrationIncomingMessageHandler; extern const char* _sObjIdCommIntegrationIncomingMessageHandlerInstance; extern const char* _sObjIdCommIntegrationOutgoingMessageHandler; extern const char* _sObjIdCommIntegrationProtocolHeaderEnricher; extern const char* _sObjIdCommIntegrationProtocolHeaderEnricherInstance; extern const char* _sObjIdCommIntegrationReplyToCacher; extern const char* _sObjIdCommIntegrationReplyToCacherInstance; extern const char* _sObjIdCommIntegrationReplyToResolver; } #endif /* commIntegrationDefines_h */ stdafx.h000066400000000000000000000010231321503522500356770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/Subsystems/commIntegration/src/* * Created on: Aug 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h #define stdafx_h #include #include #include "../../../amqpCore/src/amqpCore/amqpIntegrationCoreLink.h" #include "commIntegrationDefines.h" #include #include "CMessagePartsParser.h" #include "CMessagePartsBuilder.h" #include "CMessagePartDescriptorCalculator.h" #include "CCmsMessageUtils.h" #endif /* stdafx_h */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/000077500000000000000000000000001321503522500277605ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/000077500000000000000000000000001321503522500314035ustar00rootroot00000000000000amqpClient/000077500000000000000000000000001321503522500334215ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/includeAMQChannel.h000066400000000000000000000160231321503522500355030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQCHANNEL_H_ #define AMQCHANNEL_H_ #include "amqpClient/TCopyOnWriteContainer.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Common/CAutoMutex.h" #include "Exception/CCafException.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/AMQCommand.h" #include "amqpClient/ConsumerDispatcher.h" #include "amqpClient/ConsumerWorkService.h" #include "amqpClient/IConnectionInt.h" #include "amqpClient/IRpcContinuation.h" #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/api/AmqpMethods.h" #include "amqpClient/api/Consumer.h" #include "amqpClient/api/GetResponse.h" #include "amqpClient/api/ReturnListener.h" #include "amqpClient/api/amqpClient.h" #include "Common/CThreadSignal.h" #include "amqpClient/api/Channel.h" namespace Caf { namespace AmqpClient { class AMQChannel; CAF_DECLARE_SMART_POINTER(AMQChannel); /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Concrete implementation of a Channel object representing an AMQP channel. */ class AMQChannel : public Channel { public: AMQChannel(); virtual ~AMQChannel(); /** * @brief Initializer * @param connection the owning connection * @param workService the work service to add channel tasks to */ void init( const SmartPtrIConnectionInt& connection, const SmartPtrConsumerWorkService& workService); /** * @brief Notification of connection closure *

* Called by the AMQChannelManager to notify the channel that the parent connect * has closed for the supplied reason. * @param exception the reason for the closure */ void notifyConnectionClosed(SmartPtrCCafException& exception); /** * @brief Close the channel with the given reason * @param exception reason for closure */ void close(SmartPtrCCafException& exception); public: // Channel uint16 getChannelNumber(); void close(); bool isOpen(); public: // Basic void basicAck( const uint64 deliveryTag, const bool ackMultiple); SmartPtrGetResponse basicGet( const std::string& queue, const bool noAck); void basicPublish( const std::string& exchange, const std::string& routingKey, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); void basicPublish( const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const SmartPtrConsumer& consumer); AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const bool noAck, const SmartPtrConsumer& consumer); AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const std::string& consumerTag, const bool noAck, const bool noLocal, const bool exclusive, const SmartPtrConsumer& consumer, const SmartPtrTable& arguments = SmartPtrTable()); AmqpMethods::Basic::SmartPtrCancelOk basicCancel( const std::string& consumerTag); AmqpMethods::Basic::SmartPtrRecoverOk basicRecover( const bool requeue); AmqpMethods::Basic::SmartPtrQosOk basicQos( const uint32 prefetchSize, const uint32 prefetchCount, const bool global); void basicReject( const uint64 deliveryTag, const bool requeue); public: // Exchange AmqpMethods::Exchange::SmartPtrDeclareOk exchangeDeclare( const std::string& exchange, const std::string& type, const bool durable = false, const SmartPtrTable& arguments = SmartPtrTable()); AmqpMethods::Exchange::SmartPtrDeleteOk exchangeDelete( const std::string& exchange, const bool ifUnused); public: // Queue AmqpMethods::Queue::SmartPtrDeclareOk queueDeclare(); AmqpMethods::Queue::SmartPtrDeclareOk queueDeclare( const std::string& queue, const bool durable, const bool exclusive, const bool autoDelete, const SmartPtrTable& arguments = SmartPtrTable()); AmqpMethods::Queue::SmartPtrDeclareOk queueDeclarePassive( const std::string& queue); AmqpMethods::Queue::SmartPtrDeleteOk queueDelete( const std::string& queue, const bool ifUnused, const bool ifEmpty); AmqpMethods::Queue::SmartPtrPurgeOk queuePurge( const std::string& queue); AmqpMethods::Queue::SmartPtrBindOk queueBind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments = SmartPtrTable()); AmqpMethods::Queue::SmartPtrUnbindOk queueUnbind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments = SmartPtrTable()); void addReturnListener( const SmartPtrReturnListener& listener); bool removeReturnListener( const SmartPtrReturnListener& listener); private: bool taskHandler(); void handleCompleteInboundCommand(const SmartPtrAMQCommand& command); bool processAsync(const SmartPtrAMQCommand& command); void ensureIsOpen(); SmartPtrAMQCommand execRpc(const SmartPtrIServerMethod& method); SmartPtrIRpcContinuation nextOutstandingRpc(); void transmit(const SmartPtrIServerMethod& method); void channelCloseByServerShutdown(const AmqpMethods::Channel::SmartPtrClose& closeMethod); void callReturnListeners(const SmartPtrAMQCommand& command); private: /* * This class hooks the channel into the worker service * thread pool for channel inbound AMQP frame processing */ class ChannelTask : public CManagedThreadPool::IThreadTask { public: ChannelTask(); virtual ~ChannelTask(); /* * Initialize the thread task * channel is the pointer to the parent channel */ void init(SmartPtrAMQChannel channel); /* * Thread pool task execution callback * * Calls through to the channel to do the actual work * returns 'true' if the thread pool should remove this task * returns 'false' if the thread pool should requeue this task */ bool run(); private: SmartPtrAMQChannel _channel; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ChannelTask); }; CAF_DECLARE_SMART_POINTER(ChannelTask); private: static const uint8 DEBUGLOG_FLAG_ENTRYEXIT; static const uint8 DEBUGLOG_FLAG_AMQP; bool _isInitialized; volatile bool _isOpen; uint8 _debugLogFlags; SmartPtrIConnectionInt _connection; SmartPtrConsumerWorkService _workService; SmartPtrConsumerDispatcher _dispatcher; uint16 _channelNumber; SmartPtrCAmqpChannel _channelHandle; SmartPtrAMQCommand _command; SmartPtrIRpcContinuation _activeRpc; SmartPtrCAutoMutex _channelMutex; CThreadSignal _channelSignal; typedef std::deque ReturnListenerCollection; typedef TCopyOnWriteContainer CowReturnListenerCollection; CowReturnListenerCollection _returnListeners; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(AMQChannel); }; }} #endif /* AMQCHANNEL_H_ */ AMQChannelManager.h000066400000000000000000000050321321503522500367740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQCHANNELMANAGER_H_ #define AMQCHANNELMANAGER_H_ #include "Exception/CCafException.h" #include "amqpClient/AMQChannel.h" #include "amqpClient/ConsumerWorkService.h" #include "amqpClient/api/Channel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Manages a set of channels for a connection. * Channels are indexed by channel number (1.._channelMax). */ class AMQChannelManager { public: AMQChannelManager(); virtual ~AMQChannelManager(); public: /** * @brief Initialize the manager to control channelMax channels. * @param workService the service (thread pool) to run the channels in */ void init(const SmartPtrConsumerWorkService& workService); /** * @brief Create a new channel * @param connection The controlling #Caf::AmqpClient::IConnectionInt connection * @return the new Channel */ SmartPtrChannel createChannel(const SmartPtrIConnectionInt& connection); /** * @brief Return an existing channel on this connection. * @param channelNumber the number of the required channel * @return the #Caf::AmqpClient::Channel interface to the channel if it exists else * throws an exception */ SmartPtrChannel getChannel(const uint16 channelNumber); /** * @brief Return the number of open channels * @return the number of open channels */ size_t getOpenChannelCount(); /** * @brief Notify all channels that the connection is closed and the reason for it * @param shutdownException the exception (reason) for the closure */ void notifyConnectionClose(SmartPtrCCafException& shutdownException); /** * @brief Close achannel with the supplied reason * @param channelNumber the channel to close * @param reason the reason for closure */ void closeChannel(const uint16 channelNumber, SmartPtrCCafException& reason); /** * @brief Remove a channel from management * @param channelNumber channel number */ void removeChannel(const uint16 channelNumber); private: typedef std::map ChannelMap; bool _isInitialized; ChannelMap _channelMap; SmartPtrConsumerWorkService _workService; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(AMQChannelManager); }; CAF_DECLARE_SMART_POINTER(AMQChannelManager); }} #endif /* AMQCHANNELMANAGER_H_ */ AMQCommand.h000066400000000000000000000033161321503522500355120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQCOMMAND_H_ #define AMQCOMMAND_H_ #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/CommandAssembler.h" #include "amqpClient/amqpImpl/IContentHeader.h" #include "amqpClient/amqpImpl/IMethod.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief This class represents an AMQP command *

* This class wraps up the method, content header and body information for an * incoming AMQP command. */ class AMQCommand { public: AMQCommand(); virtual ~AMQCommand(); /** * @brief Prepare the object for frame processing */ void init(); /** * @brief Process an AMQP frame * @param frame amqp frame data */ bool handleFrame(const SmartPtrCAmqpFrame& frame); /** * @brief Return the body if available * @return the body's raw bytes if available or a null object */ SmartPtrCDynamicByteArray getContentBody(); /** * @brief Return the content header if available * @return the IContentHeader if available or a * null object */ SmartPtrIContentHeader getContentHeader(); /** * @brief Return the method * @return the IMethod object interface representing the method. * QueryInterface must be used to get to the actual method object */ SmartPtrIMethod getMethod(); private: SmartPtrCommandAssembler _assembler; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(AMQCommand); }; CAF_DECLARE_SMART_POINTER(AMQCommand); }} #endif /* AMQCOMMAND_H_ */ AMQConnection.h000066400000000000000000000073421321503522500362360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQCONNECTION_H_ #define AMQCONNECTION_H_ #include "Common/CThreadSignal.h" #include "amqpClient/CAmqpChannel.h" #include "Common/CManagedThreadPool.h" #include "amqpClient/AMQChannelManager.h" #include "amqpClient/CAmqpAuthMechanism.h" #include "amqpClient/CAmqpConnection.h" #include "amqpClient/ConnectionWeakReference.h" #include "amqpClient/ConsumerWorkService.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" #include "amqpClient/api/Channel.h" #include "amqpClient/IConnectionInt.h" #include "amqpClient/api/Connection.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Concrete class representing and managing an AMQP connection to a broker. *

* To create a broker connection, use a ConnectionFactory created * by calling #createConnectionFactory */ class AMQConnection : public Connection, public IConnectionInt { public: AMQConnection(); virtual ~AMQConnection(); public: /** * @brief Initialize the connection. * @param username name used to establish connection * @param password for username * @param address info needed to establish connection * @param certInfo info needed to establish a secure connection * @param requestedFrameMax max size of frame * @param requestedChannelMax max number of channels * @param requestedHeartbeat hearbeat in seconds * @param connectionTimeout connection timeout in milliseconds * @param consumerThreadCount number of consumer threads */ void init( const std::string username, const std::string password, const SmartPtrAddress& address, const SmartPtrCertInfo& certInfo, const uint32 requestedFrameMax, const uint32 requestedChannelMax, const uint32 requestedHeartbeat, const uint32 connectionTimeout, const uint32 consumerThreadCount, const uint16 retries, const uint16 secondsToWait); /** * @brief Start up the connection. */ void start(); public: // Connection SmartPtrChannel createChannel(); void closeChannel(const SmartPtrChannel& channel); void close(); bool isOpen(); public: // IConnectionInt AMQPStatus amqpConnectionOpenChannel(SmartPtrCAmqpChannel& channel); void notifyChannelClosedByServer(const uint16 channelNumber); void channelCloseChannel(Channel *channel); private: void initConnection(); static void closeChannel( const bool isRunning, const SmartPtrAMQChannelManager channelManager, const SmartPtrChannel& channel); static SmartPtrChannel createChannel( const bool isRunning, const SmartPtrAMQChannelManager& channelManager, const SmartPtrConnectionWeakReference& weakReferenceSelf); static void* threadFunc(void* context); void threadWorker(); private: bool _isInitialized; volatile bool _isRunning; volatile bool _shouldShutdown; bool _wasCloseCalled; GThread* _thread; CThreadSignal _connectionSignal; SmartPtrAddress _address; SmartPtrCertInfo _certInfo; uint32 _connectionTimeout; SmartPtrCAmqpConnection _connectionHandle; uint32 _requestedFrameMax; uint32 _requestedChannelMax; uint32 _requestedHeartbeat; uint16 _retries; uint16 _secondsToWait; SmartPtrCAmqpAuthMechanism _authMechanism; SmartPtrAMQChannelManager _channelManager; SmartPtrConnectionWeakReference _weakReferenceSelf; SmartPtrCManagedThreadPool _threadPool; SmartPtrConsumerWorkService _workService; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_CREATE_LOG; CAF_THREADSIGNAL_CREATE; CAF_CM_DECLARE_NOCOPY(AMQConnection); }; CAF_DECLARE_SMART_POINTER(AMQConnection); }} #endif /* AMQCONNECTION_H_ */ AmqpClientLink.h000066400000000000000000000010031321503522500364370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Author: bwilliams * Created: 10/19/2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQP_CLIENTLINK_H_ #define AMQP_CLIENTLINK_H_ #ifndef AMQPCLIENT_LINKAGE #ifdef WIN32 #ifdef AMQP_CLIENT #define AMQPCLIENT_LINKAGE __declspec(dllexport) #else #define AMQPCLIENT_LINKAGE __declspec(dllimport) #endif #else #define AMQPCLIENT_LINKAGE #endif #endif #endif /* AMQP_CLIENTLINK_H_ */ BlockingRpcContinuation.h000066400000000000000000000036521321503522500403700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BLOCKINGRPCCONTINUATION_H_ #define BLOCKINGRPCCONTINUATION_H_ #include "amqpClient/IRpcContinuation.h" #include "Exception/CCafException.h" #include "amqpClient/AMQCommand.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @brief A IRpcContinuation that blocks until the response is received. * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API */ class BlockingRpcContinuation : public IRpcContinuation { public: BlockingRpcContinuation(); virtual ~BlockingRpcContinuation(); /** * @brief Initialize the object */ void init(); /** * @brief Waits indefinately for a response to an AMQP method call * @retval null if an error occured. In this case call getException to get the exception * @retval non-null AMQCommand response */ SmartPtrAMQCommand getReply(); /** * @brief Waits for a time for a response to an AMQP method call * @param timeout time in milliseconds to wait for a response * @retval null if an error occured. In this case call getException to get the exception * @retval non-null AMQCommand response */ SmartPtrAMQCommand getReply(uint32 timeout); /** * @brief Returns the exception that occured if getReply returns null. * @return the exception. The returned exception will have its reference count increased. */ SmartPtrCCafException getException(); public: // IRpcContinuation void handleCommand(const SmartPtrAMQCommand& command); void handleAbort(SmartPtrCCafException exception); private: bool _isInitialized; TBlockingCell _blocker; SmartPtrCCafException _exception; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BlockingRpcContinuation); }; CAF_DECLARE_SMART_POINTER(BlockingRpcContinuation); }} #endif /* BLOCKINGRPCCONTINUATION_H_ */ CAmqpAuthMechanism.h000066400000000000000000000020041321503522500372360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENT_CAMQPAUTHMECHANISM_H_ #define AMQPCLIENT_CAMQPAUTHMECHANISM_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Manages a set of channels for a connection. * Channels are indexed by channel number (1.._channelMax). */ class CAmqpAuthMechanism { public: CAmqpAuthMechanism(); virtual ~CAmqpAuthMechanism(); public: AMQPStatus createClient( const std::string& username, const std::string& password); std::string getUsername() const; std::string getPassword() const; private: std::string _username; std::string _password; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CAmqpAuthMechanism); }; CAF_DECLARE_SMART_POINTER(CAmqpAuthMechanism); }} #endif /* AMQPCLIENT_CAMQPAUTHMECHANISM_H_ */ CAmqpChannel.h000066400000000000000000000060041321503522500360640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENT_CAMQPCHANNEL_H_ #define AMQPCLIENT_CAMQPCHANNEL_H_ #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/CAmqpConnection.h" #include "amqpClient/CAmqpFrame.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Manages a set of channels for a connection. * Channels are indexed by channel number (1.._channelMax). */ class CAmqpChannel { public: CAmqpChannel(); virtual ~CAmqpChannel(); void initialize( const SmartPtrCAmqpConnection& connection, const amqp_channel_t& channel); public: AMQPStatus close(); AMQPStatus closeOk(); AMQPStatus receive( SmartPtrCAmqpFrame& frame, int32 timeout); AMQPStatus getId( uint16 *id); AMQPStatus basicAck( const uint64 deliveryTag, const bool multiple); AMQPStatus basicCancel( const std::string& consumerTag, const bool noWait); AMQPStatus basicConsume( const std::string& queue, const std::string& consumerTag, const bool noLocal, const bool noAck, const bool exclusive, const bool noWait, const amqp_table_t *arguments); AMQPStatus basicGet( const std::string& queue, const bool noAck); AMQPStatus basicPublish( const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const amqp_basic_properties_t *basicProps, const SmartPtrCDynamicByteArray& body); AMQPStatus basicRecover( const bool requeue); AMQPStatus basicQos( const uint32 prefetchSize, const uint16 prefetchCount, bool global); AMQPStatus exchangeDeclare( const std::string& exchange, const std::string& type, const bool passive, const bool durable, const bool noWait, const amqp_table_t *arguments); AMQPStatus exchangeDelete( const std::string& exchange, const bool ifUnused, const bool noWait); AMQPStatus queueBind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const bool noWait, const amqp_table_t *arguments); AMQPStatus queueDeclare( const std::string& queue, const bool passive, const bool durable, const bool exclusive, const bool autoDelete, const bool noWait, const amqp_table_t *arguments); AMQPStatus queueDelete( const std::string& queue, const bool ifUnused, const bool ifEmpty, const bool noWait); AMQPStatus queuePurge( const std::string& queue, const bool noWait); AMQPStatus queueUnbind( const std::string& queue, const std::string& exchange, const std::string& bindingKey, const amqp_table_t *arguments); private: bool _isInitialized; SmartPtrCAmqpConnection _connection; amqp_channel_t _channel; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CAmqpChannel); }; }} #endif /* AMQPCLIENT_CAMQPCHANNEL_H_ */ CAmqpConnection.h000066400000000000000000000140051321503522500366130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENT_CAMQPCONNECTION_H_ #define AMQPCLIENT_CAMQPCONNECTION_H_ #include "amqpClient/CAmqpChannel.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/CAmqpAuthMechanism.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" namespace Caf { namespace AmqpClient { /** Connection states. */ typedef enum { AMQP_STATE_INITIALIZED = 0, /*!< New connection. */ AMQP_STATE_CONNECTING, /*!< Connection in progress. */ AMQP_STATE_CONNECTED, /*!< Connected. */ AMQP_STATE_DISCONNECTING, /*!< Disconnection in process. */ AMQP_STATE_DISCONNECTED, /*!< Disconnected. */ } AMQPConnectionState; /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Manages a set of channels for a connection. * Channels are indexed by channel number (1.._channelMax). */ class CAmqpConnection { private: typedef std::deque CAmqpFrames; typedef std::map CChannelFrames; CAF_DECLARE_SMART_POINTER(CChannelFrames); typedef std::set COpenChannels; CAF_DECLARE_SMART_POINTER(COpenChannels); public: CAmqpConnection(); virtual ~CAmqpConnection(); public: AMQPStatus connectionCreate( const SmartPtrAddress& address, const SmartPtrCAmqpAuthMechanism& auth, const SmartPtrCertInfo& certInfo, const uint16 channelMax, const uint32 frameMax, const uint16 heartbeat, const uint16 retries, const uint16 secondsToWait); AMQPStatus connectionConnect( const int32 flags); AMQPStatus connectionClose(); AMQPStatus connectionProcessIO(); AMQPStatus connectionWaitForIO( const int32 timeout); AMQPStatus connectionGetState( AMQPConnectionState *state); AMQPStatus connectionGetMaxChannels( uint16 *channels); AMQPStatus connectionGetMaxFrameSize( uint32 *frameSize); AMQPStatus connectionGetHeartbeatInterval( uint16 *interval); AMQPStatus connectionGetLastError( const char **error); AMQPStatus channelOpen( SmartPtrCAmqpChannel& chan); AMQPStatus channelClose( const amqp_channel_t& channel); AMQPStatus channelCloseOk( const amqp_channel_t& channel); AMQPStatus receive( const amqp_channel_t& channel, SmartPtrCAmqpFrame& frame, const int32 timeout); AMQPStatus basicAck( const amqp_channel_t& channel, const uint64 deliveryTag, const bool multiple); AMQPStatus basicCancel( const amqp_channel_t& channel, const std::string& consumerTag, const bool noWait); AMQPStatus basicConsume( const amqp_channel_t& channel, const std::string& queue, const std::string& consumerTag, const bool noLocal, const bool noAck, const bool exclusive, const bool noWait, const amqp_table_t *arguments); AMQPStatus basicGet( const amqp_channel_t& channel, const std::string& queue, const bool noAck); AMQPStatus basicPublish( const amqp_channel_t& channel, const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const amqp_basic_properties_t *basicProps, const SmartPtrCDynamicByteArray& body); AMQPStatus basicRecover( const amqp_channel_t& channel, const bool requeue); AMQPStatus basicQos( const amqp_channel_t& channel, const uint32 prefetchSize, const uint16 prefetchCount, const bool global); AMQPStatus exchangeDeclare( const amqp_channel_t& channel, const std::string& exchange, const std::string& type, const bool passive, const bool durable, const bool noWait, const amqp_table_t *arguments); AMQPStatus exchangeDelete( const amqp_channel_t& channel, const std::string& exchange, const bool ifUnused, const bool noWait); AMQPStatus queueBind( const amqp_channel_t& channel, const std::string& queue, const std::string& exchange, const std::string& routingKey, const bool noWait, const amqp_table_t *arguments); AMQPStatus queueDeclare( const amqp_channel_t& channel, const std::string& queue, const bool passive, const bool durable, const bool exclusive, const bool autoDelete, const bool noWait, const amqp_table_t *arguments); AMQPStatus queueDelete( const amqp_channel_t& channel, const std::string& queue, const bool ifUnused, const bool ifEmpty, const bool noWait); AMQPStatus queuePurge( const amqp_channel_t& channel, const std::string& queue, const bool noWait); AMQPStatus queueUnbind( const amqp_channel_t& channel, const std::string& queue, const std::string& exchange, const std::string& routingKey, const amqp_table_t *arguments); private: AMQPStatus createConnection(); AMQPStatus createSslConnection(); AMQPStatus connectConnection(); AMQPStatus closeConnection(); AMQPStatus closeChannel( const amqp_channel_t& channel); int32 receiveFrame( const amqp_connection_state_t& connectionState, SmartPtrCAmqpFrame& frame) const; void addFrames( const CAmqpFrames& frames, const SmartPtrCChannelFrames& channelFrames) const; bool isDataAvail( const amqp_connection_state_t& connectionState) const; void validateOpenChannel( const amqp_channel_t& channel) const; void restartListener( const std::string& reason) const; private: amqp_connection_state_t _connectionState; amqp_socket_t* _socket; amqp_channel_t _curChannel; AMQPConnectionState _connectionStateEnum; bool _isConnectionLost; int32 _lastStatus; SmartPtrCAmqpAuthMechanism _auth; uint16 _channelMax; uint32 _frameMax; uint16 _heartbeat; uint16 _retries; uint16 _secondsToWait; SmartPtrAddress _address; SmartPtrCertInfo _certInfo; SmartPtrCChannelFrames _channelFrames; Csetstr _cachedStrings; COpenChannels _openChannels; private: CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CAmqpConnection); }; }} #endif /* AMQPCLIENT_CAMQPCONNECTION_H_ */ CAmqpFrame.h000066400000000000000000000026171321503522500355540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENT_CAMQPFRAME_H_ #define AMQPCLIENT_CAMQPFRAME_H_ #include "amqp.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Manages a set of channels for a connection. * Channels are indexed by channel number (1.._channelMax). */ class CAmqpFrame { public: CAmqpFrame(); virtual ~CAmqpFrame(); public: void initialize( const amqp_frame_t& frame); uint8_t getFrameType() const; amqp_channel_t getChannel() const; const amqp_method_t* const getPayloadAsMethod() const; uint16_t getHeaderClassId() const; uint64_t getHeaderBodySize() const; const amqp_basic_properties_t* const getHeaderProperties() const; const amqp_bytes_t* const getBodyFragment() const; void log(const std::string& prefix) const; private: bool _isInitialized; uint8_t _frameType; amqp_channel_t _channel; amqp_method_t _method; uint16_t _propertiesClassId; uint64_t _propertiesBodySize; amqp_basic_properties_t* _propertiesDecoded; amqp_bytes_t _bodyFragment; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CAmqpFrame); }; CAF_DECLARE_SMART_POINTER(CAmqpFrame); }} #endif /* AMQPCLIENT_CAMQPFRAME_H_ */ CommandAssembler.h000066400000000000000000000052031321503522500370060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef COMMANDASSEMBLER_H_ #define COMMANDASSEMBLER_H_ #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/amqpImpl/IContentHeader.h" #include "amqpClient/amqpImpl/IMethod.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief A class that manages the assembly of AMQP frames into a complete AMQP method */ class CommandAssembler { public: CommandAssembler(); virtual ~CommandAssembler(); /** * @brief Initialize the object */ void init(); /** * @brief Process the AMQP frame * @param frame AMQP frame * @retval true all of the frames have been received and the AMQP method is complete * @retval false more frames are required to complete the AMQP method */ bool handleFrame(const SmartPtrCAmqpFrame& frame); /** * @brief Return the completion status of the method * @retval true all frames have been received and the AMQP method is complete * @retval false more frames are required to complete the AMQP method */ bool isComplete(); /** * @brief Return the Method * @return the interface to the Method. QueryInterface to the appropriate * derived type based on the class ID and method ID. */ SmartPtrIMethod getMethod(); /** * @brief Return the ContentHeader * @return the interface to the ContentHeader. QueryInterface to the appropriate * derived type based on the class ID. */ SmartPtrIContentHeader getContentHeader(); /** * @brief Return the method body * @return the method body data as raw bytes */ SmartPtrCDynamicByteArray getContentBody(); private: typedef enum { EXPECTING_METHOD, EXPECTING_CONTENT_HEADER, EXPECTING_CONTENT_BODY, COMPLETE } CAState; typedef std::deque CBodyCollection; private: void consumeBodyFrame(const SmartPtrCAmqpFrame& frame); void consumeHeaderFrame(const SmartPtrCAmqpFrame& frame); void consumeMethodFrame(const SmartPtrCAmqpFrame& frame); void updateContentBodyState(); void appendBodyFragment(const amqp_bytes_t * const fragment); SmartPtrCDynamicByteArray coalesceContentBody(); private: bool _isInitialized; CAState _state; SmartPtrIMethod _method; SmartPtrIContentHeader _contentHeader; uint32 _remainingBodyBytes; CBodyCollection _bodyCollection; uint32 _bodyLength; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CommandAssembler); }; CAF_DECLARE_SMART_POINTER(CommandAssembler); }} #endif /* COMMANDASSEMBLER_H_ */ ConnectionFactoryImpl.h000066400000000000000000000054711321503522500400520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CONNECTIONFACTORYIMPL_H_ #define CONNECTIONFACTORYIMPL_H_ #include "amqpClient/api/ConnectionFactory.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" #include "amqpClient/api/Connection.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of ConnectionFactory */ class ConnectionFactoryImpl : public ConnectionFactory { public: ConnectionFactoryImpl(); virtual ~ConnectionFactoryImpl(); public: // ConectionFactory std::string getProtocol() const; void setProtocol(const std::string& host); std::string getHost() const; void setHost(const std::string& host); uint32 getPort() const; void setPort(const uint32 port); std::string getVirtualHost() const; void setVirtualHost(const std::string& virtualHost); std::string getUsername() const; void setUsername(const std::string& username); std::string getPassword() const; void setPassword(const std::string& password); std::string getCaCertPath() const; void setCaCertPath(const std::string& caCertPath); std::string getClientCertPath() const; void setClientCertPath(const std::string& clientCertPath); std::string getClientKeyPath() const; void setClientKeyPath(const std::string& clientKeyPath); uint32 getRequestedChannelMax() const; void setRequestedChannelMax(const uint32 requestedChannelMax); uint32 getRequestedFrameMax() const; void setRequestedFrameMax(const uint32 requestedFrameMax); uint32 getRequestedHeartbeat() const; void setRequestedHeartbeat(const uint32 requestedHeartbeat); uint32 getConnectionTimeout() const; void setConnectionTimeout(const uint32 connectionTimeout); uint32 getConsumerThreadCount() const; void setConsumerThreadCount(const uint32 threadCount); uint16 getRetries() const; void setRetries(const uint16 retries); uint16 getSecondsToWait() const; void setSecondsToWait(const uint16 seconds); SmartPtrConnection newConnection(); SmartPtrConnection newConnection( const SmartPtrAddress& address, const SmartPtrCertInfo& certInfo); private: uint32 portOrDefault(const uint32 port) const; private: std::string _protocol; std::string _host; uint32 _port; std::string _virtualHost; std::string _username; std::string _password; std::string _caCertPath; std::string _clientCertPath; std::string _clientKeyPath; uint32 _requestedChannelMax; uint32 _requestedFrameMax; uint32 _requestedHeartbeat; uint32 _connectionTimeout; uint32 _consumerThreadCount; uint16 _retries; uint16 _secondsToWait; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ConnectionFactoryImpl); }; CAF_DECLARE_SMART_POINTER(ConnectionFactoryImpl); }} #endif ConnectionWeakReference.h000066400000000000000000000032521321503522500403220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CONNECTIONWEAKREFERENCE_H_ #define CONNECTIONWEAKREFERENCE_H_ #include "amqpClient/IConnectionInt.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief This class manages a weak reference to a IConnectionInt object. *

* The channel manager needs a reference to its connection. The connection object * has a reference to the channel manager. To break this reference cycle the channel * manager will be handed weak references to the connection. */ class ConnectionWeakReference : public IConnectionInt { public: ConnectionWeakReference(); virtual ~ConnectionWeakReference(); public: /** * @brief Sets the weakly referenced object * @param connection the weakly referenced object */ void setReference(IConnectionInt* connection); /** * @brief Clears the weakly referenced object. * * Calls to any Connection method on this object will result in a thrown * exception after this method has been called. */ void clearReference(); public: // IConnectionInt AMQPStatus amqpConnectionOpenChannel(SmartPtrCAmqpChannel& channel); void notifyChannelClosedByServer(const uint16 channelNumber); void channelCloseChannel(Channel *channel); private: IConnectionInt* _connection; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(ConnectionWeakReference); }; CAF_DECLARE_SMART_POINTER(ConnectionWeakReference); }} #endif /* CONNECTIONWEAKREFERENCE_H_ */ ConsumerDispatcher.h000066400000000000000000000120321321503522500373720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CONSUMERDISPATCHER_H_ #define CONSUMERDISPATCHER_H_ #include "ICafObject.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Exception/CCafException.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/ConsumerWorkService.h" #include "amqpClient/api/Consumer.h" #include "amqpClient/api/Envelope.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Dispatches notifications to a {@link Consumer} on an internally-managed work pool. *

* Each {@link Channel} has a single {@link ConsumerDispatcher}, but the work pool may be * shared with other channels, typically those on the name {@link AMQConnection}. */ class ConsumerDispatcher { public: ConsumerDispatcher(); virtual ~ConsumerDispatcher(); /** * @brief Initialize the object * @param workService work service providing a work pool for dispatching notifications */ void init( const SmartPtrConsumerWorkService& workService); /** * @brief Prepare for shutdown of all consumers on this channel */ void quiesce(); /** * @brief Lock the dispatcher *

* Place a lock on the dispatcher. All threads attemping to call the dispatcher will * be blocked until unlock is called. */ void lock(); /** * @brief unlock the dispatcher *

* Remove the lock on the dispatcher. */ void unlock(); /** * @brief Adds a consumer to the dispatcher * @param consumerTag consumer tag * @param consumer consumer object */ void addConsumer( const std::string& consumerTag, const SmartPtrConsumer& consumer); /** * @brief Removes a consumer from the dispatcher * @param consumerTag consumer tag */ void removeConsumer( const std::string& consumerTag); /** * @brief Retrieves a consumer from the dispatcher * @param consumerTag consumer tag * @return the consumer or null if not found */ SmartPtrConsumer getConsumer( const std::string& consumerTag); /** * @brief Handle basic.consume-ok * @param consumerTag consumer tag */ void handleConsumeOk( const std::string& consumerTag); /** * @brief Handle basic.cancel-ok * @param consumerTag consumer tag */ void handleCancelOk( const std::string& consumerTag); /** * @brief Handle basic.recover-ok */ void handleRecoverOk(); /** * @brief Handle basic.delivery * @param consumerTag consumer tag * @param envelope message envelope * @param properties message properties and headers * @param body message body */ void handleDelivery( const std::string& consumerTag, const SmartPtrEnvelope& envelope, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); /** * @brief Handle a channel shutdown event * @param exception reason for the shutdown */ void handleShutdown(SmartPtrCCafException exception); private: // Task support typedef enum { DISPATCH_ITEM_METHOD_HANDLE_CONSUME_OK, DISPATCH_ITEM_METHOD_HANDLE_CANCEL_OK, DISPATCH_ITEM_METHOD_HANDLE_RECOVER_OK, DISPATCH_ITEM_METHOD_HANDLE_DELIVERY, DISPATCH_ITEM_METHOD_TERMINATE } DispatchItemMethod; class DispatcherWorkItem : public ICafObject { public: DispatcherWorkItem(); void init( const DispatchItemMethod method); void init( const DispatchItemMethod method, const SmartPtrEnvelope& envelope, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); DispatchItemMethod getMethod() const; SmartPtrEnvelope getEnvelope() const; AmqpContentHeaders::SmartPtrBasicProperties getProperties() const; SmartPtrCDynamicByteArray getBody() const; private: DispatchItemMethod _method; SmartPtrEnvelope _envelope; AmqpContentHeaders::SmartPtrBasicProperties _properties; SmartPtrCDynamicByteArray _body; }; CAF_DECLARE_SMART_POINTER(DispatcherWorkItem); class DispatcherTask : public CManagedThreadPool::IThreadTask { public: DispatcherTask(); ~DispatcherTask(); void init( const std::string& consumerTag, const SmartPtrConsumer& consumer); void term(); void addWorkItem(const SmartPtrDispatcherWorkItem& workItem); bool run(); private: static void FreeWorkItem(gpointer data); private: std::string _consumerTag; SmartPtrConsumer _consumer; GAsyncQueue *_workItemQueue; }; CAF_DECLARE_SMART_POINTER(DispatcherTask); private: typedef std::pair ConsumerItem; typedef std::map ConsumerMap; ConsumerItem getConsumerItem(const std::string& consumerTag); private: bool _isInitialized; volatile bool _isShuttingDown; SmartPtrConsumerWorkService _workService; ConsumerMap _consumers; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(ConsumerDispatcher); }; CAF_DECLARE_SMART_POINTER(ConsumerDispatcher); }} #endif /* CONSUMERDISPATCHER_H_ */ ConsumerWorkService.h000066400000000000000000000023661321503522500375600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CONSUMERWORKSERVICE_H_ #define CONSUMERWORKSERVICE_H_ #include "Common/CManagedThreadPool.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief This class wraps a thread pool for executing channel worker threads */ class ConsumerWorkService { public: ConsumerWorkService(); virtual ~ConsumerWorkService(); /** * @brief Initializer * @param threadPool the thread pool used to execute channel threads */ void init(const SmartPtrCManagedThreadPool& threadPool); /** * @brief Add a worker thread to the pool * @param task the task to add */ void addWork(const CManagedThreadPool::SmartPtrIThreadTask& task); /** * @brief Respond to a connection-closed notification by terminating the thread pool */ void notifyConnectionClosed(); private: bool _isInitialized; SmartPtrCManagedThreadPool _threadPool; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(ConsumerWorkService); }; CAF_DECLARE_SMART_POINTER(ConsumerWorkService); }} #endif /* CONSUMERWORKSERVICE_H_ */ IConnectionInt.h000066400000000000000000000032301321503522500364530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 8, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef ICONNECTIONINT_H_ #define ICONNECTIONINT_H_ #include "ICafObject.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/Channel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief This interface abstracts the calls to AMQP_ConnectionXXX c-api calls *

* AMQConnection objects pass weak references to themselves to AMQChannel objects * allowing them to make calls against the channel that require the connection handle. */ struct __declspec(novtable) IConnectionInt : public ICafObject { /** * @brief Pass-through for the AMQP_ConnectionOpenChannel call * @param channel the channel handle to be returned * @return the AMQPStatus of the call. If AMQP_ERROR_OK then * channel will be set to a valid channel handle. */ virtual AMQPStatus amqpConnectionOpenChannel(SmartPtrCAmqpChannel& channel) = 0; /** * @brief Callback to notify the connection that a channel has been closed. This * is in reponse to the server sending a channel.close method. * @param channelNumber the channel number */ virtual void notifyChannelClosedByServer(const uint16 channelNumber) = 0; /** * @brief Callback to notify the connection that a channel is being * requested to close. * @param channel Channel to close */ virtual void channelCloseChannel(Channel *channel) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IConnectionInt); }} #endif /* ICONNECTIONINT_H_ */ IRpcContinuation.h000066400000000000000000000023601321503522500370230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef IRPCCONTINUATION_H_ #define IRPCCONTINUATION_H_ #include "ICafObject.h" #include "Exception/CCafException.h" #include "amqpClient/AMQCommand.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Interface for RPC worker objects *

* The channel worker thread will assemble incoming AMQP frames an then process * the compiled frames as an AMQCommand object. If the command object belongs * to an outstanding RPC call, that call will receive the command for processing. */ struct __declspec(novtable) IRpcContinuation : public ICafObject { /** * @brief Process the received AMQP command * @param command the AMQCommand command object */ virtual void handleCommand(const SmartPtrAMQCommand& command) = 0; /** * @brief Abort the command for the reason supplied * @param exception the reason as an exception */ virtual void handleAbort(SmartPtrCCafException exception) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IRpcContinuation); }} #endif /* IRPCCONTINUATION_H_ */ TCopyOnWriteContainer.h000066400000000000000000000031211321503522500400000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef TCOPYONWRITECONTAINER_H_ #define TCOPYONWRITECONTAINER_H_ namespace Caf { namespace AmqpClient { /** * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief An STL container wrapper that implements copy-on-write semantics */ template class TCopyOnWriteContainer { public: typedef TCafSmartPtr > SmartPtrContainer; TCopyOnWriteContainer() { _container.CreateInstance(); } SmartPtrContainer getAll() { return _container; } void add(const ValueType& value) { SmartPtrContainer newContainer; newContainer.CreateInstance(); newContainer->insert( newContainer->begin(), _container->begin(), _container->end()); newContainer->push_back(value); _container = newContainer; } bool remove(const ValueType& value) { bool found = false; SmartPtrContainer newContainer; newContainer.CreateInstance(); SmartPtrContainer currContainer = _container; for (typename Container::const_iterator iter = currContainer->begin(); iter != currContainer->end(); ++iter) { if (*iter == value) { found = true; } else { newContainer->push_back(*iter); } } if (found) { _container = newContainer; } return found; } void clear() { _container.CreateInstance(); } private: SmartPtrContainer _container; }; }} #endif /* TCOPYONWRITECONTAINER_H_ */ amqpImpl/000077500000000000000000000000001321503522500352015ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClientBasicAckMethod.h000066400000000000000000000021301321503522500401470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICACKMETHOD_H_ #define BASICACKMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.ack */ class BasicAckMethod :public IServerMethod { public: BasicAckMethod(); virtual ~BasicAckMethod(); /** * @brief Initialize the method * @param deliveryTag delivery tag * @param ackMultiple acknowledge multiple flag */ void init( const uint64 deliveryTag, const bool ackMultiple); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; uint64 _deliveryTag; bool _ackMultiple; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicAckMethod); }; CAF_DECLARE_SMART_POINTER(BasicAckMethod); }} #endif /* BASICACKMETHOD_H_ */ BasicCancelMethod.h000066400000000000000000000021121321503522500406360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICCANCELMETHOD_H_ #define BASICCANCELMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.cancel */ class BasicCancelMethod : public IServerMethod { public: BasicCancelMethod(); virtual ~BasicCancelMethod(); /** * @brief Initialize the method * @param consumerTag the consumer tag associated with the consumer */ void init( const std::string& consumerTag); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _consumerTag; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicCancelMethod); }; CAF_DECLARE_SMART_POINTER(BasicCancelMethod); }} #endif /* BASICCANCELMETHOD_H_ */ BasicConsumeMethod.h000066400000000000000000000031021321503522500410620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICCONSUMEMETHOD_H_ #define BASICCONSUMEMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.consume */ class BasicConsumeMethod : public IServerMethod { public: BasicConsumeMethod(); virtual ~BasicConsumeMethod(); /** * @brief Initialize the method * @param queue queue name * @param consumerTag consumer tag (or blank for server-generated tag) * @param noLocal do not send messages to the connection that published them * @param noAck no acknowledgement needed * @param exclusive request exclusive consumer access to the queue * @param arguments additional call arguments */ void init( const std::string& queue, const std::string& consumerTag, const bool noLocal, const bool noAck, const bool exclusive, const SmartPtrTable& arguments); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _queue; std::string _consumerTag; bool _noLocal; bool _noAck; bool _exclusive; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicConsumeMethod); }; CAF_DECLARE_SMART_POINTER(BasicConsumeMethod); }} #endif /* BASICCONSUMEMETHOD_H_ */ BasicGetMethod.h000066400000000000000000000021251321503522500401740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICGETMETHOD_H_ #define BASICGETMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.get */ class BasicGetMethod : public IServerMethod { public: BasicGetMethod(); virtual ~BasicGetMethod(); /** * @brief Initialize the method * @param queue queue name * @param noAck no acknowledgement (manual acknowledgement) fag */ void init( const std::string& queue, const bool noAck); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _queue; bool _noAck; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicGetMethod); }; CAF_DECLARE_SMART_POINTER(BasicGetMethod); }} #endif /* BASICGETMETHOD_H_ */ BasicProperties.h000066400000000000000000000104071321503522500404520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICPROPERTIES_H_ #define BASICPROPERTIES_H_ #include "amqpClient/api/amqpClient.h" #include "amqpClient/amqpImpl/IContentHeader.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/api/AmqpContentHeaders.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic properties */ class BasicProperties : public AmqpContentHeaders::BasicProperties, public IContentHeader { CAF_DECL_UUID("db3dbcd6-f241-47ff-b17c-d5cf6addabf8") CAF_BEGIN_QI() CAF_QI_ENTRY(AmqpContentHeaders::BasicProperties) CAF_QI_ENTRY(IContentHeader) CAF_QI_ENTRY(BasicProperties) CAF_END_QI() public: BasicProperties(); virtual ~BasicProperties(); /** * @brief Initialize the properties *

* This version creates an object with no properties. Call the setXXX methods * to add properties. */ void init(); /** * @brief Initialize the properties *

* Set the flags property to the binary 'or' (|) of * BASIC_PROPERTY_XXXX_FLAG constants representing the fields present. *

* Use 0, std::string() or * SmartPtrTable() to skip initialization of fields not included * in the object. */ void init( const uint32 flags, const std::string& contentType, const std::string& contentEncoding, const SmartPtrTable& headers, const uint8 deliveryMode, const uint8 priority, const std::string& correlationId, const std::string& replyTo, const std::string& expiration, const std::string& messageId, const uint64 timestamp, const std::string& type, const std::string& userId, const std::string& appId, const std::string& clusterId); /** * @brief Converts this class instance into a c-api amqp_basic_properties_t struct. *

* The pointers in the c-api struct point at member of this class. This class instance * must be realized as int32 as the return properties is in use. * @param properties the c-api properties structure to be filled out */ void getAsApiProperties(amqp_basic_properties_t& properties); public: // IContentHeader void init(const SmartPtrCAmqpFrame& frame); uint64 getBodySize(); public: // AmqpProperties::BasicProperties, bool areHeadersAvailable(); uint32 getFlags(); std::string getContentType(); void setContentType(const std::string& contentType); std::string getContentEncoding(); void setContentEncoding(const std::string& contentEncoding); SmartPtrTable getHeaders(); void setHeaders(const SmartPtrTable& headers); uint8 getDeliveryMode(); void setDeliveryMode(const uint8 deliveryMode); uint8 getPriority(); void setPriority(const uint8 priority); std::string getCorrelationId(); void setCorrelationId(const std::string& correlationId); std::string getReplyTo(); void setReplyTo(const std::string& replyTo); std::string getExpiration(); void setExpiration(const std::string& expiration); std::string getMessageId(); void setMessageId(const std::string& messageId); uint64 getTimestamp(); void setTimestamp(const uint64 timestamp); std::string getType(); void setType(const std::string& type); std::string getUserId(); void setUserId(const std::string& userId); std::string getAppId(); void setAppId(const std::string& appId); std::string getClusterId(); void setClusterId(const std::string& clusterId); public: // IAmqpContentHeader uint16 getClassId(); std::string getClassName(); private: void ValidatePropertyIsSet( const uint32 flag, const char* propertyName); private: bool _isInitialized; uint32 _flags; uint64 _bodySize; std::string _contentType; std::string _contentEncoding; SmartPtrTable _headers; uint8 _deliveryMode; uint8 _priority; std::string _correlationId; std::string _replyTo; std::string _expiration; std::string _messageId; uint64 _timestamp; std::string _type; std::string _userId; std::string _appId; std::string _clusterId; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicProperties); }; CAF_DECLARE_SMART_QI_POINTER(BasicProperties); }} #endif /* BASICPROPERTIES_H_ */ BasicPublishMethod.h000066400000000000000000000032311321503522500410620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICPUBLISHMETHOD_H_ #define BASICPUBLISHMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.publish */ class BasicPublishMethod : public IServerMethod { public: BasicPublishMethod(); virtual ~BasicPublishMethod(); /** * @brief Initialize the method * @param exchange exchange name * @param routingKey routing key * @param mandatory mandatory delivery flag * @param immediate immediate delivery flag * @param properties message properties * @param body message body raw bytes */ void init( const std::string& exchange, const std::string& routingKey, bool mandatory, bool immediate, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _exchange; std::string _routingKey; bool _mandatory; bool _immediate; AmqpContentHeaders::SmartPtrBasicProperties _properties; SmartPtrCDynamicByteArray _body; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicPublishMethod); }; CAF_DECLARE_SMART_POINTER(BasicPublishMethod); }} #endif /* BASICPUBLISHMETHOD_H_ */ BasicQosMethod.h000066400000000000000000000023121321503522500402150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 22, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICQOSMETHOD_H_ #define BASICQOSMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.qos */ class BasicQosMethod : public IServerMethod { public: BasicQosMethod(); virtual ~BasicQosMethod(); /** * @brief Initialize the method * @param prefetchSize prefetch window in octets * @param prefetchCount prefetch windows in messages * @param global apply to entire connection */ void init( const uint32 prefetchSize, const uint16 prefetchCount, const bool global); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; uint32 _prefetchSize; uint16 _prefetchCount; bool _global; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicQosMethod); }; CAF_DECLARE_SMART_POINTER(BasicQosMethod); }} #endif /* BASICQOSMETHOD_H_ */ BasicRecoverMethod.h000066400000000000000000000023531321503522500410650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICRECOVERMETHOD_H_ #define BASICRECOVERMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.recover */ class BasicRecoverMethod : public IServerMethod { public: BasicRecoverMethod(); virtual ~BasicRecoverMethod(); /** * @brief Initialize the method * @param requeue if false, the message will be redelivered to the * original receipient. If true, the server will attempt to requeue * the message, potentially delivering it to an alternative subscriber. */ void init( const bool requeue); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; bool _requeue; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicRecoverMethod); }; CAF_DECLARE_SMART_POINTER(BasicRecoverMethod); }} #endif /* BASICRECOVERMETHOD_H_ */ BasicRejectMethod.h000066400000000000000000000021361321503522500406730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: Aug 1, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICREJECTMETHOD_H_ #define BASICREJECTMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.Reject */ class BasicRejectMethod : public IServerMethod { public: BasicRejectMethod(); virtual ~BasicRejectMethod(); /** * @brief Initialize the method * @param deliveryTag delivery tag * @param requeue requeue flag */ void init( const uint64 deliveryTag, const bool requeue); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; uint64 _deliveryTag; bool _requeue; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicRejectMethod); }; CAF_DECLARE_SMART_POINTER(BasicRejectMethod); }} #endif /* BASICREJECTMETHOD_H_ */ ChannelCloseOkMethod.h000066400000000000000000000017231321503522500413460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 17, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHANNELCLOSEOKMETHOD_H_ #define CHANNELCLOSEOKMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementatin of AMQP channel.close-ok */ class ChannelCloseOkMethod :public IServerMethod { public: ChannelCloseOkMethod(); virtual ~ChannelCloseOkMethod(); /** * Initialize the method */ void init(); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ChannelCloseOkMethod); }; CAF_DECLARE_SMART_POINTER(ChannelCloseOkMethod); }} #endif /* CHANNELCLOSEOKMETHOD_H_ */ EnvelopeImpl.h000066400000000000000000000023071321503522500377530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef ENVELOPEIMPL_H_ #define ENVELOPEIMPL_H_ #include "amqpClient/api/Envelope.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of Envelope */ class EnvelopeImpl : public Envelope { public: EnvelopeImpl(); virtual ~EnvelopeImpl(); /** * @brief Initialize the object * @param deliveryTag delivery tag * @param redelivered redelivered flag * @param exchange exchange name * @param routingKey routing key */ void init( const uint64 deliveryTag, const bool redelivered, const std::string& exchange, const std::string& routingKey); public: // Envelope uint64 getDeliveryTag(); bool getRedelivered(); std::string getExchange(); std::string getRoutingKey(); private: bool _isInitialized; uint64 _deliveryTag; bool _redelivered; std::string _exchange; std::string _routingKey; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(EnvelopeImpl); }; CAF_DECLARE_SMART_POINTER(EnvelopeImpl); }} #endif /* ENVELOPEIMPL_H_ */ ExchangeDeclareMethod.h000066400000000000000000000026351321503522500415230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef EXCHANGEDECLAREMETHOD_H_ #define EXCHANGEDECLAREMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP exchange.declare */ class ExchangeDeclareMethod : public IServerMethod { public: ExchangeDeclareMethod(); virtual ~ExchangeDeclareMethod(); /** * @brief Initializes the method * @param exchange exchange name * @param type exchange type * @param passive passive mode call * @param durable request a durable exchange * @param arguments declaration arguments */ void init( const std::string& exchange, const std::string& type, const bool passive, const bool durable, const SmartPtrTable& arguments); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _exchange; std::string _type; bool _passive; bool _durable; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ExchangeDeclareMethod); }; CAF_DECLARE_SMART_POINTER(ExchangeDeclareMethod); }} #endif /* EXCHANGEDECLAREMETHOD_H_ */ ExchangeDeleteMethod.h000066400000000000000000000022141321503522500413570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef EXCHANGEDELETEMETHOD_H_ #define EXCHANGEDELETEMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP exchange.delete */ class ExchangeDeleteMethod : public IServerMethod { public: ExchangeDeleteMethod(); virtual ~ExchangeDeleteMethod(); /** * @brief Initializes the method * @param exchange exchange name * @param ifUnused delete only if unused flag */ void init( const std::string& exchange, const bool ifUnused); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _exchange; bool _ifUnused; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ExchangeDeleteMethod); }; CAF_DECLARE_SMART_POINTER(ExchangeDeleteMethod); }} #endif /* EXCHANGEDELETEMETHOD_H_ */ FieldImpl.h000066400000000000000000000013611321503522500372200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef FIELDIMPL_H_ #define FIELDIMPL_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of a Field object */ class FieldImpl : public Field { public: FieldImpl(); virtual ~FieldImpl(); public: // Field AmqpFieldType getAmqpType() const; GVariant* getValue() const; void setTypeAndValue(AmqpFieldType type, GVariant *value); private: AmqpFieldType _type; GVariant *_value; CAF_CM_DECLARE_NOCOPY(FieldImpl); }; CAF_DECLARE_SMART_POINTER(FieldImpl); }} #endif GetResponseImpl.h000066400000000000000000000034341321503522500404360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef GETRESPONSEIMPL_H_ #define GETRESPONSEIMPL_H_ #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/Envelope.h" #include "amqpClient/api/GetResponse.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Impelementation of the GetResponse interface *

* A class to bundle together the information from a received message. The content is * packaged into an Envelope, BasicProperties and the body for easier consumption as * a single unit. */ class GetResponseImpl : public GetResponse { public: GetResponseImpl(); virtual ~GetResponseImpl(); /** * @brief Object initializer * @param envelope the message envelope * @param properties the messsage properties * @param body the message body in raw bytes * @param messageCount the number of messages remaining in the queue */ void init( const SmartPtrEnvelope& envelope, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body, const uint32 messageCount); public: // GetResponse SmartPtrEnvelope getEnvelope(); AmqpContentHeaders::SmartPtrBasicProperties getProperties(); SmartPtrCDynamicByteArray getBody(); uint32 getMessageCount(); private: bool _isInitialized; SmartPtrEnvelope _envelope; AmqpContentHeaders::SmartPtrBasicProperties _properties; SmartPtrCDynamicByteArray _body; uint32 _messageCount; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(GetResponseImpl); }; CAF_DECLARE_SMART_POINTER(GetResponseImpl); }} #endif /* GETRESPONSEIMPL_H_ */ IContentHeader.h000066400000000000000000000020121321503522500402010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef ICONTENTHEADER_H_ #define ICONTENTHEADER_H_ #include "amqpClient/CAmqpFrame.h" #include "amqpClient/api/ContentHeader.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Base interface for AMQP content header implementation objects */ struct __declspec(novtable) IContentHeader : public ContentHeader { CAF_DECL_UUID("04068590-3083-446E-83AE-DACD90C0F470") /** * @brief Initialize the header object from c-api properties data * @param properties the properties data */ virtual void init(const SmartPtrCAmqpFrame& frame) = 0; /** * @brief Return the expected method body data size * @return the expected body size */ virtual uint64 getBodySize() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IContentHeader); }} #endif /* ICONTENTHEADER_H_ */ IMethod.h000066400000000000000000000016741321503522500367130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef IMETHOD_H_ #define IMETHOD_H_ #include "amqpClient/api/Method.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Base interface for AMQP method implementation objects */ struct __declspec(novtable) IMethod : public Method { CAF_DECL_UUID("08ba9874-b34c-4afe-bfdc-a12fffaefddb") /** * @brief Initialize the object from c-api method data * @param method the method data */ virtual void init(const amqp_method_t * const method) = 0; /** * @retval true if the method expects a content header * @retval false if the method does not expect a content header */ virtual bool hasContent() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IMethod); }} #endif /* IMETHOD_H_ */ IServerMethod.h000066400000000000000000000017221321503522500400740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef ISERVERMETHOD_H_ #define ISERVERMETHOD_H_ #include "ICafObject.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Base interface for server methods */ struct __declspec(novtable) IServerMethod : public ICafObject { CAF_DECL_UUID("ce585a8d-8b49-4312-b356-6f612142b154") /** * Return the method name * @return the method name */ virtual std::string getMethodName() const = 0; /** * Sends the command to the server * @param channel AMQP channel * @return the c-api AMQPStatus of the call */ virtual AMQPStatus send(const SmartPtrCAmqpChannel& channel) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IServerMethod); }} #endif /* ISERVERMETHOD_H_ */ QueueBindMethod.h000066400000000000000000000024411321503522500403750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEBINDMETHOD_H_ #define QUEUEBINDMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.bind */ class QueueBindMethod : public IServerMethod { public: QueueBindMethod(); virtual ~QueueBindMethod(); /** * @brief Initialize the method * @param queue queue name * @param exchange exchange name * @param routingKey routing key * @param arguments binding arguments */ void init( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _queue; std::string _exchange; std::string _routingKey; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueBindMethod); }; CAF_DECLARE_SMART_POINTER(QueueBindMethod); }} #endif /* QUEUEBINDMETHOD_H_ */ QueueDeclareMethod.h000066400000000000000000000040751321503522500410650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEDECLAREMETHOD_H_ #define QUEUEDECLAREMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.declare */ class QueueDeclareMethod : public IServerMethod { public: QueueDeclareMethod(); virtual ~QueueDeclareMethod(); /** * @brief Initialize the method using defaults *

* The defaults are: * * * * * * * * *
ParameterValue
queueblank - the server will generate a queue name
durablefalse - the queue will not be durable
exclusivetrue - the queue will be exclusive to this conenction
autoDeletetrue - the queue will be deleted when no longer used
*/ void init(); /** * @brief Initialize the method * @param queue queue name * @param durable durable queue flag * @param exclusive exclusive queue flag * @param autoDelete delete when no longer in use flag * @param arguments method arguments */ void init( const std::string& queue, bool durable, bool exclusive, bool autoDelete, const SmartPtrTable& arguments); /** * @brief Initialize the method in passive mode * @param queue queue name */ void initPassive( const std::string& queue); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _queue; bool _passive; bool _durable; bool _exclusive; bool _autoDelete; bool _noWait; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueDeclareMethod); }; CAF_DECLARE_SMART_POINTER(QueueDeclareMethod); }} #endif /* QUEUEDECLAREMETHOD_H_ */ QueueDeleteMethod.h000066400000000000000000000023031321503522500407200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEDELETEMETHOD_H_ #define QUEUEDELETEMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.delete */ class QueueDeleteMethod : public IServerMethod { public: QueueDeleteMethod(); virtual ~QueueDeleteMethod(); /** * @brief Initialize the method * @param queue queue name * @param ifUnused delete if queue is not in use flag * @param ifEmpty delete is queue is empty flag */ void init( const std::string& queue, const bool ifUnused, const bool ifEmpty); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _queue; bool _ifUnused; bool _ifEmpty; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueDeleteMethod); }; CAF_DECLARE_SMART_POINTER(QueueDeleteMethod); }} #endif /* QUEUEDELETEMETHOD_H_ */ QueuePurgeMethod.h000066400000000000000000000020061321503522500406000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEPURGEMETHOD_H_ #define QUEUEPURGEMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.purge */ class QueuePurgeMethod : public IServerMethod { public: QueuePurgeMethod(); virtual ~QueuePurgeMethod(); /** * @brief Initialize the method * @param queue queue name */ void init( const std::string& queue); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _queue; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueuePurgeMethod); }; CAF_DECLARE_SMART_POINTER(QueuePurgeMethod); }} #endif /* QUEUEPURGEMETHOD_H_ */ QueueUnbindMethod.h000066400000000000000000000024641321503522500407450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEUNBINDMETHOD_H_ #define QUEUEUNBINDMETHOD_H_ #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.unbind */ class QueueUnbindMethod : public IServerMethod { public: QueueUnbindMethod(); virtual ~QueueUnbindMethod(); /** * @brief Initialize the method * @param queue queue name * @param exchange exchange name * @param routingKey routing key * @param arguments method arguments */ void init( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments); public: // IServerMethod std::string getMethodName() const; AMQPStatus send(const SmartPtrCAmqpChannel& channel); private: bool _isInitialized; std::string _queue; std::string _exchange; std::string _routingKey; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueUnbindMethod); }; CAF_DECLARE_SMART_POINTER(QueueUnbindMethod); }} #endif /* QUEUEUNBINDMETHOD_H_ */ api/000077500000000000000000000000001321503522500341725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClientAMQExceptions.h000066400000000000000000000076011321503522500370270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 3, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_AMQEXCEPTIONS_H_ #define AMQPCLIENTAPI_AMQEXCEPTIONS_H_ #include "Exception/CCafException.h" #include "amqpClient/AmqpClientLink.h" #define AMQP_CM_DECLARE_EXCEPTION_CLASS(_exclass_) \ class AMQPCLIENT_LINKAGE _exclass_ : public Caf::CCafException { \ public: \ _exclass_(); \ virtual ~_exclass_(); \ void throwSelf(); \ void throwAddRefedSelf(); \ private: \ _exclass_(const _exclass_ &); \ _exclass_ & operator=(const _exclass_ &); \ }; \ typedef TCafSmartPtr<_exclass_, TCafObject<_exclass_> > SmartPtr##_exclass_ #define AMQP_CM_DEFINE_EXCEPTION_CLASS(_exclass_) \ _exclass_::_exclass_() : CCafException( #_exclass_ ) {} \ _exclass_::~_exclass_() {} \ void _exclass_::throwSelf() { throw this; } \ void _exclass_::throwAddRefedSelf() { this->AddRef(); throw this; } namespace Caf { namespace AmqpClient { /** * @author mdonahue * @brief Exceptions defined by this library */ namespace AmqpExceptions { /** @brief Unmapped AMQP exception */ //AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpException); class AMQPCLIENT_LINKAGE AmqpException : public Caf::CCafException { public: AmqpException(); virtual ~AmqpException(); void throwSelf(); void throwAddRefedSelf(); private: AmqpException(const AmqpException &); AmqpException & operator=(const AmqpException &); }; typedef TCafSmartPtr > SmartPtrAmqpException; /** @brief AMQP_ERROR_TIMEOUT exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpTimeoutException); /** @brief AMQP_ERROR_NO_MEMORY exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpNoMemoryException); /** @brief AMQP_ERROR_INVALID_HANDLE exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpInvalidHandleException); /** @brief AMQP_ERROR_INVALID_ARGUMENT exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpInvalidArgumentException); /** @brief AMQP_ERROR_WRONG_STATE exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpWrongStateException); /** @brief AMQP_ERROR_TOO_MANY_CHANNELS exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpTooManyChannelsException); /** @brief AMQP_ERROR_QUEUE_FULL exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpQueueFullException); /** @brief AMQP_ERROR_FRAME_TOO_LARGE exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpFrameTooLargeException); /** @brief AMQP_ERROR_IO_ERROR exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpIoErrorException); /** @brief AMQP_ERROR_PROTOCOL_ERROR exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpProtocolErrorException); /** @brief AMQP_ERROR_UNIMPLEMENTED exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpUnimplementedException); /** @brief AMQP_ERROR_IO_INTERRUPTED exception */ AMQP_CM_DECLARE_EXCEPTION_CLASS(AmqpIoInterruptedException); // Processing exceptions /** @brief Unexpected frame */ AMQP_CM_DECLARE_EXCEPTION_CLASS(UnexpectedFrameException); /** @brief Unknown class or method */ AMQP_CM_DECLARE_EXCEPTION_CLASS(UnknownClassOrMethodException); /** @brief Connection is closed */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ConnectionClosedException); /** @brief Channel is closed */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ChannelClosedException); /** @brief Connection closed because of an error */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ConnectionUnexpectedCloseException); /** @brief Connection closed because of an I/O error */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ConnectionClosedByIOException); /** @brief Channel closed by server because of an error */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ChannelClosedByServerException); /** @brief Channel closed by the application because it is shutting down */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ChannelClosedByShutdownException); /** @brief Channel closed by the application user under normal circumstances */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ChannelClosedByUserException); }}} #endif Address.h000066400000000000000000000031541321503522500357330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 4, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_ADDRESS_H_ #define AMQPCLIENTAPI_ADDRESS_H_ namespace Caf { namespace AmqpClient { /** Supported Protocols */ typedef enum { PROTOCOL_AMQP = 0, PROTOCOL_AMQPS, PROTOCOL_TUNNEL } Protocol; /** * @author mdonahue * @brief A representation of a broker network address */ class Address { public: Address(); virtual ~Address(); public: /** * @brief Construct an address from a protocol, host name, and port number * @param protocol the communication protocol (tcp, ssl, etc.) * @param host the host name or dotted ip address * @param port the port number */ void initialize( const std::string& protocol, const std::string& host, const uint32& port, const std::string& virtualHost = std::string()); /** * @return the protocol */ Protocol getProtocol() const; /** * @return the protocol */ std::string getProtocolStr() const; /** * @return the host name */ std::string getHost() const; /** * @return the port number */ uint32 getPort() const; std::string getVirtualHost() const; std::string toString() const; private: Protocol translateProtocol( const std::string& protocol, const std::string& host) const; private: bool _isInitialized; std::string _protocolStr; Protocol _protocol; std::string _host; uint32 _port; std::string _virtualHost; std::string _toString; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(Address); }; CAF_DECLARE_SMART_POINTER(Address); }} #endif AmqpContentHeaders.h000066400000000000000000000146061321503522500400770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_AMQPCONTENTHEADERS_H_ #define AMQPCLIENTAPI_AMQPCONTENTHEADERS_H_ #include "amqpClient/api/amqpClient.h" #include "amqpClient/amqpImpl/BasicProperties.h" namespace Caf { namespace AmqpClient { /** * @ingroup AmqpApi * @brief AMQP content header objects */ namespace AmqpContentHeaders { /** @brief content type property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_CONTENT_TYPE_FLAG; /** @brief content encoding property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_CONTENT_ENCODING_FLAG; /** @brief headers are present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_HEADERS_FLAG; /** @brief delivery mode property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_DEVLIVERY_MODE_FLAG; /** @brief priority property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_PRIORITY_FLAG; /** @brief correlation id property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_CORRELATION_ID_FLAG; /** @brief reply to property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_REPLY_TO_FLAG; /** @brief expiration property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_EXPIRATION_FLAG; /** @brief message id property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_MESSAGE_ID_FLAG; /** @brief timestamp property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_TIMESTAMP_FLAG; /** @brief type property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_TYPE_FLAG; /** @brief user id property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_USER_ID_FLAG; /** @brief app id property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_APP_ID_FLAG; /** @brief cluster id property is present */ extern AMQPCLIENT_LINKAGE const uint32 BASIC_PROPERTY_CLUSTER_ID_FLAG; /** * @author mdonahue * @ingroup AmqpApi * @brief Basic properties class *

* Review the AMQP protocol documentation for more information. */ struct __declspec(novtable) BasicProperties : public ContentHeader { CAF_DECL_UUID("A6DEE271-36C7-4B46-8EA8-F1F0E3493FC4") /** @return are the headers available? */ virtual bool areHeadersAvailable() = 0; /** * @remark * Use the binary 'and' (&) to test the flags against the * BASIC_PROPERTY_XXXXX_FLAGS * @return the bits representing the properties present in the object */ virtual uint32 getFlags() = 0; /** @return the content type */ virtual std::string getContentType() = 0; /** @brief Set the content type */ virtual void setContentType(const std::string& contentType) = 0; /** @return the content encoding */ virtual std::string getContentEncoding() = 0; /** @brief Set the content encoding */ virtual void setContentEncoding(const std::string& contentEncoding) = 0; /** @return the message headers */ virtual SmartPtrTable getHeaders() = 0; /** @brief Set the headers */ virtual void setHeaders(const SmartPtrTable& headers) = 0; /** @return the delivery mode */ virtual uint8 getDeliveryMode() = 0; /** @brief Set the delivery mode */ virtual void setDeliveryMode(const uint8 deliveryMode) = 0; /** @return the priority */ virtual uint8 getPriority() = 0; /** @brief Set the priority */ virtual void setPriority(const uint8 priority) = 0; /** @return the correlation id */ virtual std::string getCorrelationId() = 0; /** @brief Set the correlation id */ virtual void setCorrelationId(const std::string& correlationId) = 0; /** @return the reply to */ virtual std::string getReplyTo() = 0; /** @brief Set the reply to */ virtual void setReplyTo(const std::string& replyTo) = 0; /** @return the expiration */ virtual std::string getExpiration() = 0; /** @brief Set the expiration */ virtual void setExpiration(const std::string& expiration) = 0; /** @return the message id */ virtual std::string getMessageId() = 0; /** @brief Set the message id */ virtual void setMessageId(const std::string& messageId) = 0; /** @return the timestamp */ virtual uint64 getTimestamp() = 0; /** @brief Set the timestamp */ virtual void setTimestamp(const uint64 timestamp) = 0; /** @return the type */ virtual std::string getType() = 0; /** @brief set the type */ virtual void setType(const std::string& type) = 0; /** @return the user id */ virtual std::string getUserId() = 0; /** @brief Set the user id */ virtual void setUserId(const std::string& userId) = 0; /** @return the app id */ virtual std::string getAppId() = 0; /** @brief Set the app id */ virtual void setAppId(const std::string& appId) = 0; /** @return the cluster id */ virtual std::string getClusterId() = 0; /** @brief Set the cluster id */ virtual void setClusterId(const std::string& clusterId) = 0; }; CAF_DECLARE_SMART_POINTER(BasicProperties); /** * @author mdonahue * @ingroup AmqpApi * @brief Create a #Caf::AmqpClient::AmqpContentHeaders::BasicProperties object to be * sent with a message. *

* The object is created with no fields set. You must call the setXXX * methods before publishing the message. * @return an unpopulated basic properties object */ SmartPtrBasicProperties AMQPCLIENT_LINKAGE createBasicProperties(); /** * @author mdonahue * @ingroup AmqpApi * @brief Create an object containing #Caf::AmqpClient::AmqpContentHeaders::BasicProperties * to be sent with a message *

* Set the flags property to the binary 'or' (|) of * BASIC_PROPERTY_XXXX_FLAG constants representing the fields present. *

* Use 0, std::string() or * SmartPtrTable() to skip initialization of fields not included * in the object. * @return a basic properties object */ SmartPtrBasicProperties AMQPCLIENT_LINKAGE createBasicProperties( const uint32 flags, const std::string& contentType, const std::string& contentEncoding, const SmartPtrTable& headers, const uint8 deliveryMode, const uint8 priority, const std::string& correlationId, const std::string& replyTo, const std::string& expiration, const std::string& messageId, const uint64 timestamp, const std::string& type, const std::string& userId, const std::string& appId, const std::string& clusterId); }}} #endif AmqpMethods.h000066400000000000000000000172051321503522500365720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_AMQPMETHODS_H_ #define AMQPCLIENTAPI_AMQPMETHODS_H_ #include "amqpClient/api/Method.h" namespace Caf { namespace AmqpClient { namespace AmqpMethods { #if (1) // basic /** * @brief AMQP Basic methods * @ingroup AmqpApi */ namespace Basic { /** * @ingroup AmqpApi * @brief Interface representing the basic.get-ok method parameters */ struct __declspec(novtable) GetOk : public Method { CAF_DECL_UUID("A3CD4488-B600-4AC6-9513-03021AC06345") /** @return the delivery tag used for basic.ack calls */ virtual uint64 getDeliveryTag() = 0; /** * @retval true if the message was redelivered * @retval false if the message has not been redlivered */ virtual bool getRedelivered() = 0; /** @return the name of the exchange supplying the message */ virtual std::string getExchange() = 0; /** @return the message's routing key */ virtual std::string getRoutingKey() = 0; /** @return the number of messages remaining in the queue */ virtual uint32 getMessageCount() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(GetOk); /** * @ingroup AmqpApi * @brief Interface representing the basic.get-empty method parameters */ struct __declspec(novtable) GetEmpty : public Method { CAF_DECL_UUID("6bcd3e9e-e2b1-4824-b455-acad073737c5") }; CAF_DECLARE_SMART_INTERFACE_POINTER(GetEmpty); /** * @ingroup AmqpApi * @brief Interface representing the basic.consume-ok method parameters */ struct __declspec(novtable) ConsumeOk : public Method { CAF_DECL_UUID("29E385DA-37FB-48E4-9F6D-463555C9DDDC") virtual std::string getConsumerTag() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ConsumeOk); /** * @ingroup AmqpApi * @brief Interface representing the basic.deliver method parameters */ struct __declspec(novtable) Deliver : public Method { CAF_DECL_UUID("2AD74C5E-CC9D-4A6C-9738-DA836BC25FCA") /** @return the consumer tag associated with the consumer */ virtual std::string getConsumerTag() = 0; /** @return the delivery tag used for basic.ack calls */ virtual uint64 getDeliveryTag() = 0; /** * @retval true if the message was redelivered * @retval false if the message has not been redlivered */ virtual bool getRedelivered() = 0; /** @return the name of the exchange supplying the message */ virtual std::string getExchange() = 0; /** @return the message's routing key */ virtual std::string getRoutingKey() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Deliver); /** * @ingroup AmqpApi * @brief Interface representing the basic.consume-ok method parameters */ struct __declspec(novtable) CancelOk : public Method { CAF_DECL_UUID("759CEE2C-FDA5-4A2A-BFE0-617A879D05BF") /** @return the consumer tag associated with the consumer */ virtual std::string getConsumerTag() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(CancelOk); /** * @ingroup AmqpApi * @brief Interface representing the basic.return method parameters */ struct __declspec(novtable) Return : public Method { CAF_DECL_UUID("000A440E-AEE4-418E-B9A0-9857F5C20283") /** @return the reply code */ virtual uint16 getReplyCode() = 0; /** @return the reply text */ virtual std::string getReplyText() = 0; /** @return the exchnage name */ virtual std::string getExchange() = 0; /** @return the routing key */ virtual std::string getRoutingKey() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Return); /** * @ingroup AmqpApi * @brief Interface representing the basic.recover-ok method parameters */ struct __declspec(novtable) RecoverOk : public Method { CAF_DECL_UUID("DF71DC22-B65C-44FC-A0F4-EFAC181E2F69") }; CAF_DECLARE_SMART_INTERFACE_POINTER(RecoverOk); /** * @ingroup AmqpApi * @brief Interface representing the basic.qos-ok method */ struct __declspec(novtable) QosOk : public Method { CAF_DECL_UUID("D5710B1C-DE05-42F5-9695-95364C1D9468") }; CAF_DECLARE_SMART_INTERFACE_POINTER(QosOk); } // namespace Basic #endif #if (1) // channel /** * @ingroup AmqpApi * @brief AMQP Channel methods */ namespace Channel { /** * @ingroup AmqpApi * @brief Interface representing the channel.open-ok method parameters */ struct __declspec(novtable) OpenOk : public Method { CAF_DECL_UUID("4c027f40-db11-4a72-ac2e-cc8da89035cb") }; CAF_DECLARE_SMART_INTERFACE_POINTER(OpenOk); /** * @ingroup AmqpApi * @brief Interface representing the channel.close method parameters */ struct __declspec(novtable) Close : public Method { CAF_DECL_UUID("45d0c75f-ff48-4552-9a83-498efa5f6ad2") /** @return the reply code */ virtual uint16 getReplyCode() = 0; /** @return the reply text */ virtual std::string getReplyText() = 0; /** @return the class id of the method that caused the close */ virtual uint16 getClassId() = 0; /** @return the method id of the method that caused the close */ virtual uint16 getMethodId() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Close); /** * @ingroup AmqpApi * @brief Interface representing the channel.close-ok method parameters */ struct __declspec(novtable) CloseOk : public Method { CAF_DECL_UUID("DAF11BD3-06B6-4FA4-AC80-2B0959D2297D") }; CAF_DECLARE_SMART_INTERFACE_POINTER(CloseOk); } // namespace Channel #endif #if (1) // exchange /** * @ingroup AmqpApi * @brief AMQP Exchange methods */ namespace Exchange { /** * @ingroup AmqpApi * @brief Interface representing the exchange.declare-ok method parameters */ struct __declspec(novtable) DeclareOk : public Method { CAF_DECL_UUID("e54d9fff-7905-4e18-b1e8-090279a5cffe") }; CAF_DECLARE_SMART_INTERFACE_POINTER(DeclareOk); /** * @ingroup AmqpApi * @brief Interface representing the exchange.delete-ok method parameters */ struct __declspec(novtable) DeleteOk : public Method { CAF_DECL_UUID("9f13d0fb-1bdd-473a-873a-58e948bc256c") }; CAF_DECLARE_SMART_INTERFACE_POINTER(DeleteOk); } // namespace Exchange #endif #if (1) // queue /** * @ingroup AmqpApi * @brief AMQP Queue methods */ namespace Queue { /** * @ingroup AmqpApi * @brief Interface representing the queue.declare-ok method parameters */ struct __declspec(novtable) DeclareOk : public Method { CAF_DECL_UUID("EB96E48E-DF40-4D5F-A41F-7F4EBEBE2BE1") /** @return the name of the queue */ virtual std::string getQueueName() = 0; /** @return the number of messages in the queue */ virtual uint32 getMessageCount() = 0; /** @return the number of active consumers for the queue */ virtual uint32 getConsumerCount() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(DeclareOk); /** * @ingroup AmqpApi * @brief Interface representing the queue.delete-ok method parameters */ struct __declspec(novtable) DeleteOk : public Method { CAF_DECL_UUID("34f4b342-7ab0-44d5-b007-4eec141a4435") /** @return the number of messages deleted */ virtual uint32 getMessageCount() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(DeleteOk); /** * @ingroup AmqpApi * @brief Interface representing the queue.delete-ok method parameters */ struct __declspec(novtable) PurgeOk : public Method { CAF_DECL_UUID("63bcf694-5ac3-4067-8134-659133986099") /** @return the number of messages deleted */ virtual uint32 getMessageCount() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(PurgeOk); /** * @ingroup AmqpApi * @brief Interface representing the queue.bind-ok method parameters */ struct __declspec(novtable) BindOk : public Method { CAF_DECL_UUID("1a60c168-24d1-4184-a5ec-fcf9fca70994") }; CAF_DECLARE_SMART_INTERFACE_POINTER(BindOk); /** * @ingroup AmqpApi * @brief Interface representing the queue.unbind-ok method parameters */ struct __declspec(novtable) UnbindOk : public Method { CAF_DECL_UUID("edf78de1-eee4-44c0-9051-e4f6ee80c0a2") }; CAF_DECLARE_SMART_INTERFACE_POINTER(UnbindOk); } // namespace Queue #endif }}} #endif CertInfo.h000066400000000000000000000015741321503522500360630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 4, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_CERTINFO_H_ #define AMQPCLIENTAPI_CERTINFO_H_ namespace Caf { namespace AmqpClient { /** * @author bwilliams * @brief A representation of Cert Info */ class CertInfo { public: CertInfo(); virtual ~CertInfo(); public: void initialize( const std::string& caCertPath, const std::string& clientCertPath, const std::string& clientKeyPath); std::string getCaCertPath() const; std::string getClientCertPath() const; std::string getClientKeyPath() const; private: bool _isInitialized; std::string _caCertPath; std::string _clientCertPath; std::string _clientKeyPath; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CertInfo); }; CAF_DECLARE_SMART_POINTER(CertInfo); }} #endif Channel.h000066400000000000000000000446071321503522500357260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_CHANNEL_H_ #define AMQPCLIENTAPI_CHANNEL_H_ #include "ICafObject.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/AmqpMethods.h" #include "amqpClient/api/Consumer.h" #include "amqpClient/api/GetResponse.h" #include "amqpClient/api/ReturnListener.h" #include "amqpClient/api/amqpClient.h" #include "amqpClient/api/AmqpContentHeaders.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief Interface to an AMQP channel */ struct __declspec(novtable) Channel : public ICafObject { /** @return the channel number */ virtual uint16 getChannelNumber() = 0; /** @brief Closes the channel */ virtual void close() = 0; /** * @brief Returns the state of the channel * @retval true the Channel is open * @retval false the Channel is closed */ virtual bool isOpen() = 0; /** * @brief Acknowledge on or more messages *

* Acknowledges one or more messages delivered via the Deliver or * Get-Ok methods. The client can ask to confirm a single message or a set of * messages up to and including a specific message. * * @param deliveryTag the message's delivery tag * @param ackMultiple acknowledge multiple messages

* If set to true, the delivery tag is treated as "up to and * including", so that the client can acknowledge multiple messages with a single * method. If set to false, the delivery tag refers to a single * message. If the multiple field is true, and the delivery tag * is 0, the server will acknowledge all outstanding messages. */ virtual void basicAck( const uint64 deliveryTag, const bool ackMultiple) = 0; /** * @brief Provides a direct access to the messages in a queue *

* This method provides a direct access to the messages in a queue using a * synchronous dialogue that is designed for specific types of application where * synchronous functionality is more important than performance. * * @param queue the queue name * @param noAck no acknowledgment needed. If true, the server does not * expect acknowledgements for messages. That is, when a message is delivered to the client * the server assumes the delivery will succeed and immediately dequeues it. This * functionality may increase performance but at the cost of reliability. Messages can get * lost if a client dies before they are delivered to the application. * @return message as a GetResponse object or * a null object if there is no message available. */ virtual SmartPtrGetResponse basicGet( const std::string& queue, const bool noAck) = 0; /** * @brief Publishes a message to a specific exchange *

* This method publishes a message to a specific exchange. The message will be routed * to queues as defined by the exchange configuration and distributed to any active * consumers when the transaction, if any, is committed. * @param exchange specifies the name of the exchange to publish to. The exchange * name can be empty, meaning the default exchange. * @param routingKey specifies the routing key for the message. * @param properties specifies a #Caf::AmqpClient::AmqpContentHeaders::BasicProperties * object containing properties and headers to publish with the message. * @param body specifies the message body in raw bytes. */ virtual void basicPublish( const std::string& exchange, const std::string& routingKey, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) = 0; /** * @brief Publishes a message to a specific exchange *

* This method publishes a message to a specific exchange with control over the * mandatory and immediate bits. * The message will be routed to queues as defined by the exchange configuration and * distributed to any active consumers when the transaction, if any, is committed. * @param exchange specifies the name of the exchange to publish to. The exchange * name can be empty, meaning the default exchange. * @param routingKey specifies the routing key for the message. * @param mandatory specifies how the server is to react if the message cannot be routed * to a queue. If true, the server will return an unroutable message * with a Return method. If false, the server silently drops the * message. * @param immediate specifies how the server is to react if the message cannot be routed * to a queue consumer immediately. If true, the server will return an * undeliverable message with a Return method. If false, * the server will queue the message, but with no guarantee that it will ever be * consumed. * @param properties specifies a #Caf::AmqpClient::AmqpContentHeaders::BasicProperties * object containing properties and headers to publish with the message. * @param body specifies the message body in raw bytes. */ virtual void basicPublish( const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) = 0; /** * @brief Starts a queue consumer *

* This method asks the server to start a 'consumer', which is a transient request for * messages from a specific queue. Consumers last as int32 as the channel they were * declared on, or until the client cancels them.
* The arguments noAck, noLocal and * exclusive are false and the server will * genearate the consumer tag. * @param queue queue name * @param consumer an interface to the consumer object * @return a #Caf::AmqpClient::AmqpMethods::Basic::ConsumeOk object containing * the results of the call if successful */ virtual AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const SmartPtrConsumer& consumer) = 0; /** * @brief Starts a queue consumer *

* This method asks the server to start a 'consumer', which is a transient request for * messages from a specific queue. Consumers last as int32 as the channel they were * declared on, or until the client cancels them.
* The arguments noLocal and exclusive are * false and the server will genearate the consumer tag. * @param queue queue name * @param noAck no acknowledgment needed. If true, the server does not * expect acknowledgements for messages. That is, when a message is delivered to the client * the server assumes the delivery will succeed and immediately dequeues it. This * functionality may increase performance but at the cost of reliability. Messages can get * lost if a client dies before they are delivered to the application. * @param consumer an interface to the consumer object * @return a #Caf::AmqpClient::AmqpMethods::Basic::ConsumeOk object containing * the results of the call if successful */ virtual AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const bool noAck, const SmartPtrConsumer& consumer) = 0; /** * @brief Starts a queue consumer *

* This method asks the server to start a 'consumer', which is a transient request for * messages from a specific queue. Consumers last as int32 as the channel they were * declared on, or until the client cancels them. * @param queue queue name * @param consumerTag consumer tag (or blank to specify server-generated tag) * @param noAck acknowledgement flag * @param noLocal do not send messages to the connection that published them * @param exclusive request exclusive consumer access to the queue * @param consumer an interface to the consumer object * @param arguments a set of arguments for the declaration. The syntax of these * arguments depends on the server implementation. * @return a #Caf::AmqpClient::AmqpMethods::Basic::ConsumeOk object containing * the results of the call if successful */ virtual AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const std::string& consumerTag, const bool noAck, const bool noLocal, const bool exclusive, const SmartPtrConsumer& consumer, const SmartPtrTable& arguments = SmartPtrTable()) = 0; /** * @brief Cancels a consumer *

* This method cancels a consumer. This does not affect already delivered messages, * but it does mean the server will not send any more messages for that consumer. * The client may receive an arbitrary number of messages in between sending the cancel * method and receiving the cancel.ok reply. * @param consumerTag consumer tag to cancel * @return a #Caf::AmqpClient::AmqpMethods::Basic::CancelOk object containing * the results of the call if successful */ virtual AmqpMethods::Basic::SmartPtrCancelOk basicCancel( const std::string& consumerTag) = 0; /** * @brief Redeliver unacknowledged messages *

* This method asks the server to redeliver all unacknowledged message on the channel. * Zero or more messages may be redelivered. * @param requeue if false then the message will be redelivered to * the original receipient. If true then the server will attempt to * requeue the message, potentially delivering it to an alternate subscriber. * @return a #Caf::AmqpClient::AmqpMethods::Basic::RecoverOk object containing the * results of the call if successful */ virtual AmqpMethods::Basic::SmartPtrRecoverOk basicRecover( const bool requeue) = 0; /** * @brief Specifies quality of service *

* This method requests a specific quality of service. The QoS can be specified for * the current channel or for all channels on the connection. The particular properties * and semantics of a qos method always depend on the content class semantics. * @param prefetchSize prefetch window in octets. The client can request that messages * be sent in advance so that when the client finishes processing a message, * the following message is already help locally, rather than needing to be sent down * the channel. Prefetching gives a performance improvement. This field specifies the * prefetch window size in octets. The server will send a message in advance if it is * equal to or smaller in size than the available prefetch size (and also falls into * other prefetch limits). May be set to zero, meaning 'no specific limit', although * other prefetch limits may still apply. The prefetch-size is ignored if the no-ack * option is set. * @param prefetchCount prefetch window in messages. This field may be used in combination * with the prefetchSize field; a message will only be sent in advance if both * prefetch windows (and those at the channel and connection level) allow it. The * prefetch-count is ignored if the no-ack option is set. * @param global apply to entire connection * @return */ virtual AmqpMethods::Basic::SmartPtrQosOk basicQos( const uint32 prefetchSize, const uint32 prefetchCount, const bool global) = 0; /** * @brief Reject an incoming message *

* This method allows a client to reject a message. It can be used to interrupt and * cancel large incoming messages, or return un-treatable messages to their original * queue. * @param deliveryTag the delivery tag of the message * @param requeue if true, the server will attempt to requeue * the message. If false or the requeue attempt fails the * message is discarded or dead-lettered. */ virtual void basicReject( const uint64 deliveryTag, const bool requeue) = 0; /** * @brief Creates an exchange *

* This method creates an exchange if it does not already exist, and if the exchange * exists, verifies that it is of the correct and expected class. * @param exchange exchange name * @param type exchange type * @param durable request a durable exchange * @param arguments a set of agrguments for the declaration. The syntax of these * arguments depends on the server implementation. * @return a #Caf::AmqpClient::AmqpMethods::Exchange::DeclareOk object containing * the results of the call if successful */ virtual AmqpMethods::Exchange::SmartPtrDeclareOk exchangeDeclare( const std::string& exchange, const std::string& type, const bool durable = false, const SmartPtrTable& arguments = SmartPtrTable()) = 0; /** * @brief Deletes an exchange *

* This method deletes an exchange. When an exchange is deleted all queue bindings on * the exchange are cancelled. * @param exchange exchange name * @param ifUnused delete only if unused. If true, the server * will only delete the exchange if it has no queue bindings. If the exchange has * queue bindings the server does not delete it but raises a channel exception * instead. * @return a #Caf::AmqpClient::AmqpMethods::Exchange::DeleteOk object containing * the results of the call if successful */ virtual AmqpMethods::Exchange::SmartPtrDeleteOk exchangeDelete( const std::string& exchange, const bool ifUnused) = 0; /** * @brief Creates a queue using default parameters *

* The defaults are: * * * * * * * * *
ParameterValue
queueblank - the server will generate a queue name
durablefalse - the queue will not be durable
exclusivetrue - the queue will be exclusive to this conenction
autoDeletetrue - the queue will be deleted when no longer used
* @return a #Caf::AmqpClient::AmqpMethods::Queue::DeclareOk object containing * the results of the call if successful. This object must be examined to retrieve * the name of the queue generated by the server. */ virtual AmqpMethods::Queue::SmartPtrDeclareOk queueDeclare() = 0; /** * @brief Creates or checks a queue *

* @param queue queue name. If blank the server will generate a name. * @param durable request a durable queue * @param exclusive request an exclusive queue * @param autoDelete request that the queue be deleted when no longer in use * @param arguments a set of agrguments for the declaration. The syntax of these * arguments depends on the server implementation. * @return a #Caf::AmqpClient::AmqpMethods::Queue::DeclareOk object containing * the results of the call if successful. This object must be examined to retrieve * the name of the queue generated by the server if the queue name was blank in * the call. */ virtual AmqpMethods::Queue::SmartPtrDeclareOk queueDeclare( const std::string& queue, const bool durable, const bool exclusive, const bool autoDelete, const SmartPtrTable& arguments = SmartPtrTable()) = 0; /** * @brief Declare a queue passively; i.e. check if it exists. *

* @param queue queue name. */ virtual AmqpMethods::Queue::SmartPtrDeclareOk queueDeclarePassive( const std::string& queue) = 0; /** * @brief Deletes a queue *

* This method deletes a queue. When a queue is deleted any pending messages are * sent to a dead­-letter queue if this is defined in the server configuration, * and all consumers on the queue are cancelled. * @param queue queue name * @param ifUnused delete only if unused. If true, the server * will only delete the queue if it has no consumers. If the queue has consumers the * server does does not delete it but raises a channel exception instead. * @param ifEmpty delete only if empty. If true, the server will * only delete the queue if it has no messages. If the queue has messages the * server does does not delete it but raises a channel exception instead. * @return a #Caf::AmqpClient::AmqpMethods::Queue::DeleteOk object containing the * result of the call if successful. */ virtual AmqpMethods::Queue::SmartPtrDeleteOk queueDelete( const std::string& queue, const bool ifUnused, const bool ifEmpty) = 0; /** * @brief Purges a queue *

* This method removes all messages from a queue which are not awaiting * acknowledgment. * @param queue queue name * @return a #Caf::AmqpClient::AmqpMethods::Queue::PurgeOk containing the result * of the call if successful. */ virtual AmqpMethods::Queue::SmartPtrPurgeOk queuePurge( const std::string& queue) = 0; /** * @brief Binds a queue to an exchange *

* This method binds a queue to an exchange. Until a queue is bound it will not * receive any messages. * @param queue queue name * @param exchange exchange name * @param routingKey message routing key * @param arguments a set of agrguments for the binding. The syntax of these * arguments depends on the server implementation. * @return a #Caf::AmqpClient::AmqpMethods::Queue::BindOk containing the result * of the call if successful. */ virtual AmqpMethods::Queue::SmartPtrBindOk queueBind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments = SmartPtrTable()) = 0; /** * @brief Unbinds a queue from an exchange * @param queue queue name * @param exchange exchange name * @param routingKey message routing key * @param arguments a set of agrguments for the binding. The syntax of these * arguments depends on the server implementation. * @return a #Caf::AmqpClient::AmqpMethods::Queue::UnbindOk containing the result * of the call if successful. */ virtual AmqpMethods::Queue::SmartPtrUnbindOk queueUnbind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments = SmartPtrTable()) = 0; /** * @brief Adds a {@link ReturnListener} to the channel * @param listener the {@link ReturnListener} object to add */ virtual void addReturnListener( const SmartPtrReturnListener& listener) = 0; /** * @brief Removes a {@link ReturnListener} from the channel * @param listener the {@link ReturnListener} to remove */ virtual bool removeReturnListener( const SmartPtrReturnListener& listener) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Channel); }} #endif Connection.h000066400000000000000000000020331321503522500364400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_CONNECTION_H_ #define AMQPCLIENTAPI_CONNECTION_H_ #include "ICafObject.h" #include "amqpClient/api/Channel.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief Interface to an AMQP connection. */ struct __declspec(novtable) Connection : public ICafObject { /** * @brief Create a new channel * @return a Channel */ virtual SmartPtrChannel createChannel() = 0; /** * @brief Close a channel * @param channel the Channel to close */ virtual void closeChannel(const SmartPtrChannel& channel) = 0; /** * @brief Closes the connection and its channels */ virtual void close() = 0; /** * @brief Return the state of the connection * @retval true the connection is open * @retval false the connection is closed */ virtual bool isOpen() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Connection); }} #endif ConnectionFactory.h000066400000000000000000000146731321503522500400050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 4, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_CONNECTIONFACTORY_H_ #define AMQPCLIENTAPI_CONNECTIONFACTORY_H_ #include "ICafObject.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" #include "amqpClient/api/Connection.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief Interface to a convenience factory class to facilitate opening a * #Caf::AmqpClient::Connection to an AMQP broker. *

* ConnectionFactories are creating using the #Caf::AmqpClient::createConnectionFactory method. */ struct __declspec(novtable) ConnectionFactory : public ICafObject { /** * @return the default protocol to use for connections */ virtual std::string getProtocol() const = 0; /** * @brief Set the default protocol for connections * @param protocol the default protocol for connections */ virtual void setProtocol(const std::string& protocol) = 0; /** * @return the default host to use for connections */ virtual std::string getHost() const = 0; /** * @brief Set the default host for connections * @param host the default host for connections */ virtual void setHost(const std::string& host) = 0; /** * @return the default port to use for connections */ virtual uint32 getPort() const = 0; /** * @brief Set the default port for connections * @param port the default port for connections */ virtual void setPort(const uint32 port) = 0; /** * @return the default virtual host to use for connections */ virtual std::string getVirtualHost() const = 0; /** * @brief Set the default virtual host for connections * @param virtualHost the default virtual host for connections */ virtual void setVirtualHost(const std::string& virtualHost) = 0; /** * @return the default user name to use for connections */ virtual std::string getUsername() const = 0; /** * @brief Set the default user name for connections * @param username the default user name for connections */ virtual void setUsername(const std::string& username) = 0; /** * @return the default password to use for connections */ virtual std::string getPassword() const = 0; /** * @brief Set the default password for connections * @param password the default password for connections */ virtual void setPassword(const std::string& password) = 0; /** * @return the default CaCertPath to use for connections */ virtual std::string getCaCertPath() const = 0; /** * @brief Set the default CaCertPath for connections * @param caCertPath the default CaCertPath for connections */ virtual void setCaCertPath(const std::string& caCertPath) = 0; /** * @return the default ClientCertPath to use for connections */ virtual std::string getClientCertPath() const = 0; /** * @brief Set the default ClientCertPath for connections * @param clientCertPath the default ClientCertPath for connections */ virtual void setClientCertPath(const std::string& clientCertPath) = 0; /** * @return the default ClientKeyPath to use for connections */ virtual std::string getClientKeyPath() const = 0; /** * @brief Set the default ClientKeyPath for connections * @param clientKeyPath the default ClientKeyPath for connections */ virtual void setClientKeyPath(const std::string& clientKeyPath) = 0; /** * @return the initially requested maximum channel number; zero for unlimited */ virtual uint32 getRequestedChannelMax() const = 0; /** * @brief Set the requested maximum channel number * @param requestedChannelMax the initially requested maximum channel number; zero for unlimited */ virtual void setRequestedChannelMax(const uint32 requestedChannelMax) = 0; /** * @return the initially requested maximum frame size; zero for unlimited */ virtual uint32 getRequestedFrameMax() const = 0; /** * @brief Set the requested maximum frame size * @param requestedFrameMax the initially requested maximum frame size; zero for unlimited */ virtual void setRequestedFrameMax(const uint32 requestedFrameMax) = 0; /** * @return the initially requested heartbeat interval, in seconds; zero for none */ virtual uint32 getRequestedHeartbeat() const = 0; /** * @brief Set the requested heartbeat interval * @param requestedHeartbeat the initially requested heartbeat interval, in seconds; zero for none */ virtual void setRequestedHeartbeat(const uint32 requestedHeartbeat) = 0; /** * @return the connection timeout, in milliseconds; zero for infinite */ virtual uint32 getConnectionTimeout() const = 0; /** * @brief Set the connection timeout * @param connectionTimeout connection establishment timeout in milliseconds; zero for infinite */ virtual void setConnectionTimeout(const uint32 connectionTimeout) = 0; /** * @return the number of connection consumer processing threads */ virtual uint32 getConsumerThreadCount() const = 0; /** * @brief Set the number of connection consumer processing threads * @param threadCount the number of connection consumer processing threads */ virtual void setConsumerThreadCount(const uint32 threadCount) = 0; /** * @return the number of connection retries */ virtual uint16 getRetries() const = 0; /** * @brief Set the number of connection retries * @param retries the number of connection retries */ virtual void setRetries(const uint16 retries) = 0; /** * @return the number of connection seconds to wait */ virtual uint16 getSecondsToWait() const = 0; /** * @brief Set the number of connection retries * @param seconds the number of connection seconds to wait */ virtual void setSecondsToWait(const uint16 seconds) = 0; /** * @brief Create a new broker connection * @return a #Caf::AmqpClient::Connection interface to the connection */ virtual SmartPtrConnection newConnection() = 0; /** * @brief Create a new broker connection * @param address broker address to try * @return a #Caf::AmqpClient::Connection interface to the connection */ virtual SmartPtrConnection newConnection( const SmartPtrAddress& address, const SmartPtrCertInfo& certInfo) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ConnectionFactory); /** * @ingroup AmqpApi * @brief Create a new #Caf::AmqpClient::ConnectionFactory * @return a #Caf::AmqpClient::ConnectionFactory interface to a new connection factory */ SmartPtrConnectionFactory AMQPCLIENT_LINKAGE createConnectionFactory(); }} #endif Consumer.h000066400000000000000000000050421321503522500361370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CONSUMER_H_ #define CONSUMER_H_ #include "ICafObject.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Exception/CCafException.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/Envelope.h" #include "amqpClient/api/AmqpContentHeaders.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief Interface for application callback objects to receive notifications and messages * from a queue by subscription. *

* The methods of this interface are invoked in a dispatch thread which is separate from the * {@link Connection}'s thread. This allows {@link Consumer}s to call {@link Channel} or * {@link Connection} methods without causing a deadlock. */ struct __declspec(novtable) Consumer : public ICafObject { /** * @brief Called when the consumer is registered by a call to any of the * {@link Channel#basicConsume} methods * @param consumerTag the consumer tag associated with the consumer */ virtual void handleConsumeOk( const std::string& consumerTag) = 0; /** * @brief Called when the consumer is cancelled by a call to {@link Channel#basicCancel}. * @param consumerTag the consumer tag associated with the consumer */ virtual void handleCancelOk( const std::string& consumerTag) = 0; /** * @brief Called when a basic.recover-ok is received. * @param consumerTag the consumer tag associated with the consumer */ virtual void handleRecoverOk( const std::string& consumerTag) = 0; /** * @brief Called when a basic.deliver is received for this consumer. * @param consumerTag the consumer tag associated with the consumer * @param envelope message envelope * @param properties message properties and headers * @param body message body */ virtual void handleDelivery( const std::string& consumerTag, const SmartPtrEnvelope& envelope, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) = 0; /** * @brief Called when the channel has been shut down. * @param consumerTag the consumer tag associated with the consumer * @param reason the reason for the shut down */ virtual void handleShutdown( const std::string& consumerTag, SmartPtrCCafException& reason) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Consumer); }} #endif /* CONSUMER_H_ */ ContentHeader.h000066400000000000000000000013001321503522500370600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_CONTENTHEADER_H_ #define AMQPCLIENTAPI_CONTENTHEADER_H_ #include "ICafObject.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief Base interface for all AMQP content headers */ struct __declspec(novtable) ContentHeader : public ICafObject { /** @return the content header class id */ virtual uint16 getClassId() = 0; /** @return the content header friendly class name */ virtual std::string getClassName() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ContentHeader); }} #endif Envelope.h000066400000000000000000000020311321503522500361140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_ENVELOPE_H_ #define AMQPCLIENTAPI_ENVELOPE_H_ #include "ICafObject.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief An interface to objects that group together basic.get-ok message properties */ struct __declspec(novtable) Envelope : public ICafObject { CAF_DECL_UUID("ce68d68a-6973-49e2-a003-cb4474624f5c") /** @return the delivery tag */ virtual uint64 getDeliveryTag() = 0; /** * @retval true if the message was redelivered * @retval false if the message has not been redelivered */ virtual bool getRedelivered() = 0; /** @return the name of the exchange supplying the message */ virtual std::string getExchange() = 0; /** @return the message's routing key */ virtual std::string getRoutingKey() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Envelope); }} #endif GetResponse.h000066400000000000000000000023651321503522500366070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_GETRESPONSE_H_ #define AMQPCLIENTAPI_GETRESPONSE_H_ #include "ICafObject.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/Envelope.h" #include "amqpClient/api/AmqpContentHeaders.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief Interface representing the bundling of basic.get messages into a nicer form */ struct __declspec(novtable) GetResponse : public ICafObject { CAF_DECL_UUID("c8bda284-7eea-46e1-b9c3-791310d69b04") /** @return the message envelope information (#Caf::AmqpClient::Envelope) */ virtual SmartPtrEnvelope getEnvelope() = 0; /** @return the message properties (#Caf::AmqpClient::AmqpContentHeaders::BasicProperties) */ virtual AmqpContentHeaders::SmartPtrBasicProperties getProperties() = 0; /** @return the message body raw bytes */ virtual SmartPtrCDynamicByteArray getBody() = 0; /** @return the number of messages in the queue */ virtual uint32 getMessageCount() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(GetResponse); }} #endif Method.h000066400000000000000000000013511321503522500355630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_METHOD_H_ #define AMQPCLIENTAPI_METHOD_H_ #include "ICafObject.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief Base interface to AMQP methods */ struct __declspec(novtable) Method : public ICafObject { /** @return the method's class ID */ virtual uint16 getProtocolClassId() = 0; /** @return the method's method ID */ virtual uint16 getProtocolMethodId() = 0; /** @return the method's friendly name */ virtual std::string getProtocolMethodName() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Method); }} #endif ReturnListener.h000066400000000000000000000031751321503522500373360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef RETURNLISTENER_H_ #define RETURNLISTENER_H_ #include "ICafObject.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/AmqpContentHeaders.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApi * @brief Interface for objects that will be notified of failed message deliveries *

* When {@link Channel#basicPublish} is used with the mandatory and/or immediate * flags set and the message cannot be delivered, the server will response with a * basic.return method call. {@link ReturnListener}s can monitor * these failed messages. */ struct __declspec(novtable) ReturnListener : public ICafObject { CAF_DECL_UUID("FEB38A27-6338-4BDB-AA0E-527322A2393B") /** * @brief Callback receiving the failed message * @param replyCode server reply code * @param replyText server reply text * @param exchange exchange on which error occured * @param routingKey routing key for the message that failed * @param properties original message properties * @param body original message body */ virtual void handleReturn( const uint16 replyCode, const std::string& replyText, const std::string& exchange, const std::string& routingKey, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ReturnListener); }} #endif /* RETURNLISTENER_H_ */ amqpClient.h000066400000000000000000000170521321503522500364450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpClient/api/* * Created on: May 3, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCLIENTAPI_H_ #define AMQPCLIENTAPI_H_ #include "amqpClient/AmqpClientLink.h" #include "ICafObject.h" /** * @defgroup AmqpApi AMQP API * Documentaiton for the classes, methods and constants that can be * used directly by applications to work with the AMQP protocol as a client. */ namespace Caf { namespace AmqpClient { /** Default user name */ extern const char* DEFAULT_USER; /** Default password */ extern const char* DEFAULT_PASS; /** Default virtual host */ extern const char* DEFAULT_VHOST; /** Default protocol */ extern const char* DEFAULT_PROTOCOL; /** Default host */ extern const char* DEFAULT_HOST; /** Default maximum channel number; zero for maximum */ static const uint32 DEFAULT_CHANNEL_MAX = 0; /** Default maximum frame size; zero for maximum */ static const uint32 DEFAULT_FRAME_MAX = 131072; /** Default maximum heartbeat rate; zero for none */ static const uint32 DEFAULT_HEARTBEAT = 0; /** 'Use the default port' port */ static const uint32 USE_DEFAULT_PORT = UINT_MAX; /** The default non-ssl port */ static const uint32 DEFAULT_AMQP_PORT = 5672; /** The default ssl port */ static const uint32 DEFAULT_AMQP_SSL_PORT = 5671; /** The default connection timeout; zero means wait indefinately */ static const uint32 DEFAULT_CONNECTION_TIMEOUT = 0; /** The default number of connection consumer threads */ static const uint32 DEFAULT_CONSUMER_THREAD_COUNT = 10; /** The default number of basic.deliver messages to process in a single run of a channel consumer thread */ static const uint32 DEFAULT_CONSUMER_THREAD_MAX_DELIVERY_COUNT = 100; /** The default number of times a connection open will be retried*/ static const uint16 DEFAULT_CONNECTION_RETRIES = 5; /** The default number of seconds we will wait for each connection open attempt. 0 means wait indefinitely*/ static const uint16 DEFAULT_CONNECTION_SECONDS_TO_WAIT = 30; /** * @author mdonahue * @brief Object that maps a c-api AMQP field into a lifetime-managed GVariant */ struct __declspec(novtable) Field : public ICafObject { /** * @brief Field value types */ typedef enum { /** @brief internal value representing Not Set */ AMQP_FIELD_TYPE_NOTSET, /** @brief boolean */ AMQP_FIELD_TYPE_BOOLEAN, /** @brief signed 8-bit integer */ AMQP_FIELD_TYPE_I8, /** @brief unsigned 8-bit integer */ AMQP_FIELD_TYPE_U8, /** @brief signed 16-bit integer */ AMQP_FIELD_TYPE_I16, /** @brief unsigned 16-bit integer */ AMQP_FIELD_TYPE_U16, /** @brief signed 32-bit integer */ AMQP_FIELD_TYPE_I32, /** @brief unsigned 32-bit integer */ AMQP_FIELD_TYPE_U32, /** @brief signed 64-bit integer */ AMQP_FIELD_TYPE_I64, /** @brief unsigned 64-bit integer */ AMQP_FIELD_TYPE_U64, /** @brief 32-bit float */ AMQP_FIELD_TYPE_F32, /** @brief 64-bit double */ AMQP_FIELD_TYPE_F64, /** @brief UTF8-encoded text */ AMQP_FIELD_TYPE_UTF8, /** @brief NOT SUPPORTED */ AMQP_FIELD_TYPE_ARRAY, /** @brief NOT SUPPORTED */ AMQP_FIELD_TYPE_BYTES, /** @brief NOT SUPPORTED */ AMQP_FIELD_TYPE_DECIMAL, /** @brief NOT SUPPORTED */ AMQP_FIELD_TYPE_TIMESTAMP, /** @brief NOT SUPPORTED */ AMQP_FIELD_TYPE_TABLE, /** @brief NOT SUPPORTED */ AMQP_FIELD_TYPE_VOID } AmqpFieldType; /** * @return the field type */ virtual AmqpFieldType getAmqpType() const = 0; /** * @return the field value as a GVariant */ virtual GVariant* getValue() const = 0; /** * @brief Set the field type and value * @param type field type * @param value field value. DO NOT increment the reference count * before calling this method. This object will take ownership of * the GVariant and will call g_variant_unref upon value reassignment or destruction. */ virtual void setTypeAndValue(AmqpFieldType type, GVariant *value) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Field); /** @brief A map of field names to field objects */ typedef std::map Table; CAF_DECLARE_SMART_POINTER(Table); /** * @brief Add a boolean value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddBoolean( const std::string key, const bool val, SmartPtrTable& table); /** * @brief Add a signed 8-bit value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddInt8( const std::string key, const int8 val, SmartPtrTable& table); /** * @brief Add a unsigned 8-bit value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddUint8( const std::string key, const uint8 val, SmartPtrTable& table); /** * @brief Add a signed 16-bit value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddInt16( const std::string key, const int16 val, SmartPtrTable& table); /** * @brief Add a unsigned 16-bit value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddUint16( const std::string key, const uint16 val, SmartPtrTable& table); /** * @brief Add a signed 32-bit value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddInt32( const std::string key, const int32 val, SmartPtrTable& table); /** * @brief Add a unsigned 32-bit value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddUint32( const std::string key, const uint32 val, SmartPtrTable& table); /** * @brief Add a signed 64-bit value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddInt64( const std::string key, const int64 val, SmartPtrTable& table); /** * @brief Add a unsigned 64-bit value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddUint64( const std::string key, const uint64 val, SmartPtrTable& table); /** * @brief Add a float value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddFloat( const std::string key, const float val, SmartPtrTable& table); /** * @brief Add a double value to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddDouble( const std::string key, const double val, SmartPtrTable& table); /** * @brief Add UTF8-encoded text to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddUtf8( const std::string key, const std::string& val, SmartPtrTable& table); /** * @brief Add a time stamp (unsigned 64-bit integer) to a field table * @param key the field key * @param val the value * @param table the table to insert the field into */ void AMQPCLIENT_LINKAGE tableAddTimestamp( const std::string key, const uint64 val, SmartPtrTable& table); }} #include "amqpClient/api/AMQExceptions.h" #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/000077500000000000000000000000001321503522500331525ustar00rootroot00000000000000AbstractConnectionFactory.h000066400000000000000000000075341321503522500403700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: May 24, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_ABSTRACTCONNECTIONFACTORY_H_ #define AMQPINTEGRATIONCORE_ABSTRACTCONNECTIONFACTORY_H_ #include "amqpCore/ConnectionFactory.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpClient/api/Connection.h" #include "amqpCore/CompositeConnectionListener.h" #include "amqpCore/ConnectionListener.h" namespace Caf { namespace AmqpIntegration { class AMQPINTEGRATIONCORE_LINKAGE AbstractConnectionFactory : public ConnectionFactory { public: AbstractConnectionFactory(); virtual ~AbstractConnectionFactory(); /** * @brief Initialize the connection factory * @param amqpConnectionFactory the underlying Caf::AmqpClient::ConnectionFactory object */ void init(const AmqpClient::SmartPtrConnectionFactory& amqpConnectionFactory); virtual void setConnectionListeners(const std::deque& listeners); /** * @brief Set the default protocol for connections * @param protocol the default protocol for connections */ void setProtocol(const std::string& protocol); /** * @brief Set the default host for connections * @param host the default host for connections */ void setHost(const std::string& host); /** * @brief Set the default port for connections * @param port the default port for connections */ void setPort(const uint32 port); /** * @brief Set the default host for connections * @param virtualHost the default host for connections */ void setVirtualHost(const std::string& virtualHost); /** * @brief Set the default user name for connections * @param username the default user name for connections */ void setUsername(const std::string& username); /** * @brief Set the default password for connections * @param password the default password for connections */ void setPassword(const std::string& password); /** * @brief Set the default CaCertPath for connections * @param caCertPath the default CaCertPath for connections */ void setCaCertPath(const std::string& caCertPath); /** * @brief Set the default ClientCertPath for connections * @param clientCertPath the default ClientCertPath for connections */ void setClientCertPath(const std::string& clientCertPath); /** * @brief Set the default ClientKeyPath for connections * @param clientKeyPath the default ClientKeyPath for connections */ void setClientKeyPath(const std::string& clientKeyPath); /** * @brief Set the number of connection retries * @param retries */ void setRetries(const uint16 retries); /** * @brief Set the wait period in seconds * @param seconds */ void setSecondsToWait(const uint16 seconds); /** * @brief Set the connection timeout * @param connectionTimeout connection establishment timeout in milliseconds; zero for infinite */ void setConnectionTimeout(const uint32 connectionTimeout); public: // ConnectionFactory virtual SmartPtrConnection createConnection() = 0; std::string getProtocol(); std::string getHost(); uint32 getPort(); std::string getVirtualHost(); std::string getUsername(); std::string getPassword(); std::string getCaCertPath(); std::string getClientCertPath(); std::string getClientKeyPath(); uint16 getRetries(); uint16 getSecondsToWait(); virtual void addConnectionListener(const SmartPtrConnectionListener& listener); protected: std::string getDefaultProtocol(); std::string getDefaultHostName(); SmartPtrConnection createBareConnection(); SmartPtrConnectionListener getConnectionListener(); private: bool _isInitialized; AmqpClient::SmartPtrConnectionFactory _amqpConnectionFactory; SmartPtrCompositeConnectionListener _connectionListener; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(AbstractConnectionFactory); }; CAF_DECLARE_SMART_POINTER(AbstractConnectionFactory); }} #endif AmqpAdmin.h000066400000000000000000000052261321503522500351200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_AMQPADMIN_H_ #define AMQPINTEGRATIONCORE_AMQPADMIN_H_ #include "ICafObject.h" #include "amqpCore/Binding.h" #include "amqpCore/Exchange.h" #include "amqpCore/Queue.h" namespace Caf { namespace AmqpIntegration { /** * @brief Specifies a basic set of AMQP administrative operations for AMQP > 0.8 */ struct __declspec(novtable) AmqpAdmin : public ICafObject { CAF_DECL_UUID("B10A94BC-0CC7-476F-A38A-2794CF98D74C") /** * @brief Declare an exchange * @param exchange the exchange (#Caf::AmqpIntegration::Exchange) to declare */ virtual void declareExchange(SmartPtrExchange exchange) = 0; /** * @brief Delete an exchange * @param exchange the name of the exchange * @retval true the exchange existed and was deleted * @retval false the exchange did not exists or could not be deleted */ virtual bool deleteExchange(const std::string& exchange) = 0; /** * @brief Declare a queue whose name is automatically generated. *

* The queue is created with durable=false, exclusive=true and auto-delete=true. * @return the created queue. Call #Caf::AmqpIntegration::Queue::getName to * get the server-generated name of the queue. */ virtual SmartPtrQueue declareQueue() = 0; /** * @brief Declare a queue * @param queue the queue to declare */ virtual void declareQueue(SmartPtrQueue queue) = 0; /** * @brief Delete a queue without regard for whether it is in use or has messages in it * @param queue the name of the queue * @retval true the queue existed and was deleted * @retval false the queue did not exist or could not be deleted */ virtual bool deleteQueue(const std::string& queue) = 0; /** * @brief Delete a queue * @param queue the name of the queue * @param unused true if the queue should be deleted only if not in use * @param empty true if the queue shoudl be deleted only if empty */ virtual void deleteQueue( const std::string& queue, const bool unused, const bool empty) = 0; /** * @brief Purges the contents of a queue * @param queue the name of the queue */ virtual void purgeQueue(const std::string& queue) = 0; /** * @brief Declare a binding of a queue to an exchange * @param binding the binding information */ virtual void declareBinding(SmartPtrBinding binding) = 0; /** * @brief Remove a binding of a queue to an exchange * @param binding the binding information */ virtual void removeBinding(SmartPtrBinding binding) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(AmqpAdmin); }} #endif AmqpHeaderMapper.h000066400000000000000000000065671321503522500364360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 6, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_AMQPHEADERMAPPER_H_ #define AMQPINTEGRATIONCORE_AMQPHEADERMAPPER_H_ #include "ICafObject.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Integration/IIntMessage.h" #include "amqpClient/api/Envelope.h" namespace Caf { namespace AmqpIntegration { /** * @brief This interface is used by objects that map AMQP headers to integration message * headers and vice versa. */ struct __declspec(novtable) AMQPINTEGRATIONCORE_LINKAGE AmqpHeaderMapper : public ICafObject { CAF_DECL_UUID("5A292DD4-C3CC-4556-9809-90027C13EFA5") /* * @brief Return the collection of AMQP headers from an integration message. * @param headers the integration message headers * @return the AMQP headers */ virtual AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties fromHeaders(IIntMessage::SmartPtrCHeaders headers) = 0; /** * @brief Return the collection of integration message headers from an AMQP message. * @param properties the AMQP message properties (#Caf::AmqpClient::AmqpContentHeaders::BasicProperties). * @param envelope the AMQP message envelope (#Caf::AmqpClient::Envelope). * @return the filtered set of headers as integration message headers */ virtual IIntMessage::SmartPtrCHeaders toHeaders( AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties properties, AmqpClient::SmartPtrEnvelope envelope) = 0; /** * @brief Return the filtered collection of integration message headers from an integration message. * @param headers the input set of message headers * @return the filtered set of headers as integration message headers */ virtual IIntMessage::SmartPtrCHeaders filterHeaders( IIntMessage::SmartPtrCHeaders headers) = 0; /** @brief AMQP header prefix */ static const std::string PREFIX; /** @brief AMQP application id header */ static const std::string APP_ID; /** @brief AMQP cluster id header */ static const std::string CLUSTER_ID; /** @brief AMQP content encoding header */ static const std::string CONTENT_ENCODING; /** @brief AMQP content length hedaer */ static const std::string CONTENT_LENGTH; /** @brief AMQP content type header */ static const std::string CONTENT_TYPE; /** @brief AMQP correlation id header */ static const std::string CORRELATION_ID; /** @brief AMQP delivery mode header */ static const std::string DELIVERY_MODE; /** @brief AMQP delivery tag header */ static const std::string DELIVERY_TAG; /** @brief AMQP expiration header */ static const std::string EXPIRATION; /** @brief AMQP message count header */ static const std::string MESSAGE_COUNT; /** @brief AMQP message id header */ static const std::string MESSAGE_ID; /** @brief AMQP received exchange header */ static const std::string RECEIVED_EXCHANGE; /** @brief AMQP routing key header */ static const std::string RECEIVED_ROUTING_KEY; /** @brief AMQP redelivered header */ static const std::string REDELIVERED; /** @brief AMQP reply to header */ static const std::string REPLY_TO; /** @brief AMQP timestamp header */ static const std::string TIMESTAMP; /** @brief AMQP type header */ static const std::string TYPE; /** @brief AMQP user id header */ static const std::string USER_ID; }; CAF_DECLARE_SMART_INTERFACE_POINTER(AmqpHeaderMapper); }} #endif AmqpMessageListenerSource.h000066400000000000000000000025701321503522500403420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Aug 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AmqpMessageListenerSource_h #define AmqpMessageListenerSource_h #include "Integration/Dependencies/CPollerMetadata.h" #include "Integration/IIntMessage.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpCore/MessageListener.h" #include "Integration/Core/CAbstractPollableChannel.h" namespace Caf { namespace AmqpIntegration { class AMQPINTEGRATIONCORE_LINKAGE AmqpMessageListenerSource : public CAbstractPollableChannel, public MessageListener { public: AmqpMessageListenerSource(); virtual ~AmqpMessageListenerSource(); void init( const SmartPtrAmqpHeaderMapper& headerMapper, const SmartPtrCPollerMetadata& pollerMetadata); public: // MessageListener void onMessage(const SmartPtrIIntMessage& message); private: // CAbstractPollableChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); SmartPtrIIntMessage doReceive(const int32 timeout); private: static void QueueItemDestroyFunc(gpointer data); private: bool _isInitialized; std::string _id; GAsyncQueue *_messageQueue; SmartPtrAmqpHeaderMapper _headerMapper; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(AmqpMessageListenerSource); }; CAF_DECLARE_SMART_POINTER(AmqpMessageListenerSource); }} #endif /* AmqpMessageListenerSource_h */ AmqpOutboundEndpoint.h000066400000000000000000000112671321503522500373720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jul 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_AMQPOUTBOUNDENDPOINT_H_ #define AMQPINTEGRATIONCORE_AMQPOUTBOUNDENDPOINT_H_ #include "Integration/IMessageHandler.h" #include "Common/IAppConfig.h" #include "Common/IAppContext.h" #include "Integration/Core/CExpressionHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpCore/AmqpTemplate.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Adapter that converts and sends Messages to an AMQP exchange */ class AMQPINTEGRATIONCORE_LINKAGE AmqpOutboundEndpoint : public IMessageHandler { CAF_BEGIN_QI() CAF_QI_ENTRY(IMessageHandler) CAF_END_QI() public: AmqpOutboundEndpoint(); virtual ~AmqpOutboundEndpoint(); /** * @brief Initialize this object * @param amqpTemplate the #Caf::AmqpIntegration::AmqpTemplate used to * send and receive messages * @param appConfig the application configuration object * @param appContext the application context object */ void init( SmartPtrAmqpTemplate amqpTemplate, SmartPtrIAppConfig appConfig, SmartPtrIAppContext appContext); /** * @brief Set the name of the AMQP exchange * @param exchangeName the name of the exchange */ void setExchangeName(const std::string& exchangeName); /** * @brief Set the name of the AMQP exchange as an expression of message information * @param exchangeNameExpression the exchange name expression */ void setExchangeNameExpression(const std::string& exchangeNameExpression); /** * @brief Set the routing key * @param routingKey the routing key */ void setRoutingKey(const std::string& routingKey); /** * @brief Set the routing key as an expression of message information * @param routingKeyExpression the routing key expression */ void setRoutingKeyExpression(const std::string& routingKeyExpression); /** * @brief Set the regular expression mapping of headers to send along with the message *

* AMQP headers (amqp_XXXX) are always automatically mapped to their AMQP * BasicProperties counterparts. This expression controls which additional headers * are sent along with the message. * @param expression header mapping expression */ void setMappedRequestHeadersExpression(const std::string& expression); /** * @brief Set the expects reply flag. * @param expectReply true if a reply is expected else false */ void setExpectReply(const bool expectReply); /** * @brief Set the requires reply flag. * @param requiresReply true if a reply is required else false */ void setRequiresReply(const bool requiresReply); /** * @brief Set the friendly name of this instance. * @param name the instance name */ void setComponentName(const std::string& name); /** * @brief Set the channel resolver object * @param channelResolver the channel resolver */ void setChannelResolver(SmartPtrIChannelResolver channelResolver); public: // IMessageHandler UUID getHandlerId() const; void handleMessage(const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); private: SmartPtrIIntMessage handleRequestMessage(SmartPtrIIntMessage requestMessage); void handleResult( SmartPtrIIntMessage resultMessage, IIntMessage::SmartPtrCHeaders requestHeaders); void send( const std::string& exchangeName, const std::string& routingKey, SmartPtrIIntMessage requestMessage); SmartPtrIIntMessage sendAndReceive( const std::string& exchangeName, const std::string& routingKey, SmartPtrIIntMessage requestMessage); SmartPtrIIntMessage createReplyMessage( SmartPtrIIntMessage reply, IIntMessage::SmartPtrCHeaders requestHeaders); void sendReplyMessage( SmartPtrIIntMessage reply, const std::string& replyChannelHeaderValue); private: bool _isInitialized; UUID _id; std::string _componentName; SmartPtrAmqpTemplate _amqpTemplate; bool _expectReply; bool _requiresReply; std::string _exchangeName; std::string _exchangeNameExpression; std::string _routingKey; std::string _routingKeyExpression; std::string _requestHeaderMapperExpression; SmartPtrIChannelResolver _channelResolver; SmartPtrIMessageChannel _outputChannel; SmartPtrCExpressionHandler _exchangeNameHandler; SmartPtrCExpressionHandler _routingKeyHandler; SmartPtrAmqpHeaderMapper _requestHeaderMapper; SmartPtrAmqpHeaderMapper _responseHeaderMapper; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(AmqpOutboundEndpoint); }; CAF_DECLARE_SMART_QI_POINTER(AmqpOutboundEndpoint); }} #endif AmqpTemplate.h000066400000000000000000000151731321503522500356450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: May 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_AMQPTEMPLATE_H_ #define AMQPINTEGRATIONCORE_AMQPTEMPLATE_H_ #include "ICafObject.h" #include "Integration/IIntMessage.h" #include "amqpClient/api/Channel.h" #include "amqpCore/AmqpHeaderMapper.h" namespace Caf { namespace AmqpIntegration { /** * @brief Specifies a basic set of AMQP operations. *

* Provides synchronous send and receive methods as well as a generic executor * through a callback to a provided object. */ struct __declspec(novtable) AmqpTemplate : public ICafObject { CAF_DECL_UUID("B79DDF8E-B302-4576-9D96-DC413C76392C") /** * @brief Send a message to a default exchange with a default routing key. * @param message a message to send * @param headerMapper optional header mapper to use in place of the standard mapper */ virtual void send( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()) = 0; /** * @brief Send a message to a default exchange with a routing key. * @param routingKey the routing key * @param message a message to send * @param headerMapper optional header mapper to use in place of the standard mapper */ virtual void send( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()) = 0; /** * @brief Send a message to an exchange with a routing key. * @param exchange the name of the exchange * @param routingKey the routing key * @param message a message to send * @param headerMapper optional header mapper to use in place of the standard mapper */ virtual void send( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()) = 0; /** * @brief Receive a message if there is one from a default queue. *

* Returns immediately, possibly with a null value. * @param headerMapper optional header mapper to use in place of the standard mapper */ virtual SmartPtrIIntMessage receive( SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()) = 0; /** * @brief Receive a message if there is one from a specific queue. *

* Returns immediately, possibly with a null value. * @param queueName the name of the queue * @param headerMapper optional header mapper to use in place of the standard mapper */ virtual SmartPtrIIntMessage receive( const std::string& queueName, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()) = 0; /** * @brief Basic RPC pattern. *

* Send a message to a default exchange with a default routing key and attempt to * receive a response. The implementation will create a temporary anonymous queue * to receive the response and will use the repy-to header to notify the recipient * of the response routing. * @param message a message to send * @param requestHeaderMapper optional header mapper to use in place of the standard mapper on the outgoing message * @param responseHeaderMapper optional header mapper to use in place of the standard mapper on the incoming message */ virtual SmartPtrIIntMessage sendAndReceive( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()) = 0; /** * @brief Basic RPC pattern. *

* Send a message to a default exchange with a specific routing key and attempt to * receive a response. The implementation will create a temporary anonymous queue * to receive the response and will use the repy-to header to notify the recipient * of the response routing. * @param routingKey the routing key * @param message a message to send * @param requestHeaderMapper optional header mapper to use in place of the standard mapper on the outgoing message * @param responseHeaderMapper optional header mapper to use in place of the standard mapper on the incoming message */ virtual SmartPtrIIntMessage sendAndReceive( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()) = 0; /** * @brief Basic RPC pattern. *

* Send a message to a specific exchange with a specific routing key and attempt to * receive a response. The implementation will create a temporary anonymous queue * to receive the response and will use the repy-to header to notify the recipient * of the response routing. * @param exchange the name of the exchange * @param routingKey the routing key * @param message a message to send * @param requestHeaderMapper optional header mapper to use in place of the standard mapper on the outgoing message * @param responseHeaderMapper optional header mapper to use in place of the standard mapper on the incoming message */ virtual SmartPtrIIntMessage sendAndReceive( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()) = 0; /** * @brief Interface to objects used to execute arbitrary AMQP commands *

* This interface provides a mechanism to execute arbitrary AMQP commands. Implement * a class based on this interface with the logic required to support the desired * AMQP operation. The template will call this object with a channel on which * to execute the command. * @param channel the AMQP channel (Caf::AmqpClient::Channel in the * CAF AMQP Client Library API documentation.) * @param data user-specific data required to perform the operation * @return a pointer to a user-specified object representing the result of the * operation. */ struct Executor : public ICafObject { virtual gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data) = 0; }; CAF_DECLARE_SMART_POINTER(Executor); /** * @brief Execute an arbitrary AMQP operation * @see #Caf::AmqpIntegration::AmqpTemplate::Executor * @param executor the object used to execute the AMQP operation * @param data user-specific data required to perform the operation * @return a pointer to a user-specified object representing the result of the * operation. */ virtual gpointer execute(SmartPtrExecutor executor, gpointer data) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(AmqpTemplate); }} #endif /* AMQPINTEGRATIONCORE_AMQPTEMPLATE_H_ */ Binding.h000066400000000000000000000016621321503522500346230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 13, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_BINDING_H_ #define AMQPINTEGRATIONCORE_BINDING_H_ #include "ICafObject.h" namespace Caf { namespace AmqpIntegration { /** * @brief Simple container collecting information to describe a queue binding. Used in conjunction with RabbitAdmin. *

* Use #Caf::AmqpIntegration::createBinding to create a binding. */ struct __declspec(novtable) Binding : public ICafObject { CAF_DECL_UUID("A6067BE6-18C1-4D50-BB2F-AB9E49EA2111") /** @return the queue name */ virtual std::string getQueue() const = 0; /** @return the exchange name */ virtual std::string getExchange() const = 0; /** @return the routing key */ virtual std::string getRoutingKey() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Binding); }} #endif /* AMQPINTEGRATIONCORE_BINDING_H_ */ BindingImpl.h000066400000000000000000000020041321503522500354340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_BINDINGIMPL_H_ #define AMQPINTEGRATIONCORE_BINDINGIMPL_H_ namespace Caf { namespace AmqpIntegration { /** * @brief Implementations of the #Caf::AmqpIntegration::Binding interface. */ class AMQPINTEGRATIONCORE_LINKAGE BindingImpl : public Binding { public: BindingImpl(); virtual ~BindingImpl(); /** * @brief initialize the object * @param queue the name of the queue * @param exchange the name of the exchange * @param routingKey the routing key */ void init( const std::string queue, const std::string exchange, const std::string routingKey); std::string getQueue() const; std::string getExchange() const; std::string getRoutingKey() const; private: std::string _queue; std::string _exchange; std::string _routingKey; CAF_CM_DECLARE_NOCOPY(BindingImpl); }; CAF_DECLARE_SMART_POINTER(BindingImpl); }} #endif BindingInternal.h000066400000000000000000000015311321503522500363130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_BINDINGINTERNAL_H_ #define AMQPINTEGRATIONCORE_BINDINGINTERNAL_H_ #include "ICafObject.h" #include "amqpCore/Binding.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Interface allowing for internal management of binding integration objects */ struct __declspec(novtable) BindingInternal : public ICafObject { CAF_DECL_UUID("23D0079E-93F8-4C06-BD33-F0E795506FB2") /** * @brief Sets the delegated Binding object * @param binding the delegated binding */ virtual void setBindingInternal(SmartPtrBinding binding) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(BindingInternal); }} #endif /* AMQPINTEGRATIONCORE_BINDINGINTERNAL_H_ */ BlockingQueueConsumer.h000066400000000000000000000124601321503522500375200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jul 30, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_BLOCKINGQUEUECONSUMER_H_ #define AMQPINTEGRATIONCORE_BLOCKINGQUEUECONSUMER_H_ #include "ICafObject.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Common/CAutoRecMutex.h" #include "Exception/CCafException.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/Channel.h" #include "amqpClient/api/Envelope.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionFactory.h" #include "Integration/ILifecycle.h" namespace Caf { namespace AmqpIntegration { // Forward-declare class BlockingQueueConsumer; CAF_DECLARE_SMART_POINTER(BlockingQueueConsumer) /** * @ingroup IntObjImpl * @brief Specialized consumer encapsulating knowledge of the broker connections and having its own lifecycle */ class AMQPINTEGRATIONCORE_LINKAGE BlockingQueueConsumer : public ILifecycle { public: BlockingQueueConsumer(); virtual ~BlockingQueueConsumer(); /** * @brief object initializer * @param connectionFactory connection factory object * @param headerMapper header mapper object to map incoming headers * @param acknowledgeMode message acknowledgement mode * @param prefetchCount if acknowledgeMode is AUTO or MANUAL this * message prefetch count value will be sent to the broker via the basic.qos method. * @param queue the queue to consume */ void init( SmartPtrConnectionFactory connectionFactory, SmartPtrAmqpHeaderMapper headerMapper, AcknowledgeMode acknowledgeMode, uint32 prefetchCount, const std::string& queue); /** * @retval the underlying channel */ AmqpClient::SmartPtrChannel getChannel(); /** * @retval the AMQP consumer tag(s) */ std::string getConsumerTag(); /** * @brief Wait for the next message delivery and return it *

* This is a blocking call and will return only when a message has been delivered * or the consumer is canceled. In the case of cancellation NULL will be returned. * @retval the next message or NULL */ SmartPtrIIntMessage nextMessage(); /** * @brief Wait for the next message delivery and return it *

* This is a non-blocking call and will return when a message has been delivered * within the timeout specified or if the consumer is canceled. * @param timeout the timeout in milliseconds * @retval the next message or NULL */ SmartPtrIIntMessage nextMessage(int32 timeout); /** * @brief Acknowledges unacknowledged messages *

* Sends a basic.ack for messages that have been delivered. This method only * sends a basic.ack if the acknowledge mode flag is set to ACKNOWLEDGEMODE_AUTO. */ bool commitIfNecessary(); /** * @brief Rejects unacknowledged messaages *

* Sends a basic.reject for messages that have been delivered. This method only * sends a basic.reject if the acknowledge mode flag is set to ACKNOWLEDGEMODE_AUTO. * @param ex the application exception necessitating a rollback */ void rollbackOnExceptionIfNecessary(SmartPtrCCafException& ex); public: void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; private: class InternalConsumer : public AmqpClient::Consumer { public: InternalConsumer(); virtual ~InternalConsumer(); void init( BlockingQueueConsumer* parent); public: void handleConsumeOk( const std::string& consumerTag); void handleCancelOk( const std::string& consumerTag); void handleRecoverOk( const std::string& consumerTag); void handleDelivery( const std::string& consumerTag, const AmqpClient::SmartPtrEnvelope& envelope, const AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); void handleShutdown( const std::string& consumerTag, SmartPtrCCafException& reason); std::string getConsumerTag(); private: SmartPtrBlockingQueueConsumer _parent; AmqpClient::SmartPtrChannel _channel; std::string _consumerTag; GAsyncQueue *_deliveryQueue; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(InternalConsumer); }; CAF_DECLARE_SMART_POINTER(InternalConsumer); private: struct Delivery : public ICafObject { AmqpClient::SmartPtrEnvelope envelope; AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties properties; SmartPtrCDynamicByteArray body; }; CAF_DECLARE_SMART_POINTER(Delivery); private: void checkShutdown(); SmartPtrIIntMessage handle(SmartPtrDelivery delivery); static void destroyQueueItem(gpointer data); private: friend class InternalConsumer; bool _isInitialized; volatile bool _isRunning; volatile bool _isCanceled; std::set _deliveryTags; SmartPtrInternalConsumer _consumer; SmartPtrCAutoRecMutex _parentLock; SmartPtrCCafException _shutdownException; GAsyncQueue *_deliveryQueue; SmartPtrConnectionFactory _connectionFactory; SmartPtrConnection _connection; AmqpClient::SmartPtrChannel _channel; SmartPtrAmqpHeaderMapper _headerMapper; AcknowledgeMode _acknowledgeMode; uint32 _prefetchCount; std::string _queue; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(BlockingQueueConsumer); }; }} #endif /* AMQPINTEGRATIONCORE_BLOCKINGQUEUECONSUMER_H_ */ CachingConnectionFactory.h000066400000000000000000000165131321503522500401560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: May 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CACHINGCONNECTIONFACTORY_H_ #define CACHINGCONNECTIONFACTORY_H_ #include "amqpClient/amqpImpl/BasicProperties.h" #include "Common/CAutoRecMutex.h" #include "Exception/CCafException.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/AmqpMethods.h" #include "amqpClient/api/Channel.h" #include "amqpClient/api/Consumer.h" #include "amqpClient/api/GetResponse.h" #include "amqpClient/api/ReturnListener.h" #include "amqpClient/api/amqpClient.h" #include "amqpCore/ChannelProxy.h" #include "amqpClient/api/Connection.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/ConnectionListener.h" #include "amqpCore/AbstractConnectionFactory.h" #include "amqpCore/ConnectionProxy.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Implementation of the CachingConnectionFactory Integration Object */ class AMQPINTEGRATIONCORE_LINKAGE CachingConnectionFactory : public AbstractConnectionFactory { public: CachingConnectionFactory(); virtual ~CachingConnectionFactory(); void init(); void init(const std::string& protocol, const std::string& host, const uint32 port); void init(const std::string& protocol, const std::string& host); void init(const uint32 port); void init(const AmqpClient::SmartPtrConnectionFactory& amqpConnectionFactory); void destroy(); uint32 getChannelCacheSize(); AmqpClient::SmartPtrChannel getChannel(); void setConnectionListeners(const std::deque& listeners); void setChannelCacheSize(uint32 cacheSize); public: // ConnectionFactory SmartPtrConnection createConnection(); void addConnectionListener(const SmartPtrConnectionListener& listener); private: typedef std::deque ProxyDeque; CAF_DECLARE_SMART_POINTER(ProxyDeque); void reset(); SmartPtrChannelProxy newCachedChannelProxy(); AmqpClient::SmartPtrChannel createBareChannel(); private: class ChannelCachingConnectionProxy : public ConnectionProxy { public: ChannelCachingConnectionProxy(); virtual ~ChannelCachingConnectionProxy(); public: void init( SmartPtrConnection connection, CachingConnectionFactory *parent); void destroy(); public: // ConnectionProxy SmartPtrConnection getTargetConnection(); public: // Connection AmqpClient::SmartPtrChannel createChannel(); void close(); bool isOpen(); public: AmqpClient::SmartPtrChannel createBareChannel(); private: SmartPtrConnection _target; CachingConnectionFactory *_parent; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(ChannelCachingConnectionProxy); }; CAF_DECLARE_SMART_POINTER(ChannelCachingConnectionProxy); friend class ChannelCachingConnectionProxy; class CachedChannelHandler : public ChannelProxy { public: CachedChannelHandler(); virtual ~CachedChannelHandler(); void init( CachingConnectionFactory *parent, AmqpClient::SmartPtrChannel channel); private: void logicalClose(); void physicalClose(); void checkChannel(); void postProcessCall(SmartPtrCCafException exception); public: // ChannelProxy AmqpClient::SmartPtrChannel getTargetChannel(); public: // Channel uint16 getChannelNumber(); void close(); bool isOpen(); void basicAck( const uint64 deliveryTag, const bool ackMultiple); AmqpClient::SmartPtrGetResponse basicGet( const std::string& queue, const bool noAck); void basicPublish( const std::string& exchange, const std::string& routingKey, const AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); void basicPublish( const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const AmqpClient::SmartPtrConsumer& consumer); AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const bool noAck, const AmqpClient::SmartPtrConsumer& consumer); AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk basicConsume( const std::string& queue, const std::string& consumerTag, const bool noAck, const bool noLocal, const bool exclusive, const AmqpClient::SmartPtrConsumer& consumer, const AmqpClient::SmartPtrTable& arguments = AmqpClient::SmartPtrTable()); AmqpClient::AmqpMethods::Basic::SmartPtrCancelOk basicCancel( const std::string& consumerTag); AmqpClient::AmqpMethods::Basic::SmartPtrRecoverOk basicRecover( const bool requeue); AmqpClient::AmqpMethods::Basic::SmartPtrQosOk basicQos( const uint32 prefetchSize, const uint32 prefetchCount, const bool global); void basicReject( const uint64 deliveryTag, const bool requeue); AmqpClient::AmqpMethods::Exchange::SmartPtrDeclareOk exchangeDeclare( const std::string& exchange, const std::string& type, const bool durable = false, const AmqpClient::SmartPtrTable& arguments = AmqpClient::SmartPtrTable()); AmqpClient::AmqpMethods::Exchange::SmartPtrDeleteOk exchangeDelete( const std::string& exchange, const bool ifUnused); AmqpClient::AmqpMethods::Queue::SmartPtrDeclareOk queueDeclare(); AmqpClient::AmqpMethods::Queue::SmartPtrDeclareOk queueDeclare( const std::string& queue, const bool durable, const bool exclusive, const bool autoDelete, const AmqpClient::SmartPtrTable& arguments = AmqpClient::SmartPtrTable()); AmqpClient::AmqpMethods::Queue::SmartPtrDeclareOk queueDeclarePassive( const std::string& queue); AmqpClient::AmqpMethods::Queue::SmartPtrDeleteOk queueDelete( const std::string& queue, const bool ifUnused, const bool ifEmpty); AmqpClient::AmqpMethods::Queue::SmartPtrPurgeOk queuePurge( const std::string& queue); AmqpClient::AmqpMethods::Queue::SmartPtrBindOk queueBind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const AmqpClient::SmartPtrTable& arguments = AmqpClient::SmartPtrTable()); AmqpClient::AmqpMethods::Queue::SmartPtrUnbindOk queueUnbind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const AmqpClient::SmartPtrTable& arguments = AmqpClient::SmartPtrTable()); void addReturnListener( const AmqpClient::SmartPtrReturnListener& listener); bool removeReturnListener( const AmqpClient::SmartPtrReturnListener& listener); private: CachingConnectionFactory *_parent; AmqpClient::SmartPtrChannel _channel; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CachedChannelHandler); }; CAF_DECLARE_SMART_POINTER(CachedChannelHandler); friend class CachedChannelHandler; private: bool _isInitialized; bool _isActive; SmartPtrCAutoRecMutex _connectionMonitor; SmartPtrChannelCachingConnectionProxy _connection; uint32 _channelCacheSize; SmartPtrProxyDeque _cachedChannels; SmartPtrCAutoRecMutex _cachedChannelsMonitor; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CachingConnectionFactory); }; CAF_DECLARE_SMART_POINTER(CachingConnectionFactory); }} #endif /* CACHINGCONNECTIONFACTORY_H_ */ ChannelProxy.h000066400000000000000000000013231321503522500356550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: May 29, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHANNELPROXY_H_ #define CHANNELPROXY_H_ #include "amqpClient/api/Channel.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Interface on objects used to proxy channel objects for the various * connection objects. */ struct __declspec(novtable) ChannelProxy : public AmqpClient::Channel { /** * @brief Return the proxied Channel object * @return the proxied channel */ virtual AmqpClient::SmartPtrChannel getTargetChannel() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ChannelProxy); }} #endif /* CHANNELPROXY_H_ */ CompositeConnectionListener.h000066400000000000000000000026161321503522500407410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef COMPOSITECONNECTIONLISTENER_H_ #define COMPOSITECONNECTIONLISTENER_H_ #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionListener.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Implementation of ConnectionListener that notifies multiple delegates */ class AMQPINTEGRATIONCORE_LINKAGE CompositeConnectionListener : public ConnectionListener { public: CompositeConnectionListener(); virtual ~CompositeConnectionListener(); typedef std::deque ListenerDeque; /** * @brief Set the delegate collection * @param delegates the collection of ConnectionListener delegates */ void setDelegates(const ListenerDeque& delegates); /** * @brief Add a delegate to the collection * @param delegate the ConnectionListener delegate to add */ void addDelegate(const SmartPtrConnectionListener& delegate); public: // ConnectionListener void onCreate(const SmartPtrConnection& connection); void onClose(const SmartPtrConnection& connection); private: ListenerDeque _delegates; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CompositeConnectionListener); }; CAF_DECLARE_SMART_POINTER(CompositeConnectionListener); }} #endif /* COMPOSITECONNECTIONLISTENER_H_ */ Connection.h000066400000000000000000000017061321503522500353470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: May 24, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_CONNECTION_H_ #define AMQPINTEGRATIONCORE_CONNECTION_H_ #include "ICafObject.h" #include "amqpClient/api/Channel.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief An interface for Caf::AmqpIntegration connection objects */ struct __declspec(novtable) Connection : public ICafObject { /** * @brief Create a {@link AmqpClient::Channel Channel}. */ virtual AmqpClient::SmartPtrChannel createChannel() = 0; /** * @brief Close the connection */ virtual void close() = 0; /** * @brief Check the connection's status * @retval true the connection is open * @retval false the connection is closed */ virtual bool isOpen() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Connection); }} #endif /* AMQPINTEGRATIONCORE_CONNECTION_H_ */ ConnectionFactory.h000066400000000000000000000041021321503522500366700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: May 24, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_CONNECTIONFACTORY_H_ #define AMQPINTEGRATIONCORE_CONNECTIONFACTORY_H_ #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionListener.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Interface for connection factory implementations */ struct __declspec(novtable) ConnectionFactory : ICafObject { CAF_DECL_UUID("D2420BC6-240C-4EAC-8518-E86A93A40035") /** * @return a new Connection */ virtual SmartPtrConnection createConnection() = 0; /** * @return the default protocol to use for connections */ virtual std::string getProtocol() = 0; /** * @return the default host to use for connections */ virtual std::string getHost() = 0; /** * @return the default port to use for connections */ virtual uint32 getPort() = 0; /** * @return the default virtual host to use for connections */ virtual std::string getVirtualHost() = 0; /** * @return the default user name to use for connections */ virtual std::string getUsername() = 0; /** * @return the default password to use for connections */ virtual std::string getPassword() = 0; /** * @return the default path to the CA Cert */ virtual std::string getCaCertPath() = 0; /** * @return the default path to the Client Cert */ virtual std::string getClientCertPath() = 0; /** * @return the default path to the Client Key */ virtual std::string getClientKeyPath() = 0; /** * @return the number of connection retries */ virtual uint16 getRetries() = 0; /** * @return the number of connection seconds to wait */ virtual uint16 getSecondsToWait() = 0; /** * @brief Add a connection create/close callback * @param listener ConnectionListener callback */ virtual void addConnectionListener(const SmartPtrConnectionListener& listener) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ConnectionFactory); }} #endif /* AMQPINTEGRATIONCORE_CONNECTIONFACTORY_H_ */ ConnectionListener.h000066400000000000000000000020061321503522500370470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_CONNECTIONLISTENER_H_ #define AMQPINTEGRATIONCORE_CONNECTIONLISTENER_H_ #include "ICafObject.h" #include "amqpCore/Connection.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Connection event notification callback interface */ struct __declspec(novtable) ConnectionListener : public ICafObject { CAF_DECL_UUID("8F249C38-CF91-4553-9C68-3D714626A7EC") /** * @brief Connection created event * @param connection the Connection that has been created */ virtual void onCreate(const SmartPtrConnection& connection) = 0; /** * @brief Connection closed event * @param connection the Connection that has been closed */ virtual void onClose(const SmartPtrConnection& connection) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ConnectionListener); }} #endif /* AMQPINTEGRATIONCORE_CONNECTIONLISTENER_H_ */ ConnectionProxy.h000066400000000000000000000013571321503522500364130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: May 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_CONNECTIONPROXY_H_ #define AMQPINTEGRATIONCORE_CONNECTIONPROXY_H_ #include "amqpClient/api/Connection.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Interface on objects used to proxy connection objects for the various * connection factories. */ struct __declspec(novtable) ConnectionProxy : public Connection { /** * @brief Return the proxied Connection object * @return the proxied connection */ virtual SmartPtrConnection getTargetConnection() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ConnectionProxy); }} #endif DefaultAmqpHeaderMapper.h000066400000000000000000000037521321503522500377340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 6, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_DEFAULTAMQPHEADERMAPPER_H_ #define AMQPINTEGRATIONCORE_DEFAULTAMQPHEADERMAPPER_H_ #include "amqpClient/amqpImpl/BasicProperties.h" #include "Common/CCafRegex.h" #include "Integration/IIntMessage.h" #include "amqpClient/api/Envelope.h" #include "amqpCore/AmqpHeaderMapper.h" namespace Caf { namespace AmqpIntegration { /** * @brief This class is used to map AMQP headers to integration message * headers and vice versa. *

* This class maps headers between the AMQP message protocol and the internal * integration object message protocol. By default, standard AMQP headers are mapped and * internal and user-defined headers are not. An optional regular expression can be * supplied to allow user-defined headers to be mapped from integration messages * to AMQP. */ class AMQPINTEGRATIONCORE_LINKAGE DefaultAmqpHeaderMapper : public AmqpHeaderMapper { public: DefaultAmqpHeaderMapper(); virtual ~DefaultAmqpHeaderMapper(); /** * @brief Object initializer * @param userHeaderRegex the regular expression to apply to the integration * message header keys. Those that match are mapped to the AMQP message headers. */ void init(const std::string& userHeaderRegex = std::string()); virtual AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties fromHeaders(IIntMessage::SmartPtrCHeaders headers); virtual IIntMessage::SmartPtrCHeaders toHeaders( AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties properties, AmqpClient::SmartPtrEnvelope envelope); virtual IIntMessage::SmartPtrCHeaders filterHeaders( IIntMessage::SmartPtrCHeaders headers); private: bool _isInitialized; SmartPtrCCafRegex _userHeaderRegex; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(DefaultAmqpHeaderMapper); }; CAF_DECLARE_SMART_POINTER(DefaultAmqpHeaderMapper); }} #endif /* AMQPINTEGRATIONCORE_DEFAULTAMQPHEADERMAPPER_H_ */ Exchange.h000066400000000000000000000031051321503522500347650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_EXCHANGE_H_ #define AMQPINTEGRATIONCORE_EXCHANGE_H_ #include "ICafObject.h" namespace Caf { namespace AmqpIntegration { /** * @brief Constants representing the exchange types returned by #Caf::AmqpIntegration::Exchange::getType */ struct AMQPINTEGRATIONCORE_LINKAGE ExchangeTypes { /** @brief direct exchange */ static const char *DIRECT; /** @brief topic exchange */ static const char *TOPIC; /** @brief headers exchange */ static const char *HEADERS; /** @brief fanoout exchange */ static const char *FANOUT; }; /** * @brief Simple container collecting information to describe an exchange. Used in conjunction with RabbitAdmin. *

* Use #Caf::AmqpIntegration::createDirectExchange, #Caf::AmqpIntegration::createTopicExchange, * #Caf::AmqpIntegration::createHeadersExchange or #Caf::AmqpIntegration::createFanoutExchange * to create an exchange. */ struct __declspec(novtable) Exchange : public ICafObject { CAF_DECL_UUID("0F93E16B-E12D-4D00-8DB8-163D57BE2078") /** @return the name of the exchange */ virtual std::string getName() const = 0; /** @return the exchange type @see #Caf::AmqpIntegration::ExchangeTypes */ virtual std::string getType() const = 0; /** * @retval true the exchange is durable * @retval false the exchange is not durable */ virtual bool isDurable() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Exchange); }} #endif /* AMQPINTEGRATIONCORE_EXCHANGE_H_ */ ExchangeImpl.h000066400000000000000000000057111321503522500356140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_EXCHANGEIMPL_H_ #define AMQPINTEGRATIONCORE_EXCHANGEIMPL_H_ namespace Caf { namespace AmqpIntegration { /** * @brief Base class for implementations of the #Caf::AmqpIntegration::Exchange interface */ class AMQPINTEGRATIONCORE_LINKAGE AbstractExchange : public Exchange { public: AbstractExchange(); virtual ~AbstractExchange(); /** * @brief initalize the object * @param name exchange name * @param isDurable true if the exchange is durable else false */ void init( const std::string& name, const bool isDurable); virtual std::string getName() const; virtual std::string getType() const = 0; virtual bool isDurable() const; private: std::string _name; bool _isDurable; CAF_CM_DECLARE_NOCOPY(AbstractExchange); }; /** * @brief Implementation of the #Caf::AmqpIntegration::Exchange interface for direct exchanges */ class DirectExchange : public AbstractExchange { public: DirectExchange(); /** * @brief initalize the object * @param name exchange name * @param durable true if the exchange is durable else false */ void init( const std::string name, const bool durable); virtual std::string getType() const; CAF_CM_DECLARE_NOCOPY(DirectExchange); }; CAF_DECLARE_SMART_POINTER(DirectExchange); /** * @brief Implementation of the #Caf::AmqpIntegration::Exchange interface for topic exchanges */ class TopicExchange : public AbstractExchange { public: TopicExchange(); /** * @brief initalize the object * @param name exchange name * @param durable true if the exchange is durable else false */ void init( const std::string name, const bool durable); virtual std::string getType() const; CAF_CM_DECLARE_NOCOPY(TopicExchange); }; CAF_DECLARE_SMART_POINTER(TopicExchange); /** * @brief Implementation of the #Caf::AmqpIntegration::Exchange interface for headers exchanges */ class HeadersExchange : public AbstractExchange { public: HeadersExchange(); /** * @brief initalize the object * @param name exchange name * @param durable true if the exchange is durable else false */ void init( const std::string name, const bool durable); virtual std::string getType() const; CAF_CM_DECLARE_NOCOPY(HeadersExchange); }; CAF_DECLARE_SMART_POINTER(HeadersExchange); /** * @brief Implementation of the #Caf::AmqpIntegration::Exchange interface for fanout exchanges */ class FanoutExchange : public AbstractExchange { public: FanoutExchange(); /** * @brief initalize the object * @param name exchange name * @param durable true if the exchange is durable else false */ void init( const std::string name, const bool durable); virtual std::string getType() const; CAF_CM_DECLARE_NOCOPY(FanoutExchange); }; CAF_DECLARE_SMART_POINTER(FanoutExchange); }} #endif ExchangeInternal.h000066400000000000000000000015241321503522500364650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_EXCHANGEINTERNAL_H_ #define AMQPINTEGRATIONCORE_EXCHANGEINTERNAL_H_ #include "ICafObject.h" #include "amqpCore/Binding.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Interface allowing for internal management of exchange integration objects */ struct __declspec(novtable) ExchangeInternal : public ICafObject { CAF_DECL_UUID("5373AD13-2103-4FC4-A581-9D6D454F02A3") /** * @brief Return the bindings defined as part of the exchange definition * @return the collection of bindings */ virtual std::deque getEmbeddedBindings() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ExchangeInternal); }} #endif MessageListener.h000066400000000000000000000012171321503522500363370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Aug 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_MESSAGELISTENER_H_ #define AMQPINTEGRATIONCORE_MESSAGELISTENER_H_ #include "ICafObject.h" #include "Integration/IIntMessage.h" namespace Caf { namespace AmqpIntegration { struct __declspec(novtable) MessageListener : public ICafObject { CAF_DECL_UUID("5B2B7C47-ACEF-4FB1-97A0-1594D05AB4D9") virtual void onMessage(const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(MessageListener); }} #endif /* AMQPINTEGRATIONCORE_MESSAGELISTENER_H_ */ Queue.h000066400000000000000000000024041321503522500343300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 13, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_QUEUE_H_ #define AMQPINTEGRATIONCORE_QUEUE_H_ #include "ICafObject.h" namespace Caf { namespace AmqpIntegration { /** * @brief Simple container collecting information to describe a queue. Used in conjunction with RabbitAdmin. *

* Use #Caf::AmqpIntegration::createQueue to create a queue. */ struct __declspec(novtable) Queue : public ICafObject { CAF_DECL_UUID("082088AD-ECA3-4591-986F-8D9AFEDDEE7D") /** @return the name of the queue */ virtual std::string getName() const = 0; /** * @retval true the queue is durable * @retval false the queue is not durable */ virtual bool isDurable() const = 0; /** * @retval true the queue is exclusive to the connection * @retval false the queue is not exclusive to the connection */ virtual bool isExclusive() const = 0; /** * @retval true the server should delete the queue when it is no longer in use * @retval false the server should not delete the queue when it is no longer in use */ virtual bool isAutoDelete() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(Queue); }} #endif /* AMQPINTEGRATIONCORE_QUEUE_H_ */ QueueImpl.h000066400000000000000000000032411321503522500351520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_QUEUEIMPL_H_ #define AMQPINTEGRATIONCORE_QUEUEIMPL_H_ namespace Caf { namespace AmqpIntegration { /** * @brief Implementation of the #Caf::AmqpIntegration::Queue interface. */ class AMQPINTEGRATIONCORE_LINKAGE QueueImpl : public Queue { public: QueueImpl(); virtual ~QueueImpl(); /** * @brief initialize the object *

* durable will be set to true; * exclusive and autoDelete will be set to false. * @param name queue name */ void init(const std::string& name); /** * @brief initialize the object *

* exclusive and autoDelete will be set to false. * @param name queue name * @param durable true to make the queue durable else false */ void init( const std::string& name, const bool durable); /** * @brief initialize the object * @param name queue name * @param durable true to make the queue durable else false * @param exclusive true to make the queue exclusive else false * @param autoDelete true to make the queue auto-delete else false */ void init( const std::string& name, const bool durable, const bool exclusive, const bool autoDelete); std::string getName() const; bool isDurable() const; bool isExclusive() const; bool isAutoDelete() const; private: std::string _name; bool _durable; bool _exclusive; bool _autoDelete; CAF_CM_DECLARE_NOCOPY(QueueImpl); }; CAF_DECLARE_SMART_POINTER(QueueImpl); }} #endif QueueInternal.h000066400000000000000000000014241321503522500360260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_QUEUEINTERNAL_H_ #define AMQPINTEGRATIONCORE_QUEUEINTERNAL_H_ #include "ICafObject.h" #include "amqpCore/Queue.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Interface allowing for internal management of queue integration objects */ struct __declspec(novtable) QueueInternal : public ICafObject { CAF_DECL_UUID("E15F4DA8-C4DC-4813-82B9-1B15C69915D1") /** * @brief Sets the delegated Queue object * @param queue the delegated queue */ virtual void setQueueInternal(SmartPtrQueue queue) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(QueueInternal); }} #endif RabbitAdmin.h000066400000000000000000000057411321503522500354270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_RABBITADMIN_H_ #define AMQPINTEGRATIONCORE_RABBITADMIN_H_ #include "amqpClient/api/Channel.h" #include "amqpCore/Binding.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/Exchange.h" #include "amqpCore/Queue.h" #include "amqpCore/RabbitTemplate.h" #include "amqpCore/AmqpAdmin.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Implementation of the RabbitAdmin Integration Object */ class AMQPINTEGRATIONCORE_LINKAGE RabbitAdmin : public AmqpAdmin { public: RabbitAdmin(); virtual ~RabbitAdmin(); void init(SmartPtrConnectionFactory connectionFactory); void term(); public: // AmqpAdmin void declareExchange(SmartPtrExchange exchange); bool deleteExchange(const std::string& exchange); SmartPtrQueue declareQueue(); void declareQueue(SmartPtrQueue queue); bool deleteQueue(const std::string& queue); void deleteQueue( const std::string& queue, const bool unused, const bool empty); void purgeQueue(const std::string& queue); void declareBinding(SmartPtrBinding binding); void removeBinding(SmartPtrBinding binding); private: // Executors class DeclareExchangeExecutor : public AmqpTemplate::Executor { public: gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data); }; CAF_DECLARE_SMART_POINTER(DeclareExchangeExecutor); class DeleteExchangeExecutor : public AmqpTemplate::Executor { gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data); }; CAF_DECLARE_SMART_POINTER(DeleteExchangeExecutor); class DeclareQueueExecutor : public AmqpTemplate::Executor { gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data); }; CAF_DECLARE_SMART_POINTER(DeclareQueueExecutor); class DeleteQueueExecutor : public AmqpTemplate::Executor { gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data); }; CAF_DECLARE_SMART_POINTER(DeleteQueueExecutor); class DeleteQueueExExecutor : public AmqpTemplate::Executor { gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data); }; CAF_DECLARE_SMART_POINTER(DeleteQueueExExecutor); class PurgeQueueExecutor : public AmqpTemplate::Executor { gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data); }; CAF_DECLARE_SMART_POINTER(PurgeQueueExecutor); class DeclareBindingExecutor : public AmqpTemplate::Executor { gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data); }; CAF_DECLARE_SMART_POINTER(DeclareBindingExecutor); class RemoveBindingExecutor : public AmqpTemplate::Executor { gpointer execute(AmqpClient::SmartPtrChannel channel, gpointer data); }; CAF_DECLARE_SMART_POINTER(RemoveBindingExecutor); private: bool _isInitialized; SmartPtrRabbitTemplate _rabbitTemplate; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(RabbitAdmin); }; CAF_DECLARE_SMART_POINTER(RabbitAdmin); }} #endif RabbitTemplate.h000066400000000000000000000114151321503522500361450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Jun 5, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_RABBITTEMPLATE_H_ #define AMQPINTEGRATIONCORE_RABBITTEMPLATE_H_ #include "amqpClient/amqpImpl/BasicProperties.h" #include "Exception/CCafException.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/Channel.h" #include "amqpClient/api/Envelope.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpCore/AmqpTemplate.h" #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionFactory.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief Implementation of the RabbitTemplate Integration Object */ class AMQPINTEGRATIONCORE_LINKAGE RabbitTemplate : public AmqpTemplate { public: RabbitTemplate(); virtual ~RabbitTemplate(); void init(SmartPtrConnectionFactory connectionFactory); void term(); void setExchange(const std::string& exchange); void setRoutingKey(const std::string& routingKey); void setQueue(const std::string& queue); void setReplyTimeout(const uint32 replyTimeout); void setHeaderMapper(const SmartPtrAmqpHeaderMapper& headerMapper); public: // AmqpTemplate void send( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); void send( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); void send( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage receive( SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage receive( const std::string& queueName, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage sendAndReceive( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage sendAndReceive( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage sendAndReceive( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()); gpointer execute(SmartPtrExecutor executor, gpointer data); private: void doSend( AmqpClient::SmartPtrChannel channel, const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper = SmartPtrAmqpHeaderMapper()); SmartPtrIIntMessage doSendAndReceive( AmqpClient::SmartPtrChannel channel, const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper = SmartPtrAmqpHeaderMapper(), SmartPtrAmqpHeaderMapper responseHeaderMapper = SmartPtrAmqpHeaderMapper()); private: typedef TBlockingCell SynchronousHandoff; CAF_DECLARE_SMART_POINTER(SynchronousHandoff); class DefaultConsumer : public AmqpClient::Consumer { public: DefaultConsumer(); virtual ~DefaultConsumer(); void init( SmartPtrAmqpHeaderMapper mapper, SmartPtrSynchronousHandoff handoff); void handleConsumeOk( const std::string& consumerTag); void handleCancelOk( const std::string& consumerTag); void handleRecoverOk( const std::string& consumerTag); void handleDelivery( const std::string& consumerTag, const AmqpClient::SmartPtrEnvelope& envelope, const AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body); void handleShutdown( const std::string& consumerTag, SmartPtrCCafException& reason); private: SmartPtrAmqpHeaderMapper _mapper; SmartPtrSynchronousHandoff _handoff; }; CAF_DECLARE_SMART_POINTER(DefaultConsumer); private: static std::string DEFAULT_EXCHANGE; static std::string DEFAULT_ROUTING_KEY; static int32 DEFAULT_REPLY_TIMEOUT; private: bool _isInitialized; std::string _exchange; std::string _routingKey; std::string _queue; uint32 _replyTimeout; SmartPtrConnectionFactory _connectionFactory; SmartPtrConnection _connection; SmartPtrAmqpHeaderMapper _headerMapper; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(RabbitTemplate); }; CAF_DECLARE_SMART_POINTER(RabbitTemplate); }} #endif SimpleConnection.h000066400000000000000000000021741321503522500365210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: May 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_SIMPLECONNECTION_H_ #define AMQPINTEGRATIONCORE_SIMPLECONNECTION_H_ #include "amqpClient/api/Channel.h" #include "amqpClient/api/Connection.h" #include "amqpCore/Connection.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief A simple object that wraps a AmqpClient::Connection and exposes * it as an AmqpIntegration::Connection. */ class AMQPINTEGRATIONCORE_LINKAGE SimpleConnection : public Connection { public: SimpleConnection(); virtual ~SimpleConnection(); /** * @brief Initialize the object with the given AmqpClient::Connection * @param delegate the wrapped AmqpClient::Connection */ void init(const AmqpClient::SmartPtrConnection& delegate); public: // Connection AmqpClient::SmartPtrChannel createChannel(); void close(); bool isOpen(); private: AmqpClient::SmartPtrConnection _delegate; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(SimpleConnection); }; CAF_DECLARE_SMART_POINTER(SimpleConnection); }} #endif SimpleMessageListenerContainer.h000066400000000000000000000100751321503522500413560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/include/amqpCore/* * Created on: Aug 1, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef SIMPLEMESSAGELISTENERCONTAINER_H_ #define SIMPLEMESSAGELISTENERCONTAINER_H_ #include "Integration/IErrorHandler.h" #include "Exception/CCafException.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/IIntMessage.h" #include "Integration/IThrowable.h" #include "amqpClient/api/Channel.h" #include "amqpCore/BlockingQueueConsumer.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/MessageListener.h" #include "Integration/ILifecycle.h" #include "Integration/IRunnable.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief A simple message listener used by channels to retrieve messages *

* This container manages message acknowledgment, broker connection recoverability and * other aspects of consuming from queues. */ class AMQPINTEGRATIONCORE_LINKAGE SimpleMessageListenerContainer : public ILifecycle { public: SimpleMessageListenerContainer(); virtual ~SimpleMessageListenerContainer(); /** * @brief initialize the object */ void init(); /** * @brief initialize the object * @param connectionFactory the ConnectionFactory */ void init( SmartPtrConnectionFactory connectionFactory); public: /** * @brief Set the message acknowledgment mode * @param acknowledgeMode acknowledgment mode */ void setAcknowledgeMode(AcknowledgeMode acknowledgeMode); void setPrefetchCount(const uint32 prefetchCount); void setReceiveTimeout(const uint32 receiveTimeout); void setRecoveryInterval(const uint32 recoveryInterval); void setTxSize(const uint32 txSize); void setQueue(const std::string& queue); void setConnectionFactory(SmartPtrConnectionFactory connectionFactory); void setMessagerListener(SmartPtrMessageListener messageListener); SmartPtrMessageListener getMessageListener(); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; private: void validateConfig(); bool isActive(); bool receiveAndExecute(SmartPtrBlockingQueueConsumer consumer); void executeListener( AmqpClient::SmartPtrChannel channel, SmartPtrIIntMessage message); void doInvokeListener( SmartPtrIIntMessage message); void restart(); private: typedef TBlockingCell StartupExceptionHandoff; CAF_DECLARE_SMART_POINTER(StartupExceptionHandoff); private: class AsyncMessageProcessingConsumer : public IRunnable, public IErrorHandler { public: AsyncMessageProcessingConsumer(); ~AsyncMessageProcessingConsumer(); void init( SimpleMessageListenerContainer *parent, SmartPtrBlockingQueueConsumer consumer, SmartPtrStartupExceptionHandoff startupException, const uint32 timeout, const uint32 recoveryInterval); void run(); void cancel(); void handleError( const SmartPtrIThrowable& throwable, const SmartPtrIIntMessage& message) const; private: void handleStartupFailure(); private: SimpleMessageListenerContainer *_parent; SmartPtrBlockingQueueConsumer _consumer; SmartPtrStartupExceptionHandoff _startupException; uint32 _timeout; uint32 _recoveryInterval; bool _isCanceled; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(AsyncMessageProcessingConsumer); }; CAF_DECLARE_SMART_POINTER(AsyncMessageProcessingConsumer); private: bool _isInitialized; volatile bool _isRunning; volatile bool _isActive; bool _debugTrace; SmartPtrBlockingQueueConsumer _consumer; SmartPtrCSimpleAsyncTaskExecutor _executor; SmartPtrStartupExceptionHandoff _startupException; SmartPtrConnectionFactory _connectionFactory; SmartPtrMessageListener _messageListener; std::string _queue; AcknowledgeMode _acknowledgeMode; uint32 _receiveTimeout; uint32 _prefetchCount; uint32 _txSize; uint32 _recoveryInterval; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(SimpleMessageListenerContainer); }; CAF_DECLARE_SMART_POINTER(SimpleMessageListenerContainer); }} #endif /* SIMPLEMESSAGELISTENERCONTAINER_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/000077500000000000000000000000001321503522500305475ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/000077500000000000000000000000001321503522500326445ustar00rootroot00000000000000AMQChannel.cpp000066400000000000000000001064641321503522500352130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/AMQCommand.h" #include "amqpClient/BlockingRpcContinuation.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/ConsumerWorkService.h" #include "amqpClient/IConnectionInt.h" #include "amqpClient/IRpcContinuation.h" #include "amqpClient/TCopyOnWriteContainer.h" #include "amqpClient/amqpImpl/BasicAckMethod.h" #include "amqpClient/amqpImpl/BasicCancelMethod.h" #include "amqpClient/amqpImpl/BasicConsumeMethod.h" #include "amqpClient/amqpImpl/BasicGetMethod.h" #include "amqpClient/amqpImpl/BasicPublishMethod.h" #include "amqpClient/amqpImpl/BasicQosMethod.h" #include "amqpClient/amqpImpl/BasicRecoverMethod.h" #include "amqpClient/amqpImpl/BasicRejectMethod.h" #include "amqpClient/amqpImpl/ChannelCloseOkMethod.h" #include "amqpClient/amqpImpl/EnvelopeImpl.h" #include "amqpClient/amqpImpl/ExchangeDeclareMethod.h" #include "amqpClient/amqpImpl/ExchangeDeleteMethod.h" #include "amqpClient/amqpImpl/GetResponseImpl.h" #include "amqpClient/amqpImpl/IContentHeader.h" #include "amqpClient/amqpImpl/IMethod.h" #include "amqpClient/amqpImpl/IServerMethod.h" #include "amqpClient/amqpImpl/QueueBindMethod.h" #include "amqpClient/amqpImpl/QueueDeclareMethod.h" #include "amqpClient/amqpImpl/QueueDeleteMethod.h" #include "amqpClient/amqpImpl/QueuePurgeMethod.h" #include "amqpClient/amqpImpl/QueueUnbindMethod.h" #include "amqpClient/api/AmqpMethods.h" #include "amqpClient/api/Consumer.h" #include "amqpClient/api/GetResponse.h" #include "amqpClient/api/ReturnListener.h" #include "amqpClient/api/amqpClient.h" #include "amqpClient/AMQChannel.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "AMQUtil.h" using namespace Caf::AmqpClient; const uint8 AMQChannel::DEBUGLOG_FLAG_ENTRYEXIT = 0x01; const uint8 AMQChannel::DEBUGLOG_FLAG_AMQP = 0x02; #define AMQCHANNEL_ENTRY \ if (_debugLogFlags & DEBUGLOG_FLAG_ENTRYEXIT) { CAF_CM_LOG_DEBUG_VA0("entry"); } #define AMQCHANNEL_EXIT \ if (_debugLogFlags & DEBUGLOG_FLAG_ENTRYEXIT) { CAF_CM_LOG_DEBUG_VA0("exit"); } #if (1) // init AMQChannel::AMQChannel() : _isInitialized(false), _isOpen(false), _debugLogFlags(0), _channelNumber(0), CAF_CM_INIT_LOG("AMQChannel") { CAF_CM_INIT_THREADSAFE; _channelMutex.CreateInstance(); _channelMutex->initialize(); } AMQChannel::~AMQChannel() { if (_channelHandle) { AmqpChannel::AMQP_ChannelClose(_channelHandle); } } void AMQChannel::init( const SmartPtrIConnectionInt& connection, const SmartPtrConsumerWorkService& workService) { CAF_CM_FUNCNAME("init"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(connection); CAF_CM_VALIDATE_SMARTPTR(workService); uint32 debugFlags = 0; if (getAppConfig()->getUint32( "AMQChannel", "debugLogFlags", debugFlags, IConfigParams::PARAM_OPTIONAL)) { _debugLogFlags = debugFlags; } AMQCHANNEL_ENTRY; _connection = connection; _workService = workService; _channelSignal.initialize("channelSignal"); _dispatcher.CreateInstance(); _dispatcher->init(_workService); // Sequence is important here. Once amqpConnectionOpenChannel is called the // channel.open method will be sent. Therefore we must have an _activeRpc // registered to handle the channel.open-ok response BEFORE activating the // _channelTask. // Create the _activeRpc to listen for channel-open.ok SmartPtrBlockingRpcContinuation continuation; continuation.CreateInstance(); continuation->init(); _activeRpc = continuation; // Open the channel AMQUtil::checkAmqpStatus( _connection->amqpConnectionOpenChannel(_channelHandle), "_connection->amqpConnectionOpenChannel"); AMQUtil::checkAmqpStatus( AmqpChannel::AMQP_ChannelGetId(_channelHandle, &_channelNumber), "AmqpChannel::AMQP_ChannelGetId"); // Set up AMQP frame processing _command.CreateInstance(); _command->init(); SmartPtrChannelTask channelTask; channelTask.CreateInstance(); channelTask->init(this); _workService->addWork(channelTask); // Wait for the channel-open.ok response SmartPtrAMQCommand command; { CAF_CM_UNLOCK_LOCK; command = continuation->getReply(); } CAF_CM_VALIDATE_SMARTPTR(command); AmqpMethods::Channel::SmartPtrOpenOk openOk; openOk.QueryInterface(command->getMethod(), false); if (!openOk) { CAF_CM_EXCEPTIONEX_VA1( IllegalStateException, 0, "Expected to receive channel.open-ok but received " "%s instead. This channel cannot be used.", command->getMethod()->getProtocolMethodName().c_str()); } if (_debugLogFlags & DEBUGLOG_FLAG_AMQP) { CAF_CM_LOG_DEBUG_VA1("channel #%d is open", _channelNumber); } _isOpen = true; _isInitialized = true; AMQCHANNEL_EXIT; } uint16 AMQChannel::getChannelNumber() { CAF_CM_FUNCNAME_VALIDATE("getChannelNumber"); CAF_CM_LOCK_UNLOCK; AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ensureIsOpen(); AMQCHANNEL_EXIT; return _channelNumber; } bool AMQChannel::isOpen() { CAF_CM_LOCK_UNLOCK; return _isOpen; } void AMQChannel::close() { CAF_CM_FUNCNAME_VALIDATE("close"); AMQCHANNEL_ENTRY; _connection->channelCloseChannel(this); AMQCHANNEL_EXIT; } void AMQChannel::notifyConnectionClosed(SmartPtrCCafException& exception) { CAF_CM_FUNCNAME_VALIDATE("notifyConnectionClosed"); AMQCHANNEL_ENTRY close(exception); AMQCHANNEL_EXIT; } void AMQChannel::close(SmartPtrCCafException& exception) { CAF_CM_FUNCNAME_VALIDATE("close"); CAF_CM_LOCK_UNLOCK; AMQCHANNEL_ENTRY if (_debugLogFlags & DEBUGLOG_FLAG_AMQP) { CAF_CM_LOG_DEBUG_VA1("Closing channel #%d", _channelNumber); } if (_isOpen) { _isOpen = false; _dispatcher->quiesce(); SmartPtrIRpcContinuation activeRpc; { CAF_CM_UNLOCK_LOCK; activeRpc = nextOutstandingRpc(); } if (activeRpc) { activeRpc->handleAbort(exception); } if (_dispatcher) { _dispatcher->handleShutdown(exception); } AMQPStatus status = AmqpChannel::AMQP_ChannelClose(_channelHandle); if (status != AMQP_ERROR_OK) { CAF_CM_LOG_WARN_VA2( "channel #%d closed with API code %d", _channelNumber, status); } } AMQCHANNEL_EXIT; } #endif #if (1) // basic void AMQChannel::basicAck( const uint64 deliveryTag, const bool ackMultiple) { CAF_CM_FUNCNAME_VALIDATE("basicAck"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrBasicAckMethod method; method.CreateInstance(); method->init(deliveryTag, ackMultiple); transmit(method); AMQCHANNEL_EXIT; } SmartPtrGetResponse AMQChannel::basicGet( const std::string& queue, const bool noAck) { CAF_CM_FUNCNAME("basicGet"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrBasicGetMethod method; method.CreateInstance(); method->init(queue, noAck); SmartPtrAMQCommand reply = execRpc(method); SmartPtrIMethod replyMethod = reply->getMethod(); SmartPtrGetResponseImpl getResponse; AmqpMethods::Basic::SmartPtrGetOk getOk; getOk.QueryInterface(replyMethod, false); if (getOk) { AmqpContentHeaders::SmartPtrBasicProperties properties; SmartPtrIContentHeader contentHeader = reply->getContentHeader(); if (contentHeader) { properties.QueryInterface(contentHeader, false); if (!properties) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a basic properties content header. Received '%s'. " "Please report this bug.", contentHeader->getClassName().c_str()); } } SmartPtrEnvelopeImpl envelope; envelope.CreateInstance(); envelope->init( getOk->getDeliveryTag(), getOk->getRedelivered(), getOk->getExchange(), getOk->getRoutingKey()); getResponse.CreateInstance(); getResponse->init( envelope, properties, reply->getContentBody(), getOk->getMessageCount()); } else { AmqpMethods::Basic::SmartPtrGetEmpty getEmpty; getEmpty.QueryInterface(replyMethod, false); if(!getEmpty) { CAF_CM_EXCEPTIONEX_VA2( NoSuchInterfaceException, 0, "Expected a basic.get-ok or basic.get-empty response. Received '%s'. " "Please report this bug.", method->getMethodName().c_str(), replyMethod->getProtocolMethodName().c_str()); } } AMQCHANNEL_EXIT; return getResponse; } void AMQChannel::basicPublish( const std::string& exchange, const std::string& routingKey, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { basicPublish( exchange, routingKey, false, false, properties, body); } void AMQChannel::basicPublish( const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { CAF_CM_FUNCNAME_VALIDATE("basicPublish"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrBasicPublishMethod method; method.CreateInstance(); method->init( exchange, routingKey, mandatory, immediate, properties, body); transmit(method); AMQCHANNEL_EXIT; } AmqpMethods::Basic::SmartPtrConsumeOk AMQChannel::basicConsume( const std::string& queue, const SmartPtrConsumer& consumer) { return basicConsume(queue, false, consumer); } AmqpMethods::Basic::SmartPtrConsumeOk AMQChannel::basicConsume( const std::string& queue, const bool noAck, const SmartPtrConsumer& consumer) { return basicConsume(queue, "", noAck, false, false, consumer); } AmqpMethods::Basic::SmartPtrConsumeOk AMQChannel::basicConsume( const std::string& queue, const std::string& consumerTag, const bool noAck, const bool noLocal, const bool exclusive, const SmartPtrConsumer& consumer, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME("basicConsume"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); AmqpMethods::Basic::SmartPtrConsumeOk consumeOk; // Put a lock on the dispatcher. // DO NOT FORGET TO UNLOCK IT NO MATTER WHAT! _dispatcher->lock(); try { SmartPtrBasicConsumeMethod method; method.CreateInstance(); method->init(queue, consumerTag, noLocal, noAck, exclusive, arguments); SmartPtrAMQCommand reply = execRpc(method); SmartPtrIMethod replyMethod = reply->getMethod(); consumeOk.QueryInterface(replyMethod, false); if (consumeOk) { const std::string& consumerTagActual = consumeOk->getConsumerTag(); _dispatcher->addConsumer(consumerTagActual, consumer); _dispatcher->handleConsumeOk(consumerTagActual); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a basic.consume-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } } CAF_CM_CATCH_ALL; _dispatcher->unlock(); CAF_CM_THROWEXCEPTION; AMQCHANNEL_EXIT; return consumeOk; } AmqpMethods::Basic::SmartPtrCancelOk AMQChannel::basicCancel( const std::string& consumerTag) { CAF_CM_FUNCNAME("basicCancel"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); AmqpMethods::Basic::SmartPtrCancelOk cancelOk; SmartPtrConsumer originalConsumer = _dispatcher->getConsumer(consumerTag); if (originalConsumer) { SmartPtrBasicCancelMethod method; method.CreateInstance(); method->init(consumerTag); SmartPtrAMQCommand reply = execRpc(method); SmartPtrIMethod replyMethod = reply->getMethod(); cancelOk.QueryInterface(replyMethod, false); if (cancelOk) { try { _dispatcher->handleCancelOk(consumerTag); } CAF_CM_CATCH_ALL; _dispatcher->removeConsumer(consumerTag); CAF_CM_THROWEXCEPTION; } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a basic.cancel-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "No such consumer tag '%s'", consumerTag.c_str()); } AMQCHANNEL_EXIT; return cancelOk; } AmqpMethods::Basic::SmartPtrRecoverOk AMQChannel::basicRecover( const bool requeue) { CAF_CM_FUNCNAME("basicRecover"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); AmqpMethods::Basic::SmartPtrRecoverOk recoverOk; SmartPtrBasicRecoverMethod method; method.CreateInstance(); method->init(requeue); SmartPtrAMQCommand reply = execRpc(method); SmartPtrIMethod replyMethod = reply->getMethod(); recoverOk.QueryInterface(replyMethod, false); if (recoverOk) { _dispatcher->handleRecoverOk(); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a basic.recover-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return recoverOk; } AmqpMethods::Basic::SmartPtrQosOk AMQChannel::basicQos( const uint32 prefetchSize, const uint32 prefetchCount, const bool global) { CAF_CM_FUNCNAME("basicQos"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrBasicQosMethod method; method.CreateInstance(); method->init(prefetchSize, prefetchCount, global); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Basic::SmartPtrQosOk qosOk; SmartPtrIMethod replyMethod = reply->getMethod(); qosOk.QueryInterface(replyMethod, false); if (!qosOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a basic.qos-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return qosOk; } void AMQChannel::basicReject( const uint64 deliveryTag, const bool requeue) { CAF_CM_FUNCNAME_VALIDATE("basicReject"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrBasicRejectMethod method; method.CreateInstance(); method->init(deliveryTag, requeue); transmit(method); AMQCHANNEL_EXIT; } #endif #if (1) // exchange AmqpMethods::Exchange::SmartPtrDeclareOk AMQChannel::exchangeDeclare( const std::string& exchange, const std::string& type, const bool durable, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME("exchangeDeclare"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrExchangeDeclareMethod method; method.CreateInstance(); method->init(exchange, type, false, durable, arguments); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Exchange::SmartPtrDeclareOk declareOk; SmartPtrIMethod replyMethod = reply->getMethod(); declareOk.QueryInterface(replyMethod, false); if (!declareOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a exchange.declare-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return declareOk; } AmqpMethods::Exchange::SmartPtrDeleteOk AMQChannel::exchangeDelete( const std::string& exchange, const bool ifUnused) { CAF_CM_FUNCNAME("exchangeDelete"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrExchangeDeleteMethod method; method.CreateInstance(); method->init(exchange, ifUnused); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Exchange::SmartPtrDeleteOk deleteOk; SmartPtrIMethod replyMethod = reply->getMethod(); deleteOk.QueryInterface(replyMethod, false); if (!deleteOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a exchange.delete-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return deleteOk; } #endif #if (1) // queue AmqpMethods::Queue::SmartPtrDeclareOk AMQChannel::queueDeclare() { return queueDeclare( "", false, true, true); } AmqpMethods::Queue::SmartPtrDeclareOk AMQChannel::queueDeclare( const std::string& queue, const bool durable, const bool exclusive, const bool autoDelete, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME("queueDeclare"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrQueueDeclareMethod method; method.CreateInstance(); method->init(queue, durable, exclusive, autoDelete, arguments); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Queue::SmartPtrDeclareOk declareOk; SmartPtrIMethod replyMethod = reply->getMethod(); declareOk.QueryInterface(replyMethod, false); if (!declareOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a queue.declare-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return declareOk; } AmqpMethods::Queue::SmartPtrDeclareOk AMQChannel::queueDeclarePassive( const std::string& queue) { CAF_CM_FUNCNAME("queueDeclarePassive"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrQueueDeclareMethod method; method.CreateInstance(); method->initPassive(queue); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Queue::SmartPtrDeclareOk declareOk; SmartPtrIMethod replyMethod = reply->getMethod(); declareOk.QueryInterface(replyMethod, false); if (!declareOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a queue.declare-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return declareOk; } AmqpMethods::Queue::SmartPtrDeleteOk AMQChannel::queueDelete( const std::string& queue, const bool ifUnused, const bool ifEmpty) { CAF_CM_FUNCNAME("queueDelete"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrQueueDeleteMethod method; method.CreateInstance(); method->init(queue, ifUnused, ifEmpty); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Queue::SmartPtrDeleteOk deleteOk; SmartPtrIMethod replyMethod = reply->getMethod(); deleteOk.QueryInterface(replyMethod, false); if (!deleteOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a queue.delete-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return deleteOk; } AmqpMethods::Queue::SmartPtrPurgeOk AMQChannel::queuePurge( const std::string& queue) { CAF_CM_FUNCNAME("queuePurge"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrQueuePurgeMethod method; method.CreateInstance(); method->init(queue); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Queue::SmartPtrPurgeOk purgeOk; SmartPtrIMethod replyMethod = reply->getMethod(); purgeOk.QueryInterface(replyMethod, false); if (!purgeOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a queue.purge-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return purgeOk; } AmqpMethods::Queue::SmartPtrBindOk AMQChannel::queueBind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME("queueBind"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrQueueBindMethod method; method.CreateInstance(); method->init(queue, exchange, routingKey, arguments); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Queue::SmartPtrBindOk bindOk; SmartPtrIMethod replyMethod = reply->getMethod(); bindOk.QueryInterface(replyMethod, false); if (!bindOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a queue.bind-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return bindOk; } AmqpMethods::Queue::SmartPtrUnbindOk AMQChannel::queueUnbind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME("queueUnbind"); AMQCHANNEL_ENTRY; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrQueueUnbindMethod method; method.CreateInstance(); method->init(queue, exchange, routingKey, arguments); SmartPtrAMQCommand reply = execRpc(method); AmqpMethods::Queue::SmartPtrUnbindOk unbindOk; SmartPtrIMethod replyMethod = reply->getMethod(); unbindOk.QueryInterface(replyMethod, false); if (!unbindOk) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a queue.unbind-ok response. Received '%s'. " "Please report this bug.", replyMethod->getProtocolMethodName().c_str()); } AMQCHANNEL_EXIT; return unbindOk; } #endif #if (1) // ReturnListener void AMQChannel::addReturnListener( const SmartPtrReturnListener& listener) { CAF_CM_FUNCNAME_VALIDATE("addReturnListener"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOCK_UNLOCK; _returnListeners.add(listener); } bool AMQChannel::removeReturnListener( const SmartPtrReturnListener& listener) { CAF_CM_FUNCNAME_VALIDATE("removeReturnListener"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _returnListeners.remove(listener); } #endif #if (1) // processing /* * Worker thread execution callback. * Check for an incoming frame and if one exists, process it. * This method is also called during init() and it waiting for the * channel.open-ok. While establishing the connection we may get timeout errors * because the broker is down. In that case retry the connection for the allotted * time before giving up. */ bool AMQChannel::taskHandler() { CAF_CM_FUNCNAME("taskHandler"); CAF_CM_LOCK_UNLOCK; try { uint32 frameCount = 0; AMQPStatus status = AMQP_ERROR_OK; SmartPtrCAmqpFrame frame; while (_channelHandle && (frameCount < 1000)) { SmartPtrCAmqpChannel channelHandle = _channelHandle; { CAF_CM_UNLOCK_LOCK; status = AmqpChannel::AMQP_ChannelReceive(channelHandle, frame, 0); } if (frame) { ++frameCount; try { SmartPtrAMQCommand command = _command; if (command->handleFrame(frame)) { _command.CreateInstance(); _command->init(); handleCompleteInboundCommand(command); } } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_CRIT_VA1("channel #%d", _channelNumber); CAF_CM_LOG_CRIT_CAFEXCEPTION; // Throw away the current command _command.CreateInstance(); _command->init(); // Abort any outstanding rpc SmartPtrIRpcContinuation rpc; { CAF_CM_UNLOCK_LOCK; rpc = nextOutstandingRpc(); } if (rpc) { SmartPtrCCafException exception = CAF_CM_GETEXCEPTION; rpc->handleAbort(exception); } CAF_CM_CLEAREXCEPTION; } } else if ((status == AMQP_ERROR_TIMEOUT) || (status == AMQP_ERROR_IO_INTERRUPTED)) { break; } else { AMQUtil::checkAmqpStatus(status, "AmqpChannel::AMQP_ChannelReceive"); } } } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_CRIT_VA1("channel #%d", _channelNumber); CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } // If we get here and the _channelHandle is NULL then // the channel is closed. If so, return 'true'. // // If the _channelHandle is still good, return 'false' and let // this task run again. return (_channelHandle == NULL); } /* * A complete inbound AMQP command is available for processing. */ void AMQChannel::handleCompleteInboundCommand(const SmartPtrAMQCommand& command) { CAF_CM_FUNCNAME("handleCompleteInboundCommand"); // No LOCK_UNLOCK because there aren't any members to protect and because // this routine makes a blocking call. AMQCHANNEL_ENTRY; // Check with asyn processing first if (!processAsync(command)) { // Command was not handled so must be part of an outstanding // RPC call. Get the outstanding RPC call and have it process // it. // // The outstanding RPC call may have been aborted because we are // closing. That is the only time the RPC object should be null // when in this method SmartPtrIRpcContinuation rpc = nextOutstandingRpc(); if (rpc) { rpc->handleCommand(command); } else if (isOpen()) { CAF_CM_EXCEPTIONEX_VA3( NullPointerException, 0, "[command=%s, class_id: 0x%08x, method_id: 0x%08x] nextOutstandingRpc() returned NULL and the channel is open. " "This should never happen. Please report this bug.", command->getMethod()->getProtocolMethodName().c_str(), command->getMethod()->getProtocolClassId(), command->getMethod()->getProtocolMethodId()); } } AMQCHANNEL_EXIT; } /* * First line of incomming command processing. This method handles * non-RPC commands such as channel.close, basic.deliver, basic.recover, etc. */ bool AMQChannel::processAsync(const SmartPtrAMQCommand& command) { CAF_CM_FUNCNAME("processAsync"); CAF_CM_LOCK_UNLOCK; AMQCHANNEL_ENTRY; bool commandHandled = false; const amqp_method_number_t amqpMethodId = (command->getMethod()->getProtocolClassId() << 16) | command->getMethod()->getProtocolMethodId(); if (_debugLogFlags & DEBUGLOG_FLAG_AMQP) { CAF_CM_LOG_DEBUG_VA4( "Method [channel=%d][class id=0x%04X][method id=0x%04X][name=%s]", _channelNumber, command->getMethod()->getProtocolClassId(), command->getMethod()->getProtocolMethodId(), command->getMethod()->getProtocolMethodName().c_str()); } if (amqpMethodId == AMQP_CHANNEL_OPEN_OK_METHOD) { // no-op. let it pass through } else if (amqpMethodId == AMQP_CHANNEL_CLOSE_METHOD) { // first order of business - stop the dispatcher from handling incoming messages _dispatcher->quiesce(); AmqpMethods::Channel::SmartPtrClose chClose; chClose.QueryInterface(command->getMethod(), false); if (chClose) { if (_debugLogFlags & DEBUGLOG_FLAG_AMQP) { CAF_CM_LOG_INFO_VA5( "channel.close %s [channel=%d][code=0x%04X][class id=0x%04X][method id=0x%04X]", chClose->getReplyText().c_str(), _channelNumber, chClose->getReplyCode(), chClose->getClassId(), chClose->getMethodId()); } } else { // Okay - very weird but we need to keep on going... CAF_CM_LOG_CRIT_VA0( "Received AMQP_CHANNEL_CLOSE_METHOD but method object " "is not a AmqpMethods::Channel::Close instance. Please report " "this bug."); } { CAF_CM_UNLOCK_LOCK; channelCloseByServerShutdown(chClose); } commandHandled = true; } else if (amqpMethodId == AMQP_CHANNEL_CLOSE_OK_METHOD) { _channelHandle = AMQP_HANDLE_INVALID; commandHandled = true; } else if (isOpen()) { try { SmartPtrIMethod method = command->getMethod(); SmartPtrIContentHeader contentHeader = command->getContentHeader(); switch (amqpMethodId) { case AMQP_BASIC_DELIVER_METHOD: { commandHandled = true; AmqpMethods::Basic::SmartPtrDeliver deliverMethod; deliverMethod.QueryInterface(method, false); if (deliverMethod) { SmartPtrEnvelopeImpl envelope; envelope.CreateInstance(); envelope->init( deliverMethod->getDeliveryTag(), deliverMethod->getRedelivered(), deliverMethod->getExchange(), deliverMethod->getRoutingKey()); AmqpContentHeaders::SmartPtrBasicProperties properties; if (contentHeader) { properties.QueryInterface(contentHeader, false); if (!properties) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected a basic properties content header. Received '%s'. " "Please report this bug.", contentHeader->getClassName().c_str()); } } _dispatcher->handleDelivery( deliverMethod->getConsumerTag(), envelope, properties, command->getContentBody()); } else { CAF_CM_EXCEPTIONEX_VA0( IllegalStateException, 0, "Received AMQP_BASIC_DELIVER_METHOD but the method object " "is not a AmqpClient::AmqpMethods::Basic::Deliver instance. " "Please report this bug."); } } break; case AMQP_BASIC_RETURN_METHOD: callReturnListeners(command); commandHandled = true; break; } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; if (CAF_CM_ISEXCEPTION) { // discard the command commandHandled = true; } CAF_CM_CLEAREXCEPTION; } else { // We are shutting down so the inbound command should be // discarded per spec. 'Consume' it by returning true. if (_debugLogFlags & DEBUGLOG_FLAG_AMQP) { CAF_CM_LOG_INFO_VA0("isOpen() is false. Discarding command."); } commandHandled = true; } AMQCHANNEL_EXIT; return commandHandled; } /* * Checks the _isOpen flag and throws an exception if the * channel is closed. */ void AMQChannel::ensureIsOpen() { CAF_CM_FUNCNAME("ensureIsOpen"); CAF_CM_LOCK_UNLOCK; AMQCHANNEL_ENTRY; if (!isOpen()) { CAF_CM_EXCEPTIONEX_VA0( AmqpExceptions::ChannelClosedException, 0, "Attempt to use closed channel"); } AMQCHANNEL_EXIT; } /* * Execute a synchronous call such as basic.get, queue.declare, exchange.delete, * etc. The AMQP synchronous calls are all executed through this mechanism. */ SmartPtrAMQCommand AMQChannel::execRpc(const SmartPtrIServerMethod& method) { CAF_CM_FUNCNAME("execRpc"); AMQCHANNEL_ENTRY; SmartPtrBlockingRpcContinuation rpc; try { CAF_CM_LOCK_UNLOCK1(_channelMutex); CAF_CM_LOCK_UNLOCK; ensureIsOpen(); const std::string methodName = method->getMethodName(); rpc.CreateInstance(); rpc->init(); // Wait for the current rpc to finish while (_activeRpc) { { CAF_CM_UNLOCK_LOCK; _channelSignal.waitOrTimeout(_channelMutex, 0); } } // indicate the new active RPC call _activeRpc = rpc; if (_debugLogFlags & DEBUGLOG_FLAG_AMQP) { CAF_CM_LOG_DEBUG_VA2( "[channel=%d] Sending AMQP method %s", _channelNumber, method->getMethodName().c_str()); } // send the call to the server AMQUtil::checkAmqpStatus( method->send(_channelHandle), methodName.c_str()); } CAF_CM_CATCH_ALL; CAF_CM_THROWEXCEPTION; // Check the reply. If null there should be // a reason (exception) explaining why the call failed. // This getReply() doesn't need to be in a UNLOCK_LOCK because the LOCK_UNLOCK // was scoped by the try. SmartPtrAMQCommand reply = rpc->getReply(); CAF_CM_LOG_DEBUG_VA1("RPC reply - %s", (reply.IsNull() ? "NULL" : reply->getMethod()->getProtocolMethodName().c_str())); AMQCHANNEL_EXIT; if (!reply) { SmartPtrCCafException exception = rpc->getException(); if (exception) { exception->throwAddRefedSelf(); } else { CAF_CM_EXCEPTIONEX_VA0( IllegalStateException, 0, "AMQP reply was not returned and no exception (reason) was provided."); } } return reply; } /* * Retrieve the outstanding RPC call. This method interacts with the execRpc() * method indirectly through the _channelMutex and _channelSignal. * The execRpc() call blocks until the current RPC call is handled by the thread * running the taskHandler (which eventually calls handleCompleteInboundCommand()) * which calls this. * * When handleCompleteInboundCommand() gets the outstanding RPC to handle the command, * the _activeRpc member is cleared and _channelSignal is signaled thus freeing * the execRpc() call to execute its RPC. */ SmartPtrIRpcContinuation AMQChannel::nextOutstandingRpc() { CAF_CM_FUNCNAME_VALIDATE("nextOutstandingRpc"); CAF_CM_LOCK_UNLOCK1(_channelMutex); CAF_CM_LOCK_UNLOCK; SmartPtrIRpcContinuation result = _activeRpc; _activeRpc = NULL; _channelSignal.signal(); AMQCHANNEL_EXIT; return result; } /* * Transmit an AMQP method to the server */ void AMQChannel::transmit(const SmartPtrIServerMethod& method) { CAF_CM_FUNCNAME_VALIDATE("transmit"); CAF_CM_LOCK_UNLOCK; AMQCHANNEL_ENTRY; CAF_CM_VALIDATE_SMARTPTR(method); if (_debugLogFlags & DEBUGLOG_FLAG_AMQP) { CAF_CM_LOG_DEBUG_VA2( "[channel=%d] Sending AMQP method %s", _channelNumber, method->getMethodName().c_str()); } AMQUtil::checkAmqpStatus(method->send(_channelHandle)); AMQCHANNEL_EXIT; } /* * This method is called when we have received a channel.close method * from the server. Respond with a channel.close-ok method then * abort the outstanding RPC (if any) with the exception (reason) for the abort. */ void AMQChannel::channelCloseByServerShutdown( const AmqpMethods::Channel::SmartPtrClose& closeMethod) { CAF_CM_FUNCNAME("channelCloseByServerShutdown"); AMQCHANNEL_ENTRY; try { CAF_CM_LOCK_UNLOCK1(_channelMutex); CAF_CM_LOCK_UNLOCK; _isOpen = false; _dispatcher->quiesce(); // Send channel.close-ok SmartPtrChannelCloseOkMethod method; method.CreateInstance(); method->init(); transmit(method); // Create the reason for the shutdown. AmqpExceptions::SmartPtrChannelClosedByServerException exception; try { exception.CreateInstance(); // We *should* have received a Channel::Close method BUT you can // never be too careful... if (closeMethod) { exception->populateVA( closeMethod->getReplyCode(), _cm_className_, _cm_funcName_, "channel.close %s [channel=%d][code=0x%04X][class id=0x%04X][method id=0x%04X]", closeMethod->getReplyText().c_str(), _channelNumber, closeMethod->getReplyCode(), closeMethod->getClassId(), closeMethod->getMethodId()); } else { exception->populate( "channel.close - no other information available", 0, _cm_className_, _cm_funcName_); } // Abort the outstanding rpc if any if (_activeRpc) { SmartPtrIRpcContinuation rpc = _activeRpc; _activeRpc = NULL; rpc->handleAbort(exception); } // Notify the dispatcher _dispatcher->handleShutdown(exception); } CAF_CM_CATCH_ALL; // Tear down AmqpChannel::AMQP_ChannelClose(_channelHandle); _channelHandle = AMQP_HANDLE_INVALID; // Remove this channel from management _connection->notifyChannelClosedByServer(_channelNumber); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; AMQCHANNEL_EXIT; } void AMQChannel::callReturnListeners(const SmartPtrAMQCommand& command) { CAF_CM_FUNCNAME("callReturnListeners"); CAF_CM_LOCK_UNLOCK; try { AmqpMethods::Basic::SmartPtrReturn basicReturn; basicReturn.QueryInterface(command->getMethod(), false); if (basicReturn) { CowReturnListenerCollection::SmartPtrContainer listeners = _returnListeners.getAll(); AmqpContentHeaders::SmartPtrBasicProperties properties; properties.QueryInterface(command->getContentHeader(), false); if (properties) { for (TSmartIterator listener(*listeners); listener; listener++) { listener->handleReturn( basicReturn->getReplyCode(), basicReturn->getReplyText(), basicReturn->getExchange(), basicReturn->getRoutingKey(), properties, command->getContentBody()); } } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected content header to be a basic.properties object. Instead it is " "a '%s' object. Please report this bug.", command->getContentHeader()->getClassName().c_str()); } } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Expected command to be a basic.return command. Instead it is a " "'%s' command. Please report this bug.", command->getMethod()->getProtocolMethodName().c_str()); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } #endif #if (1) // ChannelTask AMQChannel::ChannelTask::ChannelTask() : CAF_CM_INIT("AMQChannel::ChannelTask") { } AMQChannel::ChannelTask::~ChannelTask() { } void AMQChannel::ChannelTask::init(SmartPtrAMQChannel channel) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_channel); CAF_CM_VALIDATE_PTR(channel); _channel = channel; } bool AMQChannel::ChannelTask::run() { CAF_CM_FUNCNAME_VALIDATE("run"); CAF_CM_PRECOND_ISINITIALIZED(_channel); return _channel->taskHandler(); } #endif AMQChannelManager.cpp000066400000000000000000000075141321503522500365020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/AMQChannel.h" #include "amqpClient/ConsumerWorkService.h" #include "amqpClient/api/Channel.h" #include "amqpClient/AMQChannelManager.h" #include "Exception/CCafException.h" using namespace Caf::AmqpClient; AMQChannelManager::AMQChannelManager() : _isInitialized(false), CAF_CM_INIT_LOG("AMQChannelManager") { CAF_CM_INIT_THREADSAFE; } AMQChannelManager::~AMQChannelManager() { } void AMQChannelManager::init(const SmartPtrConsumerWorkService& workService) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_PTR(workService); _workService = workService; _isInitialized = true; } SmartPtrChannel AMQChannelManager::createChannel(const SmartPtrIConnectionInt& connection) { CAF_CM_FUNCNAME("createChannel"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(connection); SmartPtrAMQChannel channel; channel.CreateInstance(); SmartPtrConsumerWorkService workService = _workService; { CAF_CM_UNLOCK_LOCK; channel->init(connection, workService); } const uint16 channelNumber = channel->getChannelNumber(); if (_channelMap.insert(ChannelMap::value_type(channelNumber, channel)).second) { } else { CAF_CM_EXCEPTIONEX_VA1( DuplicateElementException, 0, "Channel number %d is already in use. This should never happen. " "Please report this as a bug.", channelNumber); } return channel; } SmartPtrChannel AMQChannelManager::getChannel(const uint16 channelNumber) { CAF_CM_FUNCNAME("getChannel"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrChannel channel; ChannelMap::const_iterator channelIter = _channelMap.find(channelNumber); if (channelIter != _channelMap.end()) { channel = (*channelIter).second; } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Channel #%d does not exist.", channelNumber); } return channel; } size_t AMQChannelManager::getOpenChannelCount() { CAF_CM_FUNCNAME_VALIDATE("getOpenChannelCount"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _channelMap.size(); } void AMQChannelManager::notifyConnectionClose(SmartPtrCCafException& shutdownException) { CAF_CM_FUNCNAME("notifyConnectionClose"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); try { _workService->notifyConnectionClosed(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; for (TSmartMapIterator channel(_channelMap); channel; channel++) { try { CAF_CM_UNLOCK_LOCK; channel->notifyConnectionClosed(shutdownException); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } _channelMap.clear(); } void AMQChannelManager::closeChannel(const uint16 channelNumber, SmartPtrCCafException& reason) { CAF_CM_FUNCNAME("closeChannel"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ChannelMap::iterator channel = _channelMap.find(channelNumber); if (channel != _channelMap.end()) { { CAF_CM_UNLOCK_LOCK; channel->second->close(reason); } _channelMap.erase(channel); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Channel #%d is not in the channel manager", channelNumber); } } void AMQChannelManager::removeChannel(const uint16 channelNumber) { CAF_CM_FUNCNAME("removeChannel"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ChannelMap::iterator channel = _channelMap.find(channelNumber); if (channel != _channelMap.end()) { _channelMap.erase(channel); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Channel #%d is not in the channel manager", channelNumber); } } AMQCommand.cpp000066400000000000000000000025571321503522500352170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/amqpImpl/IContentHeader.h" #include "amqpClient/amqpImpl/IMethod.h" #include "amqpClient/AMQCommand.h" using namespace Caf::AmqpClient; AMQCommand::AMQCommand() : CAF_CM_INIT("AMQCommand") { } AMQCommand::~AMQCommand() { } void AMQCommand::init() { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_assembler); _assembler.CreateInstance(); _assembler->init(); } bool AMQCommand::handleFrame(const SmartPtrCAmqpFrame& frame) { CAF_CM_FUNCNAME_VALIDATE("handleFrame"); CAF_CM_PRECOND_ISINITIALIZED(_assembler); return _assembler->handleFrame(frame); } SmartPtrCDynamicByteArray AMQCommand::getContentBody() { CAF_CM_FUNCNAME_VALIDATE("getContentBody"); CAF_CM_PRECOND_ISINITIALIZED(_assembler); return _assembler->getContentBody(); } SmartPtrIContentHeader AMQCommand::getContentHeader() { CAF_CM_FUNCNAME_VALIDATE("getContentHeader"); CAF_CM_PRECOND_ISINITIALIZED(_assembler); return _assembler->getContentHeader(); } SmartPtrIMethod AMQCommand::getMethod() { CAF_CM_FUNCNAME_VALIDATE("getMethod"); CAF_CM_PRECOND_ISINITIALIZED(_assembler); return _assembler->getMethod(); } AMQConnection.cpp000066400000000000000000000322371321503522500357360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/AMQChannelManager.h" #include "amqpClient/CAmqpConnection.h" #include "amqpClient/ConnectionWeakReference.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" #include "amqpClient/api/Channel.h" #include "amqpClient/AMQConnection.h" #include "Exception/CCafException.h" #include "AMQUtil.h" using namespace Caf::AmqpClient; AMQConnection::AMQConnection() : _isInitialized(false), _isRunning(false), _shouldShutdown(false), _wasCloseCalled(false), _thread(NULL), _connectionTimeout(0), _requestedFrameMax(0), _requestedChannelMax(0), _requestedHeartbeat(0), _retries(0), _secondsToWait(0), CAF_CM_INIT_LOG("AMQConnection") { CAF_CM_FUNCNAME("AMQPConnection()"); CAF_CM_INIT_THREADSAFE; try { CAF_THREADSIGNAL_INIT; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } AMQConnection::~AMQConnection() { CAF_CM_FUNCNAME_VALIDATE("~AMQConnection()"); if (_weakReferenceSelf) { _weakReferenceSelf->clearReference(); _weakReferenceSelf = NULL; } if (_connectionHandle && !_wasCloseCalled) { CAF_CM_LOG_CRIT_VA0( "close() has not been called on this connection. " "You *** MUST *** call close() on a connection before releasing it."); } if (_connectionHandle) { AmqpConnection::AMQP_ConnectionClose(_connectionHandle); } } void AMQConnection::init( const std::string username, const std::string password, const SmartPtrAddress& address, const SmartPtrCertInfo& certInfo, const uint32 requestedFrameMax, const uint32 requestedChannelMax, const uint32 requestedHeartbeat, const uint32 connectionTimeout, const uint32 consumerThreadCount, const uint16 retries, const uint16 secondsToWait) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(username); // password is optional (e.g. AMQP Tunnel) CAF_CM_VALIDATE_SMARTPTR(address); // other parameters do not require validation CAF_CM_LOG_DEBUG_VA1( "Creating AuthPlain credential for user %s", username.c_str()); AMQPStatus status = AmqpAuthPlain::AMQP_AuthPlainCreateClient( _authMechanism, username, password); AMQUtil::checkAmqpStatus(status, "AmqpAuthPlain::AMQP_AuthPlainCreateClient"); _address = address; _certInfo = certInfo; _requestedFrameMax = requestedFrameMax; _requestedChannelMax = requestedChannelMax; _requestedHeartbeat = requestedHeartbeat; _retries = retries; _secondsToWait = secondsToWait; initConnection(); _connectionTimeout = connectionTimeout; _connectionSignal.initialize("connectionSignal"); _weakReferenceSelf.CreateInstance(); _weakReferenceSelf->setReference(this); _threadPool.CreateInstance(); _threadPool->init(address->toString(), consumerThreadCount, 100); _workService.CreateInstance(); _workService->init(_threadPool); _isInitialized = true; } void AMQConnection::start() { CAF_CM_FUNCNAME("start"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(!_isRunning); bool rc = false; GThread* thread = _thread; uint32 connectionTimeout = _connectionTimeout; { CAF_CM_UNLOCK_LOCK; CAF_THREADSIGNAL_LOCK_UNLOCK; thread = CThreadUtils::startJoinable(threadFunc, this); rc = _connectionSignal.waitOrTimeout(CAF_THREADSIGNAL_MUTEX, connectionTimeout); } _thread = thread; if (rc) { try { uint16 channelMax = 0; AMQUtil::checkAmqpStatus( AmqpConnection::AMQP_ConnectionGetMaxChannels(_connectionHandle, &channelMax), "AmqpConnection::AMQP_ConnectionGetMaxChannels"); uint32 frameMax = 0; AMQUtil::checkAmqpStatus( AmqpConnection::AMQP_ConnectionGetMaxFrameSize(_connectionHandle, &frameMax), "AmqpConnection::AMQP_ConnectionGetMaxFrameSize"); uint16 heartbeat = 0; AMQUtil::checkAmqpStatus( AmqpConnection::AMQP_ConnectionGetHeartbeatInterval(_connectionHandle, &heartbeat), "AMQUtil::checkAmqpStatus"); CAF_CM_LOG_DEBUG_VA3( "Tuned connection [chMax=%d][frameMax=%d][hbeat=%d]", channelMax, frameMax, heartbeat); _channelManager.CreateInstance(); _channelManager->init(_workService); } CAF_CM_CATCH_ALL CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } else { CAF_CM_LOG_DEBUG_VA1("Need to shutdown due to start issue: %d", rc); _shouldShutdown = true; SmartPtrCCafException threadException; GThread* thread = _thread; { CAF_CM_UNLOCK_LOCK; threadException = static_cast(g_thread_join(thread)); } _thread = NULL; if (threadException) { threadException->throwAddRefedSelf(); } else { CAF_CM_EXCEPTIONEX_VA1( AmqpExceptions::AmqpTimeoutException, 0, "Timed out trying to connect to %s", _address->toString().c_str()); } } } SmartPtrChannel AMQConnection::createChannel() { CAF_CM_FUNCNAME_VALIDATE("createChannel"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); bool isRunning; SmartPtrAMQChannelManager channelManager; SmartPtrConnectionWeakReference weakReferenceSelf; { CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); isRunning = _isRunning; channelManager = _channelManager; weakReferenceSelf = _weakReferenceSelf; } return createChannel(isRunning, channelManager, weakReferenceSelf); } void AMQConnection::closeChannel(const SmartPtrChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("closeChannel"); CAF_CM_VALIDATE_SMARTPTR(channel); bool isRunning; SmartPtrAMQChannelManager channelManager; { CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); isRunning = _isRunning; channelManager = _channelManager; } closeChannel(isRunning, channelManager, channel); } void AMQConnection::close() { CAF_CM_FUNCNAME_VALIDATE("close"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _wasCloseCalled = true; if (_isRunning) { CAF_CM_LOG_DEBUG_VA0("Need to shutdown becaue the connection is closing"); _shouldShutdown = true; _weakReferenceSelf->clearReference(); _weakReferenceSelf = NULL; _workService->notifyConnectionClosed(); if (NULL != _thread) { GThread* thread = _thread; { CAF_CM_UNLOCK_LOCK; g_thread_join(thread); } _thread = NULL; } { CAF_CM_UNLOCK_LOCK; while (_channelManager->getOpenChannelCount()) { CThreadUtils::sleep(100); } } } } bool AMQConnection::isOpen() { CAF_CM_FUNCNAME_VALIDATE("isOpen"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return (_isRunning && !_shouldShutdown); } AMQPStatus AMQConnection::amqpConnectionOpenChannel(SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("amqpConnectionOpenChannel"); CAF_CM_LOCK_UNLOCK; CAF_CM_LOG_DEBUG_VA0("calling AmqpConnection::AMQP_ConnectionOpenChannel"); AMQPStatus status = AmqpConnection::AMQP_ConnectionOpenChannel(_connectionHandle, channel); if (status == AMQP_ERROR_OK) { uint16 id = 0; AmqpChannel::AMQP_ChannelGetId(channel, &id); CAF_CM_LOG_DEBUG_VA1("created channel #%d", id); } else { CAF_CM_LOG_DEBUG_VA1("failed to create channel. status=%d", status); } return status; } void AMQConnection::notifyChannelClosedByServer(const uint16 channelNumber) { CAF_CM_LOCK_UNLOCK; _channelManager->removeChannel(channelNumber); } void AMQConnection::channelCloseChannel(Channel *channel) { CAF_CM_FUNCNAME_VALIDATE("channelCloseChannel"); CAF_CM_VALIDATE_PTR(channel); closeChannel(channel); } void AMQConnection::initConnection() { CAF_CM_FUNCNAME_VALIDATE("initConnection"); CAF_CM_LOCK_UNLOCK; CAF_CM_LOG_DEBUG_VA3( "Creating connection " "[reqChMax=%d][reqFrameMax=%d][reqHB=%d]", _requestedChannelMax, _requestedFrameMax, _requestedHeartbeat); AMQPStatus status = AmqpConnection::AMQP_ConnectionCreate( _connectionHandle, _address, _authMechanism, _certInfo, _requestedChannelMax, _requestedFrameMax, _requestedHeartbeat, _retries, _secondsToWait); AMQUtil::checkAmqpStatus(status, "AmqpConnection::AMQP_ConnectionCreate"); } void AMQConnection::closeChannel( const bool isRunning, const SmartPtrAMQChannelManager channelManager, const SmartPtrChannel& channel) { CAF_CM_STATIC_FUNC("AMQConnection", "closeChannel"); CAF_CM_VALIDATE_SMARTPTR(channelManager); CAF_CM_VALIDATE_SMARTPTR(channel); if (isRunning) { if (channel->isOpen()) { const uint16 channelNumber = channel->getChannelNumber(); SmartPtrCCafException reason; try { AmqpExceptions::SmartPtrChannelClosedByUserException exception; exception.CreateInstance(); reason = exception.GetNonAddRefedInterface(); reason->populate( "Closed by user", 0, _cm_className_, _cm_funcName_); channelManager->closeChannel(channelNumber, reason); } CAF_CM_CATCH_ALL; } } else { CAF_CM_EXCEPTIONEX_VA0( IllegalStateException, 0, "The connection is closed"); } } SmartPtrChannel AMQConnection::createChannel( const bool isRunning, const SmartPtrAMQChannelManager& channelManager, const SmartPtrConnectionWeakReference& weakReferenceSelf) { CAF_CM_STATIC_FUNC("AMQConnection", "createChannel"); if (!isRunning) { CAF_CM_EXCEPTIONEX_VA0( AmqpExceptions::ConnectionClosedException, 0, "The connection is closed"); } return channelManager->createChannel(weakReferenceSelf); } void* AMQConnection::threadFunc(void* context) { CAF_CM_STATIC_FUNC("AMQConnection", "threadFunc"); try { CAF_CM_VALIDATE_PTR(context); SmartPtrAMQConnection self = (AMQConnection*)context; self->threadWorker(); } CAF_CM_CATCH_ALL; return CAF_CM_GETEXCEPTION; } void AMQConnection::threadWorker() { CAF_CM_FUNCNAME("threadWorker"); CAF_CM_LOCK_UNLOCK; try { CAF_CM_LOG_DEBUG_VA1( "Connecting to %s", _address->toString().c_str()); AMQPStatus status = AMQP_ERROR_OK; SmartPtrCAmqpConnection connectionHandle = _connectionHandle; { CAF_CM_UNLOCK_LOCK; status = AmqpConnection::AMQP_ConnectionConnect( connectionHandle, AMQP_CONNECTION_FLAG_CLOSE_SOCKET); } AMQUtil::checkAmqpStatus(status, "AmqpConnection::AMQP_ConnectionConnect"); AMQPConnectionState state; status = AmqpConnection::AMQP_ConnectionGetState( _connectionHandle, &state); AMQUtil::checkAmqpStatus(status, "AmqpConnection::AMQP_ConnectionGetState"); while (!_shouldShutdown && (AMQP_STATE_CONNECTED != state)) { status = AmqpConnection::AMQP_ConnectionProcessIO(_connectionHandle); switch (status) { case AMQP_ERROR_OK: break; case AMQP_ERROR_IO_ERROR: { const char *err = NULL; AmqpConnection::AMQP_ConnectionGetLastError(_connectionHandle, &err); CAF_CM_LOG_WARN_VA2( "Connection to [%s] failed: %s", _address->toString().c_str(), err); _connectionHandle = AMQP_HANDLE_INVALID; CThreadUtils::sleep(250); initConnection(); AMQPStatus status = AmqpConnection::AMQP_ConnectionConnect( _connectionHandle, AMQP_CONNECTION_FLAG_CLOSE_SOCKET); AMQUtil::checkAmqpStatus(status, "AmqpConnection::AMQP_ConnectionConnect"); } break; default: { const char *err = NULL; AmqpConnection::AMQP_ConnectionGetLastError(_connectionHandle, &err); AMQUtil::checkAmqpStatus(status, err); } break; } status = AmqpConnection::AMQP_ConnectionGetState( _connectionHandle, &state); AMQUtil::checkAmqpStatus( status, "AmqpConnection::AMQP_ConnectionGetState"); } if (!_shouldShutdown && (AMQP_STATE_CONNECTED == state)) { { CAF_THREADSIGNAL_LOCK_UNLOCK; _isRunning = true; _connectionSignal.signal(); } while (!_shouldShutdown && AMQP_STATE_CONNECTED == state) { SmartPtrCAmqpConnection connectionHandle = _connectionHandle; { CAF_CM_UNLOCK_LOCK; status = AmqpConnection::AMQP_ConnectionWaitForIO(connectionHandle, 200); status = AmqpConnection::AMQP_ConnectionProcessIO(connectionHandle); status = AmqpConnection::AMQP_ConnectionGetState(connectionHandle, &state); } } _isRunning = false; CAF_CM_LOG_DEBUG_VA2( "IO loop has stopped. " "[_shouldShutdown=%d][state=%d]", _shouldShutdown, state); SmartPtrCCafException shutdownException; try { if (_shouldShutdown) { AmqpExceptions::SmartPtrChannelClosedByShutdownException exception; exception.CreateInstance(); shutdownException = exception.GetNonAddRefedInterface(); shutdownException->populate( "Normal application shutdown", 0, _cm_className_, _cm_funcName_); } else { const char* error = NULL; AmqpConnection::AMQP_ConnectionGetLastError(_connectionHandle, &error); AmqpExceptions::SmartPtrConnectionClosedByIOException exception; exception.CreateInstance(); shutdownException = exception.GetNonAddRefedInterface(); shutdownException->populate( error, 0, _cm_className_, _cm_funcName_); } { CAF_CM_UNLOCK_LOCK; _channelManager->notifyConnectionClose(shutdownException); } AmqpConnection::AMQP_ConnectionClose(_connectionHandle); _connectionHandle = AMQP_HANDLE_INVALID; } CAF_CM_CATCH_ALL; } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } AMQUtil.cpp000066400000000000000000000222301321503522500345440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 3, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/FieldImpl.h" #include "amqpClient/api/amqpClient.h" #include "Exception/CCafException.h" #include "AMQUtil.h" using namespace Caf::AmqpClient; using namespace Caf::AmqpClient::AmqpExceptions; void AMQUtil::checkAmqpStatus( const AMQPStatus status, const char* message) { CAF_CM_STATIC_FUNC("AMQUtil", "checkAmqpStatus"); const char* exMsg = message ? message : ""; switch (status) { case AMQP_ERROR_OK: break; case AMQP_ERROR_TIMEOUT: CAF_CM_EXCEPTIONEX_VA0(AmqpTimeoutException, 0, exMsg); break; case AMQP_ERROR_NO_MEMORY: CAF_CM_EXCEPTIONEX_VA0(AmqpNoMemoryException, 0, exMsg); break; case AMQP_ERROR_INVALID_HANDLE: CAF_CM_EXCEPTIONEX_VA0(AmqpInvalidHandleException, 0, exMsg); break; case AMQP_ERROR_INVALID_ARGUMENT: CAF_CM_EXCEPTIONEX_VA0(AmqpInvalidArgumentException, 0, exMsg); break; case AMQP_ERROR_WRONG_STATE: CAF_CM_EXCEPTIONEX_VA0(AmqpWrongStateException, 0, exMsg); break; case AMQP_ERROR_TOO_MANY_CHANNELS: CAF_CM_EXCEPTIONEX_VA0(AmqpTooManyChannelsException, 0, exMsg); break; case AMQP_ERROR_QUEUE_FULL: CAF_CM_EXCEPTIONEX_VA0(AmqpQueueFullException, 0, exMsg); break; case AMQP_ERROR_FRAME_TOO_LARGE: CAF_CM_EXCEPTIONEX_VA0(AmqpFrameTooLargeException, 0, exMsg); break; case AMQP_ERROR_IO_ERROR: CAF_CM_EXCEPTIONEX_VA0(AmqpIoErrorException, 0, exMsg); break; case AMQP_ERROR_PROTOCOL_ERROR: CAF_CM_EXCEPTIONEX_VA0(AmqpProtocolErrorException, 0, exMsg); break; case AMQP_ERROR_UNIMPLEMENTED: CAF_CM_EXCEPTIONEX_VA0(AmqpUnimplementedException, 0, exMsg); break; case AMQP_ERROR_IO_INTERRUPTED: CAF_CM_EXCEPTIONEX_VA0(AmqpIoInterruptedException, 0, exMsg); break; default: CAF_CM_EXCEPTIONEX_VA0(AmqpException, status, exMsg); break; } } std::string AMQUtil::amqpBytesToString(const amqp_bytes_t * const amqpBytes) { CAF_CM_STATIC_FUNC_VALIDATE("AMQUtil", "amqpBytesToString"); CAF_CM_VALIDATE_PTR(amqpBytes); CDynamicCharArray buf; buf.allocateBytes(amqpBytes->len); buf.memCpy(amqpBytes->bytes, amqpBytes->len); return buf.getPtr(); } SmartPtrTable AMQUtil::amqpApiTableToTableObj(const amqp_table_t * const amqpTable) { CAF_CM_STATIC_FUNC_LOG("AMQUtil", "amqpApiTableToTableObj"); CAF_CM_VALIDATE_PTR(amqpTable); SmartPtrTable table; table.CreateInstance(); for (int32 idx = 0; idx < amqpTable->num_entries; ++idx) { amqp_table_entry_t *entry = &amqpTable->entries[idx]; CAF_CM_VALIDATE_PTR(entry); std::string key = amqpBytesToString(&entry->key); SmartPtrFieldImpl field; field.CreateInstance(); switch (entry->value.kind) { case AMQP_FIELD_KIND_BOOLEAN: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_BOOLEAN, g_variant_new_boolean(entry->value.value.boolean)); break; case AMQP_FIELD_KIND_I8: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_I8, g_variant_new_byte(entry->value.value.i8)); break; case AMQP_FIELD_KIND_U8: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_U8, g_variant_new_byte(entry->value.value.i8)); break; case AMQP_FIELD_KIND_I16: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_I16, g_variant_new_int16(entry->value.value.i16)); break; case AMQP_FIELD_KIND_U16: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_U16, g_variant_new_uint16(entry->value.value.u16)); break; case AMQP_FIELD_KIND_I32: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_I32, g_variant_new_int32(entry->value.value.i32)); break; case AMQP_FIELD_KIND_U32: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_U32, g_variant_new_uint32(entry->value.value.u32)); break; case AMQP_FIELD_KIND_I64: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_I64, g_variant_new_int64(entry->value.value.i64)); break; case AMQP_FIELD_KIND_U64: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_U64, g_variant_new_uint64(entry->value.value.u64)); break; case AMQP_FIELD_KIND_F32: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_F32, g_variant_new_double(entry->value.value.f32)); break; case AMQP_FIELD_KIND_F64: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_F32, g_variant_new_double(entry->value.value.f64)); break; case AMQP_FIELD_KIND_UTF8: { const std::string value = amqpBytesToString(&entry->value.value.bytes); field->setTypeAndValue( Field::AMQP_FIELD_TYPE_UTF8, g_variant_new_string(value.c_str())); } break; case AMQP_FIELD_KIND_TIMESTAMP: field->setTypeAndValue( Field::AMQP_FIELD_TYPE_TIMESTAMP, g_variant_new_uint64(entry->value.value.u64)); break; // Type not currently supported case AMQP_FIELD_KIND_ARRAY: case AMQP_FIELD_KIND_BYTES: case AMQP_FIELD_KIND_DECIMAL: case AMQP_FIELD_KIND_TABLE: case AMQP_FIELD_KIND_VOID: field = NULL; CAF_CM_LOG_ERROR_VA2( "AMQP field %s type %d is not supported", key.c_str(), entry->value.kind); break; default: field = NULL; CAF_CM_LOG_ERROR_VA2( "AMQP field %s type %d is unknown", key.c_str(), entry->value.kind); break; } if (field) { if (!table->insert(std::make_pair(key, field)).second) { CAF_CM_EXCEPTIONEX_VA1( DuplicateElementException, 0, "Duplicate field '%s' detected", key.c_str()); } } } return table; } void AMQUtil::amqpTableObjToApiTable(const SmartPtrTable& table, amqp_table_t& apiTable) { CAF_CM_STATIC_FUNC_LOG("AMQUtil", "amqpTableObjToApiTable"); CAF_CM_VALIDATE_SMARTPTR(table); memset(&apiTable, 0, sizeof(apiTable)); apiTable.num_entries = static_cast(table->size()); apiTable.entries = reinterpret_cast(AmqpCommon::AMQP_Calloc( apiTable.num_entries, sizeof(*apiTable.entries))); CAF_CM_VALIDATE_PTR(apiTable.entries); try { int32 idx = 0; for (TSmartConstMapIterator tableEntry(*table); tableEntry; tableEntry++, idx++) { amqp_table_entry_t *apiEntry = &apiTable.entries[idx]; apiEntry->key = amqp_cstring_bytes(tableEntry.getKey().c_str()); const SmartPtrField& field = *tableEntry; GVariant *variant = field->getValue(); switch (field->getAmqpType()) { case Field::AMQP_FIELD_TYPE_NOTSET: CAF_CM_EXCEPTIONEX_VA1( IllegalStateException, 0, "Table entry '%s' has a value type of AMQP_FIELD_TYPE_NOTSET", tableEntry.getKey().c_str()); break; case Field::AMQP_FIELD_TYPE_BOOLEAN: apiEntry->value.kind = AMQP_FIELD_KIND_BOOLEAN; apiEntry->value.value.boolean = g_variant_get_boolean(variant); break; case Field::AMQP_FIELD_TYPE_I8: apiEntry->value.kind = AMQP_FIELD_KIND_I8; apiEntry->value.value.i8 = g_variant_get_byte(variant); break; case Field::AMQP_FIELD_TYPE_U8: apiEntry->value.kind = AMQP_FIELD_KIND_U8; apiEntry->value.value.u8 = g_variant_get_byte(variant); break; case Field::AMQP_FIELD_TYPE_I16: apiEntry->value.kind = AMQP_FIELD_KIND_I16; apiEntry->value.value.i16 = g_variant_get_int16(variant); break; case Field::AMQP_FIELD_TYPE_U16: apiEntry->value.kind = AMQP_FIELD_KIND_U16; apiEntry->value.value.u16 = g_variant_get_uint16(variant); break; case Field::AMQP_FIELD_TYPE_I32: apiEntry->value.kind = AMQP_FIELD_KIND_I32; apiEntry->value.value.i32 = g_variant_get_int32(variant); break; case Field::AMQP_FIELD_TYPE_U32: apiEntry->value.kind = AMQP_FIELD_KIND_U32; apiEntry->value.value.u32 = g_variant_get_uint32(variant); break; case Field::AMQP_FIELD_TYPE_I64: apiEntry->value.kind = AMQP_FIELD_KIND_I64; apiEntry->value.value.i64 = g_variant_get_int64(variant); break; case Field::AMQP_FIELD_TYPE_U64: apiEntry->value.kind = AMQP_FIELD_KIND_U64; apiEntry->value.value.u64 = g_variant_get_uint64(variant); break; case Field::AMQP_FIELD_TYPE_F32: apiEntry->value.kind = AMQP_FIELD_KIND_F32; apiEntry->value.value.f32 = static_cast(g_variant_get_double(variant)); break; case Field::AMQP_FIELD_TYPE_F64: apiEntry->value.kind = AMQP_FIELD_KIND_F64; apiEntry->value.value.f64 = g_variant_get_double(variant); break; case Field::AMQP_FIELD_TYPE_UTF8: apiEntry->value.kind = AMQP_FIELD_KIND_UTF8; apiEntry->value.value.bytes = amqp_cstring_bytes(g_variant_get_string(variant, NULL)); break; case Field::AMQP_FIELD_TYPE_TIMESTAMP: apiEntry->value.kind = AMQP_FIELD_KIND_TIMESTAMP; apiEntry->value.value.u64 = g_variant_get_uint64(variant); break; case Field::AMQP_FIELD_TYPE_ARRAY: case Field::AMQP_FIELD_TYPE_BYTES: case Field::AMQP_FIELD_TYPE_DECIMAL: case Field::AMQP_FIELD_TYPE_TABLE: case Field::AMQP_FIELD_TYPE_VOID: default: CAF_CM_LOG_ERROR_VA2( "AMQP field %s type %d is not supported", tableEntry.getKey().c_str(), field->getAmqpType()); break; } } } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { amqpFreeApiTable(&apiTable); memset(&apiTable, 0, sizeof(apiTable)); } CAF_CM_THROWEXCEPTION; } void AMQUtil::amqpFreeApiTable(amqp_table_t *table) { if (table) { AmqpCommon::AMQP_Free(table->entries); memset(table, 0, sizeof(*table)); } } AMQUtil.h000066400000000000000000000033321321503522500342130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 3, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQUTIL_H_ #define AMQUTIL_H_ #include "amqpClient/api/amqpClient.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief A collection of helpers for dealing with AMQP and the underlying amqp library. */ namespace AMQUtil { /** * @brief Check an AMQPStatus and throw an exception if the status is not AMQP_ERROR_OK * @param status AMQPStatus returned from amqp library calls * @param message Optional message text to add to thrown exception */ void checkAmqpStatus( const AMQPStatus status, const char* message = NULL); /** * @brief Convert an amqp_bytes_t array to a std::string * @param amqpBytes Raw string bytes * @return conversion to string */ std::string amqpBytesToString(const amqp_bytes_t * const amqpBytes); /** * @brief Convert an amqp_table_t to a smart Table object * @param amqpTable Raw table bytes * @return convertion to a smart Table object */ SmartPtrTable amqpApiTableToTableObj(const amqp_table_t * const amqpTable); /** * @brief Convert a smart Table object to an amqp_table_t struct * The caller is responsible for cleaning up the table by calling amqpFreeApiTable() * @param table smart Table object source * @param apiTable amqp_table_t output struct */ void amqpTableObjToApiTable(const SmartPtrTable& table, amqp_table_t& apiTable); /** * @brief Clean up the memory used by a amqp_table_t * @param table table to free */ void amqpFreeApiTable(amqp_table_t *table); } }} #endif /* AMQUTIL_H_ */ Address.cpp000066400000000000000000000060121321503522500346550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/Address.h" #include "Exception/CCafException.h" using namespace Caf::AmqpClient; Address::Address() : _isInitialized(false), _protocol(PROTOCOL_AMQP), _port(UINT_MAX), CAF_CM_INIT_LOG("Address") {} Address::~Address() {} void Address::initialize( const std::string& protocol, const std::string& host, const uint32& port, const std::string& virtualHost) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(protocol); CAF_CM_VALIDATE_STRING(host); _protocol = translateProtocol(protocol, host); _protocolStr = protocol; _host = host; _port = port; _virtualHost = virtualHost; std::stringstream builder; builder << _protocolStr << ":" << "host=" << _host << "," << "port=" << _port << "," << "virtualhost=" << _virtualHost; _toString = builder.str(); _isInitialized = true; } /** * @return the protocol */ Protocol Address::getProtocol() const { CAF_CM_FUNCNAME_VALIDATE("getProtocol"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _protocol; } /** * @return the protocol */ std::string Address::getProtocolStr() const { CAF_CM_FUNCNAME_VALIDATE("getProtocol"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _protocolStr; } /** * @return the host name */ std::string Address::getHost() const { CAF_CM_FUNCNAME_VALIDATE("getHost"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _host; } /** * @return the port number */ uint32 Address::getPort() const { CAF_CM_FUNCNAME_VALIDATE("getPort"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _port; } std::string Address::getVirtualHost() const { CAF_CM_FUNCNAME_VALIDATE("getVirtualHost"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _virtualHost; } std::string Address::toString() const { CAF_CM_FUNCNAME_VALIDATE("toString"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _toString; } Protocol Address::translateProtocol( const std::string& protocol, const std::string& host) const { CAF_CM_FUNCNAME("translateProtocol"); CAF_CM_VALIDATE_STRING(protocol); CAF_CM_VALIDATE_STRING(host); Protocol rc = PROTOCOL_AMQP; if (protocol.compare("amqp") == 0) { rc = PROTOCOL_AMQP; CAF_CM_LOG_DEBUG_VA1( "Parsed amqp protocol - host: %s", host.c_str()); } else if (protocol.compare("amqps") == 0) { rc = PROTOCOL_AMQPS; CAF_CM_EXCEPTION_VA0(E_FAIL, "amqps protocol not yet supported"); } else if (protocol.compare("tunnel") == 0) { if ((host.compare("localhost") == 0) || (host.compare("127.0.0.1") == 0)) { rc = PROTOCOL_TUNNEL; CAF_CM_LOG_DEBUG_VA1( "Parsed tunnel protocol - host: %s", host.c_str()); } else { CAF_CM_EXCEPTION_VA1(E_FAIL, "Tunnel protocol only supports localhost - %s", host.c_str()); } } else { CAF_CM_EXCEPTION_VA1(E_FAIL, "Unknown protocol - %s", protocol.c_str()); } return rc; } AmqpAuthPlain.cpp000066400000000000000000000012301321503522500357710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpAuthMechanism.h" #include "AmqpAuthPlain.h" #include "AmqpUtil.h" using namespace Caf::AmqpClient; AMQPStatus AmqpAuthPlain::AMQP_AuthPlainCreateClient( SmartPtrCAmqpAuthMechanism& mech, const std::string& username, const std::string& password) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpAuthPlain", "AMQP_AuthPlainCreateClient"); CAF_CM_VALIDATE_STRING(username); // password is optional mech.CreateInstance(); return mech->createClient(username, password); } AmqpAuthPlain.h000066400000000000000000000011451321503522500354430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: Oct 7, 2014 * Author: bwilliams * * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCORE_AMQPAUTHPLAIN_H_ #define AMQPCORE_AMQPAUTHPLAIN_H_ #include "amqpClient/CAmqpAuthMechanism.h" namespace Caf { namespace AmqpClient { #define SHA256_HASH_LEN 32 class AmqpAuthPlain { public: static AMQPStatus AMQP_AuthPlainCreateClient( SmartPtrCAmqpAuthMechanism& pMech, const std::string& username, const std::string& password); private: CAF_CM_DECLARE_NOCREATE (AmqpAuthPlain); }; }} #endif /* AMQPCORE_AMQPAUTHPLAIN_H_ */ AmqpChannel.cpp000066400000000000000000000024341321503522500354630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/CAmqpFrame.h" #include "AmqpChannel.h" #include "AmqpUtil.h" using namespace Caf::AmqpClient; AMQPStatus AmqpChannel::AMQP_ChannelClose( const SmartPtrCAmqpChannel& channel) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpChannel", "AMQP_ChannelClose"); CAF_CM_VALIDATE_SMARTPTR(channel); return channel->close(); } AMQPStatus AmqpChannel::AMQP_ChannelCloseOk( const SmartPtrCAmqpChannel& channel) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpChannel", "AMQP_ChannelCloseOk"); CAF_CM_VALIDATE_SMARTPTR(channel); return channel->closeOk(); } AMQPStatus AmqpChannel::AMQP_ChannelReceive( const SmartPtrCAmqpChannel& channel, SmartPtrCAmqpFrame& frame, const int32 timeout) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpChannel", "AMQP_ChannelReceive"); CAF_CM_VALIDATE_SMARTPTR(channel); return channel->receive(frame, timeout); } AMQPStatus AmqpChannel::AMQP_ChannelGetId( const SmartPtrCAmqpChannel& channel, uint16 *id) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpChannel", "AMQP_ChannelGetId"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_PTR(id); return channel->getId(id); } AmqpChannel.h000066400000000000000000000017651321503522500351360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: Oct 7, 2014 * Author: bwilliams * * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCORE_AMQPCHANNEL_H_ #define AMQPCORE_AMQPCHANNEL_H_ #include "AmqpCommon.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/CAmqpFrame.h" namespace Caf { namespace AmqpClient { /** AMQP channel state. */ typedef enum AMQPChannelState { AMQP_CHANNEL_OPEN = 0, AMQP_CHANNEL_WAITING_FOR_CLOSE_OK, AMQP_CHANNEL_CLOSED } AMQPChannelState; class AmqpChannel { public: static AMQPStatus AMQP_ChannelClose( const SmartPtrCAmqpChannel& chan); static AMQPStatus AMQP_ChannelCloseOk( const SmartPtrCAmqpChannel& chan); static AMQPStatus AMQP_ChannelReceive( const SmartPtrCAmqpChannel& chan, SmartPtrCAmqpFrame& frame, const int32 timeout); static AMQPStatus AMQP_ChannelGetId( const SmartPtrCAmqpChannel& chan, uint16 *id); private: CAF_CM_DECLARE_NOCREATE (AmqpChannel); }; } } #endif /* AMQPCORE_CHANNEL_H_ */ AmqpCommon.cpp000066400000000000000000000137331321503522500353470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "AmqpCommon.h" using namespace Caf::AmqpClient; void* AmqpCommon::AMQP_Calloc( size_t nmemb, size_t size) { return calloc(nmemb, size); } void AmqpCommon::AMQP_Free( void *ptr) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpCommon", "AMQP_Free"); CAF_CM_VALIDATE_PTR(ptr); free(ptr); } int32 AmqpCommon::sendMethod( const amqp_connection_state_t& connectionState, const amqp_channel_t& channel, const amqp_method_number_t& methodId, void *decodedMethod) { return validateStatus( "amqp_send_method - " + CStringConv::toString(methodId), amqp_send_method( connectionState, channel, methodId, decodedMethod)); } int32 AmqpCommon::validateStatusRequired( const std::string& msg, const int32 status) { CAF_CM_STATIC_FUNC_LOG("AmqpCommon", "validateStatus"); CAF_CM_VALIDATE_STRING(msg); if (status < 0) { CAF_CM_EXCEPTION_VA2(E_FAIL, "%s: %s", msg.c_str(), amqp_error_string2(status)); } return status; } int32 AmqpCommon::validateStatus( const std::string& msg, const int32 status) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("AmqpCommon", "validateStatus"); CAF_CM_VALIDATE_STRING(msg); if (status < 0) { CAF_CM_LOG_WARN_VA2("%s: %s", msg.c_str(), amqp_error_string2(status)); } return status; } int32 AmqpCommon::validateRpcReply( const std::string& msg, const amqp_rpc_reply_t& rpcReply) { CAF_CM_STATIC_FUNC_LOG("AmqpCommon", "validateRpcReply"); CAF_CM_VALIDATE_STRING(msg); int32 status = 0; switch (rpcReply.reply_type) { case AMQP_RESPONSE_NORMAL: break; case AMQP_RESPONSE_NONE: CAF_CM_EXCEPTION_VA1(E_FAIL, "%s: missing RPC reply type!", msg.c_str()); break; case AMQP_RESPONSE_LIBRARY_EXCEPTION: status = rpcReply.library_error; CAF_CM_LOG_WARN_VA2("%s: %s", msg.c_str(), amqp_error_string2(rpcReply.library_error)); break; case AMQP_RESPONSE_SERVER_EXCEPTION: switch (rpcReply.reply.id) { case AMQP_CONNECTION_CLOSE_METHOD: { amqp_connection_close_t *reply = reinterpret_cast(rpcReply.reply.decoded); CAF_CM_EXCEPTION_VA4(E_FAIL, "%s: server connection error %d, message: %.*s", msg.c_str(), reply->reply_code, reply->reply_text.len, static_cast(reply->reply_text.bytes)); break; } case AMQP_CHANNEL_CLOSE_METHOD: { amqp_connection_close_t *reply = reinterpret_cast(rpcReply.reply.decoded); CAF_CM_EXCEPTION_VA4(E_FAIL, "%s: server channel error %d, message: %.*s", msg.c_str(), reply->reply_code, reply->reply_text.len, static_cast(reply->reply_text.bytes)); break; } default: CAF_CM_EXCEPTION_VA2(E_FAIL, "%s: unknown server error, method id 0x%08X", msg.c_str(), rpcReply.reply.id); break; } break; } return status; } void AmqpCommon::strToAmqpBytes( const std::string& src, amqp_bytes_t& dest, Csetstr& cachedStrings) { if (src.empty()) { dest.len = 0; dest.bytes = NULL; } else { dest = amqp_cstring_bytes(getString(src, cachedStrings).c_str()); } } const std::string& AmqpCommon::getString( const std::string& src, Csetstr& cachedStrings) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("AmqpCommon", "getString"); CAF_CM_VALIDATE_STRING(src); if (cachedStrings.end() == cachedStrings.find(src)) { cachedStrings.insert(src); } return *(cachedStrings.find(src)); } void AmqpCommon::boolToAmqpBool( const bool src, amqp_boolean_t& dest) { dest = src ? TRUE : FALSE; } void AmqpCommon::cpTableSafely( const amqp_table_t* src, amqp_table_t& dest) { dest = (NULL == src ? amqp_empty_table : *src); } void AmqpCommon::dumpMessageBody( const void *buffer, const size_t bufferLen) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("AmqpCommon", "dumpMessageBody"); CAF_CM_VALIDATE_PTR(buffer); unsigned char *buf = (unsigned char *) buffer; int32 count = 0; int32 numinrow = 0; int32 chs[16]; int32 oldchs[16] = {0}; int32 showed_dots = 0; size_t i; for (i = 0; i < bufferLen; i++) { int32 ch = buf[i]; if (numinrow == 16) { int32 i; if (rowsEqual(oldchs, chs)) { if (!showed_dots) { showed_dots = 1; CAF_CM_LOG_DEBUG_VA0( " .. .. .. .. .. .. .. .. : .. .. .. .. .. .. .. .."); } } else { showed_dots = 0; dumpRow(count, numinrow, chs); } for (i=0; i<16; i++) { oldchs[i] = chs[i]; } numinrow = 0; } count++; chs[numinrow++] = ch; } dumpRow(count, numinrow, chs); if (numinrow != 0) { printf("%08dX:\n", count); } } bool AmqpCommon::rowsEqual( int32 *row1, int32 *row2) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("AmqpCommon", "rowsEqual"); CAF_CM_VALIDATE_PTR(row1); CAF_CM_VALIDATE_PTR(row2); int32 i = 0; for (; (i < 16) && (row1[i] == row2[i]); i++) {} return (i == 15); } void AmqpCommon::dumpRow( const int32 count, const int32 numinrow, const int32 *chs) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("AmqpCommon", "dumpRow"); CAF_CM_VALIDATE_PTR(chs); static const int32 BUFF_SIZE = 100; char buff[BUFF_SIZE]; std::string msg; #ifdef WIN32 sprintf_s(buff, BUFF_SIZE, "%08lX:", count - numinrow); #else snprintf(buff, BUFF_SIZE, "%08dX:", count - numinrow); #endif msg += buff; if (numinrow > 0) { for (int32 i = 0; i < numinrow; i++) { if (i == 8) { msg += " :"; } #ifdef WIN32 sprintf_s(buff, BUFF_SIZE, " %02X", chs[i]); #else snprintf(buff, BUFF_SIZE, " %02X", chs[i]); #endif msg += buff; } for (int32 i = numinrow; i < 16; i++) { if (i == 8) { msg += " :"; } msg += " "; } msg += " "; for (int32 i = 0; i < numinrow; i++) { if (isprint(chs[i])) { #ifdef WIN32 sprintf_s(buff, BUFF_SIZE, "%c", chs[i]); #else snprintf(buff, BUFF_SIZE, "%c", chs[i]); #endif msg += buff; } else { msg += "."; } } } CAF_CM_LOG_DEBUG_VA1("row: %s", msg.c_str()); } AmqpCommon.h000066400000000000000000000044561321503522500350160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: Oct 7, 2014 * Author: bwilliams * * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCORE_AMQPCOMMON_H_ #define AMQPCORE_AMQPCOMMON_H_ namespace Caf { namespace AmqpClient { /** AMQP status codes. */ typedef enum { AMQP_ERROR_OK = 0, /**< AMQP_ERROR_OK */ AMQP_ERROR_TIMEOUT, /**< AMQP_ERROR_TIMEOUT */ AMQP_ERROR_NO_MEMORY, /**< AMQP_ERROR_NO_MEMORY */ AMQP_ERROR_INVALID_HANDLE, /**< AMQP_ERROR_INVALID_HANDLE */ AMQP_ERROR_INVALID_ARGUMENT, /**< AMQP_ERROR_INVALID_ARGUMENT */ AMQP_ERROR_WRONG_STATE, /**< AMQP_ERROR_WRONG_STATE */ AMQP_ERROR_TOO_MANY_CHANNELS, /**< AMQP_ERROR_TOO_MANY_CHANNELS */ AMQP_ERROR_QUEUE_FULL, /**< AMQP_ERROR_QUEUE_FULL */ AMQP_ERROR_FRAME_TOO_LARGE, /**< AMQP_ERROR_FRAME_TOO_LARGE */ AMQP_ERROR_IO_ERROR, /**< AMQP_ERROR_IO_ERROR */ AMQP_ERROR_PROTOCOL_ERROR, /**< AMQP_ERROR_PROTOCOL_ERROR */ AMQP_ERROR_UNIMPLEMENTED, /**< AMQP_ERROR_UNIMPLEMENTED */ AMQP_ERROR_IO_INTERRUPTED, /**< AMQP_ERROR_IO_INTERRUPTED */ AMQP_ERROR_MAX, /**< AMQP_ERROR_MAX */ } AMQPStatus; class AmqpCommon { public: static void *AMQP_Calloc( size_t nmemb, size_t size); static void AMQP_Free(void *ptr); static int32 sendMethod( const amqp_connection_state_t& connectionState, const amqp_channel_t& channel, const amqp_method_number_t& methodId, void *decodedMethod); static int32 validateStatusRequired( const std::string& msg, const int32 status); static int32 validateStatus( const std::string& msg, const int32 status); static int32 validateRpcReply( const std::string& msg, const amqp_rpc_reply_t& rpcReply); static void strToAmqpBytes( const std::string& src, amqp_bytes_t& dest, Csetstr& cachedStrings); static void boolToAmqpBool( const bool src, amqp_boolean_t& dest); static void cpTableSafely( const amqp_table_t* src, amqp_table_t& dest); static void dumpMessageBody( const void *buffer, const size_t bufferLen); private: static bool rowsEqual( int32 *row1, int32 *row2); static void dumpRow( const int32 count, const int32 numinrow, const int32 *chs); static const std::string& getString( const std::string& src, Csetstr& cachedStrings); private: CAF_CM_DECLARE_NOCREATE (AmqpCommon); }; }} #endif /* AMQPCORE_AMQPCOMMON_H_ */ AmqpConnection.cpp000066400000000000000000000075251321503522500362200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/CAmqpAuthMechanism.h" #include "amqpClient/CAmqpConnection.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" #include "AmqpConnection.h" using namespace Caf::AmqpClient; AMQPStatus AmqpConnection::AMQP_ConnectionCreate( SmartPtrCAmqpConnection& conn, const SmartPtrAddress& address, const SmartPtrCAmqpAuthMechanism& auth, const SmartPtrCertInfo& certInfo, const uint16 channelMax, const uint32 frameMax, const uint16 heartbeat, const uint16 retries, const uint16 secondsToWait) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionCreate"); CAF_CM_VALIDATE_SMARTPTR(address); CAF_CM_VALIDATE_SMARTPTR(auth); conn.CreateInstance(); return conn->connectionCreate(address, auth, certInfo, channelMax, frameMax, heartbeat, retries, secondsToWait); } AMQPStatus AmqpConnection::AMQP_ConnectionConnect( const SmartPtrCAmqpConnection& conn, const int32 flags) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionConnect"); CAF_CM_VALIDATE_SMARTPTR(conn); return conn->connectionConnect(flags); } AMQPStatus AmqpConnection::AMQP_ConnectionOpenChannel( const SmartPtrCAmqpConnection& conn, SmartPtrCAmqpChannel& chan) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionOpenChannel"); CAF_CM_VALIDATE_SMARTPTR(conn); return conn->channelOpen(chan); } AMQPStatus AmqpConnection::AMQP_ConnectionClose( const SmartPtrCAmqpConnection& conn) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionClose"); CAF_CM_VALIDATE_SMARTPTR(conn); return conn->connectionClose(); } AMQPStatus AmqpConnection::AMQP_ConnectionProcessIO( const SmartPtrCAmqpConnection& conn) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionProcessIO"); CAF_CM_VALIDATE_SMARTPTR(conn); return conn->connectionProcessIO(); } AMQPStatus AmqpConnection::AMQP_ConnectionWaitForIO( const SmartPtrCAmqpConnection& conn, const int32 timeout) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionWaitForIO"); CAF_CM_VALIDATE_SMARTPTR(conn); return conn->connectionWaitForIO(timeout); } AMQPStatus AmqpConnection::AMQP_ConnectionGetState( const SmartPtrCAmqpConnection& conn, AMQPConnectionState *state) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionGetState"); CAF_CM_VALIDATE_SMARTPTR(conn); CAF_CM_VALIDATE_PTR(state); return conn->connectionGetState(state); } AMQPStatus AmqpConnection::AMQP_ConnectionGetMaxChannels( const SmartPtrCAmqpConnection& conn, uint16 *channels) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionGetMaxChannels"); CAF_CM_VALIDATE_SMARTPTR(conn); CAF_CM_VALIDATE_PTR(channels); return conn->connectionGetMaxChannels(channels); } AMQPStatus AmqpConnection::AMQP_ConnectionGetMaxFrameSize( const SmartPtrCAmqpConnection& conn, uint32 *frameSize) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionGetMaxFrameSize"); CAF_CM_VALIDATE_SMARTPTR(conn); CAF_CM_VALIDATE_PTR(frameSize); return conn->connectionGetMaxFrameSize(frameSize); } AMQPStatus AmqpConnection::AMQP_ConnectionGetHeartbeatInterval( const SmartPtrCAmqpConnection& conn, uint16 *interval) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionGetHeartbeatInterval"); CAF_CM_VALIDATE_SMARTPTR(conn); CAF_CM_VALIDATE_PTR(interval); return conn->connectionGetHeartbeatInterval(interval); } AMQPStatus AmqpConnection::AMQP_ConnectionGetLastError( const SmartPtrCAmqpConnection& conn, const char **error) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpConnection", "AMQP_ConnectionGetLastError"); CAF_CM_VALIDATE_SMARTPTR(conn); CAF_CM_VALIDATE_PTR(error); return conn->connectionGetLastError(error); } AmqpConnection.h000066400000000000000000000064161321503522500356630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: Oct 7, 2014 * Author: bwilliams * * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCORE_AMQPCONNECTION_H_ #define AMQPCORE_AMQPCONNECTION_H_ #include "amqpClient/CAmqpChannel.h" #include "amqpClient/CAmqpAuthMechanism.h" #include "amqpClient/CAmqpConnection.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" namespace Caf { namespace AmqpClient { /** Default maximum number of channels. */ static const uint16 AMQP_CHANNEL_MAX_DEFAULT = 0; /* Unlimited. */ /** Default maximum frame size. */ static const uint32 AMQP_FRAME_MAX_DEFAULT = 131072; /* 128kB */ /** Default heartbeat frequency. */ static const uint16 AMQP_HEARTBEAT_DEFAULT = 0; /* No heartbeat. */ /** AMQP connection internal state details. */ typedef enum AMQPConnectionInternalState { AMQP_CONNECTION_INITIALIZED = 0, AMQP_CONNECTION_CONNECTING, AMQP_CONNECTION_WAITING_FOR_START, AMQP_CONNECTION_WAITING_FOR_SECURE, AMQP_CONNECTION_WAITING_FOR_TUNE, AMQP_CONNECTION_WAITING_FOR_OPEN_OK, AMQP_CONNECTION_OPEN, AMQP_CONNECTION_WAITING_FOR_CLOSE_OK, AMQP_CONNECTION_SENT_CLOSE_OK, AMQP_CONNECTION_CLOSED } AMQPConnectionInternalState; /** Close the socket when the connection is closed. */ #define AMQP_CONNECTION_FLAG_CLOSE_SOCKET (1 << 0) /** Don't lock the connection against multi-threaded applications. */ #define AMQP_CONNECTION_FLAG_NO_LOCK (1 << 1) /** Don't retry I/O when interrupted by signals. */ #define AMQP_CONNECTION_FLAG_NO_IO_RETRY (1 << 2) /** Mode to poll the socket. */ typedef enum { AMQP_WANT_READ = 0x1, /*!< Poll socket for readability. */ AMQP_WANT_WRITE = 0x2, /*!< Poll socket for writability. */ AMQP_POLL_NO_IO_RETRY = 0x4, /*!< Don't retry I/O on EINTR. */ } AMQPPollFlags; class AmqpConnection { public: static AMQPStatus AMQP_ConnectionCreate( SmartPtrCAmqpConnection& pConn, const SmartPtrAddress& address, const SmartPtrCAmqpAuthMechanism& auth, const SmartPtrCertInfo& certInfo, const uint16 channelMax, const uint32 frameMax, const uint16 heartbeat, const uint16 retries, const uint16 secondsToWait); static AMQPStatus AMQP_ConnectionConnect( const SmartPtrCAmqpConnection& conn, const int32 flags); static AMQPStatus AMQP_ConnectionOpenChannel( const SmartPtrCAmqpConnection& conn, SmartPtrCAmqpChannel& chan); static AMQPStatus AMQP_ConnectionClose( const SmartPtrCAmqpConnection& conn); static AMQPStatus AMQP_ConnectionProcessIO( const SmartPtrCAmqpConnection& conn); static AMQPStatus AMQP_ConnectionWaitForIO( const SmartPtrCAmqpConnection& conn, const int32 timeout); static AMQPStatus AMQP_ConnectionGetState( const SmartPtrCAmqpConnection& conn, AMQPConnectionState *state); static AMQPStatus AMQP_ConnectionGetMaxChannels( const SmartPtrCAmqpConnection& conn, uint16 *channels); static AMQPStatus AMQP_ConnectionGetMaxFrameSize( const SmartPtrCAmqpConnection& conn, uint32 *frameSize); static AMQPStatus AMQP_ConnectionGetHeartbeatInterval( const SmartPtrCAmqpConnection& conn, uint16 *interval); static AMQPStatus AMQP_ConnectionGetLastError( const SmartPtrCAmqpConnection& conn, const char **error); private: CAF_CM_DECLARE_NOCREATE (AmqpConnection); }; } } #endif /* AMQPCORE_AMQPCONNECTION_H_ */ AmqpUtil.cpp000066400000000000000000000134251321503522500350320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "AmqpUtil.h" using namespace Caf::AmqpClient; AMQPStatus AmqpUtil::AMQP_BasicAck( const SmartPtrCAmqpChannel& channel, const uint64 deliveryTag, const bool multiple) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_BasicAck"); CAF_CM_VALIDATE_SMARTPTR(channel); return channel->basicAck(deliveryTag, multiple); } AMQPStatus AmqpUtil::AMQP_BasicCancel( const SmartPtrCAmqpChannel& channel, const std::string& consumerTag, const bool noWait) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_BasicCancel"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(consumerTag); return channel->basicCancel(consumerTag, noWait); } AMQPStatus AmqpUtil::AMQP_BasicConsume( const SmartPtrCAmqpChannel& channel, const std::string& queue, const std::string& consumerTag, const bool noLocal, const bool noAck, const bool exclusive, const bool noWait, const amqp_table_t *arguments) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_BasicConsume"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(queue); return channel->basicConsume(queue, consumerTag, noLocal, noAck, exclusive, noWait, arguments); } AMQPStatus AmqpUtil::AMQP_BasicGet( const SmartPtrCAmqpChannel& channel, const std::string& queue, const bool noAck) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_BasicGet"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(queue); return channel->basicGet(queue, noAck); } AMQPStatus AmqpUtil::AMQP_BasicPublish( const SmartPtrCAmqpChannel& channel, const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const amqp_basic_properties_t *basicProps, const SmartPtrCDynamicByteArray& body) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_BasicPublish"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(routingKey); CAF_CM_VALIDATE_PTR(basicProps); CAF_CM_VALIDATE_SMARTPTR(body); return channel->basicPublish(exchange, routingKey, mandatory, immediate, basicProps, body); } AMQPStatus AmqpUtil::AMQP_BasicRecover( const SmartPtrCAmqpChannel& channel, const bool requeue) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_BasicRecover"); CAF_CM_VALIDATE_SMARTPTR(channel); return channel->basicRecover(requeue); } AMQPStatus AmqpUtil::AMQP_BasicQos( const SmartPtrCAmqpChannel& channel, const uint32 prefetchSize, const uint16 prefetchCount, const bool global) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_BasicQos"); CAF_CM_VALIDATE_SMARTPTR(channel); return channel->basicQos(prefetchSize, prefetchCount, global); } AMQPStatus AmqpUtil::AMQP_ExchangeDeclare( const SmartPtrCAmqpChannel& channel, const std::string& exchange, const std::string& type, const bool passive, const bool durable, const bool noWait, const amqp_table_t *arguments) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_ExchangeDeclare"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(type); return channel->exchangeDeclare(exchange, type, passive, durable, noWait, arguments); } AMQPStatus AmqpUtil::AMQP_ExchangeDelete( const SmartPtrCAmqpChannel& channel, const std::string& exchange, const bool ifUnused, const bool noWait) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_ExchangeDelete"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(exchange); return channel->exchangeDelete(exchange, ifUnused, noWait); } AMQPStatus AmqpUtil::AMQP_QueueBind( const SmartPtrCAmqpChannel& channel, const std::string& queue, const std::string& exchange, const std::string& routingKey, const bool noWait, const amqp_table_t *arguments) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_QueueBind"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(queue); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(routingKey); return channel->queueBind(queue, exchange, routingKey, noWait, arguments); } AMQPStatus AmqpUtil::AMQP_QueueDeclare( const SmartPtrCAmqpChannel& channel, const std::string& queue, const bool passive, const bool durable, const bool exclusive, const bool autoDelete, const bool noWait, const amqp_table_t *arguments) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_QueueDeclare"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(queue); return channel->queueDeclare(queue, passive, durable, exclusive, autoDelete, noWait, arguments); } AMQPStatus AmqpUtil::AMQP_QueueDelete( const SmartPtrCAmqpChannel& channel, const std::string& queue, const bool ifUnused, const bool ifEmpty, const bool noWait) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_QueueDelete"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(queue); return channel->queueDelete(queue, ifUnused, ifEmpty, noWait); } AMQPStatus AmqpUtil::AMQP_QueuePurge( const SmartPtrCAmqpChannel& channel, const std::string& queue, const bool noWait) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_QueuePurge"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(queue); return channel->queuePurge(queue, noWait); } AMQPStatus AmqpUtil::AMQP_QueueUnbind( const SmartPtrCAmqpChannel& channel, const std::string& queue, const std::string& exchange, const std::string& bindingKey, const amqp_table_t *arguments) { CAF_CM_STATIC_FUNC_VALIDATE("AmqpUtil", "AMQP_QueueUnbind"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_STRING(queue); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(bindingKey); return channel->queueUnbind(queue, exchange, bindingKey, arguments); } AmqpUtil.h000066400000000000000000000057641321503522500345060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: Oct 7, 2014 * Author: bwilliams * * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPCORE_AMQPUTIL_H_ #define AMQPCORE_AMQPUTIL_H_ #include "amqpClient/CAmqpChannel.h" #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { namespace AmqpClient { class AmqpUtil { public: static AMQPStatus AMQP_BasicAck( const SmartPtrCAmqpChannel& channel, const uint64 deliveryTag, const bool multiple); static AMQPStatus AMQP_BasicCancel( const SmartPtrCAmqpChannel& channel, const std::string& consumerTag, const bool noWait); static AMQPStatus AMQP_BasicConsume( const SmartPtrCAmqpChannel& channel, const std::string& queue, const std::string& consumerTag, const bool noLocal, const bool noAck, const bool exclusive, const bool noWait, const amqp_table_t *arguments); static AMQPStatus AMQP_BasicGet( const SmartPtrCAmqpChannel& channel, const std::string& queue, const bool noAck); static AMQPStatus AMQP_BasicPublish( const SmartPtrCAmqpChannel& channel, const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const amqp_basic_properties_t *basicProps, const SmartPtrCDynamicByteArray& body); static AMQPStatus AMQP_BasicRecover( const SmartPtrCAmqpChannel& channel, const bool requeue); static AMQPStatus AMQP_BasicQos( const SmartPtrCAmqpChannel& channel, const uint32 prefetchSize, const uint16 prefetchCount, bool global); static AMQPStatus AMQP_ExchangeDeclare( const SmartPtrCAmqpChannel& channel, const std::string& exchange, const std::string& type, const bool passive, const bool durable, const bool noWait, const amqp_table_t *arguments); static AMQPStatus AMQP_ExchangeDelete( const SmartPtrCAmqpChannel& channel, const std::string& exchange, const bool ifUnused, const bool noWait); static AMQPStatus AMQP_QueueBind( const SmartPtrCAmqpChannel& channel, const std::string& queue, const std::string& exchange, const std::string& routingKey, const bool noWait, const amqp_table_t *arguments); static AMQPStatus AMQP_QueueDeclare( const SmartPtrCAmqpChannel& channel, const std::string& queue, const bool passive, const bool durable, const bool exclusive, const bool autoDelete, const bool noWait, const amqp_table_t *arguments); static AMQPStatus AMQP_QueueDelete( const SmartPtrCAmqpChannel& channel, const std::string& queue, const bool ifUnused, const bool ifEmpty, const bool noWait); static AMQPStatus AMQP_QueuePurge( const SmartPtrCAmqpChannel& channel, const std::string& queue, const bool noWait); static AMQPStatus AMQP_QueueUnbind( const SmartPtrCAmqpChannel& channel, const std::string& queue, const std::string& exchange, const std::string& bindingKey, const amqp_table_t *arguments); private: CAF_CM_DECLARE_NOCREATE (AmqpUtil); }; }} #endif /* AMQPCORE_AMQPUTIL_H_ */ BlockingRpcContinuation.cpp000066400000000000000000000031061321503522500400610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "amqpClient/AMQCommand.h" #include "amqpClient/BlockingRpcContinuation.h" using namespace Caf::AmqpClient; BlockingRpcContinuation::BlockingRpcContinuation() : _isInitialized(false), CAF_CM_INIT("BlockingRpcContinuation") { } BlockingRpcContinuation::~BlockingRpcContinuation() { } void BlockingRpcContinuation::init() { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } SmartPtrAMQCommand BlockingRpcContinuation::getReply() { CAF_CM_FUNCNAME_VALIDATE("getReply"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _blocker.get(); } SmartPtrAMQCommand BlockingRpcContinuation::getReply(uint32 timeout) { CAF_CM_FUNCNAME_VALIDATE("getReply"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _blocker.get(timeout); } SmartPtrCCafException BlockingRpcContinuation::getException() { CAF_CM_FUNCNAME_VALIDATE("getException"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _exception; } void BlockingRpcContinuation::handleCommand(const SmartPtrAMQCommand& command) { CAF_CM_FUNCNAME_VALIDATE("handleCommand"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _blocker.set(command); } void BlockingRpcContinuation::handleAbort(SmartPtrCCafException exception) { CAF_CM_FUNCNAME_VALIDATE("handleAbort"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _exception = exception; _blocker.set(NULL); } CAmqpAuthMechanism.cpp000066400000000000000000000016571321503522500367520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpAuthMechanism.h" using namespace Caf::AmqpClient; CAmqpAuthMechanism::CAmqpAuthMechanism() : CAF_CM_INIT("CAmqpAuthMechanism") { CAF_CM_INIT_THREADSAFE; } CAmqpAuthMechanism::~CAmqpAuthMechanism() { } AMQPStatus CAmqpAuthMechanism::createClient( const std::string& username, const std::string& password) { CAF_CM_FUNCNAME_VALIDATE("createClient"); CAF_CM_VALIDATE_STRING(username); // password is optional _username = username; _password = password; return AMQP_ERROR_OK; } std::string CAmqpAuthMechanism::getUsername() const { CAF_CM_FUNCNAME_VALIDATE("getUsername"); CAF_CM_VALIDATE_STRING(_username); return _username; } std::string CAmqpAuthMechanism::getPassword() const { // password is optional return _password; } CAmqpChannel.cpp000066400000000000000000000151671321503522500355750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/CAmqpConnection.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/CAmqpChannel.h" using namespace Caf::AmqpClient; CAmqpChannel::CAmqpChannel() : _isInitialized(false), _channel(0), CAF_CM_INIT("CAmqpChannel") { CAF_CM_INIT_THREADSAFE; } CAmqpChannel::~CAmqpChannel() { } void CAmqpChannel::initialize( const SmartPtrCAmqpConnection& connection, const amqp_channel_t& channel) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(connection); _connection = connection; _channel = channel; _isInitialized = true; } AMQPStatus CAmqpChannel::close() { AMQPStatus rc = AMQP_ERROR_OK; if (_isInitialized) { rc = _connection->channelClose(_channel); _connection = NULL; _channel = 0; _isInitialized = false; } return rc; } AMQPStatus CAmqpChannel::closeOk() { CAF_CM_FUNCNAME_VALIDATE("closeOk"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _connection->channelCloseOk(_channel); } AMQPStatus CAmqpChannel::receive( SmartPtrCAmqpFrame& frame, int32 timeout) { CAF_CM_FUNCNAME_VALIDATE("receive"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _connection->receive(_channel, frame, timeout); } AMQPStatus CAmqpChannel::getId( uint16 *id) { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_PTR(id); *id = _channel; return AMQP_ERROR_OK; } AMQPStatus CAmqpChannel::basicAck( const uint64 deliveryTag, const bool multiple) { CAF_CM_FUNCNAME_VALIDATE("basicAck"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _connection->basicAck(_channel, deliveryTag, multiple); } AMQPStatus CAmqpChannel::basicCancel( const std::string& consumerTag, const bool noWait) { CAF_CM_FUNCNAME_VALIDATE("basicCancel"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(consumerTag); return _connection->basicCancel(_channel, consumerTag, noWait); } AMQPStatus CAmqpChannel::basicConsume( const std::string& queue, const std::string& consumerTag, const bool noLocal, const bool noAck, const bool exclusive, const bool noWait, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("basicConsume"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); return _connection->basicConsume(_channel, queue, consumerTag, noLocal, noAck, exclusive, noWait, arguments); } AMQPStatus CAmqpChannel::basicGet( const std::string& queue, const bool noAck) { CAF_CM_FUNCNAME_VALIDATE("basicGet"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); return _connection->basicGet(_channel, queue, noAck); } AMQPStatus CAmqpChannel::basicPublish( const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const amqp_basic_properties_t *basicProps, const SmartPtrCDynamicByteArray& body) { CAF_CM_FUNCNAME_VALIDATE("basicPublish"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(routingKey); CAF_CM_VALIDATE_PTR(basicProps); CAF_CM_VALIDATE_SMARTPTR(body); return _connection->basicPublish(_channel, exchange, routingKey, mandatory, immediate, basicProps, body); } AMQPStatus CAmqpChannel::basicRecover( const bool requeue) { CAF_CM_FUNCNAME_VALIDATE("basicRecover"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _connection->basicRecover(_channel, requeue); } AMQPStatus CAmqpChannel::basicQos( const uint32 prefetchSize, const uint16 prefetchCount, const bool global) { CAF_CM_FUNCNAME_VALIDATE("basicQos"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _connection->basicQos(_channel, prefetchSize, prefetchCount, global); } AMQPStatus CAmqpChannel::exchangeDeclare( const std::string& exchange, const std::string& type, const bool passive, const bool durable, const bool noWait, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("exchangeDeclare"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(type); return _connection->exchangeDeclare(_channel, exchange, type, passive, durable, noWait, arguments); } AMQPStatus CAmqpChannel::exchangeDelete( const std::string& exchange, const bool ifUnused, const bool noWait) { CAF_CM_FUNCNAME_VALIDATE("exchangeDelete"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(exchange); return _connection->exchangeDelete(_channel, exchange, ifUnused, noWait); } AMQPStatus CAmqpChannel::queueBind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const bool noWait, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("queueBind"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(routingKey); return _connection->queueBind(_channel, queue, exchange, routingKey, noWait, arguments); } AMQPStatus CAmqpChannel::queueDeclare( const std::string& queue, const bool passive, const bool durable, const bool exclusive, const bool autoDelete, const bool noWait, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("queueDeclare"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); return _connection->queueDeclare(_channel, queue, passive, durable, exclusive, autoDelete, noWait, arguments); } AMQPStatus CAmqpChannel::queueDelete( const std::string& queue, const bool ifUnused, const bool ifEmpty, const bool noWait) { CAF_CM_FUNCNAME_VALIDATE("queueDelete"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); return _connection->queueDelete(_channel, queue, ifUnused, ifEmpty, noWait); } AMQPStatus CAmqpChannel::queuePurge( const std::string& queue, const bool noWait) { CAF_CM_FUNCNAME_VALIDATE("queuePurge"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); return _connection->queuePurge(_channel, queue, noWait); } AMQPStatus CAmqpChannel::queueUnbind( const std::string& queue, const std::string& exchange, const std::string& bindingKey, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("queueUnbind"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(bindingKey); return _connection->queueUnbind(_channel, queue, exchange, bindingKey, arguments); } CAmqpConnection.cpp000066400000000000000000000731061321503522500363210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/CAmqpAuthMechanism.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" #include "amqpClient/CAmqpConnection.h" #include "Exception/CCafException.h" using namespace Caf::AmqpClient; CAmqpConnection::CAmqpConnection() : _connectionState(NULL), _socket(NULL), _curChannel(0), _connectionStateEnum(AMQP_STATE_DISCONNECTED), _isConnectionLost(false), _lastStatus(0), _channelMax(0), _frameMax(0), _heartbeat(0), _retries(0), _secondsToWait(0), CAF_CM_INIT_LOG("CAmqpConnection") { CAF_CM_INIT_THREADSAFE; } CAmqpConnection::~CAmqpConnection() { CAF_CM_LOCK_UNLOCK; if (NULL != _connectionState) { closeConnection(); } } AMQPStatus CAmqpConnection::connectionCreate( const SmartPtrAddress& address, const SmartPtrCAmqpAuthMechanism& auth, const SmartPtrCertInfo& certInfo, const uint16 channelMax, const uint32 frameMax, const uint16 heartbeat, const uint16 retries, const uint16 secondsToWait) { CAF_CM_FUNCNAME("connectionCreate"); CAF_CM_VALIDATE_SMARTPTR(address); CAF_CM_VALIDATE_SMARTPTR(auth); CAF_CM_LOCK_UNLOCK; _address = address; _auth = auth; _certInfo = certInfo; _channelMax = channelMax; _frameMax = frameMax; _heartbeat = heartbeat; _channelFrames.CreateInstance(); _retries = retries; _secondsToWait = secondsToWait; AMQPStatus rc = AMQP_ERROR_OK; switch(_address->getProtocol()) { case PROTOCOL_AMQP: rc = createConnection(); break; case PROTOCOL_AMQPS: rc = createSslConnection(); break; case PROTOCOL_TUNNEL: rc = createSslConnection(); break; default: CAF_CM_EXCEPTION_VA1(E_FAIL, "Unknown protocol - %d", _address->getProtocol()); } return rc; } AMQPStatus CAmqpConnection::connectionConnect( const int32 flags) { CAF_CM_LOCK_UNLOCK; return connectConnection(); } AMQPStatus CAmqpConnection::connectionClose() { CAF_CM_LOCK_UNLOCK; return closeConnection(); } AMQPStatus CAmqpConnection::connectionProcessIO() { //TODO: Is this call necessary anymore? return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::connectionWaitForIO( int32 timeout) { CAF_CM_FUNCNAME_VALIDATE("connectionWaitForIO"); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); AMQPStatus rc = AMQP_ERROR_TIMEOUT; if (isDataAvail(_connectionState)) { rc = AMQP_ERROR_OK; } else { if (timeout > 0) { { CAF_CM_UNLOCK_LOCK; CThreadUtils::sleep(timeout); } if (isDataAvail(_connectionState)) { rc = AMQP_ERROR_OK; } } } return rc; } AMQPStatus CAmqpConnection::connectionGetState( AMQPConnectionState *state) { CAF_CM_FUNCNAME_VALIDATE("connectionGetState"); CAF_CM_VALIDATE_PTR(state); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); *state = _connectionStateEnum; return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::connectionGetMaxChannels( uint16 *channels) { CAF_CM_FUNCNAME_VALIDATE("connectionGetMaxChannels"); CAF_CM_VALIDATE_PTR(channels); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); *channels = amqp_get_channel_max(_connectionState); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::connectionGetMaxFrameSize( uint32 *frameSize) { CAF_CM_FUNCNAME_VALIDATE("connectionGetMaxFrameSize"); CAF_CM_VALIDATE_PTR(frameSize); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); *frameSize = amqp_get_frame_max(_connectionState); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::connectionGetHeartbeatInterval( uint16 *interval) { CAF_CM_FUNCNAME_VALIDATE("connectionGetHeartbeatInterval"); CAF_CM_VALIDATE_PTR(interval); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); *interval = amqp_get_heartbeat(_connectionState); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::connectionGetLastError( const char **error) { CAF_CM_FUNCNAME_VALIDATE("connectionGetLastError"); CAF_CM_VALIDATE_PTR(error); CAF_CM_LOCK_UNLOCK; *error = amqp_error_string2(_lastStatus); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::channelClose( const amqp_channel_t& channel) { CAF_CM_FUNCNAME_VALIDATE("channelClose"); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); _openChannels.erase(channel); return closeChannel(channel); } AMQPStatus CAmqpConnection::channelCloseOk( const amqp_channel_t& channel) { CAF_CM_FUNCNAME_VALIDATE("channelCloseOk"); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); amqp_channel_close_ok_t method = {}; AmqpCommon::sendMethod(_connectionState, channel, AMQP_CHANNEL_CLOSE_OK_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::receive( const amqp_channel_t& channel, SmartPtrCAmqpFrame& frame, const int32 timeout) { CAF_CM_FUNCNAME_VALIDATE("receive"); frame = SmartPtrCAmqpFrame(); AMQPStatus rc = AMQP_ERROR_OK; CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); //amqp_maybe_release_buffers(_connectionState); int32 status = AMQP_STATUS_OK; CChannelFrames::iterator iter = _channelFrames->find(channel); if ((_channelFrames->end() == iter) || iter->second.empty()) { CAmqpFrames frames; SmartPtrCAmqpFrame frame; status = receiveFrame(_connectionState, frame); if ((AMQP_STATUS_TIMEOUT == status) && (timeout > 0)) { CAF_CM_UNLOCK_LOCK; CThreadUtils::sleep(timeout); } while (AMQP_STATUS_OK == status) { CAF_CM_VALIDATE_SMARTPTR(frame); frames.push_back(frame); status = receiveFrame(_connectionState, frame); } _lastStatus = status; addFrames(frames, _channelFrames); } switch (status) { case AMQP_STATUS_OK: case AMQP_STATUS_TIMEOUT: { iter = _channelFrames->find(channel); if ((_channelFrames->end() == iter) || iter->second.empty()) { rc = AMQP_ERROR_TIMEOUT; } else { frame = iter->second.front(); iter->second.pop_front(); } } break; case AMQP_STATUS_CONNECTION_CLOSED: { if (! _isConnectionLost) { CAF_CM_LOG_ERROR_VA1("Connection closed... restarting listener - %s", amqp_error_string2(status)); _isConnectionLost = true; restartListener(amqp_error_string2(status)); } rc = AMQP_ERROR_IO_INTERRUPTED; } break; case AMQP_STATUS_SOCKET_ERROR: { // Enhance the logic to restart listener after certain number of errors. if (! _isConnectionLost) { CAF_CM_LOG_ERROR_VA1("SOCKET_ERROR... restarting listener - %s", amqp_error_string2(status)); _isConnectionLost = true; restartListener(amqp_error_string2(status)); } rc = AMQP_ERROR_IO_INTERRUPTED; } break; default: { CAF_CM_LOG_ERROR_VA1("Received error status - %s", amqp_error_string2(status)); } break; } if (! frame.IsNull()) { frame->log("Returned"); } return rc; } AMQPStatus CAmqpConnection::channelOpen( SmartPtrCAmqpChannel& chan) { CAF_CM_FUNCNAME("channelOpen"); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); _curChannel++; const amqp_channel_t channel = _curChannel; CAF_CM_LOG_DEBUG_VA1("Calling amqp_channel_open - %d", channel); amqp_channel_open_t method = {}; method.out_of_band = amqp_empty_bytes; AmqpCommon::sendMethod(_connectionState, channel, AMQP_CHANNEL_OPEN_METHOD, &method); chan.CreateInstance(); chan->initialize(this, channel); if (! _openChannels.insert(channel).second) { CAF_CM_EXCEPTION_VA1(E_FAIL, "Inserted duplicated channel - %d", channel); } return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::basicAck( const amqp_channel_t& channel, const uint64 deliveryTag, const bool multiple) { CAF_CM_FUNCNAME_VALIDATE("basicAck"); CAF_CM_LOG_DEBUG_VA1( "Calling amqp_basic_ack - channel: %d", channel); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); _lastStatus = AmqpCommon::validateStatus( "amqp_basic_ack", amqp_basic_ack( _connectionState, channel, deliveryTag, multiple ? TRUE : FALSE)); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::basicCancel( const amqp_channel_t& channel, const std::string& consumerTag, const bool noWait) { CAF_CM_FUNCNAME_VALIDATE("basicCancel"); CAF_CM_VALIDATE_STRING(consumerTag); CAF_CM_LOG_DEBUG_VA2( "Calling amqp_basic_cancel - channel: %d, consumerTag: %s", channel, consumerTag.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); amqp_basic_cancel_t method = {}; AmqpCommon::strToAmqpBytes(consumerTag, method.consumer_tag, _cachedStrings); AmqpCommon::boolToAmqpBool(noWait, method.nowait); AmqpCommon::sendMethod(_connectionState, channel, AMQP_BASIC_CANCEL_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::basicConsume( const amqp_channel_t& channel, const std::string& queue, const std::string& consumerTag, const bool noLocal, const bool noAck, const bool exclusive, const bool noWait, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("basicConsume"); CAF_CM_VALIDATE_STRING(queue); CAF_CM_LOG_DEBUG_VA3( "Calling amqp_basic_consume - channel: %d, queue: %s, consumerTag: %s", channel, queue.c_str(), (consumerTag.empty() ? "NULL" : consumerTag.c_str())); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); amqp_basic_consume_t method = {}; AmqpCommon::strToAmqpBytes(queue, method.queue, _cachedStrings); AmqpCommon::strToAmqpBytes(consumerTag, method.consumer_tag, _cachedStrings); AmqpCommon::boolToAmqpBool(noLocal, method.no_local); AmqpCommon::boolToAmqpBool(noAck, method.no_ack); AmqpCommon::boolToAmqpBool(exclusive, method.exclusive); AmqpCommon::boolToAmqpBool(noWait, method.nowait); AmqpCommon::cpTableSafely(arguments, method.arguments); AmqpCommon::sendMethod(_connectionState, channel, AMQP_BASIC_CONSUME_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::basicGet( const amqp_channel_t& channel, const std::string& queue, const bool noAck) { CAF_CM_FUNCNAME_VALIDATE("basicGet"); CAF_CM_VALIDATE_STRING(queue); CAF_CM_LOG_DEBUG_VA2( "Calling amqp_basic_get - channel: %d, queue: %s", channel, queue.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); AmqpCommon::validateRpcReply( "amqp_basic_get", amqp_basic_get( _connectionState, channel, amqp_cstring_bytes(queue.c_str()), noAck ? TRUE : FALSE)); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::basicPublish( const amqp_channel_t& channel, const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const amqp_basic_properties_t *basicProps, const SmartPtrCDynamicByteArray& body) { CAF_CM_FUNCNAME_VALIDATE("basicPublish"); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(routingKey); CAF_CM_VALIDATE_PTR(basicProps); CAF_CM_VALIDATE_SMARTPTR(body); CAF_CM_LOG_DEBUG_VA3( "Calling amqp_basic_publish - channel: %d, exchange: %s, routingKey: %s", channel, exchange.c_str(), routingKey.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); amqp_bytes_t bodyRaw; bodyRaw.bytes = body->getNonConstPtr(); bodyRaw.len = body->getByteCount(); _lastStatus = AmqpCommon::validateStatus( "amqp_basic_publish", amqp_basic_publish( _connectionState, channel, amqp_cstring_bytes(exchange.c_str()), amqp_cstring_bytes(routingKey.c_str()), mandatory ? TRUE : FALSE, immediate ? TRUE : FALSE, basicProps, bodyRaw)); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::basicRecover( const amqp_channel_t& channel, const bool requeue) { CAF_CM_FUNCNAME_VALIDATE("basicRecover"); CAF_CM_LOG_DEBUG_VA1( "Calling amqp_basic_recover - channel: %d", channel); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); amqp_basic_recover_t method = {}; AmqpCommon::boolToAmqpBool(requeue, method.requeue); AmqpCommon::sendMethod(_connectionState, channel, AMQP_BASIC_RECOVER_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::basicQos( const amqp_channel_t& channel, const uint32 prefetchSize, const uint16 prefetchCount, const bool global) { CAF_CM_FUNCNAME_VALIDATE("basicQos"); CAF_CM_LOG_DEBUG_VA1( "Calling amqp_basic_qos - channel: %d", channel); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); amqp_basic_qos_t method = {}; method.prefetch_size = prefetchSize; method.prefetch_count = prefetchCount; AmqpCommon::boolToAmqpBool(global, method.global); AmqpCommon::sendMethod(_connectionState, channel, AMQP_BASIC_QOS_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::exchangeDeclare( const amqp_channel_t& channel, const std::string& exchange, const std::string& type, const bool passive, const bool durable, const bool noWait, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("exchangeDeclare"); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(type); CAF_CM_LOG_DEBUG_VA3( "Calling amqp_exchange_declare - channel: %d, exchange: %s, type: %s", channel, exchange.c_str(), type.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); const bool autoDelete = false; amqp_exchange_declare_t method = {}; AmqpCommon::strToAmqpBytes(exchange, method.exchange, _cachedStrings); AmqpCommon::strToAmqpBytes(type, method.type, _cachedStrings); AmqpCommon::boolToAmqpBool(passive, method.passive); AmqpCommon::boolToAmqpBool(durable, method.durable); AmqpCommon::boolToAmqpBool(noWait, method.nowait); AmqpCommon::cpTableSafely(arguments, method.arguments); AmqpCommon::boolToAmqpBool(autoDelete, method.auto_delete); AmqpCommon::sendMethod(_connectionState, channel, AMQP_EXCHANGE_DECLARE_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::exchangeDelete( const amqp_channel_t& channel, const std::string& exchange, const bool ifUnused, const bool noWait) { CAF_CM_FUNCNAME_VALIDATE("exchangeDelete"); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_LOG_DEBUG_VA2( "Calling amqp_exchange_delete - channel: %d, exchange: %s", channel, exchange.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); amqp_exchange_delete_t method = {}; AmqpCommon::strToAmqpBytes(exchange, method.exchange, _cachedStrings); AmqpCommon::boolToAmqpBool(ifUnused, method.if_unused); AmqpCommon::boolToAmqpBool(noWait, method.nowait); AmqpCommon::sendMethod(_connectionState, channel, AMQP_EXCHANGE_DELETE_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::queueBind( const amqp_channel_t& channel, const std::string& queue, const std::string& exchange, const std::string& routingKey, const bool noWait, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("queueBind"); CAF_CM_VALIDATE_STRING(queue); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(routingKey); CAF_CM_LOG_DEBUG_VA4( "Calling amqp_queue_bind - channel: %d, queue: %s, exchange: %s, routingKey: %s", channel, queue.c_str(), exchange.c_str(), routingKey.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); CAF_CM_VALIDATE_BOOL(_address->getProtocol() != PROTOCOL_TUNNEL); validateOpenChannel(channel); amqp_queue_bind_t method = {}; AmqpCommon::strToAmqpBytes(queue, method.queue, _cachedStrings); AmqpCommon::strToAmqpBytes(exchange, method.exchange, _cachedStrings); AmqpCommon::strToAmqpBytes(routingKey, method.routing_key, _cachedStrings); AmqpCommon::boolToAmqpBool(noWait, method.nowait); AmqpCommon::cpTableSafely(arguments, method.arguments); AmqpCommon::sendMethod(_connectionState, channel, AMQP_QUEUE_BIND_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::queueDeclare( const amqp_channel_t& channel, const std::string& queue, const bool passive, const bool durable, const bool exclusive, const bool autoDelete, const bool noWait, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("queueDeclare"); CAF_CM_VALIDATE_STRING(queue); CAF_CM_LOG_DEBUG_VA2( "Calling amqp_queue_declare - channel: %d, queue: %s", channel, queue.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); CAF_CM_VALIDATE_BOOL(_address->getProtocol() != PROTOCOL_TUNNEL); validateOpenChannel(channel); amqp_queue_declare_t method = {}; AmqpCommon::strToAmqpBytes(queue, method.queue, _cachedStrings); AmqpCommon::boolToAmqpBool(passive, method.passive); AmqpCommon::boolToAmqpBool(durable, method.durable); AmqpCommon::boolToAmqpBool(exclusive, method.exclusive); AmqpCommon::boolToAmqpBool(autoDelete, method.auto_delete); AmqpCommon::boolToAmqpBool(noWait, method.nowait); AmqpCommon::cpTableSafely(arguments, method.arguments); AmqpCommon::sendMethod(_connectionState, channel, AMQP_QUEUE_DECLARE_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::queueDelete( const amqp_channel_t& channel, const std::string& queue, const bool ifUnused, const bool ifEmpty, const bool noWait) { CAF_CM_FUNCNAME_VALIDATE("queueDelete"); CAF_CM_VALIDATE_STRING(queue); CAF_CM_LOG_DEBUG_VA2( "Calling amqp_queue_delete - channel: %d, queue: %s", channel, queue.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); CAF_CM_VALIDATE_BOOL(_address->getProtocol() != PROTOCOL_TUNNEL); validateOpenChannel(channel); amqp_queue_delete_t method = {}; AmqpCommon::strToAmqpBytes(queue, method.queue, _cachedStrings); AmqpCommon::boolToAmqpBool(ifUnused, method.if_unused); AmqpCommon::boolToAmqpBool(ifEmpty, method.if_empty); AmqpCommon::boolToAmqpBool(noWait, method.nowait); AmqpCommon::sendMethod(_connectionState, channel, AMQP_QUEUE_DELETE_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::queuePurge( const amqp_channel_t& channel, const std::string& queue, const bool noWait) { CAF_CM_FUNCNAME_VALIDATE("queuePurge"); CAF_CM_VALIDATE_STRING(queue); CAF_CM_LOG_DEBUG_VA2( "Calling amqp_queue_purge - channel: %d, queue: %s", channel, queue.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); validateOpenChannel(channel); amqp_queue_purge_t method = {}; AmqpCommon::strToAmqpBytes(queue, method.queue, _cachedStrings); AmqpCommon::boolToAmqpBool(noWait, method.nowait); AmqpCommon::sendMethod(_connectionState, channel, AMQP_QUEUE_PURGE_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::queueUnbind( const amqp_channel_t& channel, const std::string& queue, const std::string& exchange, const std::string& routingKey, const amqp_table_t *arguments) { CAF_CM_FUNCNAME_VALIDATE("queueUnbind"); CAF_CM_VALIDATE_STRING(queue); CAF_CM_VALIDATE_STRING(exchange); CAF_CM_VALIDATE_STRING(routingKey); CAF_CM_LOG_DEBUG_VA4( "Calling amqp_queue_unbind - channel: %d, queue: %s, exchange: %s, routingKey: %s", channel, queue.c_str(), exchange.c_str(), routingKey.c_str()); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); CAF_CM_VALIDATE_BOOL(_address->getProtocol() != PROTOCOL_TUNNEL); validateOpenChannel(channel); amqp_queue_unbind_t method = {}; AmqpCommon::strToAmqpBytes(queue, method.queue, _cachedStrings); AmqpCommon::strToAmqpBytes(exchange, method.exchange, _cachedStrings); AmqpCommon::strToAmqpBytes(routingKey, method.routing_key, _cachedStrings); AmqpCommon::cpTableSafely(arguments, method.arguments); AmqpCommon::sendMethod(_connectionState, channel, AMQP_QUEUE_UNBIND_METHOD, &method); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::createConnection() { CAF_CM_FUNCNAME_VALIDATE("createConnection"); CAF_CM_VALIDATE_NULLPTR(_connectionState); CAF_CM_VALIDATE_NULLPTR(_socket); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_DISCONNECTED); CAF_CM_LOG_DEBUG_VA0( "Calling amqp_new_connection/amqp_tcp_socket_new"); _connectionState = amqp_new_connection(); CAF_CM_VALIDATE_PTR(_connectionState); _socket = amqp_tcp_socket_new(_connectionState); CAF_CM_VALIDATE_PTR(_socket); _connectionStateEnum = AMQP_STATE_INITIALIZED; return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::createSslConnection() { CAF_CM_FUNCNAME_VALIDATE("createSslConnection"); CAF_CM_VALIDATE_NULLPTR(_connectionState); CAF_CM_VALIDATE_NULLPTR(_socket); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_DISCONNECTED); CAF_CM_VALIDATE_SMARTPTR(_certInfo); CAF_CM_LOG_DEBUG_VA0( "Calling amqp_new_connection/amqp_ssl_socket_new"); _connectionState = amqp_new_connection(); CAF_CM_VALIDATE_PTR(_connectionState); _socket = amqp_ssl_socket_new(_connectionState); CAF_CM_VALIDATE_PTR(_socket); CAF_CM_LOG_DEBUG_VA0( "Disable peer verification (amqp_ssl_socket_set_verify_peer)"); amqp_ssl_socket_set_verify_peer(_socket, false); CAF_CM_LOG_DEBUG_VA0( "Disable hostname verification (amqp_ssl_socket_set_verify_hostname)"); amqp_ssl_socket_set_verify_hostname(_socket, false); CAF_CM_LOG_DEBUG_VA0( "Setting ssl protocol >= 1.2 (amqp_ssl_socket_set_ssl_versions)"); amqp_ssl_socket_set_ssl_versions (_socket, AMQP_TLSv1_2, AMQP_TLSvLATEST); CAF_CM_LOG_DEBUG_VA1( "Calling amqp_ssl_socket_set_cacert - caCertPath: %s", _certInfo->getCaCertPath().c_str()); _lastStatus = AmqpCommon::validateStatusRequired( "amqp_ssl_socket_set_cacert", amqp_ssl_socket_set_cacert( _socket, _certInfo->getCaCertPath().c_str())); CAF_CM_LOG_DEBUG_VA2( "Calling amqp_ssl_socket_set_key - clientCert: %s, clientKey: %s", _certInfo->getClientCertPath().c_str(), _certInfo->getClientKeyPath().c_str()); _lastStatus = AmqpCommon::validateStatusRequired( "amqp_ssl_socket_set_key", amqp_ssl_socket_set_key( _socket, _certInfo->getClientCertPath().c_str(), _certInfo->getClientKeyPath().c_str())); _connectionStateEnum = AMQP_STATE_INITIALIZED; return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::connectConnection() { CAF_CM_FUNCNAME("connectConnection"); CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_PTR(_socket); CAF_CM_VALIDATE_SMARTPTR(_address); CAF_CM_VALIDATE_SMARTPTR(_auth); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_INITIALIZED); CAF_CM_LOG_DEBUG_VA3( "Calling amqp_socket_open_noblock - protocol: %s, host: %s, port: %d", _address->getProtocolStr().c_str(), _address->getHost().c_str(), _address->getPort()); struct timeval timeout; struct timeval *pTimeout = NULL; if (_secondsToWait) { memset(&timeout, 0, sizeof(timeval)); timeout.tv_sec = _secondsToWait; pTimeout = &timeout; } uint16 retries = _retries; do { CAF_CM_LOG_DEBUG_VA2( "Calling amqp_socket_open_noblock - retries: %d, wait: %d", retries, _secondsToWait); if (retries == 1 ) { // Throw an exception if the last attempt fails _lastStatus = AmqpCommon::validateStatusRequired( "amqp_socket_open_noblock", amqp_socket_open_noblock( _socket, _address->getHost().c_str(), _address->getPort(), pTimeout)); } else { _lastStatus = AmqpCommon::validateStatus( "amqp_socket_open_noblock", amqp_socket_open_noblock( _socket, _address->getHost().c_str(), _address->getPort(), pTimeout)); } } while (_lastStatus != AMQP_STATUS_OK && --retries); CAF_CM_LOG_DEBUG_VA2( "Calling amqp_login - virtualHost: %s, username: %s", _address->getVirtualHost().c_str(), _auth->getUsername().c_str()); _lastStatus = AmqpCommon::validateRpcReply( "amqp_login", amqp_login( _connectionState, _address->getVirtualHost().c_str(), _channelMax, _frameMax, _heartbeat, AMQP_SASL_METHOD_PLAIN, _auth->getUsername().c_str(), _auth->getPassword().empty() ? "" :_auth->getPassword().c_str())); CAF_CM_LOG_DEBUG_VA2( "Called amqp_login - virtualHost: %s, username: %s", _address->getVirtualHost().c_str(), _auth->getUsername().c_str()); if (0 == _lastStatus) { _connectionStateEnum = AMQP_STATE_CONNECTED; } else { CAF_CM_EXCEPTION_VA3(E_FAIL, "Failed to login - error: %s, vhost: %s, username: %s", amqp_error_string2(_lastStatus), _address->getVirtualHost().c_str(), _auth->getUsername().c_str()); } return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::closeConnection() { CAF_CM_FUNCNAME_VALIDATE("closeConnection"); if ((_connectionStateEnum == AMQP_STATE_INITIALIZED) || (_connectionStateEnum == AMQP_STATE_CONNECTING) || (_connectionStateEnum == AMQP_STATE_CONNECTED)) { CAF_CM_VALIDATE_SMARTPTR(_address); CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_LOG_DEBUG_VA4( "Calling amqp_connection_close/amqp_destroy_connection - protocol: %s, host: %s, port: %d, virtualHost: %s", _address->getProtocolStr().c_str(), _address->getHost().c_str(), _address->getPort(), _address->getVirtualHost().c_str()); for (COpenChannels::const_iterator iter = _openChannels.begin(); iter != _openChannels.end(); iter++) { const amqp_channel_t channel = *iter; closeChannel(channel); } AmqpCommon::validateRpcReply( "amqp_connection_close", amqp_connection_close(_connectionState, AMQP_REPLY_SUCCESS)); _lastStatus = AmqpCommon::validateStatus( "amqp_destroy_connection", amqp_destroy_connection(_connectionState)); } _connectionState = NULL; _socket = NULL; _curChannel = 0; _connectionStateEnum = AMQP_STATE_DISCONNECTED; _channelFrames = NULL; _openChannels.clear(); return AMQP_ERROR_OK; } AMQPStatus CAmqpConnection::closeChannel( const amqp_channel_t& channel) { CAF_CM_FUNCNAME_VALIDATE("closeChannel"); CAF_CM_VALIDATE_PTR(_connectionState); CAF_CM_VALIDATE_BOOL(_connectionStateEnum == AMQP_STATE_CONNECTED); CAF_CM_LOG_DEBUG_VA1("Calling amqp_channel_close - channel: %d", channel); AmqpCommon::validateRpcReply( "amqp_channel_close", amqp_channel_close( _connectionState, channel, AMQP_REPLY_SUCCESS)); return AMQP_ERROR_OK; } int32 CAmqpConnection::receiveFrame( const amqp_connection_state_t& connectionState, SmartPtrCAmqpFrame& frame) const { CAF_CM_FUNCNAME_VALIDATE("receiveFrame"); CAF_CM_VALIDATE_PTR(connectionState); frame = SmartPtrCAmqpFrame(); timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; amqp_frame_t decoded_frame; int32 status = amqp_simple_wait_frame_noblock( connectionState, &decoded_frame, &tv); if (AMQP_STATUS_OK == status) { frame.CreateInstance(); frame->initialize(decoded_frame); frame->log("Received"); if (AMQP_FRAME_METHOD == frame->getFrameType()) { const amqp_method_t* amqpMethod = frame->getPayloadAsMethod(); if (AMQP_CONNECTION_CLOSE_METHOD == amqpMethod->id) { status = AMQP_STATUS_CONNECTION_CLOSED; } } } return status; } void CAmqpConnection::addFrames( const CAmqpFrames& frames, const SmartPtrCChannelFrames& channelFrames) const { for (CAmqpFrames::const_iterator iter = frames.begin(); iter != frames.end(); iter++) { const SmartPtrCAmqpFrame frame = *iter; CChannelFrames::iterator fndIter = channelFrames->find(frame->getChannel()); if (channelFrames->end() == fndIter) { channelFrames->insert(std::make_pair( frame->getChannel(), CAmqpFrames())); fndIter = channelFrames->find(frame->getChannel()); } fndIter->second.push_back(frame); } } void CAmqpConnection::validateOpenChannel( const amqp_channel_t& channel) const { CAF_CM_FUNCNAME("validateOpenChannel"); if (_openChannels.end() == _openChannels.find(channel)) { CAF_CM_EXCEPTION_VA1(E_FAIL, "Channel not found - %d", channel); } } bool CAmqpConnection::isDataAvail( const amqp_connection_state_t& connectionState) const { CAF_CM_FUNCNAME_VALIDATE("isDataAvail"); CAF_CM_VALIDATE_PTR(connectionState); return (amqp_frames_enqueued(connectionState)) || (amqp_data_in_buffer(connectionState)); } void CAmqpConnection::restartListener( const std::string& reason) const { CAF_CM_FUNCNAME_VALIDATE("restartListener"); CAF_CM_VALIDATE_STRING(reason); const std::string monitorDir = AppConfigUtils::getRequiredString("monitor_dir"); const std::string monitorDirExp = CStringUtils::expandEnv(monitorDir); FileSystemUtils::saveTextFile(monitorDirExp, "restartListener.txt", reason); } CAmqpFrame.cpp000066400000000000000000000075001321503522500352470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpFrame.h" using namespace Caf::AmqpClient; CAmqpFrame::CAmqpFrame() : _isInitialized(false), _frameType(0), _channel(0), _propertiesClassId(0), _propertiesBodySize(0), _propertiesDecoded(NULL), CAF_CM_INIT_LOG("CAmqpFrame") { _method.decoded = NULL; _method.id = 0; _bodyFragment.bytes = NULL; _bodyFragment.len = 0; } CAmqpFrame::~CAmqpFrame() { } void CAmqpFrame::initialize( const amqp_frame_t& frame) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _channel = frame.channel; _frameType = frame.frame_type; switch (_frameType) { case AMQP_FRAME_METHOD: { _method = frame.payload.method; } break; case AMQP_FRAME_HEADER: { _propertiesClassId = frame.payload.properties.class_id; _propertiesBodySize = frame.payload.properties.body_size; CAF_CM_VALIDATE_NOTZERO(static_cast(_propertiesBodySize)); CAF_CM_VALIDATE_PTR(frame.payload.properties.decoded); _propertiesDecoded = static_cast( frame.payload.properties.decoded); } break; case AMQP_FRAME_BODY: { _bodyFragment = frame.payload.body_fragment; } break; default: CAF_CM_LOG_ERROR_VA1("Unknown frame type - %d", frame.frame_type); } _isInitialized = true; } uint8_t CAmqpFrame::getFrameType() const { CAF_CM_FUNCNAME_VALIDATE("getFrameType"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _frameType; } amqp_channel_t CAmqpFrame::getChannel() const { CAF_CM_FUNCNAME_VALIDATE("getChannel"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _channel; } const amqp_method_t* const CAmqpFrame::getPayloadAsMethod() const { CAF_CM_FUNCNAME_VALIDATE("getPayloadAsMethod"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(_frameType == AMQP_FRAME_METHOD); return &_method; } uint16_t CAmqpFrame::getHeaderClassId() const { CAF_CM_FUNCNAME_VALIDATE("getHeaderClassId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(_frameType == AMQP_FRAME_HEADER); return _propertiesClassId; } uint64_t CAmqpFrame::getHeaderBodySize() const { CAF_CM_FUNCNAME_VALIDATE("getHeaderBodySize"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(_frameType == AMQP_FRAME_HEADER); return _propertiesBodySize; } const amqp_basic_properties_t* const CAmqpFrame::getHeaderProperties() const { CAF_CM_FUNCNAME_VALIDATE("getPayloadAsMethod"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(_frameType == AMQP_FRAME_HEADER); return _propertiesDecoded; } const amqp_bytes_t* const CAmqpFrame::getBodyFragment() const { CAF_CM_FUNCNAME_VALIDATE("getBodyFragment"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(_frameType == AMQP_FRAME_BODY); return &_bodyFragment; } void CAmqpFrame::log( const std::string& prefix) const { CAF_CM_FUNCNAME_VALIDATE("log"); CAF_CM_VALIDATE_STRING(prefix); switch (_frameType) { case AMQP_FRAME_METHOD: CAF_CM_LOG_DEBUG_VA4( "%s - type: AMQP_FRAME_METHOD, channel: %d, methodId: 0x%08x, methodName: %s", prefix.c_str(), _channel, _method.id, amqp_method_name(_method.id)); break; case AMQP_FRAME_HEADER: CAF_CM_LOG_DEBUG_VA4( "%s - type: AMQP_FRAME_HEADER, channel: %d, classId: 0x%04x, bodySize: %d", prefix.c_str(), _channel, _propertiesClassId, _propertiesBodySize); break; case AMQP_FRAME_BODY: CAF_CM_LOG_DEBUG_VA3( "%s - type: AMQP_FRAME_BODY, channel: %d, bodyLen: %d", prefix.c_str(), _channel, _bodyFragment.len); // AmqpCommon::dumpMessageBody(_bodyFragment.bytes, _bodyFragment.len); break; default: CAF_CM_LOG_ERROR_VA1("Unknown frame type - %d", _frameType); } } CertInfo.cpp000066400000000000000000000024471321503522500350110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/CertInfo.h" using namespace Caf::AmqpClient; CertInfo::CertInfo() : _isInitialized(false), CAF_CM_INIT_LOG("CertInfo") {} CertInfo::~CertInfo() {} void CertInfo::initialize( const std::string& caCertPath, const std::string& clientCertPath, const std::string& clientKeyPath) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(caCertPath); CAF_CM_VALIDATE_STRING(clientCertPath); CAF_CM_VALIDATE_STRING(clientKeyPath); _caCertPath = caCertPath; _clientCertPath = clientCertPath; _clientKeyPath = clientKeyPath; _isInitialized = true; } std::string CertInfo::getCaCertPath() const { CAF_CM_FUNCNAME_VALIDATE("getCaCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _caCertPath; } std::string CertInfo::getClientCertPath() const { CAF_CM_FUNCNAME_VALIDATE("getClientCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _clientCertPath; } std::string CertInfo::getClientKeyPath() const { CAF_CM_FUNCNAME_VALIDATE("getClientKeyPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _clientKeyPath; } CommandAssembler.cpp000066400000000000000000000110761321503522500365120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/amqpImpl/IContentHeader.h" #include "amqpClient/amqpImpl/IMethod.h" #include "amqpClient/CommandAssembler.h" #include "Exception/CCafException.h" using namespace Caf::AmqpClient; CommandAssembler::CommandAssembler() : _isInitialized(false), _state(EXPECTING_METHOD), _remainingBodyBytes(0), _bodyLength(0), CAF_CM_INIT("CommandAssembler") { } CommandAssembler::~CommandAssembler() { } void CommandAssembler::init() { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } bool CommandAssembler::handleFrame(const SmartPtrCAmqpFrame& frame) { CAF_CM_FUNCNAME("handleFrame"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_PTR(frame); switch (_state) { case EXPECTING_METHOD: consumeMethodFrame(frame); break; case EXPECTING_CONTENT_HEADER: consumeHeaderFrame(frame); break; case EXPECTING_CONTENT_BODY: consumeBodyFrame(frame); break; default: CAF_CM_EXCEPTIONEX_VA2( IllegalStateException, 0, "Bad command state [channel=%d][state=%d]", frame->getChannel(), _state); break; } return isComplete(); } bool CommandAssembler::isComplete() { CAF_CM_FUNCNAME_VALIDATE("isComplete"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return (_state == COMPLETE); } SmartPtrIMethod CommandAssembler::getMethod() { CAF_CM_FUNCNAME_VALIDATE("getMethod"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _method; } SmartPtrCDynamicByteArray CommandAssembler::getContentBody() { CAF_CM_FUNCNAME_VALIDATE("getContentBody"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return coalesceContentBody(); } SmartPtrIContentHeader CommandAssembler::getContentHeader() { CAF_CM_FUNCNAME_VALIDATE("getContentHeader"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _contentHeader; } void CommandAssembler::consumeBodyFrame(const SmartPtrCAmqpFrame& frame) { CAF_CM_FUNCNAME("consumeBodyFrame"); if (frame->getFrameType() == AMQP_FRAME_BODY) { const amqp_bytes_t * const fragment = frame->getBodyFragment(); _remainingBodyBytes -= static_cast(fragment->len); updateContentBodyState(); appendBodyFragment(fragment); } else { CAF_CM_EXCEPTIONEX_VA1( AmqpExceptions::UnexpectedFrameException, 0, "Expected an AMQP body frame. Received type %d", frame->getFrameType()); } } void CommandAssembler::consumeHeaderFrame(const SmartPtrCAmqpFrame& frame) { CAF_CM_FUNCNAME("consumeHeaderFrame"); if (frame->getFrameType() == AMQP_FRAME_HEADER) { _contentHeader = AMQPImpl::headerFromFrame(frame); _remainingBodyBytes = static_cast(_contentHeader->getBodySize()); updateContentBodyState(); } else { CAF_CM_EXCEPTIONEX_VA1( AmqpExceptions::UnexpectedFrameException, 0, "Expected an AMQP header frame. Received type %d", frame->getFrameType()); } } void CommandAssembler::consumeMethodFrame(const SmartPtrCAmqpFrame& frame) { CAF_CM_FUNCNAME("consumeMethodFrame"); if (frame->getFrameType() == AMQP_FRAME_METHOD) { _method = AMQPImpl::methodFromFrame(frame->getPayloadAsMethod()); _state = _method->hasContent() ? EXPECTING_CONTENT_HEADER : COMPLETE; } else { CAF_CM_EXCEPTIONEX_VA1( AmqpExceptions::UnexpectedFrameException, 0, "Expected an AMQP method frame. Received type %d", frame->getFrameType()); } } void CommandAssembler::updateContentBodyState() { _state = (_remainingBodyBytes > 0) ? EXPECTING_CONTENT_BODY : COMPLETE; } void CommandAssembler::appendBodyFragment(const amqp_bytes_t * const fragment) { if (fragment && fragment->len) { SmartPtrCDynamicByteArray fragmentData; fragmentData.CreateInstance(); fragmentData->allocateBytes(fragment->len); fragmentData->memCpy(fragment->bytes, fragment->len); _bodyCollection.push_back(fragmentData); _bodyLength += static_cast(fragment->len); } } SmartPtrCDynamicByteArray CommandAssembler::coalesceContentBody() { SmartPtrCDynamicByteArray body; body.CreateInstance(); if (_bodyLength) { if (_bodyCollection.size() == 1) { body = _bodyCollection.front(); } else { body->allocateBytes(_bodyLength); for (TSmartIterator fragment(_bodyCollection); fragment; fragment++) { body->memAppend(fragment->getPtr(), fragment->getByteCount()); *fragment = NULL; } } _bodyCollection.clear(); _bodyCollection.push_back(body); } return body; } ConnectionFactoryImpl.cpp000066400000000000000000000125531321503522500375500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/AMQConnection.h" #include "amqpClient/api/Address.h" #include "amqpClient/api/CertInfo.h" #include "amqpClient/api/Connection.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpClient/ConnectionFactoryImpl.h" using namespace Caf::AmqpClient; SmartPtrConnectionFactory AMQPCLIENT_LINKAGE Caf::AmqpClient::createConnectionFactory() { SmartPtrConnectionFactoryImpl factory; factory.CreateInstance(); return factory; } ConnectionFactoryImpl::ConnectionFactoryImpl() : _protocol(DEFAULT_PROTOCOL), _host(DEFAULT_HOST), _port(USE_DEFAULT_PORT), _virtualHost(DEFAULT_VHOST), _username(DEFAULT_USER), _password(DEFAULT_PASS), _requestedChannelMax(DEFAULT_CHANNEL_MAX), _requestedFrameMax(DEFAULT_FRAME_MAX), _requestedHeartbeat(DEFAULT_HEARTBEAT), _connectionTimeout(DEFAULT_CONNECTION_TIMEOUT), _consumerThreadCount(DEFAULT_CONSUMER_THREAD_COUNT), _retries(DEFAULT_CONNECTION_RETRIES), _secondsToWait(DEFAULT_CONNECTION_SECONDS_TO_WAIT), CAF_CM_INIT("ConnectionFactoryImpl") { } ConnectionFactoryImpl::~ConnectionFactoryImpl() { } std::string ConnectionFactoryImpl::getProtocol() const { return _protocol; } void ConnectionFactoryImpl::setProtocol(const std::string& protocol) { _protocol = protocol; } std::string ConnectionFactoryImpl::getHost() const { return _host; } void ConnectionFactoryImpl::setHost(const std::string& host) { _host = host; } uint32 ConnectionFactoryImpl::getPort() const { return portOrDefault(_port); } void ConnectionFactoryImpl::setPort(const uint32 port) { _port = port; } std::string ConnectionFactoryImpl::getVirtualHost() const { return _virtualHost; } void ConnectionFactoryImpl::setVirtualHost(const std::string& virtualHost) { _virtualHost = virtualHost; } std::string ConnectionFactoryImpl::getUsername() const { return _username; } void ConnectionFactoryImpl::setUsername(const std::string& username) { _username = username; } std::string ConnectionFactoryImpl::getPassword() const { return _password; } void ConnectionFactoryImpl::setPassword(const std::string& password) { _password = password; } std::string ConnectionFactoryImpl::getCaCertPath() const { return _caCertPath; } void ConnectionFactoryImpl::setCaCertPath(const std::string& caCertPath) { _caCertPath = caCertPath; } std::string ConnectionFactoryImpl::getClientCertPath() const { return _clientCertPath; } void ConnectionFactoryImpl::setClientCertPath(const std::string& clientCertPath) { _clientCertPath = clientCertPath; } std::string ConnectionFactoryImpl::getClientKeyPath() const { return _clientKeyPath; } void ConnectionFactoryImpl::setClientKeyPath(const std::string& clientKeyPath) { _clientKeyPath = clientKeyPath; } uint32 ConnectionFactoryImpl::getRequestedChannelMax() const { return _requestedChannelMax; } void ConnectionFactoryImpl::setRequestedChannelMax(const uint32 requestedChannelMax) { _requestedChannelMax = requestedChannelMax; } uint32 ConnectionFactoryImpl::getRequestedFrameMax() const { return _requestedFrameMax; } void ConnectionFactoryImpl::setRequestedFrameMax(const uint32 requestedFrameMax) { _requestedFrameMax = requestedFrameMax; } uint32 ConnectionFactoryImpl::getRequestedHeartbeat() const { return _requestedHeartbeat; } void ConnectionFactoryImpl::setRequestedHeartbeat(const uint32 requestedHeartbeat) { _requestedHeartbeat = requestedHeartbeat; } uint32 ConnectionFactoryImpl::getConnectionTimeout() const { return _connectionTimeout; } void ConnectionFactoryImpl::setConnectionTimeout(const uint32 connectionTimeout) { _connectionTimeout = connectionTimeout; } uint32 ConnectionFactoryImpl::getConsumerThreadCount() const { return _consumerThreadCount; } void ConnectionFactoryImpl::setConsumerThreadCount(const uint32 threadCount) { CAF_CM_FUNCNAME_VALIDATE("setConsumerThreadCount"); CAF_CM_VALIDATE_NOTZERO(threadCount); _consumerThreadCount = threadCount; } uint16 ConnectionFactoryImpl::getRetries() const { return _retries; } void ConnectionFactoryImpl::setRetries(const uint16 retries) { _retries = retries; } uint16 ConnectionFactoryImpl::getSecondsToWait() const { return _secondsToWait; } void ConnectionFactoryImpl::setSecondsToWait(const uint16 seconds) { _secondsToWait = seconds; } SmartPtrConnection ConnectionFactoryImpl::newConnection() { SmartPtrAddress address; address.CreateInstance(); address->initialize(getProtocol(), getHost(), getPort(), getVirtualHost()); SmartPtrCertInfo certInfo; if (! getCaCertPath().empty() && ! getClientCertPath().empty() && ! getClientKeyPath().empty()) { certInfo.CreateInstance(); certInfo->initialize(getCaCertPath(), getClientCertPath(), getClientKeyPath()); } return newConnection(address, certInfo); } SmartPtrConnection ConnectionFactoryImpl::newConnection( const SmartPtrAddress& address, const SmartPtrCertInfo& certInfo) { SmartPtrAMQConnection conn; conn.CreateInstance(); conn->init( _username, _password, address, certInfo, _requestedFrameMax, _requestedChannelMax, _requestedHeartbeat, _connectionTimeout, _consumerThreadCount, _retries, _secondsToWait); conn->start(); return conn; } uint32 ConnectionFactoryImpl::portOrDefault(const uint32 port) const { return (USE_DEFAULT_PORT == port) ? DEFAULT_AMQP_PORT : port; } ConnectionWeakReference.cpp000066400000000000000000000033671321503522500400300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/ConnectionWeakReference.h" #include "Exception/CCafException.h" using namespace Caf::AmqpClient; ConnectionWeakReference::ConnectionWeakReference() : _connection(NULL), CAF_CM_INIT("ConnectionWeakReference") { CAF_CM_INIT_THREADSAFE; } ConnectionWeakReference::~ConnectionWeakReference() { } void ConnectionWeakReference::setReference(IConnectionInt* connection) { CAF_CM_FUNCNAME_VALIDATE("setReference"); CAF_CM_VALIDATE_PTR(connection); CAF_CM_LOCK_UNLOCK; _connection = connection; } void ConnectionWeakReference::clearReference() { CAF_CM_LOCK_UNLOCK; _connection = NULL; } AMQPStatus ConnectionWeakReference::amqpConnectionOpenChannel(SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME("amqpConnectionOpenChannel"); CAF_CM_LOCK_UNLOCK; AMQPStatus status = AMQP_ERROR_OK; if (_connection) { status = _connection->amqpConnectionOpenChannel(channel); } else { CAF_CM_EXCEPTIONEX_VA0( NullPointerException, 0, "The weak reference is not set"); } return status; } void ConnectionWeakReference::notifyChannelClosedByServer(const uint16 channelNumber) { CAF_CM_FUNCNAME("notifyChannelClosedByServer"); CAF_CM_LOCK_UNLOCK; if (_connection) { _connection->notifyChannelClosedByServer(channelNumber); } else { CAF_CM_EXCEPTIONEX_VA0( NullPointerException, 0, "The weak reference is not set"); } } void ConnectionWeakReference::channelCloseChannel(Channel *channel) { // It's okay for the weak reference to be unset in this call if (_connection) { _connection->channelCloseChannel(channel); } } ConsumerDispatcher.cpp000066400000000000000000000221131321503522500370720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/ConsumerWorkService.h" #include "amqpClient/api/Consumer.h" #include "amqpClient/api/Envelope.h" #include "amqpClient/ConsumerDispatcher.h" #include "Exception/CCafException.h" using namespace Caf::AmqpClient; ConsumerDispatcher::ConsumerDispatcher() : _isInitialized(false), _isShuttingDown(false), CAF_CM_INIT_LOG("ConsumerDispatcher") { CAF_CM_INIT_THREADSAFE; } ConsumerDispatcher::~ConsumerDispatcher() { } void ConsumerDispatcher::init(const SmartPtrConsumerWorkService& workService) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(workService); _workService = workService; _isInitialized = true; } void ConsumerDispatcher::quiesce() { CAF_CM_LOCK_UNLOCK; _isShuttingDown = true; } void ConsumerDispatcher::lock() { CAF_CM_LOCK; } void ConsumerDispatcher::unlock() { CAF_CM_UNLOCK; } void ConsumerDispatcher::addConsumer( const std::string& consumerTag, const SmartPtrConsumer& consumer) { CAF_CM_FUNCNAME("addConsumer"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(consumerTag); CAF_CM_VALIDATE_SMARTPTR(consumer); SmartPtrDispatcherTask consumerTask; consumerTask.CreateInstance(); consumerTask->init(consumerTag, consumer); if (_consumers.insert( ConsumerMap::value_type( consumerTag, ConsumerItem(consumer, consumerTask))).second) { _workService->addWork(consumerTask); } else { CAF_CM_EXCEPTIONEX_VA1( DuplicateElementException, 0, "A consumer with consumer tag '%s' is already registered", consumerTag.c_str()); } } void ConsumerDispatcher::removeConsumer( const std::string& consumerTag) { CAF_CM_FUNCNAME_VALIDATE("removeConsumer"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(consumerTag); ConsumerMap::iterator consumer = _consumers.find(consumerTag); if (consumer != _consumers.end()) { (consumer->second).second->term(); _consumers.erase(consumer); } } SmartPtrConsumer ConsumerDispatcher::getConsumer( const std::string& consumerTag) { CAF_CM_FUNCNAME_VALIDATE("getConsumer"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(consumerTag); SmartPtrConsumer result; ConsumerMap::iterator consumer = _consumers.find(consumerTag); if (consumer != _consumers.end()) { result = (consumer->second).first; } return result; } void ConsumerDispatcher::handleShutdown(SmartPtrCCafException exception) { CAF_CM_FUNCNAME("handleShutdown"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); for (TMapIterator consumerItem(_consumers); consumerItem; consumerItem++) { try { consumerItem->second->term(); consumerItem->first->handleShutdown(consumerItem.getKey(), exception); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } _consumers.clear(); } void ConsumerDispatcher::handleConsumeOk(const std::string& consumerTag) { CAF_CM_FUNCNAME("handleConsumeOk"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); try { if (!_isShuttingDown) { SmartPtrDispatcherWorkItem workItem; workItem.CreateInstance(); workItem->init(DISPATCH_ITEM_METHOD_HANDLE_CONSUME_OK); getConsumerItem(consumerTag).second->addWorkItem(workItem); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } void ConsumerDispatcher::handleCancelOk(const std::string& consumerTag) { CAF_CM_FUNCNAME("handleCancelOk"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); try { if (!_isShuttingDown) { SmartPtrDispatcherWorkItem workItem; workItem.CreateInstance(); workItem->init(DISPATCH_ITEM_METHOD_HANDLE_CANCEL_OK); getConsumerItem(consumerTag).second->addWorkItem(workItem); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } void ConsumerDispatcher::handleRecoverOk() { CAF_CM_FUNCNAME("handleRecoverOk"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); try { if (!_isShuttingDown) { for (TMapIterator consumerItem(_consumers); consumerItem; consumerItem++) { if (!_isShuttingDown) { SmartPtrDispatcherWorkItem workItem; workItem.CreateInstance(); workItem->init(DISPATCH_ITEM_METHOD_HANDLE_RECOVER_OK); consumerItem->second->addWorkItem(workItem); } } } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } void ConsumerDispatcher::handleDelivery( const std::string& consumerTag, const SmartPtrEnvelope& envelope, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { CAF_CM_FUNCNAME("handleDelivery"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); try { if (!_isShuttingDown) { SmartPtrDispatcherWorkItem workItem; workItem.CreateInstance(); workItem->init( DISPATCH_ITEM_METHOD_HANDLE_DELIVERY, envelope, properties, body); getConsumerItem(consumerTag).second->addWorkItem(workItem); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } ConsumerDispatcher::ConsumerItem ConsumerDispatcher::getConsumerItem(const std::string& consumerTag) { CAF_CM_FUNCNAME("getConsumerItem"); ConsumerMap::const_iterator consumerItem = _consumers.find(consumerTag); if (consumerItem == _consumers.end()) { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Consumer '%s' is not in the collection", consumerTag.c_str()); } return consumerItem->second; } #if (1) // DispatcherWorkItem ConsumerDispatcher::DispatcherWorkItem::DispatcherWorkItem() : _method(DISPATCH_ITEM_METHOD_TERMINATE) { } void ConsumerDispatcher::DispatcherWorkItem::init( const DispatchItemMethod method) { _method = method; } void ConsumerDispatcher::DispatcherWorkItem::init( const DispatchItemMethod method, const SmartPtrEnvelope& envelope, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { _method = method; _envelope = envelope; _properties = properties; _body = body; } ConsumerDispatcher::DispatchItemMethod ConsumerDispatcher::DispatcherWorkItem::getMethod() const { return _method; } SmartPtrEnvelope ConsumerDispatcher::DispatcherWorkItem::getEnvelope() const { return _envelope; } AmqpContentHeaders::SmartPtrBasicProperties ConsumerDispatcher::DispatcherWorkItem::getProperties() const { return _properties; } SmartPtrCDynamicByteArray ConsumerDispatcher::DispatcherWorkItem::getBody() const { return _body; } #endif #if (1) // DispatcherTask ConsumerDispatcher::DispatcherTask::DispatcherTask() : _workItemQueue(NULL) { } ConsumerDispatcher::DispatcherTask::~DispatcherTask() { if (_workItemQueue) { g_async_queue_unref(_workItemQueue); } } void ConsumerDispatcher::DispatcherTask::init( const std::string& consumerTag, const SmartPtrConsumer& consumer) { _consumerTag = consumerTag; _consumer = consumer; _workItemQueue = g_async_queue_new_full(FreeWorkItem); } void ConsumerDispatcher::DispatcherTask::term() { SmartPtrDispatcherWorkItem workItem; workItem.CreateInstance(); workItem->init(DISPATCH_ITEM_METHOD_TERMINATE); addWorkItem(workItem); } void ConsumerDispatcher::DispatcherTask::addWorkItem( const ConsumerDispatcher::SmartPtrDispatcherWorkItem& workItem) { g_async_queue_push(_workItemQueue, workItem.GetAddRefedInterface()); } bool ConsumerDispatcher::DispatcherTask::run() { uint32 itemsProcessed = 0; bool isTerminated = false; gpointer data = g_async_queue_try_pop(_workItemQueue); while (data) { DispatcherWorkItem *workItemPtr = reinterpret_cast(data); SmartPtrDispatcherWorkItem workItem(workItemPtr); workItemPtr->Release(); data = NULL; switch (workItem->getMethod()) { case DISPATCH_ITEM_METHOD_HANDLE_CONSUME_OK: _consumer->handleConsumeOk(_consumerTag); break; case DISPATCH_ITEM_METHOD_HANDLE_CANCEL_OK: _consumer->handleCancelOk(_consumerTag); break; case DISPATCH_ITEM_METHOD_HANDLE_RECOVER_OK: _consumer->handleRecoverOk(_consumerTag); break; case DISPATCH_ITEM_METHOD_HANDLE_DELIVERY: _consumer->handleDelivery( _consumerTag, workItemPtr->getEnvelope(), workItemPtr->getProperties(), workItemPtr->getBody()); break; case DISPATCH_ITEM_METHOD_TERMINATE: isTerminated = true; break; } if (!isTerminated && (++itemsProcessed < DEFAULT_CONSUMER_THREAD_MAX_DELIVERY_COUNT)) { data = g_async_queue_try_pop(_workItemQueue); } } return isTerminated; } void ConsumerDispatcher::DispatcherTask::FreeWorkItem(gpointer data) { CAF_CM_STATIC_FUNC_LOG_ONLY("ConsumerDispatcher::DispatcherTask","FreeWorkItem"); DispatcherWorkItem *workItemPtr = reinterpret_cast(data); CAF_CM_LOG_DEBUG_VA1("Clearing workItem [method=%d]", workItemPtr->getMethod()); workItemPtr->Release(); } #endif ConsumerWorkService.cpp000066400000000000000000000022011321503522500372430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CManagedThreadPool.h" #include "amqpClient/ConsumerWorkService.h" using namespace Caf::AmqpClient; ConsumerWorkService::ConsumerWorkService() : _isInitialized(false), CAF_CM_INIT_LOG("ConsumerWorkService") { } ConsumerWorkService::~ConsumerWorkService() { CAF_CM_FUNCNAME("~ConsumerWorkService"); try { if (_threadPool) { _threadPool->term(); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } void ConsumerWorkService::init(const SmartPtrCManagedThreadPool& threadPool) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_threadPool); _threadPool = threadPool; } void ConsumerWorkService::addWork(const CManagedThreadPool::SmartPtrIThreadTask& task) { CAF_CM_FUNCNAME_VALIDATE("addWork"); CAF_CM_PRECOND_ISINITIALIZED(_threadPool); _threadPool->enqueue(task); } void ConsumerWorkService::notifyConnectionClosed() { if (!_threadPool.IsNull()) { _threadPool->term(); _threadPool = NULL; } } amqpClient.cpp000066400000000000000000000015311321503522500353660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/amqpClient.h" namespace Caf { namespace AmqpClient { const char* DEFAULT_USER = "guest"; const char* DEFAULT_PASS ="guest"; const char* DEFAULT_VHOST = "/"; const char* DEFAULT_PROTOCOL = "amqp"; const char* DEFAULT_HOST = "localhost"; }} #ifdef WIN32 extern "C" BOOL APIENTRY DllMain(HINSTANCE hModule, uint32 dwReason, LPVOID) { return TRUE; } #endif /** * @todo Make number of frames processed per thread slice configurable * @todo Make # threads in the connection thrad pool configurable * @todo Make thread pool refresh rate configurable * @todo Create stats module so we can figure out how to turn performance */ class amqpClientTodo { }; amqpImpl/000077500000000000000000000000001321503522500343455ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClientAMQExceptions.cpp000066400000000000000000000030411321503522500375270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 3, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/AMQExceptions.h" using namespace Caf::AmqpClient::AmqpExceptions; AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpTimeoutException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpNoMemoryException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpInvalidHandleException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpInvalidArgumentException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpWrongStateException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpTooManyChannelsException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpQueueFullException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpFrameTooLargeException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpIoErrorException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpProtocolErrorException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpUnimplementedException); AMQP_CM_DEFINE_EXCEPTION_CLASS(AmqpIoInterruptedException); AMQP_CM_DEFINE_EXCEPTION_CLASS(UnexpectedFrameException); AMQP_CM_DEFINE_EXCEPTION_CLASS(UnknownClassOrMethodException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ConnectionClosedException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ChannelClosedException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ConnectionUnexpectedCloseException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ConnectionClosedByIOException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ChannelClosedByServerException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ChannelClosedByShutdownException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ChannelClosedByUserException); AMQPImpl.cpp000066400000000000000000000065501321503522500364370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/amqpImpl/IContentHeader.h" #include "amqpClient/amqpImpl/IMethod.h" #include "Exception/CCafException.h" #include "AMQPImpl.h" #include "amqpImplInt.h" namespace Caf { namespace AmqpClient { typedef Caf::AmqpClient::SmartPtrIMethod (*FN_CREATOR)(); typedef std::map MethodCreatorMap; typedef MethodCreatorMap::value_type creatorEntry; }} using namespace Caf::AmqpClient; const creatorEntry creatorEntries[] = { creatorEntry(AMQP_BASIC_GET_OK_METHOD, BasicGetOkMethod::Creator), creatorEntry(AMQP_BASIC_GET_EMPTY_METHOD, BasicGetEmptyMethod::Creator), creatorEntry(AMQP_BASIC_CONSUME_OK_METHOD, BasicConsumeOkMethod::Creator), creatorEntry(AMQP_BASIC_DELIVER_METHOD, BasicDeliverMethod::Creator), creatorEntry(AMQP_BASIC_CANCEL_OK_METHOD, BasicCancelOkMethod::Creator), creatorEntry(AMQP_BASIC_RETURN_METHOD, BasicReturnMethod::Creator), creatorEntry(AMQP_BASIC_RECOVER_OK_METHOD, BasicRecoverOkMethod::Creator), creatorEntry(AMQP_BASIC_QOS_OK_METHOD, BasicQosOkMethod::Creator), creatorEntry(AMQP_CHANNEL_OPEN_OK_METHOD, ChannelOpenOkMethod::Creator), creatorEntry(AMQP_CHANNEL_CLOSE_OK_METHOD, ChannelCloseOkFromServerMethod::Creator), creatorEntry(AMQP_CHANNEL_CLOSE_METHOD, ChannelCloseMethod::Creator), creatorEntry(AMQP_EXCHANGE_DECLARE_OK_METHOD, ExchangeDeclareOkMethod::Creator), creatorEntry(AMQP_EXCHANGE_DELETE_OK_METHOD, ExchangeDeleteOkMethod::Creator), creatorEntry(AMQP_QUEUE_DECLARE_OK_METHOD, QueueDeclareOkMethod::Creator), creatorEntry(AMQP_QUEUE_DELETE_OK_METHOD, QueueDeleteOkMethod::Creator), creatorEntry(AMQP_QUEUE_PURGE_OK_METHOD, QueuePurgeOkMethod::Creator), creatorEntry(AMQP_QUEUE_BIND_OK_METHOD, QueueBindOkMethod::Creator), creatorEntry(AMQP_QUEUE_UNBIND_OK_METHOD, QueueUnbindOkMethod::Creator) }; const MethodCreatorMap creatorMap( creatorEntries, creatorEntries + (sizeof(creatorEntries)/sizeof(creatorEntries[0]))); SmartPtrIMethod AMQPImpl::methodFromFrame(const amqp_method_t * const method) { CAF_CM_STATIC_FUNC("AMQPImpl", "methodFromFrame"); CAF_CM_VALIDATE_PTR(method); SmartPtrIMethod methodObj; MethodCreatorMap::const_iterator methodCreator = creatorMap.find(method->id); if (methodCreator != creatorMap.end()) { methodObj = (*(methodCreator->second))(); } else { const uint16 classId = (uint16)((method->id & 0xffff0000) >> 16); const uint16 methodId = (uint16)(method->id & 0x0000ffff); CAF_CM_EXCEPTIONEX_VA2( AmqpExceptions::UnknownClassOrMethodException, 0, "[class=0x%04X][id=0x%04X]", classId, methodId); } methodObj->init(method); return methodObj; } SmartPtrIContentHeader AMQPImpl::headerFromFrame( const SmartPtrCAmqpFrame& frame) { CAF_CM_STATIC_FUNC("AMQPImpl", "headerFromFrame"); CAF_CM_VALIDATE_PTR(frame); SmartPtrIContentHeader header; if (frame->getHeaderClassId() == AMQP_BASIC_CLASS) { SmartPtrBasicProperties propsObj; propsObj.CreateInstance(); propsObj->init(frame); header = propsObj; } else { CAF_CM_EXCEPTIONEX_VA1( AmqpExceptions::UnknownClassOrMethodException, 0, "[class=0x%04X]", frame->getHeaderClassId()); } return header; } AMQPImpl.h000066400000000000000000000020471321503522500361010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPIMPL_H_ #define AMQPIMPL_H_ #include "amqpClient/amqpImpl/IContentHeader.h" #include "amqpClient/amqpImpl/IMethod.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief A set of helpers to convert c-api data structures into C++ objects */ class AMQPImpl { public: /** * @brief Convert a c-api method structure into the appropriate IMethod object * @param method c-api method data * @return IMethod object */ static SmartPtrIMethod methodFromFrame(const amqp_method_t * const method); /** * @brief Convert a c-api properties structure into the appropriate IContentHedaer object * @param properties c-api properties data * @return IContentHeader object */ static SmartPtrIContentHeader headerFromFrame(const SmartPtrCAmqpFrame& frame); }; }} #endif /* AMQPIMPL_H_ */ AmqpClientImpl.cpp000066400000000000000000000072021321503522500377310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/FieldImpl.h" #include "amqpClient/api/amqpClient.h" #include "Exception/CCafException.h" using namespace Caf; using namespace Caf::AmqpClient; void tableAddField( const std::string key, const AmqpClient::Field::AmqpFieldType type, GVariant* variant, AmqpClient::SmartPtrTable& table) { CAF_CM_STATIC_FUNC_LOG("AmqpClient", "tableAddField"); CAF_CM_VALIDATE_STRING(key); CAF_CM_VALIDATE_PTR(variant); CAF_CM_VALIDATE_SMARTPTR(table); AmqpClient::SmartPtrFieldImpl field; field.CreateInstance(); field->setTypeAndValue(type, variant); if (!table->insert(std::make_pair(key, field)).second) { g_variant_unref(variant); CAF_CM_EXCEPTIONEX_VA1( DuplicateElementException, 0, "Duplicate table entry '%s'", key.c_str()); } } void AmqpClient::tableAddBoolean( const std::string key, const bool val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_BOOLEAN, g_variant_new_boolean(val), table); } void AmqpClient::tableAddInt8( const std::string key, const int8 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_I8, g_variant_new_byte(val), table); } void AmqpClient::tableAddUint8( const std::string key, const uint8 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_U8, g_variant_new_byte(val), table); } void AmqpClient::tableAddInt16( const std::string key, const int16 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_I16, g_variant_new_int16(val), table); } void AmqpClient::tableAddUint16( const std::string key, const uint16 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_U16, g_variant_new_uint16(val), table); } void AmqpClient::tableAddInt32( const std::string key, const int32 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_I32, g_variant_new_int32(val), table); } void AmqpClient::tableAddUint32( const std::string key, const uint32 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_U32, g_variant_new_uint32(val), table); } void AmqpClient::tableAddInt64( const std::string key, const int64 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_I64, g_variant_new_int64(val), table); } void AmqpClient::tableAddUint64( const std::string key, const uint64 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_U64, g_variant_new_uint64(val), table); } void AmqpClient::tableAddFloat( const std::string key, const float val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_F32, g_variant_new_double(val), table); } void AmqpClient::tableAddDouble( const std::string key, const double val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_F64, g_variant_new_double(val), table); } void AmqpClient::tableAddUtf8( const std::string key, const std::string& val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_UTF8, g_variant_new_string(val.c_str()), table); } void AmqpClient::tableAddTimestamp( const std::string key, const uint64 val, SmartPtrTable& table) { tableAddField( key, AmqpClient::Field::AMQP_FIELD_TYPE_TIMESTAMP, g_variant_new_uint64(val), table); } AmqpContentHeadersImpl.cpp000066400000000000000000000047111321503522500414230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "amqpClient/api/amqpClient.h" using namespace Caf::AmqpClient; const uint32 AmqpContentHeaders::BASIC_PROPERTY_CONTENT_TYPE_FLAG = 0x8000; const uint32 AmqpContentHeaders::BASIC_PROPERTY_CONTENT_ENCODING_FLAG = 0x4000; const uint32 AmqpContentHeaders::BASIC_PROPERTY_HEADERS_FLAG = 0x2000; const uint32 AmqpContentHeaders::BASIC_PROPERTY_DEVLIVERY_MODE_FLAG = 0x1000; const uint32 AmqpContentHeaders::BASIC_PROPERTY_PRIORITY_FLAG = 0x800; const uint32 AmqpContentHeaders::BASIC_PROPERTY_CORRELATION_ID_FLAG = 0x400; const uint32 AmqpContentHeaders::BASIC_PROPERTY_REPLY_TO_FLAG = 0x200; const uint32 AmqpContentHeaders::BASIC_PROPERTY_EXPIRATION_FLAG = 0x100; const uint32 AmqpContentHeaders::BASIC_PROPERTY_MESSAGE_ID_FLAG = 0x80; const uint32 AmqpContentHeaders::BASIC_PROPERTY_TIMESTAMP_FLAG = 0x40; const uint32 AmqpContentHeaders::BASIC_PROPERTY_TYPE_FLAG = 0x20; const uint32 AmqpContentHeaders::BASIC_PROPERTY_USER_ID_FLAG = 0x10; const uint32 AmqpContentHeaders::BASIC_PROPERTY_APP_ID_FLAG = 0x8; const uint32 AmqpContentHeaders::BASIC_PROPERTY_CLUSTER_ID_FLAG = 0x4; AmqpContentHeaders::SmartPtrBasicProperties AmqpContentHeaders::createBasicProperties() { Caf::AmqpClient::SmartPtrBasicProperties props; props.CreateInstance(); props->init(); SmartPtrBasicProperties result; result.QueryInterface(props); return result; } AmqpContentHeaders::SmartPtrBasicProperties AmqpContentHeaders::createBasicProperties( const uint32 flags, const std::string& contentType, const std::string& contentEncoding, const SmartPtrTable& headers, const uint8 deliveryMode, const uint8 priority, const std::string& correlationId, const std::string& replyTo, const std::string& expiration, const std::string& messageId, const uint64 timestamp, const std::string& type, const std::string& userId, const std::string& appId, const std::string& clusterId) { Caf::AmqpClient::SmartPtrBasicProperties props; props.CreateInstance(); props->init( flags, contentType, contentEncoding, headers, deliveryMode, priority, correlationId, replyTo, expiration, messageId, timestamp, type, userId, appId, clusterId); SmartPtrBasicProperties result; result.QueryInterface(props); return result; } BasicAckMethod.cpp000066400000000000000000000020041321503522500376460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicAckMethod.h" using namespace Caf::AmqpClient; BasicAckMethod::BasicAckMethod() : _isInitialized(false), _deliveryTag(0), _ackMultiple(false), CAF_CM_INIT("BasicAckMethod") { } BasicAckMethod::~BasicAckMethod() { } void BasicAckMethod::init( const uint64 deliveryTag, const bool ackMultiple) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _deliveryTag = deliveryTag; _ackMultiple = ackMultiple; _isInitialized = true; } std::string BasicAckMethod::getMethodName() const { return "basic.ack"; } AMQPStatus BasicAckMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_BasicAck( channel, _deliveryTag, _ackMultiple); } BasicCancelMethod.cpp000066400000000000000000000016761321503522500403530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicCancelMethod.h" using namespace Caf::AmqpClient; BasicCancelMethod::BasicCancelMethod() : _isInitialized(false), CAF_CM_INIT("BasicCancelMethod") { } BasicCancelMethod::~BasicCancelMethod() { } void BasicCancelMethod::init( const std::string& consumerTag) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _consumerTag = consumerTag; _isInitialized = true; } std::string BasicCancelMethod::getMethodName() const { return "basic.cancel"; } AMQPStatus BasicCancelMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_BasicCancel(channel, _consumerTag, false); } BasicCancelOkMethod.cpp000066400000000000000000000014751321503522500406420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "BasicCancelOkMethod.h" using namespace Caf::AmqpClient; BasicCancelOkMethod::BasicCancelOkMethod() : CAF_CM_INIT("BasicCancelOkMethod") { } BasicCancelOkMethod::~BasicCancelOkMethod() { } void BasicCancelOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_BASIC_CANCEL_OK_METHOD == method->id); const amqp_basic_cancel_ok_t * const decoded = reinterpret_cast(method->decoded); _consumerTag = AMQUtil::amqpBytesToString(&decoded->consumer_tag); } std::string BasicCancelOkMethod::getConsumerTag() { return _consumerTag; } BasicCancelOkMethod.h000066400000000000000000000020111321503522500402720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICCANCELOKMETHOD_H_ #define BASICCANCELOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.cancel-ok */ class BasicCancelOkMethod : public TMethodImpl, public AmqpMethods::Basic::CancelOk { METHOD_DECL( AmqpMethods::Basic::CancelOk, AMQP_BASIC_CANCEL_OK_METHOD, "basic.cancel-ok", false) public: BasicCancelOkMethod(); virtual ~BasicCancelOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Basic::CancelOk std::string getConsumerTag(); private: std::string _consumerTag; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicCancelOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(BasicCancelOkMethod); }} #endif /* BASICCANCELOKMETHOD_H_ */ BasicConsumeMethod.cpp000066400000000000000000000024731321503522500405730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" #include "amqpClient/amqpImpl/BasicConsumeMethod.h" using namespace Caf::AmqpClient; BasicConsumeMethod::BasicConsumeMethod() : _isInitialized(false), _noLocal(false), _noAck(false), _exclusive(false), CAF_CM_INIT("BasicConsumeMethod") { } BasicConsumeMethod::~BasicConsumeMethod() { } void BasicConsumeMethod::init( const std::string& queue, const std::string& consumerTag, const bool noLocal, const bool noAck, const bool exclusive, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _queue = queue; _consumerTag = consumerTag; _noLocal = noLocal; _noAck = noAck; _exclusive = exclusive; _isInitialized = true; } std::string BasicConsumeMethod::getMethodName() const { return "basic.consume"; } AMQPStatus BasicConsumeMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_BasicConsume( channel, _queue, _consumerTag, _noLocal, _noAck, _exclusive, false, NULL); } BasicConsumeOkMethod.cpp000066400000000000000000000015101321503522500410540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "BasicConsumeOkMethod.h" using namespace Caf::AmqpClient; BasicConsumeOkMethod::BasicConsumeOkMethod() : CAF_CM_INIT("BasicConsumeOkMethod") { } BasicConsumeOkMethod::~BasicConsumeOkMethod() { } void BasicConsumeOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_BASIC_CONSUME_OK_METHOD == method->id); const amqp_basic_consume_ok_t * const decoded = reinterpret_cast(method->decoded); _consumerTag = AMQUtil::amqpBytesToString(&decoded->consumer_tag); } std::string BasicConsumeOkMethod::getConsumerTag() { return _consumerTag; } BasicConsumeOkMethod.h000066400000000000000000000020301321503522500405170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICCONSUMEOKMETHOD_H_ #define BASICCONSUMEOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.consume-ok */ class BasicConsumeOkMethod : public TMethodImpl, public AmqpMethods::Basic::ConsumeOk { METHOD_DECL( AmqpMethods::Basic::ConsumeOk, AMQP_BASIC_CONSUME_OK_METHOD, "basic.consume-ok", false) public: BasicConsumeOkMethod(); virtual ~BasicConsumeOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Basic::ConsumeOk std::string getConsumerTag(); private: std::string _consumerTag; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicConsumeOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(BasicConsumeOkMethod); }} #endif /* BASICCONSUMEOKMETHOD_H_ */ BasicDeliverMethod.cpp000066400000000000000000000024771321503522500405600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "BasicDeliverMethod.h" using namespace Caf::AmqpClient; BasicDeliverMethod::BasicDeliverMethod() : _deliveryTag(0), _redelivered(false), CAF_CM_INIT("BasicDeliverMethod") { } BasicDeliverMethod::~BasicDeliverMethod() { } void BasicDeliverMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_BASIC_DELIVER_METHOD == method->id); const amqp_basic_deliver_t * const decoded = reinterpret_cast(method->decoded); _consumerTag = AMQUtil::amqpBytesToString(&decoded->consumer_tag); _deliveryTag = decoded->delivery_tag; _exchange = AMQUtil::amqpBytesToString(&decoded->exchange); _redelivered = decoded->redelivered; _routingKey = AMQUtil::amqpBytesToString(&decoded->routing_key); } std::string BasicDeliverMethod::getConsumerTag() { return _consumerTag; } uint64 BasicDeliverMethod::getDeliveryTag() { return _deliveryTag; } std::string BasicDeliverMethod::getExchange() { return _exchange; } bool BasicDeliverMethod::getRedelivered() { return _redelivered; } std::string BasicDeliverMethod::getRoutingKey() { return _routingKey; } BasicDeliverMethod.h000066400000000000000000000022761321503522500402220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICDELIVERMETHOD_H_ #define BASICDELIVERMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.deliver */ class BasicDeliverMethod : public TMethodImpl, public AmqpMethods::Basic::Deliver { METHOD_DECL( AmqpMethods::Basic::Deliver, AMQP_BASIC_DELIVER_METHOD, "basic.deliver", true) public: BasicDeliverMethod(); virtual ~BasicDeliverMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Basic::Deliver std::string getConsumerTag(); uint64 getDeliveryTag(); std::string getExchange(); bool getRedelivered(); std::string getRoutingKey(); private: std::string _consumerTag; uint64 _deliveryTag; std::string _exchange; bool _redelivered; std::string _routingKey; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicDeliverMethod); }; CAF_DECLARE_SMART_QI_POINTER(BasicDeliverMethod); }} #endif /* BASICDELIVERMETHOD_H_ */ BasicGetEmptyMethod.cpp000066400000000000000000000010571321503522500407150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "BasicGetEmptyMethod.h" using namespace Caf::AmqpClient; BasicGetEmptyMethod::BasicGetEmptyMethod() : CAF_CM_INIT("BasicGetEmptyMethod") { } BasicGetEmptyMethod::~BasicGetEmptyMethod() { } void BasicGetEmptyMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_BASIC_GET_EMPTY_METHOD == method->id); } BasicGetEmptyMethod.h000066400000000000000000000017161321503522500403640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICGETEMPTYMETHOD_H_ #define BASICGETEMPTYMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.get-empty */ class BasicGetEmptyMethod : public TMethodImpl, public AmqpMethods::Basic::GetEmpty { METHOD_DECL( AmqpMethods::Basic::GetEmpty, AMQP_BASIC_GET_EMPTY_METHOD, "basic.get-empty", false) public: BasicGetEmptyMethod(); virtual ~BasicGetEmptyMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Basic::GetEmpty private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicGetEmptyMethod); }; CAF_DECLARE_SMART_QI_POINTER(BasicGetEmptyMethod); }} #endif /* BASICGETEMPTYMETHOD_H_ */ BasicGetMethod.cpp000066400000000000000000000016711321503522500377000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicGetMethod.h" using namespace Caf::AmqpClient; BasicGetMethod::BasicGetMethod() : _isInitialized(false), _noAck(false), CAF_CM_INIT("BasicGetMethod") { } BasicGetMethod::~BasicGetMethod() { } void BasicGetMethod::init( const std::string& queue, const bool noAck) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _queue = queue; _noAck = noAck; _isInitialized = true; } std::string BasicGetMethod::getMethodName() const { return "basic.get"; } AMQPStatus BasicGetMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_BasicGet(channel, _queue, _noAck); } BasicGetOkMethod.cpp000066400000000000000000000024301321503522500401640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "BasicGetOkMethod.h" using namespace Caf::AmqpClient; BasicGetOkMethod::BasicGetOkMethod() : _deliveryTag(0), _messageCount(0), _redelivered(false), CAF_CM_INIT("BasicGetOkMethod") { } BasicGetOkMethod::~BasicGetOkMethod() { } void BasicGetOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_BASIC_GET_OK_METHOD == method->id); const amqp_basic_get_ok_t * const decoded = reinterpret_cast(method->decoded); _deliveryTag = decoded->delivery_tag; _exchange = AMQUtil::amqpBytesToString(&decoded->exchange); _messageCount = decoded->message_count; _redelivered = decoded->redelivered; _routingKey = AMQUtil::amqpBytesToString(&decoded->routing_key); } uint64 BasicGetOkMethod::getDeliveryTag() { return _deliveryTag; } std::string BasicGetOkMethod::getExchange() { return _exchange; } uint32 BasicGetOkMethod::getMessageCount() { return _messageCount; } bool BasicGetOkMethod::getRedelivered() { return _redelivered; } std::string BasicGetOkMethod::getRoutingKey() { return _routingKey; } BasicGetOkMethod.h000066400000000000000000000023031321503522500376300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICGETOKMETHOD_H_ #define BASICGETOKMETHOD_H_ #include "amqpClient/api/AmqpMethods.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.get-ok */ class BasicGetOkMethod : public TMethodImpl, public AmqpMethods::Basic::GetOk { METHOD_DECL( AmqpMethods::Basic::GetOk, AMQP_BASIC_GET_OK_METHOD, "basic.get-ok", true) public: BasicGetOkMethod(); virtual ~BasicGetOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Basic::GetOk uint64 getDeliveryTag(); std::string getExchange(); uint32 getMessageCount(); bool getRedelivered(); std::string getRoutingKey(); private: uint64 _deliveryTag; std::string _exchange; uint32 _messageCount; bool _redelivered; std::string _routingKey; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicGetOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(BasicGetOkMethod); }} #endif /* BASICGETOKMETHOD_H_ */ BasicProperties.cpp000066400000000000000000000362631321503522500401610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpFrame.h" #include "amqpClient/api/amqpClient.h" #include "Exception/CCafException.h" #include "amqpClient/amqpImpl/BasicProperties.h" using namespace Caf::AmqpClient; BasicProperties::BasicProperties() : _isInitialized(false), _flags(0), _bodySize(0), _deliveryMode(0), _priority(0), _timestamp(0), CAF_CM_INIT("BasicProperties") { } BasicProperties::~BasicProperties() { } void BasicProperties::init() { _isInitialized = true; } void BasicProperties::init( const uint32 flags, const std::string& contentType, const std::string& contentEncoding, const SmartPtrTable& headers, const uint8 deliveryMode, const uint8 priority, const std::string& correlationId, const std::string& replyTo, const std::string& expiration, const std::string& messageId, const uint64 timestamp, const std::string& type, const std::string& userId, const std::string& appId, const std::string& clusterId) { CAF_CM_FUNCNAME_VALIDATE("init"); _flags = flags; if (flags & AmqpContentHeaders::BASIC_PROPERTY_CONTENT_TYPE_FLAG) { CAF_CM_VALIDATE_STRING(contentType); _contentType = contentType; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_CONTENT_ENCODING_FLAG) { CAF_CM_VALIDATE_STRING(contentEncoding); _contentEncoding = contentEncoding; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_HEADERS_FLAG) { CAF_CM_VALIDATE_SMARTPTR(headers); _headers = headers; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_DEVLIVERY_MODE_FLAG) { _deliveryMode = deliveryMode; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_PRIORITY_FLAG) { _priority = priority; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_CORRELATION_ID_FLAG) { _correlationId = correlationId; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_REPLY_TO_FLAG) { _replyTo = replyTo; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_EXPIRATION_FLAG) { _expiration = expiration; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_MESSAGE_ID_FLAG) { _messageId = messageId; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_TIMESTAMP_FLAG) { _timestamp = timestamp; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_TYPE_FLAG) { _type = type; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_USER_ID_FLAG) { _userId = userId; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_APP_ID_FLAG) { _appId = appId; } if (flags & AmqpContentHeaders::BASIC_PROPERTY_CLUSTER_ID_FLAG) { _clusterId = clusterId; } _isInitialized = true; } void BasicProperties::init(const SmartPtrCAmqpFrame& frame) { CAF_CM_FUNCNAME("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_PTR(frame); if (frame->getFrameType() != AMQP_FRAME_HEADER) { CAF_CM_EXCEPTIONEX_VA1( AmqpExceptions::UnexpectedFrameException, 0, "Expected an AMQP header frame. Received type %d", frame->getFrameType()); } if (frame->getHeaderClassId() != AMQP_BASIC_CLASS) { CAF_CM_EXCEPTIONEX_VA1( AmqpExceptions::UnknownClassOrMethodException, 0, "[class=0x%04X]", frame->getHeaderClassId()); } const amqp_basic_properties_t * const decoded = frame->getHeaderProperties(); _bodySize = frame->getHeaderBodySize(); const amqp_flags_t flags = decoded->_flags; if (flags & AMQP_BASIC_CONTENT_TYPE_FLAG) { _contentType = AMQUtil::amqpBytesToString(&decoded->content_type); _flags |= AmqpContentHeaders::BASIC_PROPERTY_CONTENT_TYPE_FLAG; } if (flags & AMQP_BASIC_CONTENT_ENCODING_FLAG) { _contentEncoding = AMQUtil::amqpBytesToString(&decoded->content_encoding); _flags |= AmqpContentHeaders::BASIC_PROPERTY_CONTENT_ENCODING_FLAG; } if (flags & AMQP_BASIC_HEADERS_FLAG) { _headers = AMQUtil::amqpApiTableToTableObj(&decoded->headers); _flags |= AmqpContentHeaders::BASIC_PROPERTY_HEADERS_FLAG; } if (flags & AMQP_BASIC_DELIVERY_MODE_FLAG) { _deliveryMode = decoded->delivery_mode; _flags |= AmqpContentHeaders::BASIC_PROPERTY_DEVLIVERY_MODE_FLAG; } if (flags & AMQP_BASIC_PRIORITY_FLAG) { _priority = decoded->priority; _flags |= AmqpContentHeaders::BASIC_PROPERTY_PRIORITY_FLAG; } if (flags & AMQP_BASIC_CORRELATION_ID_FLAG) { _correlationId = AMQUtil::amqpBytesToString(&decoded->correlation_id); _flags |= AmqpContentHeaders::BASIC_PROPERTY_CORRELATION_ID_FLAG; } if (flags & AMQP_BASIC_REPLY_TO_FLAG) { _replyTo = AMQUtil::amqpBytesToString(&decoded->reply_to); _flags |= AmqpContentHeaders::BASIC_PROPERTY_REPLY_TO_FLAG; } if (flags & AMQP_BASIC_EXPIRATION_FLAG) { _expiration = AMQUtil::amqpBytesToString(&decoded->expiration); _flags |= AmqpContentHeaders::BASIC_PROPERTY_EXPIRATION_FLAG; } if (flags & AMQP_BASIC_MESSAGE_ID_FLAG) { _messageId = AMQUtil::amqpBytesToString(&decoded->message_id); _flags |= AmqpContentHeaders::BASIC_PROPERTY_MESSAGE_ID_FLAG; } if (flags & AMQP_BASIC_TIMESTAMP_FLAG) { _timestamp = decoded->timestamp; _flags |= AmqpContentHeaders::BASIC_PROPERTY_TIMESTAMP_FLAG; } if (flags & AMQP_BASIC_TYPE_FLAG) { _type = AMQUtil::amqpBytesToString(&decoded->type); _flags |= AmqpContentHeaders::BASIC_PROPERTY_TYPE_FLAG; } if (flags & AMQP_BASIC_USER_ID_FLAG) { _userId = AMQUtil::amqpBytesToString(&decoded->user_id); _flags |= AmqpContentHeaders::BASIC_PROPERTY_USER_ID_FLAG; } if (flags & AMQP_BASIC_APP_ID_FLAG) { _appId = AMQUtil::amqpBytesToString(&decoded->app_id); _flags |= AmqpContentHeaders::BASIC_PROPERTY_APP_ID_FLAG; } if (flags & AMQP_BASIC_CLUSTER_ID_FLAG) { _clusterId = AMQUtil::amqpBytesToString(&decoded->cluster_id); _flags |= AmqpContentHeaders::BASIC_PROPERTY_CLUSTER_ID_FLAG; } _isInitialized = true; } bool BasicProperties::areHeadersAvailable() { return (_flags & AmqpContentHeaders::BASIC_PROPERTY_HEADERS_FLAG); } void BasicProperties::getAsApiProperties(amqp_basic_properties_t& properties) { CAF_CM_FUNCNAME_VALIDATE("getAsApiProperties"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); memset(&properties, 0, sizeof(properties)); if (_flags & AmqpContentHeaders::BASIC_PROPERTY_CONTENT_TYPE_FLAG) { properties.content_type.len = _contentType.length(); properties.content_type.bytes = const_cast(_contentType.c_str()); properties._flags |= AMQP_BASIC_CONTENT_TYPE_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_CONTENT_ENCODING_FLAG) { properties.content_encoding.len = _contentEncoding.length(); properties.content_encoding.bytes = const_cast(_contentEncoding.c_str()); properties._flags |= AMQP_BASIC_CONTENT_ENCODING_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_HEADERS_FLAG) { AMQUtil::amqpTableObjToApiTable(_headers, properties.headers); properties._flags |= AMQP_BASIC_HEADERS_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_DEVLIVERY_MODE_FLAG) { properties.delivery_mode = _deliveryMode; properties._flags |= AMQP_BASIC_DELIVERY_MODE_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_PRIORITY_FLAG) { properties.priority = _priority; properties._flags |= AMQP_BASIC_PRIORITY_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_CORRELATION_ID_FLAG) { properties.correlation_id.len = _correlationId.length(); properties.correlation_id.bytes = const_cast(_correlationId.c_str()); properties._flags |= AMQP_BASIC_CORRELATION_ID_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_REPLY_TO_FLAG) { properties.reply_to.len = _replyTo.length(); properties.reply_to.bytes = const_cast(_replyTo.c_str()); properties._flags |= AMQP_BASIC_REPLY_TO_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_EXPIRATION_FLAG) { properties.expiration.len = _expiration.length(); properties.expiration.bytes = const_cast(_expiration.c_str()); properties._flags |= AMQP_BASIC_EXPIRATION_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_MESSAGE_ID_FLAG) { properties.message_id.len = _messageId.length(); properties.message_id.bytes = const_cast(_messageId.c_str()); properties._flags |= AMQP_BASIC_MESSAGE_ID_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_TIMESTAMP_FLAG) { properties.timestamp = _timestamp; properties._flags |= AMQP_BASIC_TIMESTAMP_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_TYPE_FLAG) { properties.type.len = _type.length(); properties.type.bytes = const_cast(_type.c_str()); properties._flags |= AMQP_BASIC_TYPE_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_USER_ID_FLAG) { properties.user_id.len = _userId.length(); properties.user_id.bytes = const_cast(_userId.c_str()); properties._flags |= AMQP_BASIC_USER_ID_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_APP_ID_FLAG) { properties.app_id.len = _appId.length(); properties.app_id.bytes = const_cast(_appId.c_str()); properties._flags |= AMQP_BASIC_APP_ID_FLAG; } if (_flags & AmqpContentHeaders::BASIC_PROPERTY_CLUSTER_ID_FLAG) { properties.cluster_id.len = _clusterId.length(); properties.cluster_id.bytes = const_cast(_clusterId.c_str()); properties._flags |= AMQP_BASIC_CLUSTER_ID_FLAG; } } uint16 BasicProperties::getClassId() { return AMQP_BASIC_CLASS; } std::string BasicProperties::getClassName() { return "basic"; } uint64 BasicProperties::getBodySize() { return _bodySize; } uint32 BasicProperties::getFlags() { CAF_CM_FUNCNAME_VALIDATE("getFlags"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _flags; } std::string BasicProperties::getContentType() { CAF_CM_FUNCNAME_VALIDATE("getContentType"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_CONTENT_TYPE_FLAG, "contentType"); return _contentType; } std::string BasicProperties::getContentEncoding() { CAF_CM_FUNCNAME_VALIDATE("getContentType"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_CONTENT_ENCODING_FLAG, "contentEncoding"); return _contentEncoding; } SmartPtrTable BasicProperties::getHeaders() { CAF_CM_FUNCNAME_VALIDATE("getHeaders"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_HEADERS_FLAG, "headers"); return _headers; } uint8 BasicProperties::getDeliveryMode() { CAF_CM_FUNCNAME_VALIDATE("getDeliveryMode"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_DEVLIVERY_MODE_FLAG, "deliveryMode"); return _deliveryMode; } uint8 BasicProperties::getPriority() { CAF_CM_FUNCNAME_VALIDATE("getPriority"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_PRIORITY_FLAG, "priority"); return _priority; } std::string BasicProperties::getCorrelationId() { CAF_CM_FUNCNAME_VALIDATE("getCorrelationId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_CORRELATION_ID_FLAG, "correlationId"); return _correlationId; } std::string BasicProperties::getReplyTo() { CAF_CM_FUNCNAME_VALIDATE("getReplyTo"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_REPLY_TO_FLAG, "replyTo"); return _replyTo; } std::string BasicProperties::getExpiration() { CAF_CM_FUNCNAME_VALIDATE("getExpiration"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_EXPIRATION_FLAG, "expiration"); return _expiration; } std::string BasicProperties::getMessageId() { CAF_CM_FUNCNAME_VALIDATE("getMessageId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_MESSAGE_ID_FLAG, "messageId"); return _messageId; } uint64 BasicProperties::getTimestamp() { CAF_CM_FUNCNAME_VALIDATE("getTimestamp"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_TIMESTAMP_FLAG, "timestamp"); return _timestamp; } std::string BasicProperties::getType() { CAF_CM_FUNCNAME_VALIDATE("getType"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_TYPE_FLAG, "type"); return _type; } std::string BasicProperties::getUserId() { CAF_CM_FUNCNAME_VALIDATE("getUserId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_USER_ID_FLAG, "userId"); return _userId; } std::string BasicProperties::getAppId() { CAF_CM_FUNCNAME_VALIDATE("getAppId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_APP_ID_FLAG, "appId"); return _appId; } std::string BasicProperties::getClusterId() { CAF_CM_FUNCNAME_VALIDATE("getClusterId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ValidatePropertyIsSet( AmqpContentHeaders::BASIC_PROPERTY_CLUSTER_ID_FLAG, "clusterId"); return _clusterId; } void BasicProperties::setContentType(const std::string& contentType) { _contentType = contentType; _flags |= AmqpContentHeaders::BASIC_PROPERTY_CONTENT_TYPE_FLAG; } void BasicProperties::setContentEncoding(const std::string& contentEncoding) { _contentEncoding = contentEncoding; _flags |= AmqpContentHeaders::BASIC_PROPERTY_CONTENT_ENCODING_FLAG; } void BasicProperties::setHeaders(const SmartPtrTable& headers) { if (headers) { _headers = headers; _flags |= AmqpContentHeaders::BASIC_PROPERTY_HEADERS_FLAG; } } void BasicProperties::setDeliveryMode(const uint8 deliveryMode) { _deliveryMode = deliveryMode; _flags |= AmqpContentHeaders::BASIC_PROPERTY_DEVLIVERY_MODE_FLAG; } void BasicProperties::setPriority(const uint8 priority) { _priority = priority; _flags |= AmqpContentHeaders::BASIC_PROPERTY_PRIORITY_FLAG; } void BasicProperties::setCorrelationId(const std::string& correlationId) { _correlationId = correlationId; _flags |= AmqpContentHeaders::BASIC_PROPERTY_CORRELATION_ID_FLAG; } void BasicProperties::setReplyTo(const std::string& replyTo) { _replyTo = replyTo; _flags |= AmqpContentHeaders::BASIC_PROPERTY_REPLY_TO_FLAG; } void BasicProperties::setExpiration(const std::string& expiration) { _expiration = expiration; _flags |= AmqpContentHeaders::BASIC_PROPERTY_EXPIRATION_FLAG; } void BasicProperties::setMessageId(const std::string& messageId) { _messageId = messageId; _flags |= AmqpContentHeaders::BASIC_PROPERTY_MESSAGE_ID_FLAG; } void BasicProperties::setTimestamp(const uint64 timestamp) { _timestamp = timestamp; _flags |= AmqpContentHeaders::BASIC_PROPERTY_TIMESTAMP_FLAG; } void BasicProperties::setType(const std::string& type) { _type = type; _flags |= AmqpContentHeaders::BASIC_PROPERTY_TYPE_FLAG; } void BasicProperties::setUserId(const std::string& userId) { _userId = userId; _flags |= AmqpContentHeaders::BASIC_PROPERTY_USER_ID_FLAG; } void BasicProperties::setAppId(const std::string& appId) { _appId = appId; _flags |= AmqpContentHeaders::BASIC_PROPERTY_APP_ID_FLAG; } void BasicProperties::setClusterId(const std::string& clusterId) { _clusterId = clusterId; _flags |= AmqpContentHeaders::BASIC_PROPERTY_CLUSTER_ID_FLAG; } void BasicProperties::ValidatePropertyIsSet( const uint32 flag, const char* propertyName) { CAF_CM_FUNCNAME("ValidatePropertyIsSet"); if (!(_flags & flag)) { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "The property '%s' is not set", propertyName); } } BasicPublishMethod.cpp000066400000000000000000000037111321503522500405640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/amqpImpl/BasicPublishMethod.h" using namespace Caf::AmqpClient; struct MethodBodyFreeData { SmartPtrCDynamicByteArray body; }; BasicPublishMethod::BasicPublishMethod() : _isInitialized(false), _mandatory(false), _immediate(false), CAF_CM_INIT("BasicPublishMethod") { } BasicPublishMethod::~BasicPublishMethod() { } void BasicPublishMethod::init( const std::string& exchange, const std::string& routingKey, bool mandatory, bool immediate, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _exchange = exchange; _routingKey = routingKey; _mandatory = mandatory; _immediate = immediate; _properties = properties; _body = body; _isInitialized = true; } std::string BasicPublishMethod::getMethodName() const { return "basic.publish"; } AMQPStatus BasicPublishMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); AMQPStatus status = AMQP_ERROR_OK; amqp_basic_properties_t properties; try { if (_properties) { SmartPtrBasicProperties propertiesClass; propertiesClass.QueryInterface(_properties); propertiesClass->getAsApiProperties(properties); } else { memset(&properties, 0, sizeof(properties)); } status = AmqpUtil::AMQP_BasicPublish( channel, _exchange, _routingKey, _mandatory, _immediate, &properties, _body); } CAF_CM_CATCH_ALL; if (properties.headers.entries) { AMQUtil::amqpFreeApiTable(&properties.headers); } CAF_CM_THROWEXCEPTION; return status; } BasicQosMethod.cpp000066400000000000000000000021261321503522500377170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 22, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicQosMethod.h" using namespace Caf::AmqpClient; BasicQosMethod::BasicQosMethod() : _isInitialized(false), _prefetchSize(0), _prefetchCount(0), _global(false), CAF_CM_INIT("BasicQosMethod") { } BasicQosMethod::~BasicQosMethod() { } void BasicQosMethod::init( const uint32 prefetchSize, const uint16 prefetchCount, const bool global) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _prefetchSize = prefetchSize; _prefetchCount = prefetchCount; _global = global; _isInitialized = true; } std::string BasicQosMethod::getMethodName() const { return "basic.qos"; } AMQPStatus BasicQosMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_BasicQos( channel, _prefetchSize, _prefetchCount, _global); } BasicQosOkMethod.cpp000066400000000000000000000010301321503522500402020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 22, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "BasicQosOkMethod.h" using namespace Caf::AmqpClient; BasicQosOkMethod::BasicQosOkMethod() : CAF_CM_INIT("BasicQosOkMethod") { } BasicQosOkMethod::~BasicQosOkMethod() { } void BasicQosOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_BASIC_QOS_OK_METHOD == method->id); } BasicQosOkMethod.h000066400000000000000000000016421321503522500376600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 22, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICQOSOKMETHOD_H_ #define BASICQOSOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.qos-ok */ class BasicQosOkMethod : public TMethodImpl, public AmqpMethods::Basic::QosOk { METHOD_DECL( AmqpMethods::Basic::QosOk, AMQP_BASIC_QOS_OK_METHOD, "basic.qos-ok", false) public: BasicQosOkMethod(); virtual ~BasicQosOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Basic::QosOk private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicQosOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(BasicQosOkMethod); }} #endif /* BASICQOSOKMETHOD_H_ */ BasicRecoverMethod.cpp000066400000000000000000000017021321503522500405610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicRecoverMethod.h" using namespace Caf::AmqpClient; BasicRecoverMethod::BasicRecoverMethod() : _isInitialized(false), _requeue(false), CAF_CM_INIT("BasicRecoverMethod") { } BasicRecoverMethod::~BasicRecoverMethod() { } void BasicRecoverMethod::init( const bool requeue) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _requeue = requeue; _isInitialized = true; } std::string BasicRecoverMethod::getMethodName() const { return "basic.recover"; } AMQPStatus BasicRecoverMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_BasicRecover( channel, _requeue); } BasicRecoverOkMethod.cpp000066400000000000000000000010701321503522500410510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "BasicRecoverOkMethod.h" using namespace Caf::AmqpClient; BasicRecoverOkMethod::BasicRecoverOkMethod() : CAF_CM_INIT("BasicRecoverOkMethod") { } BasicRecoverOkMethod::~BasicRecoverOkMethod() { } void BasicRecoverOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_BASIC_RECOVER_OK_METHOD == method->id); } BasicRecoverOkMethod.h000066400000000000000000000017431321503522500405250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICRECOVEROKMETHOD_H_ #define BASICRECOVEROKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.recover-ok */ class BasicRecoverOkMethod : public TMethodImpl, public AmqpMethods::Basic::RecoverOk { METHOD_DECL( AmqpMethods::Basic::RecoverOk, AMQP_BASIC_RECOVER_OK_METHOD, "basic.recover-ok", false) public: BasicRecoverOkMethod(); virtual ~BasicRecoverOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Basic::BasicRecoverOk private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicRecoverOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(BasicRecoverOkMethod); }} #endif /* BASICRECOVEROKMETHOD_H_ */ BasicRejectMethod.cpp000066400000000000000000000020601321503522500403660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: Aug 1, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/BasicRejectMethod.h" using namespace Caf::AmqpClient; BasicRejectMethod::BasicRejectMethod() : _isInitialized(false), _deliveryTag(0), _requeue(false), CAF_CM_INIT("BasicRejectMethod") { } BasicRejectMethod::~BasicRejectMethod() { } void BasicRejectMethod::init( const uint64 deliveryTag, const bool requeue) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _deliveryTag = deliveryTag; _requeue = requeue; _isInitialized = true; } std::string BasicRejectMethod::getMethodName() const { return "basic.Reject"; } AMQPStatus BasicRejectMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // return AMQP_BasicReject( // channel, // _deliveryTag, // _requeue); return AMQP_ERROR_UNIMPLEMENTED; } BasicReturnMethod.cpp000066400000000000000000000022361321503522500404360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "BasicReturnMethod.h" using namespace Caf::AmqpClient; BasicReturnMethod::BasicReturnMethod() : _replyCode(0), CAF_CM_INIT("BasicReturnMethod") { } BasicReturnMethod::~BasicReturnMethod() { } void BasicReturnMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_BASIC_RETURN_METHOD == method->id); const amqp_basic_return_t * const decoded = reinterpret_cast(method->decoded); _replyCode = decoded->reply_code; _replyText = AMQUtil::amqpBytesToString(&decoded->reply_text); _exchange = AMQUtil::amqpBytesToString(&decoded->exchange); _routingKey = AMQUtil::amqpBytesToString(&decoded->routing_key); } uint16 BasicReturnMethod::getReplyCode() { return _replyCode; } std::string BasicReturnMethod::getReplyText() { return _replyText; } std::string BasicReturnMethod::getExchange() { return _exchange; } std::string BasicReturnMethod::getRoutingKey() { return _routingKey; } BasicReturnMethod.h000066400000000000000000000021731321503522500401030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 21, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BASICRETURNMETHOD_H_ #define BASICRETURNMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP basic.return */ class BasicReturnMethod : public TMethodImpl, public AmqpMethods::Basic::Return { METHOD_DECL( AmqpMethods::Basic::Return, AMQP_BASIC_RETURN_METHOD, "basic.return", true) public: BasicReturnMethod(); virtual ~BasicReturnMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Basic::Return uint16 getReplyCode(); std::string getReplyText(); std::string getExchange(); std::string getRoutingKey(); private: uint16 _replyCode; std::string _replyText; std::string _exchange; std::string _routingKey; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(BasicReturnMethod); }; CAF_DECLARE_SMART_QI_POINTER(BasicReturnMethod); }} #endif /* BASICRETURNMETHOD_H_ */ ChannelCloseMethod.cpp000066400000000000000000000021711321503522500405510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 17, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "ChannelCloseMethod.h" using namespace Caf::AmqpClient; ChannelCloseMethod::ChannelCloseMethod() : _replyCode(0), _classId(0), _methodId(0), CAF_CM_INIT("ChannelCloseMethod") { } ChannelCloseMethod::~ChannelCloseMethod() { } void ChannelCloseMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_CHANNEL_CLOSE_METHOD == method->id); const amqp_channel_close_t * const decoded = reinterpret_cast(method->decoded); _replyCode = decoded->reply_code; _replyText = AMQUtil::amqpBytesToString(&decoded->reply_text); _classId = decoded->class_id; _methodId = decoded->method_id; } uint16 ChannelCloseMethod::getReplyCode() { return _replyCode; } std::string ChannelCloseMethod::getReplyText() { return _replyText; } uint16 ChannelCloseMethod::getClassId() { return _classId; } uint16 ChannelCloseMethod::getMethodId() { return _methodId; } ChannelCloseMethod.h000066400000000000000000000021601321503522500402140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 17, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHANNELCLOSEMETHOD_H_ #define CHANNELCLOSEMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementaiton of AMQP channel.close */ class ChannelCloseMethod : public TMethodImpl, public AmqpMethods::Channel::Close { METHOD_DECL( AmqpMethods::Channel::Close, AMQP_CHANNEL_CLOSE_METHOD, "channel.close", false) public: ChannelCloseMethod(); virtual ~ChannelCloseMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Channel::Close uint16 getReplyCode(); std::string getReplyText(); uint16 getClassId(); uint16 getMethodId(); private: uint16 _replyCode; std::string _replyText; uint16 _classId; uint16 _methodId; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ChannelCloseMethod); }; CAF_DECLARE_SMART_QI_POINTER(ChannelCloseMethod); }} #endif /* CHANNELCLOSEMETHOD_H_ */ ChannelCloseOkFromServerMethod.cpp000066400000000000000000000011761321503522500430620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 22, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "ChannelCloseOkFromServerMethod.h" using namespace Caf::AmqpClient; ChannelCloseOkFromServerMethod::ChannelCloseOkFromServerMethod() : CAF_CM_INIT("ChannelCloseOkFromServerMethod") { } ChannelCloseOkFromServerMethod::~ChannelCloseOkFromServerMethod() { } void ChannelCloseOkFromServerMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_CHANNEL_CLOSE_OK_METHOD == method->id); } ChannelCloseOkFromServerMethod.h000066400000000000000000000021161321503522500425220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 22, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHANNELCLOSEOKFROMSERVERMETHOD_H_ #define CHANNELCLOSEOKFROMSERVERMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP channel.close-ok (received from server) */ class ChannelCloseOkFromServerMethod : public TMethodImpl, public AmqpMethods::Channel::CloseOk { METHOD_DECL( AmqpMethods::Channel::CloseOk, AMQP_CHANNEL_CLOSE_OK_METHOD, "channel.close-ok", false) public: ChannelCloseOkFromServerMethod(); virtual ~ChannelCloseOkFromServerMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Channel::CloseOk private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ChannelCloseOkFromServerMethod); }; CAF_DECLARE_SMART_QI_POINTER(ChannelCloseOkFromServerMethod); }} #endif /* CHANNELCLOSEOKFROMSERVERMETHOD_H_ */ ChannelCloseOkMethod.cpp000066400000000000000000000016171321503522500410470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 17, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/ChannelCloseOkMethod.h" using namespace Caf::AmqpClient; ChannelCloseOkMethod::ChannelCloseOkMethod() : _isInitialized(false), CAF_CM_INIT("ChannelCloseOkMethod") { } ChannelCloseOkMethod::~ChannelCloseOkMethod() { } void ChannelCloseOkMethod::init() { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } std::string ChannelCloseOkMethod::getMethodName() const { return "channel.close-ok"; } AMQPStatus ChannelCloseOkMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpChannel::AMQP_ChannelCloseOk(channel); } ChannelOpenOkMethod.cpp000066400000000000000000000016021321503522500406750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "ChannelOpenOkMethod.h" using namespace Caf::AmqpClient; ChannelOpenOkMethod::ChannelOpenOkMethod() : CAF_CM_INIT("ChannelOpenOkMethod") { } ChannelOpenOkMethod::~ChannelOpenOkMethod() { } void ChannelOpenOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_CHANNEL_OPEN_OK_METHOD == method->id); const amqp_bytes_t * const bytes = reinterpret_cast(method->decoded); _channelId.CreateInstance(); if (bytes->len) { _channelId->memCpy(bytes->bytes, bytes->len); } } SmartPtrCDynamicByteArray ChannelOpenOkMethod::getChannelId() { return _channelId; } ChannelOpenOkMethod.h000066400000000000000000000021221321503522500403400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHANNELOPENOKMETHOD_H_ #define CHANNELOPENOKMETHOD_H_ #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP channel.open-ok */ class ChannelOpenOkMethod : public TMethodImpl, public AmqpMethods::Channel::OpenOk { METHOD_DECL( AmqpMethods::Channel::OpenOk, AMQP_CHANNEL_OPEN_OK_METHOD, "channel.open-ok", false) public: ChannelOpenOkMethod(); virtual ~ChannelOpenOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Channel::OpenOk SmartPtrCDynamicByteArray getChannelId(); private: SmartPtrCDynamicByteArray _channelId; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ChannelOpenOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(ChannelOpenOkMethod); }} #endif /* CHANNELOPENOKMETHOD_H_ */ EnvelopeImpl.cpp000066400000000000000000000024361321503522500374550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/EnvelopeImpl.h" using namespace Caf::AmqpClient; EnvelopeImpl::EnvelopeImpl() : _isInitialized(false), _deliveryTag(0), _redelivered(false), CAF_CM_INIT("EnvelopeImpl") { } EnvelopeImpl::~EnvelopeImpl() { } void EnvelopeImpl::init( const uint64 deliveryTag, const bool redeliver, const std::string& exchange, const std::string& routingKey) { _deliveryTag = deliveryTag; _redelivered = redeliver; _exchange = exchange; _routingKey = routingKey; _isInitialized = true; } uint64 EnvelopeImpl::getDeliveryTag() { CAF_CM_FUNCNAME_VALIDATE("getDeliveryTag"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _deliveryTag; } bool EnvelopeImpl::getRedelivered() { CAF_CM_FUNCNAME_VALIDATE("getRedelivered"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _redelivered; } std::string EnvelopeImpl::getExchange() { CAF_CM_FUNCNAME_VALIDATE("getExchange"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _exchange; } std::string EnvelopeImpl::getRoutingKey() { CAF_CM_FUNCNAME_VALIDATE("getRoutingKey"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _routingKey; } ExchangeDeclareMethod.cpp000066400000000000000000000023701321503522500412160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" #include "amqpClient/amqpImpl/ExchangeDeclareMethod.h" using namespace Caf::AmqpClient; ExchangeDeclareMethod::ExchangeDeclareMethod() : _isInitialized(false), _passive(false), _durable(false), CAF_CM_INIT("ExchangeDeclareMethod") { } ExchangeDeclareMethod::~ExchangeDeclareMethod() { } void ExchangeDeclareMethod::init( const std::string& exchange, const std::string& type, const bool passive, const bool durable, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _exchange = exchange; _type = type; _passive = false; _durable = durable; _isInitialized = true; } std::string ExchangeDeclareMethod::getMethodName() const { return "exchange.declare"; } AMQPStatus ExchangeDeclareMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_ExchangeDeclare( channel, _exchange, _type, false, _durable, false, NULL); } ExchangeDeclareOkMethod.cpp000066400000000000000000000011171321503522500415060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "ExchangeDeclareOkMethod.h" using namespace Caf::AmqpClient; ExchangeDeclareOkMethod::ExchangeDeclareOkMethod() : CAF_CM_INIT("ExchangeDeclareOkMethod") { } ExchangeDeclareOkMethod::~ExchangeDeclareOkMethod() { } void ExchangeDeclareOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_EXCHANGE_DECLARE_OK_METHOD == method->id); } ExchangeDeclareOkMethod.h000066400000000000000000000020071321503522500411520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef EXCHANGEDECLAREOKMETHOD_H_ #define EXCHANGEDECLAREOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP exchange.declare-ok */ class ExchangeDeclareOkMethod : public TMethodImpl, public AmqpMethods::Exchange::DeclareOk { METHOD_DECL( AmqpMethods::Exchange::DeclareOk, AMQP_EXCHANGE_DECLARE_OK_METHOD, "exchange.declare-ok", false) public: ExchangeDeclareOkMethod(); virtual ~ExchangeDeclareOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Queue::DeclareOk private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ExchangeDeclareOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(ExchangeDeclareOkMethod); }} #endif /* EXCHANGEDECLAREOKMETHOD_H_ */ ExchangeDeleteMethod.cpp000066400000000000000000000020511321503522500410550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/ExchangeDeleteMethod.h" using namespace Caf::AmqpClient; ExchangeDeleteMethod::ExchangeDeleteMethod() : _isInitialized(false), _ifUnused(false), CAF_CM_INIT("ExchangeDeleteMethod") { } ExchangeDeleteMethod::~ExchangeDeleteMethod() { } void ExchangeDeleteMethod::init( const std::string& exchange, const bool ifUnused) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _exchange = exchange; _ifUnused = ifUnused; _isInitialized = true; } std::string ExchangeDeleteMethod::getMethodName() const { return "exchange.delete"; } AMQPStatus ExchangeDeleteMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_ExchangeDelete( channel, _exchange, _ifUnused, false); } ExchangeDeleteOkMethod.cpp000066400000000000000000000011071321503522500413500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "ExchangeDeleteOkMethod.h" using namespace Caf::AmqpClient; ExchangeDeleteOkMethod::ExchangeDeleteOkMethod() : CAF_CM_INIT("ExchangeDeleteOkMethod") { } ExchangeDeleteOkMethod::~ExchangeDeleteOkMethod() { } void ExchangeDeleteOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_EXCHANGE_DELETE_OK_METHOD == method->id); } ExchangeDeleteOkMethod.h000066400000000000000000000017711321503522500410240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef EXCHANGEDELETEOKMETHOD_H_ #define EXCHANGEDELETEOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP exchange.delete-ok */ class ExchangeDeleteOkMethod : public TMethodImpl, public AmqpMethods::Exchange::DeleteOk { METHOD_DECL( AmqpMethods::Exchange::DeleteOk, AMQP_EXCHANGE_DELETE_OK_METHOD, "exchange.delete-ok", false) public: ExchangeDeleteOkMethod(); virtual ~ExchangeDeleteOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Queue::DeclareOk private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ExchangeDeleteOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(ExchangeDeleteOkMethod); }} #endif /* EXCHANGEDELETEOKMETHOD_H_ */ FieldImpl.cpp000066400000000000000000000012751321503522500367230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/FieldImpl.h" using namespace Caf::AmqpClient; FieldImpl::FieldImpl() : _type(AMQP_FIELD_TYPE_NOTSET), _value(NULL) { } FieldImpl::~FieldImpl() { if (_value) { g_variant_unref(_value); } } Field::AmqpFieldType FieldImpl::getAmqpType() const { return _type; } GVariant* FieldImpl::getValue() const { return _value; } void FieldImpl::setTypeAndValue(AmqpFieldType type, GVariant* value) { if (_value) { g_variant_unref(_value); } _type = type; _value = g_variant_ref_sink(value); } GetResponseImpl.cpp000066400000000000000000000031341321503522500401320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/Envelope.h" #include "amqpClient/amqpImpl/GetResponseImpl.h" using namespace Caf::AmqpClient; GetResponseImpl::GetResponseImpl() : _isInitialized(false), _messageCount(0), CAF_CM_INIT("GetResponseImpl") { } GetResponseImpl::~GetResponseImpl() { } void GetResponseImpl::init( const SmartPtrEnvelope& envelope, const AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body, const uint32 messageCount) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _envelope = envelope; _properties = properties; _body = body; _messageCount = messageCount; _isInitialized = true; } SmartPtrEnvelope GetResponseImpl::getEnvelope() { CAF_CM_FUNCNAME_VALIDATE("getEnvelope"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _envelope; } AmqpContentHeaders::SmartPtrBasicProperties GetResponseImpl::getProperties() { CAF_CM_FUNCNAME_VALIDATE("getProperties"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _properties; } SmartPtrCDynamicByteArray GetResponseImpl::getBody() { CAF_CM_FUNCNAME_VALIDATE("getBody"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _body; } uint32 GetResponseImpl::getMessageCount() { CAF_CM_FUNCNAME_VALIDATE("getMessageCount"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _messageCount; } QueueBindMethod.cpp000066400000000000000000000021701321503522500400730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" #include "amqpClient/amqpImpl/QueueBindMethod.h" using namespace Caf::AmqpClient; QueueBindMethod::QueueBindMethod() : _isInitialized(false), CAF_CM_INIT("QueueBindMethod") { } QueueBindMethod::~QueueBindMethod() { } void QueueBindMethod::init( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _queue = queue; _exchange = exchange; _routingKey = routingKey; _isInitialized = true; } std::string QueueBindMethod::getMethodName() const { return "queue.bind"; } AMQPStatus QueueBindMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_QueueBind( channel, _queue, _exchange, _routingKey, false, NULL); } QueueBindOkMethod.cpp000066400000000000000000000010371321503522500403660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "QueueBindOkMethod.h" using namespace Caf::AmqpClient; QueueBindOkMethod::QueueBindOkMethod() : CAF_CM_INIT("QueueBindOkMethod") { } QueueBindOkMethod::~QueueBindOkMethod() { } void QueueBindOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_QUEUE_BIND_OK_METHOD == method->id); } QueueBindOkMethod.h000066400000000000000000000016601321503522500400350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEBINDOKMETHOD_H_ #define QUEUEBINDOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.bind-ok */ class QueueBindOkMethod : public TMethodImpl, public AmqpMethods::Queue::BindOk { METHOD_DECL( AmqpMethods::Queue::BindOk, AMQP_QUEUE_BIND_OK_METHOD, "queue.bind-ok", false) public: QueueBindOkMethod(); virtual ~QueueBindOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Queue::BindOk private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueBindOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(QueueBindOkMethod); }} #endif /* QUEUEBINDOKMETHOD_H_ */ QueueDeclareMethod.cpp000066400000000000000000000033511321503522500405600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" #include "amqpClient/amqpImpl/QueueDeclareMethod.h" using namespace Caf::AmqpClient; QueueDeclareMethod::QueueDeclareMethod() : _isInitialized(false), _passive(false), _durable(false), _exclusive(false), _autoDelete(false), _noWait(false), CAF_CM_INIT("QueueDeclareMethod") { } QueueDeclareMethod::~QueueDeclareMethod() { } void QueueDeclareMethod::init() { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); init( "", false, true, true, SmartPtrTable()); } void QueueDeclareMethod::init( const std::string& queue, bool durable, bool exclusive, bool autoDelete, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _queue = queue; _passive = false; _durable = durable; _exclusive = exclusive; _autoDelete = autoDelete; _noWait = false; _isInitialized = true; } void QueueDeclareMethod::initPassive( const std::string& queue) { CAF_CM_FUNCNAME_VALIDATE("initPassive"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _queue = queue; _passive = true; _noWait = false; _isInitialized = true; } std::string QueueDeclareMethod::getMethodName() const { return "queue.declare"; } AMQPStatus QueueDeclareMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_QueueDeclare( channel, _queue, _passive, _durable, _exclusive, _autoDelete, _noWait, NULL); } QueueDeclareOkMethod.cpp000066400000000000000000000021151321503522500410470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "QueueDeclareOkMethod.h" using namespace Caf::AmqpClient; QueueDeclareOkMethod::QueueDeclareOkMethod() : _messageCount(0), _consumerCount(0), CAF_CM_INIT("QueueDeclareOkMethod") { } QueueDeclareOkMethod::~QueueDeclareOkMethod() { } void QueueDeclareOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_QUEUE_DECLARE_OK_METHOD == method->id); const amqp_queue_declare_ok_t * const decoded = reinterpret_cast(method->decoded); _queueName = AMQUtil::amqpBytesToString(&decoded->queue); _messageCount = decoded->message_count; _consumerCount = decoded->consumer_count; } std::string QueueDeclareOkMethod::getQueueName() { return _queueName; } uint32 QueueDeclareOkMethod::getMessageCount() { return _messageCount; } uint32 QueueDeclareOkMethod::getConsumerCount() { return _consumerCount; } QueueDeclareOkMethod.h000066400000000000000000000021711321503522500405160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEDECLAREOKMETHOD_H_ #define QUEUEDECLAREOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.declare-ok */ class QueueDeclareOkMethod : public TMethodImpl, public AmqpMethods::Queue::DeclareOk { METHOD_DECL( AmqpMethods::Queue::DeclareOk, AMQP_QUEUE_DECLARE_OK_METHOD, "queue.declare-ok", false) public: QueueDeclareOkMethod(); virtual ~QueueDeclareOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Queue::DeclareOk std::string getQueueName(); uint32 getMessageCount(); uint32 getConsumerCount(); private: std::string _queueName; uint32 _messageCount; uint32 _consumerCount; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueDeclareOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(QueueDeclareOkMethod); }} #endif /* QUEUEDECLAREOKMETHOD_H_ */ QueueDeleteMethod.cpp000066400000000000000000000021051321503522500404170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/QueueDeleteMethod.h" using namespace Caf::AmqpClient; QueueDeleteMethod::QueueDeleteMethod() : _isInitialized(false), _ifUnused(false), _ifEmpty(false), CAF_CM_INIT("QueueDeleteMethod") { } QueueDeleteMethod::~QueueDeleteMethod() { } void QueueDeleteMethod::init( const std::string& queue, const bool ifUnused, const bool ifEmpty) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _queue = queue; _ifUnused = ifUnused; _ifEmpty = ifEmpty; _isInitialized = true; } std::string QueueDeleteMethod::getMethodName() const { return "queue.delete"; } AMQPStatus QueueDeleteMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_QueueDelete( channel, _queue, _ifUnused, _ifEmpty, false); } QueueDeleteOkMethod.cpp000066400000000000000000000014611321503522500407150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "QueueDeleteOkMethod.h" using namespace Caf::AmqpClient; QueueDeleteOkMethod::QueueDeleteOkMethod() : _messageCount(0), CAF_CM_INIT("QueueDeleteOkMethod") { } QueueDeleteOkMethod::~QueueDeleteOkMethod() { } void QueueDeleteOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_QUEUE_DELETE_OK_METHOD == method->id); const amqp_queue_delete_ok_t * const decoded = reinterpret_cast(method->decoded); _messageCount = decoded->message_count; } uint32 QueueDeleteOkMethod::getMessageCount() { return _messageCount; } QueueDeleteOkMethod.h000066400000000000000000000020011321503522500403510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEDELETEOKMETHOD_H_ #define QUEUEDELETEOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.delete-ok */ class QueueDeleteOkMethod : public TMethodImpl, public AmqpMethods::Queue::DeleteOk { METHOD_DECL( AmqpMethods::Queue::DeleteOk, AMQP_QUEUE_DELETE_OK_METHOD, "queue.delete-ok", false) public: QueueDeleteOkMethod(); virtual ~QueueDeleteOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Queue::DeclareOk uint32 getMessageCount(); private: uint32 _messageCount; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueDeleteOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(QueueDeleteOkMethod); }} #endif /* QUEUEDELETEOKMETHOD_H_ */ QueuePurgeMethod.cpp000066400000000000000000000016431321503522500403050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/amqpImpl/QueuePurgeMethod.h" using namespace Caf::AmqpClient; QueuePurgeMethod::QueuePurgeMethod() : _isInitialized(false), CAF_CM_INIT("QueuePurgeMethod") { } QueuePurgeMethod::~QueuePurgeMethod() { } void QueuePurgeMethod::init( const std::string& queue) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _queue = queue; _isInitialized = true; } std::string QueuePurgeMethod::getMethodName() const { return "queue.purge"; } AMQPStatus QueuePurgeMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_QueuePurge( channel, _queue, false); } QueuePurgeOkMethod.cpp000066400000000000000000000014461321503522500406000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "QueuePurgeOkMethod.h" using namespace Caf::AmqpClient; QueuePurgeOkMethod::QueuePurgeOkMethod() : _messageCount(0), CAF_CM_INIT("QueuePurgeOkMethod") { } QueuePurgeOkMethod::~QueuePurgeOkMethod() { } void QueuePurgeOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_QUEUE_PURGE_OK_METHOD == method->id); const amqp_queue_purge_ok_t * const decoded = reinterpret_cast(method->decoded); _messageCount = decoded->message_count; } uint32 QueuePurgeOkMethod::getMessageCount() { return _messageCount; } QueuePurgeOkMethod.h000066400000000000000000000017611321503522500402450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QueuePurgeOKMETHOD_H_ #define QueuePurgeOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.purge-ok */ class QueuePurgeOkMethod : public TMethodImpl, public AmqpMethods::Queue::PurgeOk { METHOD_DECL( AmqpMethods::Queue::PurgeOk, AMQP_QUEUE_PURGE_OK_METHOD, "queue.purge-ok", false) public: QueuePurgeOkMethod(); virtual ~QueuePurgeOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Queue::PurgeOk uint32 getMessageCount(); private: uint32 _messageCount; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueuePurgeOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(QueuePurgeOkMethod); }} #endif /* QueuePurgeOKMETHOD_H_ */ QueueUnbindMethod.cpp000066400000000000000000000022031321503522500404330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/CAmqpChannel.h" #include "amqpClient/api/amqpClient.h" #include "amqpClient/amqpImpl/QueueUnbindMethod.h" using namespace Caf::AmqpClient; QueueUnbindMethod::QueueUnbindMethod() : _isInitialized(false), CAF_CM_INIT("QueueUnbindMethod") { } QueueUnbindMethod::~QueueUnbindMethod() { } void QueueUnbindMethod::init( const std::string& queue, const std::string& exchange, const std::string& routingKey, const SmartPtrTable& arguments) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _queue = queue; _exchange = exchange; _routingKey = routingKey; _isInitialized = true; } std::string QueueUnbindMethod::getMethodName() const { return "queue.unbind"; } AMQPStatus QueueUnbindMethod::send(const SmartPtrCAmqpChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return AmqpUtil::AMQP_QueueUnbind( channel, _queue, _exchange, _routingKey, NULL); } QueueUnbindOkMethod.cpp000066400000000000000000000010571321503522500407330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "QueueUnbindOkMethod.h" using namespace Caf::AmqpClient; QueueUnbindOkMethod::QueueUnbindOkMethod() : CAF_CM_INIT("QueueUnbindOkMethod") { } QueueUnbindOkMethod::~QueueUnbindOkMethod() { } void QueueUnbindOkMethod::init(const amqp_method_t * const method) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_PTR(method); CAF_CM_ASSERT(AMQP_QUEUE_UNBIND_OK_METHOD == method->id); } QueueUnbindOkMethod.h000066400000000000000000000017151321503522500404010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef QUEUEUNBINDOKMETHOD_H_ #define QUEUEUNBINDOKMETHOD_H_ namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Implementation of AMQP queue.ubind-ok */ class QueueUnbindOkMethod : public TMethodImpl, public AmqpMethods::Queue::UnbindOk { METHOD_DECL( AmqpMethods::Queue::UnbindOk, AMQP_QUEUE_UNBIND_OK_METHOD, "queue.unbind-ok", false) public: QueueUnbindOkMethod(); virtual ~QueueUnbindOkMethod(); public: // IMethod void init(const amqp_method_t * const method); public: // AmqpMethods::Queue::UnbindOk private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(QueueUnbindOkMethod); }; CAF_DECLARE_SMART_QI_POINTER(QueueUnbindOkMethod); }} #endif /* QUEUEUNBINDOKMETHOD_H_ */ TMethodImpl.h000066400000000000000000000024441321503522500367100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 11, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef TMETHODIMPL_H_ #define TMETHODIMPL_H_ #include "amqpClient/amqpImpl/IMethod.h" namespace Caf { namespace AmqpClient { /** * @author mdonahue * @ingroup AmqpApiImpl * @remark LIBRARY IMPLEMENTATION - NOT PART OF THE PUBLIC API * @brief Template implementing the static creator function for AMQP method implementations */ template class TMethodImpl : public IMethod { public: /** * @brief Create the method object * @return the method object */ static SmartPtrIMethod Creator(); }; template SmartPtrIMethod TMethodImpl::Creator() { TCafSmartPtr > method; method.CreateInstance(); return method; } }} #define METHOD_DECL(_amqpImpl_, _num_, _name_, _has_content_) \ CAF_BEGIN_QI() \ CAF_QI_ENTRY(IMethod) \ CAF_QI_ENTRY(_amqpImpl_) \ CAF_END_QI() \ public: \ bool hasContent() { \ return _has_content_; \ } \ uint16 getProtocolClassId() { \ return (uint16)((_num_ & 0xffff0000) >> 16); \ } \ \ uint16 getProtocolMethodId() { \ return (uint16)(_num_ & 0x0000ffff); \ } \ \ virtual std::string getProtocolMethodName() { \ return _name_; \ } #endif /* TMETHODIMPL_H_ */ amqpImplInt.h000066400000000000000000000016731321503522500367600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl /* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPMETHODIMPLINT_H_ #define AMQPMETHODIMPLINT_H_ using namespace Caf::AmqpClient; #include "TMethodImpl.h" #include "AMQPImpl.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "BasicGetOkMethod.h" #include "BasicGetEmptyMethod.h" #include "BasicConsumeOkMethod.h" #include "BasicDeliverMethod.h" #include "BasicCancelOkMethod.h" #include "BasicReturnMethod.h" #include "BasicRecoverOkMethod.h" #include "BasicQosOkMethod.h" #include "ChannelOpenOkMethod.h" #include "ChannelCloseMethod.h" #include "ChannelCloseOkFromServerMethod.h" #include "ExchangeDeclareOkMethod.h" #include "ExchangeDeleteOkMethod.h" #include "QueueDeclareOkMethod.h" #include "QueueDeleteOkMethod.h" #include "QueuePurgeOkMethod.h" #include "QueueBindOkMethod.h" #include "QueueUnbindOkMethod.h" #endif stdafx.h000066400000000000000000000004351321503522500360110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/amqpImpl/* * Created on: May 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPIMPL_STDAFX_H_ #define AMQPIMPL_STDAFX_H_ #include "../stdafx.h" #include "../AMQUtil.h" #include "amqpImplInt.h" #endif stdafx.h000066400000000000000000000026201321503522500342270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpClient/* * Created on: May 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #include "amqpClient/AmqpClientLink.h" #include //extern "C" { #include #include #include //} #if !defined(sun) #include #include #include #endif /* !sun */ #define AMQP_HANDLE_INVALID NULL; // Forward-declare because the connection creates the channel // and the channel hangs onto the connection. namespace Caf { namespace AmqpClient { CAF_DECLARE_CLASS_AND_SMART_POINTER(CAmqpConnection); CAF_DECLARE_CLASS_AND_SMART_POINTER(CAmqpChannel); }} #include "AmqpCommon.h" #include "amqpClient/CAmqpChannel.h" #include "AmqpConnection.h" #include "AmqpAuthPlain.h" #include "AmqpChannel.h" #include "AmqpUtil.h" #include "amqpImpl/amqpImplInt.h" /** * @defgroup AmqpApiImpl AMQP API Implementation * Documentation for the implementation of the AMQP API. *

* These classes, methods and constants cannot be used directly by application code. */ /** * @mainpage * Documentation of the CAF AMQP Client Library. *

* This library allows applications to interact with an AMQP broker as a * client using first-class C++ objects representing AMQP entities and operations. */ #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/000077500000000000000000000000001321503522500323165ustar00rootroot00000000000000AbstractConnectionFactory.cpp000066400000000000000000000153411321503522500400620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: May 24, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/Connection.h" #include "amqpCore/ConnectionListener.h" #include "amqpCore/SimpleConnection.h" #include "amqpCore/AbstractConnectionFactory.h" using namespace Caf::AmqpIntegration; AbstractConnectionFactory::AbstractConnectionFactory() : _isInitialized(false), CAF_CM_INIT("AbstractConnectionFactory") { } AbstractConnectionFactory::~AbstractConnectionFactory() { } void AbstractConnectionFactory::init( const AmqpClient::SmartPtrConnectionFactory& amqpConnectionFactory) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(amqpConnectionFactory); _amqpConnectionFactory = amqpConnectionFactory; _connectionListener.CreateInstance(); _isInitialized = true; } void AbstractConnectionFactory::setProtocol(const std::string& protocol) { CAF_CM_FUNCNAME_VALIDATE("setProtocol"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setProtocol(protocol); } void AbstractConnectionFactory::setHost(const std::string& host) { CAF_CM_FUNCNAME_VALIDATE("setHost"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setHost(host); } void AbstractConnectionFactory::setPort(const uint32 port) { CAF_CM_FUNCNAME_VALIDATE("setPort"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setPort(port); } void AbstractConnectionFactory::setVirtualHost(const std::string& virtualHost) { CAF_CM_FUNCNAME_VALIDATE("setVirtualHost"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setVirtualHost(virtualHost); } void AbstractConnectionFactory::setUsername(const std::string& username) { CAF_CM_FUNCNAME_VALIDATE("setUsername"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setUsername(username); } void AbstractConnectionFactory::setPassword(const std::string& password) { CAF_CM_FUNCNAME_VALIDATE("setPassword"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setPassword(password); } void AbstractConnectionFactory::setCaCertPath(const std::string& caCertPath) { CAF_CM_FUNCNAME_VALIDATE("setCaCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setCaCertPath(caCertPath); } void AbstractConnectionFactory::setClientCertPath(const std::string& clientCertPath) { CAF_CM_FUNCNAME_VALIDATE("setClientCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setClientCertPath(clientCertPath); } void AbstractConnectionFactory::setClientKeyPath(const std::string& clientKeyPath) { CAF_CM_FUNCNAME_VALIDATE("setClientKeyPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setClientKeyPath(clientKeyPath); } void AbstractConnectionFactory::setConnectionTimeout(const uint32 connectionTimeout) { CAF_CM_FUNCNAME_VALIDATE("setConnectionTimeout"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setConnectionTimeout(connectionTimeout); } void AbstractConnectionFactory::setRetries(const uint16 retries) { CAF_CM_FUNCNAME_VALIDATE("setRetries"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setRetries(retries); } void AbstractConnectionFactory::setSecondsToWait(const uint16 seconds) { CAF_CM_FUNCNAME_VALIDATE("setSecondsToWait"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _amqpConnectionFactory->setSecondsToWait(seconds); } std::string AbstractConnectionFactory::getDefaultProtocol() { return Caf::AmqpClient::DEFAULT_PROTOCOL; } std::string AbstractConnectionFactory::getDefaultHostName() { return g_get_host_name(); } SmartPtrConnection AbstractConnectionFactory::createBareConnection() { CAF_CM_FUNCNAME_VALIDATE("createBareConnection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrSimpleConnection connection; connection.CreateInstance(); connection->init(_amqpConnectionFactory->newConnection()); return connection; } SmartPtrConnectionListener AbstractConnectionFactory::getConnectionListener() { return _connectionListener; } void AbstractConnectionFactory::setConnectionListeners( const std::deque& listeners) { CAF_CM_FUNCNAME_VALIDATE("setConnectionListeners"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _connectionListener->setDelegates(listeners); } void AbstractConnectionFactory::addConnectionListener( const SmartPtrConnectionListener& listener) { CAF_CM_FUNCNAME_VALIDATE("addConnectionListener"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _connectionListener->addDelegate(listener); } std::string AbstractConnectionFactory::getProtocol() { CAF_CM_FUNCNAME_VALIDATE("getProtocol"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getProtocol(); } std::string AbstractConnectionFactory::getHost() { CAF_CM_FUNCNAME_VALIDATE("getHost"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getHost(); } uint32 AbstractConnectionFactory::getPort() { CAF_CM_FUNCNAME_VALIDATE("getPort"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getPort(); } std::string AbstractConnectionFactory::getVirtualHost() { CAF_CM_FUNCNAME_VALIDATE("getVirtualHost"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getVirtualHost(); } std::string AbstractConnectionFactory::getUsername() { CAF_CM_FUNCNAME_VALIDATE("getUsername"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getUsername(); } std::string AbstractConnectionFactory::getPassword() { CAF_CM_FUNCNAME_VALIDATE("getPassword"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getPassword(); } std::string AbstractConnectionFactory::getCaCertPath() { CAF_CM_FUNCNAME_VALIDATE("getCaCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getCaCertPath(); } std::string AbstractConnectionFactory::getClientCertPath() { CAF_CM_FUNCNAME_VALIDATE("getClientCertPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getClientCertPath(); } std::string AbstractConnectionFactory::getClientKeyPath() { CAF_CM_FUNCNAME_VALIDATE("getClientKeyPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getClientKeyPath(); } uint16 AbstractConnectionFactory::getRetries() { CAF_CM_FUNCNAME_VALIDATE("getRetries"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getRetries(); } uint16 AbstractConnectionFactory::getSecondsToWait() { CAF_CM_FUNCNAME_VALIDATE("getSecondsToWait"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _amqpConnectionFactory->getSecondsToWait(); } AmqpHeaderMapper.cpp000066400000000000000000000035101321503522500361160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 6, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpCore/AmqpHeaderMapper.h" using namespace Caf::AmqpIntegration; const std::string AmqpHeaderMapper::PREFIX = "amqp_"; const std::string AmqpHeaderMapper::APP_ID = AmqpHeaderMapper::PREFIX + "appId"; const std::string AmqpHeaderMapper::CLUSTER_ID = AmqpHeaderMapper::PREFIX + "clusterId"; const std::string AmqpHeaderMapper::CONTENT_ENCODING = AmqpHeaderMapper::PREFIX + "contentEncoding"; const std::string AmqpHeaderMapper::CONTENT_TYPE = AmqpHeaderMapper::PREFIX + "contentType"; const std::string AmqpHeaderMapper::CORRELATION_ID = AmqpHeaderMapper::PREFIX + "correlationId"; const std::string AmqpHeaderMapper::DELIVERY_MODE = AmqpHeaderMapper::PREFIX + "deliveryMode"; const std::string AmqpHeaderMapper::DELIVERY_TAG = AmqpHeaderMapper::PREFIX + "deliveryTag"; const std::string AmqpHeaderMapper::EXPIRATION = AmqpHeaderMapper::PREFIX + "expiration"; const std::string AmqpHeaderMapper::MESSAGE_COUNT = AmqpHeaderMapper::PREFIX + "messageCount"; const std::string AmqpHeaderMapper::MESSAGE_ID = AmqpHeaderMapper::PREFIX + "messageId"; const std::string AmqpHeaderMapper::RECEIVED_EXCHANGE = AmqpHeaderMapper::PREFIX + "receivedExchange"; const std::string AmqpHeaderMapper::RECEIVED_ROUTING_KEY = AmqpHeaderMapper::PREFIX + "receivedRoutingKey"; const std::string AmqpHeaderMapper::REDELIVERED = AmqpHeaderMapper::PREFIX + "redelivered"; const std::string AmqpHeaderMapper::REPLY_TO = AmqpHeaderMapper::PREFIX + "replyTo"; const std::string AmqpHeaderMapper::TIMESTAMP = AmqpHeaderMapper::PREFIX + "timestamp"; const std::string AmqpHeaderMapper::TYPE = AmqpHeaderMapper::PREFIX + "type"; const std::string AmqpHeaderMapper::USER_ID = AmqpHeaderMapper::PREFIX + "userId"; AmqpIntegrationCoreDefines.h000066400000000000000000000012551321503522500376240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jul 31, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCOREDEFINES_H_ #define AMQPINTEGRATIONCOREDEFINES_H_ namespace Caf { namespace AmqpIntegration { /** * @brief Message acknowledgment mode flags */ typedef enum { /** @brief No acks will be sent. AMQP broker will assume all messages are acked. */ ACKNOWLEDGEMODE_NONE, /** @brief The listener must acknowledge all messages by calling Channel.basicAck() */ ACKNOWLEDGEMODE_MANUAL, /** @brief The container will acknowledge messages automatically. */ ACKNOWLEDGEMODE_AUTO } AcknowledgeMode; }} #endif AmqpIntegrationCoreFunc.h000066400000000000000000000064361321503522500371500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCOREFUNC_H_ #define AMQPINTEGRATIONCOREFUNC_H_ #include "amqpCore/Binding.h" #include "amqpCore/Exchange.h" #include "amqpCore/Queue.h" namespace Caf { /** @brief CAF AMQP Integration */ namespace AmqpIntegration { /** * @brief Create a #Caf::AmqpIntegration::Queue object *

* durable will be set to true; * exclusive and autoDelete will be set to false. * @param name the name of the queue * @return the queue object */ SmartPtrQueue AMQPINTEGRATIONCORE_LINKAGE createQueue( const std::string& name); /** * @brief Create a #Caf::AmqpIntegration::Queue object *

* exclusive and autoDelete will be set to false. * @param name the name of the queue * @param durable true to make the queue durable else false * @return the queue object */ SmartPtrQueue AMQPINTEGRATIONCORE_LINKAGE createQueue( const std::string& name, const bool durable); /** * @brief Create a #Caf::AmqpIntegration::Queue object * @param name the name of the queue or blank for a server-generated name * @param durable true to make the queue durable else false * @param exclusive true to make the queue exclusive else false * @param autoDelete true to make the queue auto-delete else false * @return the queue object */ SmartPtrQueue AMQPINTEGRATIONCORE_LINKAGE createQueue( const std::string& name, const bool durable, const bool exclusive, const bool autoDelete); /** * @brief Create a #Caf::AmqpIntegration::Exchange object representing a direct exchange * @param name the name of the exchange * @param durable true to make the exchange durable else false */ SmartPtrExchange AMQPINTEGRATIONCORE_LINKAGE createDirectExchange( const std::string& name, const bool durable = true); /** * @brief Create a #Caf::AmqpIntegration::Exchange object representing a topic exchange * @param name the name of the exchange * @param durable true to make the exchange durable else false */ SmartPtrExchange AMQPINTEGRATIONCORE_LINKAGE createTopicExchange( const std::string& name, const bool durable = true); /** * @brief Create a #Caf::AmqpIntegration::Exchange object representing a headers exchange * @param name the name of the exchange * @param durable true to make the exchange durable else false */ SmartPtrExchange AMQPINTEGRATIONCORE_LINKAGE createHeadersExchange( const std::string& name, const bool durable = true); /** * @brief Create a #Caf::AmqpIntegration::Exchange object representing a fanout exchange * @param name the name of the exchange * @param durable true to make the exchange durable else false */ SmartPtrExchange AMQPINTEGRATIONCORE_LINKAGE createFanoutExchange( const std::string& name, const bool durable = true); /** * @brief Create a #Caf::AmqpIntegration::Binding object * @param queue the queue name * @param exchange the exchange name * @param routingKey the routing key */ SmartPtrBinding AMQPINTEGRATIONCORE_LINKAGE createBinding( const std::string queue, const std::string exchange, const std::string routingKey); }} #endif AmqpIntegrationExceptions.cpp000066400000000000000000000007621321503522500401140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jul 18, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "AmqpIntegrationExceptions.h" using namespace Caf::AmqpIntegration::AmqpIntExceptions; AMQP_CM_DEFINE_EXCEPTION_CLASS(ReplyRequiredException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ChannelResolutionException); AMQP_CM_DEFINE_EXCEPTION_CLASS(ExpressionResultNull); AMQP_CM_DEFINE_EXCEPTION_CLASS(ExpressionResultWrongType); AmqpIntegrationExceptions.h000066400000000000000000000017711321503522500375620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jul 18, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_AMQPINTEGRATIONEXCEPTIONS_H_ #define AMQPINTEGRATIONCORE_AMQPINTEGRATIONEXCEPTIONS_H_ #include "amqpClient/api/AMQExceptions.h" namespace Caf { namespace AmqpIntegration { /** * @brief Exceptions defined by this library */ namespace AmqpIntExceptions { /** @brief A reply was required but was not produced */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ReplyRequiredException); /** @brief Thrown by a ChannelResolver when it cannot resolve a channel name */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ChannelResolutionException); /** @brief Thrown if an expression failed to return a result */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ExpressionResultNull); /** @brief Thrown if an expression resolved to an incorrect result type */ AMQP_CM_DECLARE_EXCEPTION_CLASS(ExpressionResultWrongType); }}} #endif /* AMQPINTEGRATIONCORE_AMQPINTEGRATIONEXCEPTIONS_H_ */ AmqpMessageListenerSource.cpp000066400000000000000000000056761321503522500400530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Aug 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntMessage.h" #include "Integration/Dependencies/CPollerMetadata.h" #include "Integration/IIntMessage.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpCore/AmqpMessageListenerSource.h" #include "Exception/CCafException.h" using namespace Caf::AmqpIntegration; AmqpMessageListenerSource::AmqpMessageListenerSource() : _isInitialized(false), _messageQueue(NULL), CAF_CM_INIT("AmqpMessageListenerSource") { } AmqpMessageListenerSource::~AmqpMessageListenerSource() { } void AmqpMessageListenerSource::init( const SmartPtrAmqpHeaderMapper& headerMapper, const SmartPtrCPollerMetadata& pollerMetadata) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_PTR(pollerMetadata); // headerMapper is optional _headerMapper = headerMapper; _messageQueue = g_async_queue_new_full(QueueItemDestroyFunc); setPollerMetadata(pollerMetadata); _isInitialized = true; } void AmqpMessageListenerSource::onMessage(const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("onMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); SmartPtrIIntMessage queuedMessage = message; if (_headerMapper) { SmartPtrCIntMessage filteredMessage; filteredMessage.CreateInstance(); filteredMessage->initialize( queuedMessage->getPayload(), _headerMapper->filterHeaders(queuedMessage->getHeaders()), NULL); queuedMessage = filteredMessage; } g_async_queue_push( _messageQueue, queuedMessage.GetAddRefedInterface()); } bool AmqpMessageListenerSource::doSend( const SmartPtrIIntMessage& message, int32 timeout) { CAF_CM_FUNCNAME("doSend"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_EXCEPTIONEX_VA1( UnsupportedOperationException, E_NOTIMPL, "This is not a sending channel: %s", _id.c_str()); return false; } SmartPtrIIntMessage AmqpMessageListenerSource::doReceive(const int32 timeout) { CAF_CM_FUNCNAME("doReceive"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); gpointer data = NULL; if (timeout < 0) { // blocking CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Infinite blocking is not supported for a polled channel: %s", _id.c_str()); //data = g_async_queue_pop(_messageQueue); } else if (timeout == 0) { // immediate data = g_async_queue_try_pop(_messageQueue); } else { // timed guint64 microTimeout = static_cast(timeout) * 1000; data = g_async_queue_timeout_pop(_messageQueue, microTimeout); } SmartPtrIIntMessage message; if (data) { IIntMessage *messagePtr = reinterpret_cast(data); message = messagePtr; messagePtr->Release(); } return message; } void AmqpMessageListenerSource::QueueItemDestroyFunc(gpointer data) { reinterpret_cast(data)->Release(); } AmqpOutboundEndpoint.cpp000066400000000000000000000204011321503522500370570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jul 16, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppConfig.h" #include "Common/IAppContext.h" #include "IVariant.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IChannelResolver.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "amqpCore/AmqpTemplate.h" #include "amqpCore/DefaultAmqpHeaderMapper.h" #include "Exception/CCafException.h" #include "amqpCore/AmqpOutboundEndpoint.h" #include "Integration/Core/MessageHeaders.h" using namespace Caf::AmqpIntegration; AmqpOutboundEndpoint::AmqpOutboundEndpoint() : _isInitialized(false), _id(CAFCOMMON_GUID_NULL), _expectReply(false), _requiresReply(false), CAF_CM_INIT("AmqpOutboundEndpoint") { } AmqpOutboundEndpoint::~AmqpOutboundEndpoint() { } void AmqpOutboundEndpoint::init( SmartPtrAmqpTemplate amqpTemplate, SmartPtrIAppConfig appConfig, SmartPtrIAppContext appContext) { CAF_CM_FUNCNAME("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(amqpTemplate); CAF_CM_VALIDATE_SMARTPTR(appConfig); CAF_CM_VALIDATE_SMARTPTR(appContext); _amqpTemplate = amqpTemplate; if (!_exchangeName.length() && !_exchangeNameExpression.length()) { CAF_CM_EXCEPTIONEX_VA0( IllegalStateException, 0, "exchange-name or exchange-name-expression must be set before calling init()"); } if (!_routingKey.length() && !_routingKeyExpression.length()) { CAF_CM_EXCEPTIONEX_VA0( IllegalStateException, 0, "routing-key or routing-key-expression must be set before calling init()"); } ::UuidCreate(&_id); if (_exchangeNameExpression.length()) { _exchangeNameHandler.CreateInstance(); _exchangeNameHandler->init(appConfig, appContext, _exchangeNameExpression); } if (_routingKeyExpression.length()) { _routingKeyHandler.CreateInstance(); _routingKeyHandler->init(appConfig, appContext, _routingKeyExpression); } if (_requestHeaderMapperExpression.length()) { SmartPtrDefaultAmqpHeaderMapper mapper; mapper.CreateInstance(); mapper->init(_requestHeaderMapperExpression); _requestHeaderMapper = mapper; } _isInitialized = true; } void AmqpOutboundEndpoint::setExchangeName(const std::string& exchangeName) { _exchangeName = exchangeName; } void AmqpOutboundEndpoint::setExchangeNameExpression(const std::string& exchangeNameExpression) { _exchangeNameExpression = exchangeNameExpression; } void AmqpOutboundEndpoint::setRoutingKey(const std::string& routingKey) { _routingKey = routingKey; } void AmqpOutboundEndpoint::setRoutingKeyExpression(const std::string& routingKeyExpression) { _routingKeyExpression = routingKeyExpression; } void AmqpOutboundEndpoint::setMappedRequestHeadersExpression(const std::string& expression) { _requestHeaderMapperExpression = expression; } void AmqpOutboundEndpoint::setExpectReply(const bool expectReply) { _expectReply = expectReply; } void AmqpOutboundEndpoint::setRequiresReply(const bool requiresReply) { _requiresReply = requiresReply; } void AmqpOutboundEndpoint::setComponentName(const std::string& name) { _componentName = name; } void AmqpOutboundEndpoint::setChannelResolver(SmartPtrIChannelResolver channelResolver) { _channelResolver = channelResolver; } UUID AmqpOutboundEndpoint::getHandlerId() const { CAF_CM_FUNCNAME_VALIDATE("getHandlerId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void AmqpOutboundEndpoint::handleMessage(const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(message); SmartPtrIIntMessage result = handleRequestMessage(message); if (result) { IIntMessage::SmartPtrCHeaders requestHeaders = message->getHeaders(); handleResult(result, requestHeaders); } else if (_requiresReply) { std::stringstream msg; msg << "No reply produced by handler '"; if (_componentName.length()) { msg << _componentName; } else { msg << BasePlatform::UuidToString(_id); } msg << "', and its 'requiresReply' property is set to true."; CAF_CM_EXCEPTIONEX_VA0( AmqpIntExceptions::ReplyRequiredException, 0, msg.str().c_str()); } } SmartPtrIIntMessage AmqpOutboundEndpoint::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return NULL; } void AmqpOutboundEndpoint::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); } SmartPtrIIntMessage AmqpOutboundEndpoint::handleRequestMessage( SmartPtrIIntMessage requestMessage) { SmartPtrIIntMessage reply; std::string exchangeName = _exchangeName; std::string routingKey = _routingKey; if (_expectReply) { reply = sendAndReceive(exchangeName, routingKey, requestMessage); } else { send(exchangeName, routingKey, requestMessage); } return reply; } void AmqpOutboundEndpoint::handleResult( SmartPtrIIntMessage resultMessage, IIntMessage::SmartPtrCHeaders requestHeaders) { SmartPtrIIntMessage reply = createReplyMessage(resultMessage, requestHeaders); sendReplyMessage( reply, resultMessage->findRequiredHeader(MessageHeaders::_sREPLY_CHANNEL)->toString()); } void AmqpOutboundEndpoint::send( const std::string& exchangeName, const std::string& routingKey, SmartPtrIIntMessage requestMessage) { CAF_CM_FUNCNAME("send"); std::string resolvedExchange = exchangeName; std::string resolvedRoutingKey = routingKey; SmartPtrIVariant evalResult; if (_exchangeNameHandler) { evalResult = _exchangeNameHandler->evaluate(requestMessage); if (evalResult) { resolvedExchange = evalResult->toString(); } else { CAF_CM_EXCEPTIONEX_VA0( AmqpIntExceptions::ExpressionResultNull, 0, "The exchange name was not resolved"); } } if (_routingKeyHandler) { evalResult = _routingKeyHandler->evaluate(requestMessage); if (evalResult) { resolvedRoutingKey = evalResult->toString(); } else { CAF_CM_EXCEPTIONEX_VA0( AmqpIntExceptions::ExpressionResultNull, 0, "The routing key was not resolved"); } } _amqpTemplate->send( resolvedExchange, resolvedRoutingKey, requestMessage, _requestHeaderMapper); } SmartPtrIIntMessage AmqpOutboundEndpoint::sendAndReceive( const std::string& exchangeName, const std::string& routingKey, SmartPtrIIntMessage requestMessage) { CAF_CM_FUNCNAME("sendAndReceive"); std::string resolvedExchange = exchangeName; std::string resolvedRoutingKey = routingKey; SmartPtrIVariant evalResult; if (_exchangeNameHandler) { evalResult = _exchangeNameHandler->evaluate(requestMessage); if (evalResult) { resolvedExchange = evalResult->toString(); } else { CAF_CM_EXCEPTIONEX_VA0( AmqpIntExceptions::ExpressionResultNull, 0, "The exchange name was not resolved"); } } if (_routingKeyHandler) { evalResult = _routingKeyHandler->evaluate(requestMessage); if (evalResult) { resolvedRoutingKey = evalResult->toString(); } else { CAF_CM_EXCEPTIONEX_VA0( AmqpIntExceptions::ExpressionResultNull, 0, "The routing key was not resolved"); } } return _amqpTemplate->sendAndReceive( resolvedExchange, resolvedRoutingKey, requestMessage, _requestHeaderMapper, _responseHeaderMapper); } SmartPtrIIntMessage AmqpOutboundEndpoint::createReplyMessage( SmartPtrIIntMessage reply, IIntMessage::SmartPtrCHeaders requestHeaders) { SmartPtrCIntMessage replyMessage; replyMessage.CreateInstance(); replyMessage->initialize( reply->getPayload(), reply->getHeaders(), requestHeaders); return replyMessage; } void AmqpOutboundEndpoint::sendReplyMessage( SmartPtrIIntMessage reply, const std::string& replyChannelHeaderValue) { CAF_CM_FUNCNAME("sendReplyMessage"); if (_outputChannel) { _outputChannel->send(reply); } else if (replyChannelHeaderValue.length()) { if (_channelResolver) { SmartPtrIMessageChannel channel = _channelResolver->resolveChannelName(replyChannelHeaderValue); channel->send(reply); } else { CAF_CM_EXCEPTIONEX_VA0( AmqpIntExceptions::ChannelResolutionException, 0, "No ChannelResolver is available"); } } else { CAF_CM_EXCEPTIONEX_VA0( AmqpIntExceptions::ChannelResolutionException, 0, "No output-channel or replyChannel header available"); } } AutoChannelClose.cpp000066400000000000000000000007121321503522500361320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Aug 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/Channel.h" #include "AutoChannelClose.h" using namespace Caf::AmqpIntegration; AutoChannelClose::AutoChannelClose(AmqpClient::SmartPtrChannel channel) : _channel(channel) {} AutoChannelClose::~AutoChannelClose() { if (_channel) { _channel->close(); } } AutoChannelClose.h000066400000000000000000000016711321503522500356040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_AUTOCHANNELCLOSE_H_ #define AMQPINTEGRATIONCORE_AUTOCHANNELCLOSE_H_ #include "amqpClient/api/Channel.h" namespace Caf { namespace AmqpIntegration { /** * @ingroup IntObjImpl * @brief A helper class to automatically close a channel *

* This class is helpful to mimic try/catch/finally logic in the code. * Simply declare an instance on the stack, initialized with the channel. * When the instance goes out of scope it will close the channel. */ class AMQPINTEGRATIONCORE_LINKAGE AutoChannelClose { public: /** * @brief Construct the instance with the given channel * @param channel the channel to auto-close */ AutoChannelClose(AmqpClient::SmartPtrChannel channel); ~AutoChannelClose(); private: AmqpClient::SmartPtrChannel _channel; }; }} #endif BindingImpl.cpp000066400000000000000000000020001321503522500351270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpCore/Binding.h" #include "amqpCore/BindingImpl.h" using namespace Caf::AmqpIntegration; BindingImpl::BindingImpl() { } BindingImpl::~BindingImpl() { } void BindingImpl::init( const std::string queue, const std::string exchange, const std::string routingKey) { _queue = queue; _exchange = exchange; _routingKey = routingKey; } std::string BindingImpl::getQueue() const { return _queue; } std::string BindingImpl::getExchange() const { return _exchange; } std::string BindingImpl::getRoutingKey() const { return _routingKey; } SmartPtrBinding AMQPINTEGRATIONCORE_LINKAGE Caf::AmqpIntegration::createBinding( const std::string queue, const std::string exchange, const std::string routingKey) { SmartPtrBindingImpl binding; binding.CreateInstance(); binding->init(queue, exchange, routingKey); return binding; } BlockingQueueConsumer.cpp000066400000000000000000000277451321503522500372330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jul 30, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/Channel.h" #include "amqpClient/api/Envelope.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/BlockingQueueConsumer.h" #include "Integration/Core/CIntException.h" #include "Exception/CCafException.h" using namespace Caf::AmqpIntegration; #if (1) // BlockingQueueConsumer BlockingQueueConsumer::BlockingQueueConsumer() : _isInitialized(false), _isRunning(false), _isCanceled(false), _deliveryQueue(NULL), _acknowledgeMode(ACKNOWLEDGEMODE_NONE), _prefetchCount(0), CAF_CM_INIT_LOG("BlockingQueueConsumer") { _parentLock.CreateInstance(); _parentLock->initialize(); } BlockingQueueConsumer::~BlockingQueueConsumer() { if (_deliveryQueue) { g_async_queue_unref(_deliveryQueue); } } void BlockingQueueConsumer::init( SmartPtrConnectionFactory connectionFactory, SmartPtrAmqpHeaderMapper headerMapper, AcknowledgeMode acknowledgeMode, uint32 prefetchCount, const std::string& queue) { CAF_CM_FUNCNAME("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(connectionFactory); CAF_CM_VALIDATE_INTERFACE(headerMapper); CAF_CM_VALIDATE_STRING(queue); CAF_CM_ASSERT(acknowledgeMode != ACKNOWLEDGEMODE_MANUAL); _connectionFactory = connectionFactory; _headerMapper = headerMapper; _acknowledgeMode = acknowledgeMode; _prefetchCount = prefetchCount; _queue = queue; _deliveryQueue = g_async_queue_new_full(destroyQueueItem); _isInitialized = true; } AmqpClient::SmartPtrChannel BlockingQueueConsumer::getChannel() { CAF_CM_FUNCNAME("getChannel"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(_isRunning); return _channel; } std::string BlockingQueueConsumer::getConsumerTag() { CAF_CM_FUNCNAME("getConsumerTag"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(_isRunning); return _consumer->getConsumerTag(); } SmartPtrIIntMessage BlockingQueueConsumer::nextMessage() { CAF_CM_FUNCNAME("nextMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(_isRunning); // simulate a blocking pop from the queue gpointer data = g_async_queue_try_pop(_deliveryQueue); while (!data && !_isCanceled) { CThreadUtils::sleep(100); data = g_async_queue_try_pop(_deliveryQueue); } checkShutdown(); SmartPtrIIntMessage message; if (data) { Delivery *deliveryPtr = reinterpret_cast(data); SmartPtrDelivery delivery(deliveryPtr); deliveryPtr->Release(); message = handle(delivery); } return message; } SmartPtrIIntMessage BlockingQueueConsumer::nextMessage(int32 timeout) { CAF_CM_FUNCNAME("nextMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(_isRunning); guint64 microTimeout = static_cast(timeout) * 1000; gpointer data = g_async_queue_timeout_pop(_deliveryQueue, microTimeout); checkShutdown(); SmartPtrIIntMessage message; if (data) { Delivery *deliveryPtr = reinterpret_cast(data); SmartPtrDelivery delivery(deliveryPtr); deliveryPtr->Release(); message = handle(delivery); } return message; } bool BlockingQueueConsumer::commitIfNecessary() { CAF_CM_FUNCNAME("commitIfNecessary"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(_isRunning); bool result = false; std::set deliveryTags; { CAF_CM_LOCK_UNLOCK1(_parentLock); deliveryTags = _deliveryTags; } try { if (deliveryTags.size()) { result = true; if (_acknowledgeMode == ACKNOWLEDGEMODE_AUTO) { std::set::const_reverse_iterator tag = deliveryTags.rbegin(); CAF_CM_ASSERT(tag != deliveryTags.rend()); CAF_CM_LOG_DEBUG_VA2( "basicAck [tag=%Ld][tag count=%d]", *tag, deliveryTags.size()); _channel->basicAck(*tag, true); } } } CAF_CM_CATCH_ALL; { CAF_CM_LOCK_UNLOCK1(_parentLock); _deliveryTags.clear(); } CAF_CM_THROWEXCEPTION; return result; } void BlockingQueueConsumer::rollbackOnExceptionIfNecessary(SmartPtrCCafException& ex) { CAF_CM_FUNCNAME("rollbackOnExceptionIfNecessary"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(_isRunning); if (_acknowledgeMode == ACKNOWLEDGEMODE_AUTO) { std::set deliveryTags; { CAF_CM_LOCK_UNLOCK1(_parentLock); deliveryTags = _deliveryTags; } CAF_CM_LOG_DEBUG_VA2( "Rejecting %d messages on app exception: %s", deliveryTags.size(), ex->getMsg().c_str()); try { for (TConstIterator > tag(deliveryTags); tag; tag++) { #ifdef FIXED _channel->basicReject(*tag, true); #endif } } CAF_CM_CATCH_ALL; { CAF_CM_LOCK_UNLOCK1(_parentLock); _deliveryTags.clear(); } if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_ERROR_VA1( "App exception overridden by rollback exception: " "%s", ex->getFullMsg().c_str()); ex = NULL; CAF_CM_THROWEXCEPTION; } } } void BlockingQueueConsumer::checkShutdown() { CAF_CM_LOCK_UNLOCK1(_parentLock); if (_shutdownException) { _shutdownException->throwAddRefedSelf(); } } void BlockingQueueConsumer::start(const uint32 timeoutMs) { CAF_CM_FUNCNAME("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(!_isRunning); CAF_CM_LOG_DEBUG_VA0("Starting consumer"); _isCanceled = false; _connection = _connectionFactory->createConnection(); _channel = _connection->createChannel(); try { _consumer.CreateInstance(); _consumer->init(this); // Set the prefetchCount if ack mode is not NONE (broker-auto) if (_acknowledgeMode != ACKNOWLEDGEMODE_NONE) { _channel->basicQos(0, _prefetchCount, false); } if (_connectionFactory->getProtocol().compare("tunnel") != 0) { // Verify that the queue exists try { _channel->queueDeclarePassive(_queue); } catch (AmqpClient::AmqpExceptions::AmqpIoErrorException *ex) { std::string exMsg = ex->getMsg(); ex->Release(); CAF_CM_EXCEPTIONEX_VA1( FatalListenerStartupException, 0, "Cannot prepare queue for listener. " "Either the queue does not exist or the broker will not allow us to use it. %s", exMsg.c_str()); } } CAF_CM_LOG_DEBUG_VA1("Starting on queue '%s'", _queue.c_str()); _channel->basicConsume( _queue, _acknowledgeMode == ACKNOWLEDGEMODE_NONE, _consumer); CAF_CM_LOG_DEBUG_VA1("Started on queue '%s'", _queue.c_str()); _isRunning = true; } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_CRIT_CAFEXCEPTION; if (_channel) { _channel->close(); _channel = NULL; } if (_connection) { _connection->close(); _connection = NULL; } } CAF_CM_THROWEXCEPTION; } void BlockingQueueConsumer::stop(const uint32 timeoutMs) { CAF_CM_FUNCNAME("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _isCanceled = true; try { std::string consumerTag = _consumer ? _consumer->getConsumerTag() : std::string(); if (_channel && consumerTag.length()) { if (_channel->isOpen()) { CAF_CM_LOG_DEBUG_VA1( "Canceling consumer '%s'", consumerTag.c_str()); _channel->basicCancel(consumerTag); // If we are not using broker auto-ack then re-queue the messages if (_acknowledgeMode != ACKNOWLEDGEMODE_NONE) { _channel->basicRecover(true); } // Wait for the cancelOk response CAF_CM_LOG_DEBUG_VA0("Waiting for consumer handler to receive cancel.ok"); uint64 start = CDateTimeUtils::getTimeMs(); while (CDateTimeUtils::calcRemainingTime(start, timeoutMs)) { gpointer data = g_async_queue_try_pop(_deliveryQueue); if (data) { Delivery *delivery = reinterpret_cast(data); if (!delivery->envelope) { break; } delivery->Release(); } } } } } CAF_CM_CATCH_ALL; SmartPtrCCafException savedException; if (CAF_CM_ISEXCEPTION) { savedException = CAF_CM_GETEXCEPTION; CAF_CM_CLEAREXCEPTION; } try { if (_channel) { _channel->close(); _channel = NULL; } if (_connection) { _connection->close(); _connection = NULL; } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; _consumer = NULL; _isRunning = false; _isCanceled = false; if (_shutdownException) { _shutdownException = NULL; } { CAF_CM_LOCK_UNLOCK1(_parentLock); _deliveryTags.clear(); } if (savedException) { savedException->throwAddRefedSelf(); } } bool BlockingQueueConsumer::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _isRunning; } SmartPtrIIntMessage BlockingQueueConsumer::handle(SmartPtrDelivery delivery) { CAF_CM_FUNCNAME_VALIDATE("handle"); CAF_CM_VALIDATE_INTERFACE(delivery); IIntMessage::SmartPtrCHeaders headers = _headerMapper->toHeaders( delivery->properties, delivery->envelope); SmartPtrCIntMessage message; message.CreateInstance(); message->initialize(delivery->body, headers, NULL); { CAF_CM_LOCK_UNLOCK1(_parentLock); _deliveryTags.insert(delivery->envelope->getDeliveryTag()); } return message; } void BlockingQueueConsumer::destroyQueueItem(gpointer data) { reinterpret_cast(data)->Release(); } #endif #if (1) // BlockingQueueConsumer::InternalConsumer BlockingQueueConsumer::InternalConsumer::InternalConsumer() : _deliveryQueue(NULL), CAF_CM_INIT_LOG("InternalConsumer") { } BlockingQueueConsumer::InternalConsumer::~InternalConsumer() { if (_deliveryQueue) { g_async_queue_unref(_deliveryQueue); } } void BlockingQueueConsumer::InternalConsumer::init( BlockingQueueConsumer* parent) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_VALIDATE_PTR(parent); _parent = parent; _deliveryQueue = _parent->_deliveryQueue; g_async_queue_ref(_deliveryQueue); } void BlockingQueueConsumer::InternalConsumer::handleConsumeOk( const std::string& consumerTag) { CAF_CM_FUNCNAME_VALIDATE("handleConsumeOk"); _consumerTag = consumerTag; CAF_CM_LOG_DEBUG_VA1("Received ConsumeOk - consumer='%s'", _consumerTag.c_str()); } void BlockingQueueConsumer::InternalConsumer::handleCancelOk( const std::string& consumerTag) { CAF_CM_FUNCNAME_VALIDATE("handleCancelOk"); CAF_CM_LOG_DEBUG_VA1("Received CancelOk - consumer='%s'", consumerTag.c_str()); BlockingQueueConsumer::SmartPtrDelivery delivery; delivery.CreateInstance(); g_async_queue_push( _deliveryQueue, delivery.GetAddRefedInterface()); } void BlockingQueueConsumer::InternalConsumer::handleRecoverOk( const std::string& consumerTag) { } void BlockingQueueConsumer::InternalConsumer::handleDelivery( const std::string& consumerTag, const AmqpClient::SmartPtrEnvelope& envelope, const AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { CAF_CM_FUNCNAME_VALIDATE("handleDelivery"); CAF_CM_VALIDATE_SMARTPTR(_parent); if (_parent->_isCanceled) { CAF_CM_LOG_DEBUG_VA0("Received message but parent is canceled."); } else { BlockingQueueConsumer::SmartPtrDelivery delivery; delivery.CreateInstance(); delivery->envelope = envelope; delivery->properties = properties; delivery->body = body; g_async_queue_push( _deliveryQueue, delivery.GetAddRefedInterface()); if (CAF_CM_IS_LOG_DEBUG_ENABLED) { CAF_CM_LOG_DEBUG_VA4( "Received message [exchange='%s'][rk='%s'][tag=%Lu][len=%d]", envelope->getExchange().c_str(), envelope->getRoutingKey().c_str(), envelope->getDeliveryTag(), body->getByteCount()); } } } void BlockingQueueConsumer::InternalConsumer::handleShutdown( const std::string& consumerTag, SmartPtrCCafException& reason) { CAF_CM_FUNCNAME_VALIDATE("handleShutdown"); CAF_CM_VALIDATE_SMARTPTR(_parent); CAF_CM_LOG_DEBUG_VA1( "Received shutdown signal - consumer='%s'", consumerTag.c_str()); CAF_CM_LOCK_UNLOCK1(_parent->_parentLock); _parent->_shutdownException = reason; _parent->_deliveryTags.clear(); _parent = NULL; } std::string BlockingQueueConsumer::InternalConsumer::getConsumerTag() { return _consumerTag; } #endif CachedChannelHandler.cpp000066400000000000000000000243741321503522500367130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 1, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Exception/CCafException.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/AmqpMethods.h" #include "amqpClient/api/Channel.h" #include "amqpClient/api/Consumer.h" #include "amqpClient/api/GetResponse.h" #include "amqpClient/api/ReturnListener.h" #include "amqpClient/api/amqpClient.h" #include "amqpCore/CachingConnectionFactory.h" using namespace Caf::AmqpIntegration; CachingConnectionFactory::CachedChannelHandler::CachedChannelHandler() : _parent(NULL), CAF_CM_INIT_LOG("CachingConnectionFactory::CachedChannelHandler") { CAF_CM_INIT_THREADSAFE; } CachingConnectionFactory::CachedChannelHandler::~CachedChannelHandler() { } void CachingConnectionFactory::CachedChannelHandler::init( CachingConnectionFactory *parent, AmqpClient::SmartPtrChannel channel) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_VALIDATE_PTR(parent); CAF_CM_VALIDATE_SMARTPTR(channel); _parent = parent; _channel = channel; } void CachingConnectionFactory::CachedChannelHandler::logicalClose() { if (_channel && !_channel->isOpen()) { _channel = NULL; } else { // Allow for multiple close calls - if this channel is already // in the cached channels container then noop else add it // to the cached channel collection TSmartConstIterator proxy(*(_parent->_cachedChannels)); while (proxy) { if (*proxy == this) { break; } proxy++; } if (!proxy) { _parent->_cachedChannels->push_back(this); } } } void CachingConnectionFactory::CachedChannelHandler::physicalClose() { if (_channel && _channel->isOpen()) { _channel->close(); _channel = NULL; } } void CachingConnectionFactory::CachedChannelHandler::checkChannel() { if (!_channel || !_channel->isOpen()) { _channel = _parent->createBareChannel(); } } void CachingConnectionFactory::CachedChannelHandler::postProcessCall(SmartPtrCCafException exception) { CAF_CM_FUNCNAME_VALIDATE("postProcessCall"); if (exception) { if (!_channel || !_channel->isOpen()) { CAF_CM_LOG_DEBUG_VA0("Detected closed channel on exception. Re-initializing"); _channel = _parent->createBareChannel(); } exception->throwAddRefedSelf(); } } AmqpClient::SmartPtrChannel CachingConnectionFactory::CachedChannelHandler::getTargetChannel() { CAF_CM_LOCK_UNLOCK; return _channel; } void CachingConnectionFactory::CachedChannelHandler::close() { CAF_CM_LOCK_UNLOCK; bool shouldPhysicallyClose = true; if (_parent->_isActive) { CAF_CM_LOCK_UNLOCK1(_parent->_cachedChannelsMonitor); if (_parent->_cachedChannels->size() < _parent->getChannelCacheSize()) { logicalClose(); shouldPhysicallyClose = false; } } if (shouldPhysicallyClose) { physicalClose(); } } bool CachingConnectionFactory::CachedChannelHandler::isOpen() { CAF_CM_LOCK_UNLOCK; return (_channel && _channel->isOpen()); } uint16 CachingConnectionFactory::CachedChannelHandler::getChannelNumber() { CAF_CM_LOCK_UNLOCK; checkChannel(); return _channel->getChannelNumber(); } void CachingConnectionFactory::CachedChannelHandler::basicAck( const uint64 deliveryTag, const bool ackMultiple) { CAF_CM_FUNCNAME("basicAck"); CAF_CM_LOCK_UNLOCK; checkChannel(); try { _channel->basicAck(deliveryTag, ackMultiple); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); } AmqpClient::SmartPtrGetResponse CachingConnectionFactory::CachedChannelHandler::basicGet( const std::string& queue, const bool noAck) { CAF_CM_FUNCNAME("basicAck"); CAF_CM_LOCK_UNLOCK; checkChannel(); AmqpClient::SmartPtrGetResponse response; try { response = _channel->basicGet(queue, noAck); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); return response; } void CachingConnectionFactory::CachedChannelHandler::basicPublish( const std::string& exchange, const std::string& routingKey, const AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { CAF_CM_FUNCNAME("basicPublish"); CAF_CM_LOCK_UNLOCK; checkChannel(); try { _channel->basicPublish(exchange, routingKey, properties, body); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); } void CachingConnectionFactory::CachedChannelHandler::basicPublish( const std::string& exchange, const std::string& routingKey, const bool mandatory, const bool immediate, const AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { CAF_CM_FUNCNAME("basicPublish"); CAF_CM_LOCK_UNLOCK; checkChannel(); try { _channel->basicPublish( exchange, routingKey, mandatory, immediate, properties, body); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); } AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk CachingConnectionFactory::CachedChannelHandler::basicConsume( const std::string& queue, const AmqpClient::SmartPtrConsumer& consumer) { CAF_CM_FUNCNAME("basicConsume"); CAF_CM_LOCK_UNLOCK; checkChannel(); AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk consumeOk; try { consumeOk = _channel->basicConsume(queue, consumer); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); return consumeOk; } AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk CachingConnectionFactory::CachedChannelHandler::basicConsume( const std::string& queue, const bool noAck, const AmqpClient::SmartPtrConsumer& consumer) { CAF_CM_FUNCNAME("basicConsume"); CAF_CM_LOCK_UNLOCK; checkChannel(); AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk consumeOk; try { consumeOk = _channel->basicConsume(queue, noAck, consumer); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); return consumeOk; } AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk CachingConnectionFactory::CachedChannelHandler::basicConsume( const std::string& queue, const std::string& consumerTag, const bool noAck, const bool noLocal, const bool exclusive, const AmqpClient::SmartPtrConsumer& consumer, const AmqpClient::SmartPtrTable& arguments) { CAF_CM_FUNCNAME("basicConsume"); CAF_CM_LOCK_UNLOCK; checkChannel(); AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk consumeOk; try { consumeOk = _channel->basicConsume( queue, consumerTag, noAck, noLocal, exclusive, consumer, arguments); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); return consumeOk; } AmqpClient::AmqpMethods::Basic::SmartPtrCancelOk CachingConnectionFactory::CachedChannelHandler::basicCancel( const std::string& consumerTag) { CAF_CM_FUNCNAME("basicCancel"); CAF_CM_LOCK_UNLOCK; checkChannel(); AmqpClient::AmqpMethods::Basic::SmartPtrCancelOk cancelOk; try { cancelOk = _channel->basicCancel(consumerTag); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); return cancelOk; } AmqpClient::AmqpMethods::Basic::SmartPtrRecoverOk CachingConnectionFactory::CachedChannelHandler::basicRecover( const bool requeue) { CAF_CM_FUNCNAME("basicRecover"); CAF_CM_LOCK_UNLOCK; checkChannel(); AmqpClient::AmqpMethods::Basic::SmartPtrRecoverOk recoverOk; try { recoverOk = _channel->basicRecover(requeue); } CAF_CM_CATCH_ALL; postProcessCall(CAF_CM_GETEXCEPTION); return recoverOk; } AmqpClient::AmqpMethods::Basic::SmartPtrQosOk CachingConnectionFactory::CachedChannelHandler::basicQos( const uint32 prefetchSize, const uint32 prefetchCount, const bool global) { return _channel->basicQos(prefetchSize, prefetchCount, global); } void CachingConnectionFactory::CachedChannelHandler::basicReject( const uint64 deliveryTag, const bool requeue) { return _channel->basicReject(deliveryTag, requeue); } AmqpClient::AmqpMethods::Exchange::SmartPtrDeclareOk CachingConnectionFactory::CachedChannelHandler::exchangeDeclare( const std::string& exchange, const std::string& type, const bool durable, const AmqpClient::SmartPtrTable& arguments) { return _channel->exchangeDeclare(exchange, type, durable, arguments); } AmqpClient::AmqpMethods::Exchange::SmartPtrDeleteOk CachingConnectionFactory::CachedChannelHandler::exchangeDelete( const std::string& exchange, const bool ifUnused) { return _channel->exchangeDelete(exchange, ifUnused); } AmqpClient::AmqpMethods::Queue::SmartPtrDeclareOk CachingConnectionFactory::CachedChannelHandler::queueDeclare() { return _channel->queueDeclare(); } AmqpClient::AmqpMethods::Queue::SmartPtrDeclareOk CachingConnectionFactory::CachedChannelHandler::queueDeclare( const std::string& queue, const bool durable, const bool exclusive, const bool autoDelete, const AmqpClient::SmartPtrTable& arguments) { return _channel->queueDeclare( queue, durable, exclusive, autoDelete, arguments); } AmqpClient::AmqpMethods::Queue::SmartPtrDeclareOk CachingConnectionFactory::CachedChannelHandler::queueDeclarePassive( const std::string& queue) { return _channel->queueDeclarePassive(queue); } AmqpClient::AmqpMethods::Queue::SmartPtrDeleteOk CachingConnectionFactory::CachedChannelHandler::queueDelete( const std::string& queue, const bool ifUnused, const bool ifEmpty) { return _channel->queueDelete(queue, ifUnused, ifEmpty); } AmqpClient::AmqpMethods::Queue::SmartPtrPurgeOk CachingConnectionFactory::CachedChannelHandler::queuePurge( const std::string& queue) { return _channel->queuePurge(queue); } AmqpClient::AmqpMethods::Queue::SmartPtrBindOk CachingConnectionFactory::CachedChannelHandler::queueBind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const AmqpClient::SmartPtrTable& arguments) { return _channel->queueBind( queue, exchange, routingKey, arguments); } AmqpClient::AmqpMethods::Queue::SmartPtrUnbindOk CachingConnectionFactory::CachedChannelHandler::queueUnbind( const std::string& queue, const std::string& exchange, const std::string& routingKey, const AmqpClient::SmartPtrTable& arguments) { return _channel->queueUnbind( queue, exchange, routingKey, arguments); } void CachingConnectionFactory::CachedChannelHandler::addReturnListener( const AmqpClient::SmartPtrReturnListener& listener) { return _channel->addReturnListener(listener); } bool CachingConnectionFactory::CachedChannelHandler::removeReturnListener( const AmqpClient::SmartPtrReturnListener& listener) { return _channel->removeReturnListener(listener); } CachingConnectionFactory.cpp000066400000000000000000000134631321503522500376560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: May 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/Channel.h" #include "amqpClient/api/Connection.h" #include "amqpCore/ChannelProxy.h" #include "amqpCore/ConnectionListener.h" #include "amqpCore/CachingConnectionFactory.h" using namespace Caf::AmqpIntegration; CachingConnectionFactory::CachingConnectionFactory() : _isInitialized(false), _isActive(true), _channelCacheSize(2), CAF_CM_INIT_LOG("CachingConnectionFactory") { _connectionMonitor.CreateInstance(); _connectionMonitor->initialize(); _cachedChannelsMonitor.CreateInstance(); _cachedChannelsMonitor->initialize(); } CachingConnectionFactory::~CachingConnectionFactory() { CAF_CM_FUNCNAME("~CachingConnectionFactory"); if (_connection) { try { try { _connection->close(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (_cachedChannels) { CAF_CM_LOCK_UNLOCK1(_cachedChannelsMonitor); _cachedChannels->clear(); _cachedChannels = NULL; } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } } void CachingConnectionFactory::init() { init(std::string(),std::string()); } void CachingConnectionFactory::init( const std::string& protocol, const std::string& host, const uint32 port) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); AbstractConnectionFactory::init(AmqpClient::createConnectionFactory()); setConnectionTimeout(10000); std::string locProtocol = protocol; if (locProtocol.empty()) { locProtocol = getDefaultProtocol(); } std::string hostname = host; if (hostname.empty()) { hostname = getDefaultHostName(); } setHost(hostname); setPort(port); _cachedChannels.CreateInstance(); _isInitialized = true; } void CachingConnectionFactory::init( const std::string& protocol, const std::string& host) { init(protocol, host, AmqpClient::DEFAULT_AMQP_PORT); } void CachingConnectionFactory::init( const uint32 port) { init(std::string(), std::string(), port); } void CachingConnectionFactory::init( const AmqpClient::SmartPtrConnectionFactory& amqpConnectionFactory) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); AbstractConnectionFactory::init(amqpConnectionFactory); _cachedChannels.CreateInstance(); _isInitialized = true; } void CachingConnectionFactory::destroy() { CAF_CM_FUNCNAME_VALIDATE("destroy"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // This method ends up calling reset() during _connection->destroy() which // sets _connection to NULL. To prevent the wheels from disappearing from // underneath the _connection, store a temporary reference to it. SmartPtrChannelCachingConnectionProxy connectionRef = _connection; CAF_CM_LOCK_UNLOCK1(_connectionMonitor); if (_connection) { _connection->destroy(); _connection = NULL; } reset(); } uint32 CachingConnectionFactory::getChannelCacheSize() { return _channelCacheSize; } AmqpClient::SmartPtrChannel CachingConnectionFactory::getChannel() { CAF_CM_FUNCNAME_VALIDATE("getChannel"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); AmqpClient::SmartPtrChannel channel; { CAF_CM_LOCK_UNLOCK1(_cachedChannelsMonitor); if (_cachedChannels->size()) { channel = _cachedChannels->front(); _cachedChannels->pop_front(); } } if (channel) { CAF_CM_LOG_DEBUG_VA1("found cached rabbit channel #%d", channel->getChannelNumber()); } else { channel = newCachedChannelProxy(); } return channel; } void CachingConnectionFactory::setConnectionListeners( const std::deque& listeners) { CAF_CM_FUNCNAME_VALIDATE("setConnectionListeners"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); AbstractConnectionFactory::setConnectionListeners(listeners); if (_connection) { getConnectionListener()->onCreate(_connection); } } void CachingConnectionFactory::setChannelCacheSize(uint32 cacheSize) { CAF_CM_FUNCNAME("setChannelCacheSize"); CAF_CM_ASSERT(cacheSize >= 1); _channelCacheSize = cacheSize; } void CachingConnectionFactory::addConnectionListener( const SmartPtrConnectionListener& listener) { CAF_CM_FUNCNAME_VALIDATE("addConnectionListener"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(listener); AbstractConnectionFactory::addConnectionListener(listener); if (_connection) { listener->onCreate(_connection); } } SmartPtrConnection CachingConnectionFactory::createConnection() { CAF_CM_FUNCNAME_VALIDATE("createConnection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOCK_UNLOCK1(_connectionMonitor); if (!_connection) { _connection.CreateInstance(); _connection->init(createBareConnection(), this); getConnectionListener()->onCreate(_connection); } return _connection; } void CachingConnectionFactory::reset() { CAF_CM_FUNCNAME("reset"); _isActive = false; CAF_CM_LOCK_UNLOCK1(_cachedChannelsMonitor); for (TSmartIterator channel(*_cachedChannels); channel; channel++) { try { AmqpClient::SmartPtrChannel target = channel->getTargetChannel(); if (target) { target->close(); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } try { _cachedChannels->clear(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; _isActive = true; _connection = NULL; } SmartPtrChannelProxy CachingConnectionFactory::newCachedChannelProxy(){ AmqpClient::SmartPtrChannel channel = createBareChannel(); SmartPtrCachedChannelHandler proxy; proxy.CreateInstance(); proxy->init(this, channel); return proxy; } AmqpClient::SmartPtrChannel CachingConnectionFactory::createBareChannel() { if (!_connection || !_connection->isOpen()) { _connection = NULL; createConnection(); } return _connection->createBareChannel(); } ChannelCachingConnectionProxy.cpp000066400000000000000000000033571321503522500406620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 1, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/Channel.h" #include "amqpClient/api/Connection.h" #include "amqpCore/CachingConnectionFactory.h" using namespace Caf::AmqpIntegration; CachingConnectionFactory::ChannelCachingConnectionProxy::ChannelCachingConnectionProxy() : _parent(NULL), CAF_CM_INIT_LOG("CachingConnectionFactory::ChannelCachingConnectionProxy") { } CachingConnectionFactory::ChannelCachingConnectionProxy::~ChannelCachingConnectionProxy() { _target = NULL; _parent = NULL; } void CachingConnectionFactory::ChannelCachingConnectionProxy::init( SmartPtrConnection connection, CachingConnectionFactory *parent) { _target = connection; _parent = parent; } void CachingConnectionFactory::ChannelCachingConnectionProxy::destroy() { CAF_CM_FUNCNAME("destroy"); if (_target) { _parent->getConnectionListener()->onClose(_target); try { _target->close(); } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; try { _parent->reset(); } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; } _target = NULL; } SmartPtrConnection CachingConnectionFactory::ChannelCachingConnectionProxy::getTargetConnection() { return _target; } AmqpClient::SmartPtrChannel CachingConnectionFactory::ChannelCachingConnectionProxy::createChannel() { return _parent->getChannel(); } void CachingConnectionFactory::ChannelCachingConnectionProxy::close() { } bool CachingConnectionFactory::ChannelCachingConnectionProxy::isOpen() { return _target && _target->isOpen(); } AmqpClient::SmartPtrChannel CachingConnectionFactory::ChannelCachingConnectionProxy::createBareChannel() { return _target->createChannel(); } CompositeConnectionListener.cpp000066400000000000000000000030071321503522500404330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 2, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/Connection.h" #include "amqpCore/CompositeConnectionListener.h" using namespace Caf::AmqpIntegration; CompositeConnectionListener::CompositeConnectionListener() : CAF_CM_INIT_LOG("CompositeConnectionListener") { } CompositeConnectionListener::~CompositeConnectionListener() { } void CompositeConnectionListener::setDelegates( const ListenerDeque& delegates) { _delegates = delegates; } void CompositeConnectionListener::addDelegate( const SmartPtrConnectionListener& delegate) { CAF_CM_FUNCNAME_VALIDATE("addDelegate"); CAF_CM_VALIDATE_SMARTPTR(delegate); _delegates.push_back(delegate); } void CompositeConnectionListener::onCreate( const SmartPtrConnection& connection) { CAF_CM_FUNCNAME("onCreate"); CAF_CM_VALIDATE_SMARTPTR(connection); for (TSmartIterator delegate(_delegates); delegate; delegate++) { try { delegate->onCreate(connection); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } } void CompositeConnectionListener::onClose( const SmartPtrConnection& connection) { CAF_CM_FUNCNAME("onClose"); CAF_CM_VALIDATE_SMARTPTR(connection); for (TSmartIterator delegate(_delegates); delegate; delegate++) { try { delegate->onClose(connection); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } } DefaultAmqpHeaderMapper.cpp000066400000000000000000000250221321503522500374250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 6, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Common/CVariant.h" #include "Integration/IIntMessage.h" #include "amqpClient/api/Envelope.h" #include "amqpClient/api/amqpClient.h" #include "amqpCore/DefaultAmqpHeaderMapper.h" #include "Integration/Core/CIntMessageHeaders.h" #include "Exception/CCafException.h" #include "HeaderUtils.h" using namespace Caf::AmqpIntegration; DefaultAmqpHeaderMapper::DefaultAmqpHeaderMapper() : _isInitialized(false), CAF_CM_INIT("DefaultAmqpHeaderMapper") { } DefaultAmqpHeaderMapper::~DefaultAmqpHeaderMapper() { } void DefaultAmqpHeaderMapper::init(const std::string& userHeaderRegex) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); if (!userHeaderRegex.empty()) { _userHeaderRegex.CreateInstance(); _userHeaderRegex->initialize(userHeaderRegex); } _isInitialized = true; } AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties DefaultAmqpHeaderMapper::fromHeaders( IIntMessage::SmartPtrCHeaders headers) { CAF_CM_FUNCNAME("fromHeaders"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties properties; properties = AmqpClient::AmqpContentHeaders::createBasicProperties(); SmartPtrCVariant variant; variant = HeaderUtils::getHeaderString(headers, APP_ID); if (variant) { properties->setAppId(g_variant_get_string(variant->get(), NULL)); } variant = HeaderUtils::getHeaderString(headers, CONTENT_ENCODING); if (variant) { properties->setContentEncoding(g_variant_get_string(variant->get(), NULL)); } else { properties->setContentEncoding("UTF8"); } variant = HeaderUtils::getHeaderString(headers, CONTENT_TYPE); if (variant) { properties->setContentType(g_variant_get_string(variant->get(), NULL)); } else { properties->setContentType("text/plain"); } variant = HeaderUtils::getHeaderString(headers, CORRELATION_ID); if (variant) { properties->setCorrelationId(g_variant_get_string(variant->get(), NULL)); } variant = HeaderUtils::getHeaderUint8(headers, DELIVERY_MODE); if (variant) { properties->setDeliveryMode(g_variant_get_byte(variant->get())); } variant = HeaderUtils::getHeaderString(headers, EXPIRATION); if (variant) { properties->setExpiration(g_variant_get_string(variant->get(), NULL)); } variant = HeaderUtils::getHeaderString(headers, MESSAGE_ID); if (variant) { properties->setMessageId(g_variant_get_string(variant->get(), NULL)); } variant = HeaderUtils::getHeaderString(headers, REPLY_TO); if (variant) { properties->setReplyTo(g_variant_get_string(variant->get(), NULL)); } variant = HeaderUtils::getHeaderUint64(headers, TIMESTAMP); if (variant) { properties->setTimestamp(g_variant_get_uint64(variant->get())); } variant = HeaderUtils::getHeaderString(headers, TYPE); if (variant) { properties->setType(g_variant_get_string(variant->get(), NULL)); } variant = HeaderUtils::getHeaderString(headers, USER_ID); if (variant) { properties->setUserId(g_variant_get_string(variant->get(), NULL)); } // map user-defined headers if (_userHeaderRegex) { AmqpClient::SmartPtrTable propertyHeaders; propertyHeaders.CreateInstance(); for (IIntMessage::CHeaders::const_iterator headerIter = headers->begin(); headerIter != headers->end(); headerIter++) { const std::string headerName = headerIter->first; if (_userHeaderRegex->isMatched(headerName)) { const SmartPtrIVariant headerValue = headerIter->second.first; CAF_CM_VALIDATE_SMARTPTR(headerValue); GVariant *headerVal = headerValue->get(); if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_STRING)) { AmqpClient::tableAddUtf8( headerName, headerValue->toString(), propertyHeaders); } else if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_BOOLEAN)) { AmqpClient::tableAddBoolean( headerName, g_variant_get_boolean(headerVal), propertyHeaders); } else if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_BYTE)) { AmqpClient::tableAddUint8( headerName, g_variant_get_byte(headerVal), propertyHeaders); } else if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_INT16)) { AmqpClient::tableAddInt16( headerName, g_variant_get_int16(headerVal), propertyHeaders); } else if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_UINT16)) { AmqpClient::tableAddUint16( headerName, g_variant_get_uint16(headerVal), propertyHeaders); } else if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_INT32)) { AmqpClient::tableAddInt32( headerName, g_variant_get_int32(headerVal), propertyHeaders); } else if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_UINT32)) { AmqpClient::tableAddUint32( headerName, g_variant_get_uint32(headerVal), propertyHeaders); } else if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_INT64)) { AmqpClient::tableAddInt64( headerName, g_variant_get_int64(headerVal), propertyHeaders); } else if (g_variant_is_of_type(headerVal, G_VARIANT_TYPE_UINT64)) { AmqpClient::tableAddUint64( headerName, g_variant_get_uint64(headerVal), propertyHeaders); } else { CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, 0, "Unsupported GVariant conversion. [name='%s'][type='%s']", headerName.c_str(), g_variant_get_type_string(headerVal)); } } } if (propertyHeaders->size()) { properties->setHeaders(propertyHeaders); } } return properties; } IIntMessage::SmartPtrCHeaders DefaultAmqpHeaderMapper::toHeaders( AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties properties, AmqpClient::SmartPtrEnvelope envelope) { CAF_CM_FUNCNAME_VALIDATE("toHeaders"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CIntMessageHeaders messageHeaders; messageHeaders.insertUint64(DELIVERY_TAG, envelope->getDeliveryTag()); messageHeaders.insertString(RECEIVED_ROUTING_KEY, envelope->getRoutingKey()); messageHeaders.insertBool(REDELIVERED, envelope->getRedelivered()); // The exchange name can be empty, meaning the default exchange messageHeaders.insertStringOpt(RECEIVED_EXCHANGE, envelope->getExchange()); const uint32 flags = properties->getFlags(); if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_APP_ID_FLAG) { messageHeaders.insertString(APP_ID, properties->getAppId()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_CONTENT_ENCODING_FLAG) { messageHeaders.insertString(CONTENT_ENCODING, properties->getContentEncoding()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_CONTENT_TYPE_FLAG) { messageHeaders.insertString(CONTENT_TYPE, properties->getContentType()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_CORRELATION_ID_FLAG) { messageHeaders.insertString(CORRELATION_ID, properties->getCorrelationId()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_DEVLIVERY_MODE_FLAG) { messageHeaders.insertUint8(DELIVERY_MODE, properties->getDeliveryMode()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_EXPIRATION_FLAG) { messageHeaders.insertString(EXPIRATION, properties->getExpiration()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_MESSAGE_ID_FLAG) { messageHeaders.insertString(MESSAGE_ID, properties->getMessageId()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_REPLY_TO_FLAG) { messageHeaders.insertString(REPLY_TO, properties->getReplyTo()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_TIMESTAMP_FLAG) { messageHeaders.insertUint64(TIMESTAMP, properties->getTimestamp()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_TYPE_FLAG) { messageHeaders.insertString(TYPE, properties->getType()); } if (flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_USER_ID_FLAG) { messageHeaders.insertString(USER_ID, properties->getUserId()); } if ((flags & AmqpClient::AmqpContentHeaders::BASIC_PROPERTY_HEADERS_FLAG) && _userHeaderRegex) { AmqpClient::SmartPtrTable table = properties->getHeaders(); for (TSmartConstMapIterator field(*table); field; field++) { const std::string fieldName = field.getKey(); if (_userHeaderRegex->isMatched(fieldName)) { GVariant *fieldVar = field->getValue(); switch (field->getAmqpType()) { case AmqpClient::Field::AMQP_FIELD_TYPE_UTF8: messageHeaders.insertString(fieldName, g_variant_get_string(fieldVar, NULL)); break; case AmqpClient::Field::AMQP_FIELD_TYPE_BOOLEAN: messageHeaders.insertBool(fieldName, g_variant_get_boolean(fieldVar)); break; case AmqpClient::Field::AMQP_FIELD_TYPE_I8: case AmqpClient::Field::AMQP_FIELD_TYPE_U8: messageHeaders.insertUint8(fieldName, g_variant_get_byte(fieldVar)); break; case AmqpClient::Field::AMQP_FIELD_TYPE_I16: messageHeaders.insertInt16(fieldName, g_variant_get_int16(fieldVar)); break; case AmqpClient::Field::AMQP_FIELD_TYPE_U16: messageHeaders.insertUint16(fieldName, g_variant_get_uint16(fieldVar)); break; case AmqpClient::Field::AMQP_FIELD_TYPE_I32: messageHeaders.insertInt32(fieldName, g_variant_get_int32(fieldVar)); break; case AmqpClient::Field::AMQP_FIELD_TYPE_U32: messageHeaders.insertUint32(fieldName, g_variant_get_uint32(fieldVar)); break; case AmqpClient::Field::AMQP_FIELD_TYPE_I64: messageHeaders.insertInt64(fieldName, g_variant_get_int64(fieldVar)); break; case AmqpClient::Field::AMQP_FIELD_TYPE_U64: case AmqpClient::Field::AMQP_FIELD_TYPE_TIMESTAMP: messageHeaders.insertUint64(fieldName, g_variant_get_uint64(fieldVar)); break; default: break; } } } } return messageHeaders.getHeaders(); } IIntMessage::SmartPtrCHeaders DefaultAmqpHeaderMapper::filterHeaders( IIntMessage::SmartPtrCHeaders headers) { CAF_CM_FUNCNAME_VALIDATE("filterHeaders"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); IIntMessage::SmartPtrCHeaders filteredHeaders; filteredHeaders.CreateInstance(); if (_userHeaderRegex) { for (IIntMessage::CHeaders::const_iterator headerIter = headers->begin(); headerIter != headers->end(); headerIter++) { const std::string headerName = headerIter->first; if (_userHeaderRegex->isMatched(headerName)) { filteredHeaders->insert( IIntMessage::CHeaders::value_type( headerName, std::make_pair(headerIter->second.first, headerIter->second.second))); } } } return filteredHeaders; } ExchangeImpl.cpp000066400000000000000000000053541321503522500353160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpCore/Exchange.h" #include "amqpCore/ExchangeImpl.h" using namespace Caf::AmqpIntegration; const char *ExchangeTypes::DIRECT = "direct"; const char *ExchangeTypes::TOPIC = "topic"; const char *ExchangeTypes::HEADERS = "headers"; const char *ExchangeTypes::FANOUT = "fanout"; AbstractExchange::AbstractExchange() : _isDurable(true) { } AbstractExchange::~AbstractExchange() { } void AbstractExchange::init( const std::string& name, const bool isDurable) { _name = name; _isDurable = isDurable; } std::string AbstractExchange::getName() const { return _name; } bool AbstractExchange::isDurable() const { return _isDurable; } DirectExchange::DirectExchange() { } void DirectExchange::init( const std::string name, const bool durable) { AbstractExchange::init(name, durable); } std::string DirectExchange::getType() const { return ExchangeTypes::DIRECT; } SmartPtrExchange AMQPINTEGRATIONCORE_LINKAGE Caf::AmqpIntegration::createDirectExchange( const std::string& name, const bool durable) { SmartPtrDirectExchange exchange; exchange.CreateInstance(); exchange->init(name, durable); return exchange; } TopicExchange::TopicExchange() { } void TopicExchange::init( const std::string name, const bool durable) { AbstractExchange::init(name, durable); } std::string TopicExchange::getType() const { return ExchangeTypes::TOPIC; } SmartPtrExchange AMQPINTEGRATIONCORE_LINKAGE Caf::AmqpIntegration::createTopicExchange( const std::string& name, const bool durable) { SmartPtrTopicExchange exchange; exchange.CreateInstance(); exchange->init(name, durable); return exchange; } HeadersExchange::HeadersExchange() { } void HeadersExchange::init( const std::string name, const bool durable) { AbstractExchange::init(name, durable); } std::string HeadersExchange::getType() const { return ExchangeTypes::HEADERS; } SmartPtrExchange AMQPINTEGRATIONCORE_LINKAGE Caf::AmqpIntegration::createHeadersExchange( const std::string& name, const bool durable) { SmartPtrHeadersExchange exchange; exchange.CreateInstance(); exchange->init(name, durable); return exchange; } FanoutExchange::FanoutExchange() { } void FanoutExchange::init( const std::string name, const bool durable) { AbstractExchange::init(name, durable); } std::string FanoutExchange::getType() const { return ExchangeTypes::FANOUT; } SmartPtrExchange AMQPINTEGRATIONCORE_LINKAGE Caf::AmqpIntegration::createFanoutExchange( const std::string& name, const bool durable) { SmartPtrFanoutExchange exchange; exchange.CreateInstance(); exchange->init(name, durable); return exchange; } HeaderUtils.cpp000066400000000000000000000070131321503522500351550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 6, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CVariant.h" #include "Integration/IIntMessage.h" #include "HeaderUtils.h" using namespace Caf::AmqpIntegration; SmartPtrCVariant HeaderUtils::getHeaderString( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { SmartPtrCVariant variant; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { variant = CVariant::createString(header->second.first->toString()); } return variant; } SmartPtrCVariant HeaderUtils::getHeaderUint8( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { SmartPtrCVariant variant; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_BYTE)) { variant = CVariant::createUint8(g_variant_get_byte(header->second.first->get())); } else { variant = CVariant::createUint8( CStringConv::fromString(header->second.first->toString())); } } return variant; } SmartPtrCVariant HeaderUtils::getHeaderUint16( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { SmartPtrCVariant variant; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_UINT16)) { variant = CVariant::createUint16(g_variant_get_uint16(header->second.first->get())); } else { variant = CVariant::createUint16( CStringConv::fromString(header->second.first->toString())); } } return variant; } SmartPtrCVariant HeaderUtils::getHeaderUint32( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { SmartPtrCVariant variant; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_UINT32)) { variant = CVariant::createUint32(g_variant_get_uint32(header->second.first->get())); } else { variant = CVariant::createUint32( CStringConv::fromString(header->second.first->toString())); } } return variant; } SmartPtrCVariant HeaderUtils::getHeaderUint64( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { SmartPtrCVariant variant; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_UINT64)) { variant = CVariant::createUint64(g_variant_get_uint64(header->second.first->get())); } else { variant = CVariant::createUint64( CStringConv::fromString(header->second.first->toString())); } } return variant; } SmartPtrCVariant HeaderUtils::getHeaderBool( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { SmartPtrCVariant variant; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_BOOLEAN)) { variant = CVariant::createBool(g_variant_get_boolean(header->second.first->get())); } else { const std::string val = header->second.first->toString(); variant = CVariant::createBool( (val == "0") || (g_ascii_strncasecmp(val.c_str(), "false", val.length()) == 0) ? false : true); } } return variant; } HeaderUtils.h000066400000000000000000000043071321503522500346250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 6, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORE_HEADERUTILS_H_ #define AMQPINTEGRATIONCORE_HEADERUTILS_H_ #include "Common/CVariant.h" #include "Integration/IIntMessage.h" namespace Caf { namespace AmqpIntegration { /** * @brief A collection of helper functions */ class AMQPINTEGRATIONCORE_LINKAGE HeaderUtils { public: /** * @brief Extract a header value as text * @param headers message headers * @param tag value name * @return the value as a variant String */ static SmartPtrCVariant getHeaderString( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); /** * @brief Extract a header value as an unsigned 8-bit integer * @param headers message headers * @param tag value name * @return the value as a variant Uint8 */ static SmartPtrCVariant getHeaderUint8( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); /** * @brief Extract a header value as an unsigned 16-bit integer * @param headers message headers * @param tag value name * @return the value as a variant Uint16 */ static SmartPtrCVariant getHeaderUint16( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); /** * @brief Extract a header value as an unsigned 32-bit integer * @param headers message headers * @param tag value name * @return the value as a variant Uint32 */ static SmartPtrCVariant getHeaderUint32( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); /** * @brief Extract a header value as an unsigned 64-bit integer * @param headers message headers * @param tag value name * @return the value as a variant Uint64 */ static SmartPtrCVariant getHeaderUint64( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); /** * @brief Extract a header value as a boolean * @param headers message headers * @param tag value name * @return the value as a variant Bool */ static SmartPtrCVariant getHeaderBool( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); }; }} #endif /* AMQPINTEGRATIONCORE_HEADERUTILS_H_ */ QueueImpl.cpp000066400000000000000000000033341321503522500346540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 14, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpCore/Queue.h" #include "amqpCore/QueueImpl.h" using namespace Caf::AmqpIntegration; QueueImpl::QueueImpl() : _durable(false), _exclusive(false), _autoDelete(false) { } QueueImpl::~QueueImpl() { } void QueueImpl::init(const std::string& name) { init(name, true, false, false); } void QueueImpl::init( const std::string& name, const bool durable) { init(name, durable, false, false); } void QueueImpl::init( const std::string& name, const bool durable, const bool exclusive, const bool autoDelete) { _name = name; _durable = durable; _exclusive = exclusive; _autoDelete = autoDelete; } std::string QueueImpl::getName() const { return _name; } bool QueueImpl::isDurable() const { return _durable; } bool QueueImpl::isExclusive() const { return _exclusive; } bool QueueImpl::isAutoDelete() const { return _autoDelete; } SmartPtrQueue AMQPINTEGRATIONCORE_LINKAGE Caf::AmqpIntegration::createQueue( const std::string& name) { SmartPtrQueueImpl queue; queue.CreateInstance(); queue->init(name); return queue; } SmartPtrQueue AMQPINTEGRATIONCORE_LINKAGE Caf::AmqpIntegration::createQueue( const std::string& name, const bool durable) { SmartPtrQueueImpl queue; queue.CreateInstance(); queue->init(name, durable); return queue; } SmartPtrQueue AMQPINTEGRATIONCORE_LINKAGE Caf::AmqpIntegration::createQueue( const std::string& name, const bool durable, const bool exclusive, const bool autoDelete) { SmartPtrQueueImpl queue; queue.CreateInstance(); queue->init(name, durable, exclusive, autoDelete); return queue; } RabbitAdmin.cpp000066400000000000000000000224411321503522500351220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CVariant.h" #include "amqpClient/api/AmqpMethods.h" #include "amqpClient/api/Channel.h" #include "amqpCore/Binding.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/Exchange.h" #include "amqpCore/Queue.h" #include "amqpCore/RabbitAdmin.h" using namespace Caf::AmqpIntegration; RabbitAdmin::RabbitAdmin() : _isInitialized(false), CAF_CM_INIT_LOG("RabbitAdmin") { } RabbitAdmin::~RabbitAdmin() { CAF_CM_FUNCNAME("~RabbitAdmin"); try { if (_rabbitTemplate) { _rabbitTemplate->term(); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } void RabbitAdmin::init(SmartPtrConnectionFactory connectionFactory) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(connectionFactory); _rabbitTemplate.CreateInstance(); _rabbitTemplate->init(connectionFactory); _isInitialized = true; } void RabbitAdmin::term() { CAF_CM_FUNCNAME_VALIDATE("term"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _rabbitTemplate->term(); _rabbitTemplate = NULL; } void RabbitAdmin::declareExchange(SmartPtrExchange exchange) { CAF_CM_FUNCNAME_VALIDATE("declareExchange"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(exchange); SmartPtrDeclareExchangeExecutor executor; executor.CreateInstance(); _rabbitTemplate->execute(executor, exchange.GetNonAddRefedInterface()); } bool RabbitAdmin::deleteExchange(const std::string& exchange) { CAF_CM_FUNCNAME_VALIDATE("deleteExchange"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(exchange); SmartPtrDeleteExchangeExecutor executor; executor.CreateInstance(); gpointer result = _rabbitTemplate->execute( executor, const_cast(exchange.c_str())); return result != NULL; } SmartPtrQueue RabbitAdmin::declareQueue() { CAF_CM_FUNCNAME_VALIDATE("declareQueue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrDeclareQueueExecutor executor; executor.CreateInstance(); gpointer result = _rabbitTemplate->execute(executor, NULL); CAF_CM_VALIDATE_PTR(result); Queue *queuePtr = reinterpret_cast(result); SmartPtrQueue queue(queuePtr); queuePtr->Release(); return queue; } void RabbitAdmin::declareQueue(SmartPtrQueue queue) { CAF_CM_FUNCNAME_VALIDATE("declareQueue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrDeclareQueueExecutor executor; executor.CreateInstance(); _rabbitTemplate->execute(executor, queue.GetNonAddRefedInterface()); } bool RabbitAdmin::deleteQueue(const std::string& queue) { CAF_CM_FUNCNAME_VALIDATE("deleteQueue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); SmartPtrDeleteQueueExecutor executor; executor.CreateInstance(); gpointer result = _rabbitTemplate->execute( executor, const_cast(queue.c_str())); return result != NULL; } void RabbitAdmin::deleteQueue( const std::string& queue, const bool unused, const bool empty) { CAF_CM_FUNCNAME_VALIDATE("deleteQueue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); SmartPtrCVariant args[3]; args[0] = CVariant::createString(queue); args[1] = CVariant::createBool(unused); args[2] = CVariant::createBool(empty); SmartPtrDeleteQueueExExecutor executor; executor.CreateInstance(); _rabbitTemplate->execute(executor, args); } void RabbitAdmin::purgeQueue(const std::string& queue) { CAF_CM_FUNCNAME_VALIDATE("purgeQueue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); SmartPtrPurgeQueueExecutor executor; executor.CreateInstance(); _rabbitTemplate->execute( executor, const_cast(queue.c_str())); } void RabbitAdmin::declareBinding(SmartPtrBinding binding) { CAF_CM_FUNCNAME_VALIDATE("declareBinding"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(binding); SmartPtrDeclareBindingExecutor executor; executor.CreateInstance(); _rabbitTemplate->execute( executor, binding.GetNonAddRefedInterface()); } void RabbitAdmin::removeBinding(SmartPtrBinding binding) { CAF_CM_FUNCNAME_VALIDATE("removeBinding"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(binding); SmartPtrRemoveBindingExecutor executor; executor.CreateInstance(); _rabbitTemplate->execute( executor, binding.GetNonAddRefedInterface()); } gpointer RabbitAdmin::DeclareExchangeExecutor::execute( AmqpClient::SmartPtrChannel channel, gpointer data) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RabbitAdmin::DeclareExchangeExecutor", "execute"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_PTR(data); Exchange *exchange = reinterpret_cast(data); CAF_CM_LOG_DEBUG_VA3( "declaring exchange '%s' type '%s' durable=%d", exchange->getName().c_str(), exchange->getType().c_str(), exchange->isDurable()); channel->exchangeDeclare( exchange->getName(), exchange->getType(), exchange->isDurable()); return NULL; } gpointer RabbitAdmin::DeleteExchangeExecutor::execute( AmqpClient::SmartPtrChannel channel, gpointer data) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RabbitAdmin::DeleteExchangeExecutor", "execute"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_PTR(data); const char *exchange = reinterpret_cast(data); CAF_CM_LOG_DEBUG_VA1( "deleting exchange '%s'", exchange); gpointer result = NULL; try { channel->exchangeDelete(exchange, false); result = reinterpret_cast(0x01); } catch (AmqpClient::AmqpExceptions::ChannelClosedByServerException *ex) { ex->Release(); } return NULL; } gpointer RabbitAdmin::DeclareQueueExecutor::execute( AmqpClient::SmartPtrChannel channel, gpointer data) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RabbitAdmin::DeclareQueueExecutor", "execute"); CAF_CM_VALIDATE_SMARTPTR(channel); gpointer result = NULL; if (data) { Queue *queue = reinterpret_cast(data); const std::string queueName = queue->getName(); if (queueName.find("amq.", 0) == 0) { CAF_CM_LOG_ERROR_VA1( "Cannot declare queue '%s' because it's name begins with 'amq.'", queueName.c_str()); } else { CAF_CM_LOG_DEBUG_VA4( "declaring queue '%s' [durable=%d][exclusive=%d][autoDelete=%d]", queueName.c_str(), queue->isDurable(), queue->isExclusive(), queue->isAutoDelete()); channel->queueDeclare( queue->getName(), queue->isDurable(), queue->isExclusive(), queue->isAutoDelete()); } } else { AmqpClient::AmqpMethods::Queue::SmartPtrDeclareOk declareOk = channel->queueDeclare(); SmartPtrQueue queue = createQueue( declareOk->getQueueName(), false, true, true); result = queue.GetAddRefedInterface(); } return result; } gpointer RabbitAdmin::DeleteQueueExecutor::execute( AmqpClient::SmartPtrChannel channel, gpointer data) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RabbitAdmin::DeleteQueueExecutor", "execute"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_PTR(data); const char *queue = reinterpret_cast(data); CAF_CM_LOG_DEBUG_VA1( "deleting queue '%s'", queue); gpointer result = NULL; try { channel->queueDelete(queue, false, false); result = reinterpret_cast(0x01); } catch (AmqpClient::AmqpExceptions::ChannelClosedByServerException *ex) { ex->Release(); } return result; } gpointer RabbitAdmin::DeleteQueueExExecutor::execute( AmqpClient::SmartPtrChannel channel, gpointer data) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RabbitAdmin::DeleteQueueExExecutor", "execute"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_PTR(data); SmartPtrCVariant *args = reinterpret_cast(data); CAF_CM_LOG_DEBUG_VA3( "deleting queue '%s' [unused=%d][empty=%d]", g_variant_get_string(args[0]->get(), NULL), g_variant_get_boolean(args[1]->get()), g_variant_get_boolean(args[2]->get())); channel->queueDelete( g_variant_get_string(args[0]->get(), NULL), g_variant_get_boolean(args[1]->get()), g_variant_get_boolean(args[2]->get())); return NULL; } gpointer RabbitAdmin::PurgeQueueExecutor::execute( AmqpClient::SmartPtrChannel channel, gpointer data) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RabbitAdmin::PurgeQueueExecutor", "execute"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_PTR(data); const char *queue = reinterpret_cast(data); CAF_CM_LOG_DEBUG_VA1( "purging queue '%s'", queue); channel->queuePurge(queue); return NULL; } gpointer RabbitAdmin::DeclareBindingExecutor::execute( AmqpClient::SmartPtrChannel channel, gpointer data) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RabbitAdmin::DeclareBindingExecutor", "execute"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_PTR(data); Binding *binding = reinterpret_cast(data); channel->queueBind( binding->getQueue(), binding->getExchange(), binding->getRoutingKey()); return NULL; } gpointer RabbitAdmin::RemoveBindingExecutor::execute( AmqpClient::SmartPtrChannel channel, gpointer data) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RabbitAdmin::RemoveBindingExecutor", "execute"); CAF_CM_VALIDATE_SMARTPTR(channel); CAF_CM_VALIDATE_PTR(data); Binding *binding = reinterpret_cast(data); channel->queueUnbind( binding->getQueue(), binding->getExchange(), binding->getRoutingKey()); return NULL; } RabbitTemplate.cpp000066400000000000000000000223641321503522500356510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 5, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/amqpImpl/BasicProperties.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "amqpClient/api/AmqpMethods.h" #include "amqpClient/api/Channel.h" #include "amqpClient/api/Envelope.h" #include "amqpClient/api/GetResponse.h" #include "amqpCore/AmqpHeaderMapper.h" #include "amqpCore/AmqpTemplate.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/DefaultAmqpHeaderMapper.h" #include "amqpCore/RabbitTemplate.h" #include "Exception/CCafException.h" #include "AutoChannelClose.h" using namespace Caf::AmqpIntegration; std::string RabbitTemplate::DEFAULT_EXCHANGE = ""; std::string RabbitTemplate::DEFAULT_ROUTING_KEY = ""; int32 RabbitTemplate::DEFAULT_REPLY_TIMEOUT = 5000; RabbitTemplate::RabbitTemplate() : _isInitialized(false), _exchange(DEFAULT_EXCHANGE), _routingKey(DEFAULT_ROUTING_KEY), _replyTimeout(DEFAULT_REPLY_TIMEOUT), CAF_CM_INIT_LOG("RabbitTemplate") { } RabbitTemplate::~RabbitTemplate() { CAF_CM_FUNCNAME("~RabbitTemplate"); try { term(); } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; } void RabbitTemplate::init(SmartPtrConnectionFactory connectionFactory) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(connectionFactory); SmartPtrDefaultAmqpHeaderMapper defaultMapper; defaultMapper.CreateInstance(); defaultMapper->init(); _headerMapper = defaultMapper; _connectionFactory = connectionFactory; _connection = _connectionFactory->createConnection(); _isInitialized = true; } void RabbitTemplate::term() { if (_connection) { _connection->close(); _connection = NULL; } } void RabbitTemplate::setExchange(const std::string& exchange) { _exchange = exchange; } void RabbitTemplate::setRoutingKey(const std::string& routingKey) { _routingKey = routingKey; } void RabbitTemplate::setQueue(const std::string& queue) { _queue = queue; } void RabbitTemplate::setReplyTimeout(const uint32 replyTimeout) { _replyTimeout = replyTimeout; } void RabbitTemplate::setHeaderMapper(const SmartPtrAmqpHeaderMapper& headerMapper) { CAF_CM_FUNCNAME_VALIDATE("setHeaderMapper"); CAF_CM_VALIDATE_SMARTPTR(headerMapper); _headerMapper = headerMapper; } void RabbitTemplate::send( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper) { send( _exchange, _routingKey, message, headerMapper); } void RabbitTemplate::send( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper) { send( _exchange, routingKey, message, headerMapper); } void RabbitTemplate::send( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); AmqpClient::SmartPtrChannel channel = _connection->createChannel(); AutoChannelClose closer(channel); doSend(channel, exchange, routingKey, message, headerMapper); } SmartPtrIIntMessage RabbitTemplate::receive(SmartPtrAmqpHeaderMapper headerMapper) { return receive(_queue, headerMapper); } SmartPtrIIntMessage RabbitTemplate::receive( const std::string& queueName, SmartPtrAmqpHeaderMapper headerMapper) { CAF_CM_FUNCNAME_VALIDATE("receive"); CAF_CM_VALIDATE_STRING(queueName); SmartPtrCIntMessage message; AmqpClient::SmartPtrChannel channel = _connection->createChannel(); AutoChannelClose closer(channel); AmqpClient::SmartPtrGetResponse response = channel->basicGet(queueName, true); if (response) { if (!headerMapper) { headerMapper = _headerMapper; } IIntMessage::SmartPtrCHeaders headers = headerMapper->toHeaders( response->getProperties(), response->getEnvelope()); message.CreateInstance(); message->initialize(response->getBody(), headers, IIntMessage::SmartPtrCHeaders()); } return message; } SmartPtrIIntMessage RabbitTemplate::sendAndReceive( SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper, SmartPtrAmqpHeaderMapper responseHeaderMapper) { return sendAndReceive( _exchange, _routingKey, message, requestHeaderMapper, responseHeaderMapper); } SmartPtrIIntMessage RabbitTemplate::sendAndReceive( const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper, SmartPtrAmqpHeaderMapper responseHeaderMapper) { return sendAndReceive( _exchange, routingKey, message, requestHeaderMapper, responseHeaderMapper); } SmartPtrIIntMessage RabbitTemplate::sendAndReceive( const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper, SmartPtrAmqpHeaderMapper responseHeaderMapper) { AmqpClient::SmartPtrChannel channel = _connection->createChannel(); AutoChannelClose closer(channel); return doSendAndReceive( channel, exchange, routingKey, message, requestHeaderMapper, responseHeaderMapper); } gpointer RabbitTemplate::execute(SmartPtrExecutor executor, gpointer data) { CAF_CM_FUNCNAME_VALIDATE("execute"); CAF_CM_VALIDATE_INTERFACE(executor); AmqpClient::SmartPtrChannel channel = _connection->createChannel(); CAF_CM_VALIDATE_SMARTPTR(channel); AutoChannelClose closer(channel); return executor->execute(channel, data); } void RabbitTemplate::doSend( AmqpClient::SmartPtrChannel channel, const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper headerMapper) { CAF_CM_FUNCNAME_VALIDATE("doSend"); CAF_CM_LOG_DEBUG_VA2( "Publishing message on exchange [%s], routingKey= [%s]", exchange.c_str(), routingKey.c_str()); if (!headerMapper) { headerMapper = _headerMapper; } AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties props = headerMapper->fromHeaders(message->getHeaders()); channel->basicPublish( exchange, routingKey, false, false, props, message->getPayload()); } SmartPtrIIntMessage RabbitTemplate::doSendAndReceive( AmqpClient::SmartPtrChannel channel, const std::string& exchange, const std::string& routingKey, SmartPtrIIntMessage message, SmartPtrAmqpHeaderMapper requestHeaderMapper, SmartPtrAmqpHeaderMapper responseHeaderMapper) { CAF_CM_FUNCNAME("doSendAndReceive"); if (!requestHeaderMapper) { requestHeaderMapper = _headerMapper; } if (!responseHeaderMapper) { responseHeaderMapper = _headerMapper; } IIntMessage::SmartPtrCHeaders headers = message->getHeaders(); if (headers->find(AmqpHeaderMapper::REPLY_TO) != headers->end()) { CAF_CM_EXCEPTIONEX_VA1( IllegalStateException, 0, "Send-and-receive methods can only be used if the message " "does not already have a %s property", AmqpHeaderMapper::REPLY_TO.c_str()); } // Declare a temporary queue and set the replyTo AmqpClient::AmqpMethods::Queue::SmartPtrDeclareOk queueDeclareOk = channel->queueDeclare(); headers->insert( std::make_pair( AmqpHeaderMapper::REPLY_TO, std::make_pair( CVariant::createString(queueDeclareOk->getQueueName()), SmartPtrICafObject()))); // Create an inter-thread RPC mechanism to capture the response SmartPtrSynchronousHandoff handoff; handoff.CreateInstance(); // Spin up a consumer to wait for the response SmartPtrDefaultConsumer consumer; consumer.CreateInstance(); consumer->init(responseHeaderMapper, handoff); const std::string consumerTag = CStringUtils::createRandomUuid(); const bool noAck = false; const bool noLocal = true; const bool exclusive = true; AmqpClient::AmqpMethods::Basic::SmartPtrConsumeOk consumeOk = channel->basicConsume( queueDeclareOk->getQueueName(), consumerTag, noAck, noLocal, exclusive, consumer); // Send the message doSend(channel, exchange, routingKey, message, requestHeaderMapper); // Wait for the reply SmartPtrIIntMessage reply = handoff->get(_replyTimeout); // Cancel the consumer channel->basicCancel(consumerTag); return reply; } RabbitTemplate::DefaultConsumer::DefaultConsumer() { } RabbitTemplate::DefaultConsumer::~DefaultConsumer() { } void RabbitTemplate::DefaultConsumer::init( SmartPtrAmqpHeaderMapper mapper, SmartPtrSynchronousHandoff handoff) { _mapper = mapper; _handoff = handoff; } void RabbitTemplate::DefaultConsumer::handleDelivery( const std::string& consumerTag, const AmqpClient::SmartPtrEnvelope& envelope, const AmqpClient::AmqpContentHeaders::SmartPtrBasicProperties& properties, const SmartPtrCDynamicByteArray& body) { const IIntMessage::SmartPtrCHeaders headers = _mapper->toHeaders(properties, envelope); SmartPtrCIntMessage message; message.CreateInstance(); message->initialize(body, headers, IIntMessage::SmartPtrCHeaders()); _handoff->set(message); } void RabbitTemplate::DefaultConsumer::handleConsumeOk( const std::string& consumerTag) { } void RabbitTemplate::DefaultConsumer::handleCancelOk( const std::string& consumerTag) { } void RabbitTemplate::DefaultConsumer::handleRecoverOk( const std::string& consumerTag) { } void RabbitTemplate::DefaultConsumer::handleShutdown( const std::string& consumerTag, SmartPtrCCafException& reason) { } SimpleConnection.cpp000066400000000000000000000020061321503522500362120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: May 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "amqpClient/api/Channel.h" #include "amqpCore/SimpleConnection.h" using namespace Caf::AmqpIntegration; SimpleConnection::SimpleConnection() : CAF_CM_INIT("SimpleConnection") { } SimpleConnection::~SimpleConnection() { } void SimpleConnection::init(const AmqpClient::SmartPtrConnection& delegate) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_delegate); CAF_CM_VALIDATE_SMARTPTR(delegate); _delegate = delegate; } AmqpClient::SmartPtrChannel SimpleConnection::createChannel() { CAF_CM_FUNCNAME_VALIDATE("createChannel"); CAF_CM_PRECOND_ISINITIALIZED(_delegate); return _delegate->createChannel(); } void SimpleConnection::close() { CAF_CM_FUNCNAME_VALIDATE("close"); CAF_CM_PRECOND_ISINITIALIZED(_delegate); _delegate->close(); } bool SimpleConnection::isOpen() { return _delegate && _delegate->isOpen(); } SimpleMessageListenerContainer.cpp000066400000000000000000000265421321503522500410630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Aug 1, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IIntMessage.h" #include "Integration/IThrowable.h" #include "amqpClient/api/Channel.h" #include "amqpCore/BlockingQueueConsumer.h" #include "amqpClient/api/ConnectionFactory.h" #include "amqpCore/DefaultAmqpHeaderMapper.h" #include "amqpCore/MessageListener.h" #include "amqpCore/SimpleMessageListenerContainer.h" #include "Integration/Core/CIntException.h" #include "Exception/CCafException.h" using namespace Caf::AmqpIntegration; SimpleMessageListenerContainer::SimpleMessageListenerContainer() : _isInitialized(false), _isRunning(false), _isActive(false), _debugTrace(true), _acknowledgeMode(ACKNOWLEDGEMODE_NONE), _receiveTimeout(5000), _prefetchCount(0), _txSize(1), _recoveryInterval(30000), CAF_CM_INIT_LOG("SimpleMessageListenerContainer") { } SimpleMessageListenerContainer::~SimpleMessageListenerContainer() { } void SimpleMessageListenerContainer::init() { init(_connectionFactory); } void SimpleMessageListenerContainer::init( SmartPtrConnectionFactory connectionFactory) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(_connectionFactory); _connectionFactory = connectionFactory; validateConfig(); _isInitialized = true; } void SimpleMessageListenerContainer::setAcknowledgeMode( AcknowledgeMode acknowledgeMode) { CAF_CM_FUNCNAME_VALIDATE("setAcknowledgeMode"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _acknowledgeMode = acknowledgeMode; } void SimpleMessageListenerContainer::setPrefetchCount( const uint32 prefetchCount) { CAF_CM_FUNCNAME_VALIDATE("setPrefetchCount"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _prefetchCount = prefetchCount; } void SimpleMessageListenerContainer::setReceiveTimeout( const uint32 receiveTimeout) { CAF_CM_FUNCNAME_VALIDATE("setReceiveTimeout"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_NOTZERO(receiveTimeout); _receiveTimeout = receiveTimeout; } void SimpleMessageListenerContainer::setRecoveryInterval( const uint32 recoveryInterval) { CAF_CM_FUNCNAME_VALIDATE("setRecoveryInterval"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_NOTZERO(recoveryInterval); _recoveryInterval = recoveryInterval; } void SimpleMessageListenerContainer::setTxSize( const uint32 txSize) { CAF_CM_FUNCNAME_VALIDATE("setTxSize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_NOTZERO(txSize); _txSize = txSize; } void SimpleMessageListenerContainer::setQueue( const std::string& queue) { CAF_CM_FUNCNAME_VALIDATE("setQueue"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(queue); _queue = queue; } void SimpleMessageListenerContainer::setConnectionFactory( SmartPtrConnectionFactory connectionFactory) { CAF_CM_FUNCNAME_VALIDATE("setConnectionFactory"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(connectionFactory); _connectionFactory = connectionFactory; } void SimpleMessageListenerContainer::setMessagerListener( SmartPtrMessageListener messageListener) { CAF_CM_FUNCNAME_VALIDATE("setMessageListener"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageListener); _messageListener = messageListener; } SmartPtrMessageListener SimpleMessageListenerContainer::getMessageListener() { return _messageListener; } void SimpleMessageListenerContainer::start(const uint32 timeout) { CAF_CM_FUNCNAME("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_ASSERT(!_isRunning); _isActive = true; CAF_CM_LOG_DEBUG_VA0("Starting Rabbit listener container"); _startupException.CreateInstance(); // There is no point in prefetching less than the transaction size because // the consumer will stall since the broker will not receive an ack for delivered // messages const uint32 actualPrefetchCount = _prefetchCount > _txSize ? _prefetchCount : _txSize; CAF_CM_LOG_DEBUG_VA3( "Config: [prefetchCount=%d][txSize=%d][actualPrefetchCount=%d]", _prefetchCount, _txSize, actualPrefetchCount); // At this level simply allow all headers to pass through. // The message listener consuming the message will have // an opportunity to filter the headers. SmartPtrDefaultAmqpHeaderMapper headerMapper; headerMapper.CreateInstance(); headerMapper->init(".*"); _consumer.CreateInstance(); _consumer->init( _connectionFactory, headerMapper, _acknowledgeMode, actualPrefetchCount, _queue); SmartPtrAsyncMessageProcessingConsumer processor; processor.CreateInstance(); processor->init( this, _consumer, _startupException, timeout, _recoveryInterval); _executor.CreateInstance(); _executor->initialize(processor, processor); _executor->execute(timeout); // Wait for the consumer to start or fail const uint64 remainingTime = CDateTimeUtils::calcRemainingTime( CDateTimeUtils::getTimeMs(), timeout); if (remainingTime) { SmartPtrCCafException ex = _startupException->get(static_cast(remainingTime)); if (ex) { CAF_CM_LOG_CRIT_VA0("Fatal exception on listener startup"); ex->throwAddRefedSelf(); } } else { try { _executor->cancel(timeout); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; CAF_CM_EXCEPTIONEX_VA0( TimeoutException, 0, "The timeout value specified is not int32 enough to determine " "if the consumer has started. Increase the timeout value."); } _startupException = NULL; _isRunning = true; } void SimpleMessageListenerContainer::stop(const uint32 timeout) { CAF_CM_FUNCNAME("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _isActive = false; if (_isRunning) { try { _executor->cancel(timeout); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } _isRunning = false; } bool SimpleMessageListenerContainer::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _isRunning; } void SimpleMessageListenerContainer::validateConfig() { CAF_CM_FUNCNAME_VALIDATE("validateConfig"); CAF_CM_VALIDATE_INTERFACE(_connectionFactory); CAF_CM_VALIDATE_INTERFACE(_messageListener); CAF_CM_VALIDATE_STRING(_queue); CAF_CM_VALIDATE_NOTZERO(_receiveTimeout); CAF_CM_VALIDATE_NOTZERO(_recoveryInterval); CAF_CM_VALIDATE_NOTZERO(_txSize); } bool SimpleMessageListenerContainer::isActive() { return _isActive; } bool SimpleMessageListenerContainer::receiveAndExecute( SmartPtrBlockingQueueConsumer consumer) { CAF_CM_FUNCNAME("receiveAndExecute"); AmqpClient::SmartPtrChannel channel = _consumer->getChannel(); for (uint32 i = 0; i < _txSize; ++i) { if (_debugTrace) { CAF_CM_LOG_DEBUG_VA0("Waiting for message from consumer"); } SmartPtrIIntMessage message = _consumer->nextMessage(_receiveTimeout); if (!message) { break; } try { executeListener(channel, message); } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { SmartPtrCCafException ex = CAF_CM_GETEXCEPTION; CAF_CM_CLEAREXCEPTION; _consumer->rollbackOnExceptionIfNecessary(ex); ex->throwAddRefedSelf(); } } return _consumer->commitIfNecessary(); } void SimpleMessageListenerContainer::executeListener( AmqpClient::SmartPtrChannel channel, SmartPtrIIntMessage message) { doInvokeListener(message); } void SimpleMessageListenerContainer::doInvokeListener( SmartPtrIIntMessage message) { CAF_CM_FUNCNAME("doInvokeListener"); try { _messageListener->onMessage(message); } catch (ListenerExecutionFailedException *ex) { // noop - let 'er rip ex->throwSelf(); } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { const std::string orig = CAF_CM_EXCEPTION_GET_FULLMSG; CAF_CM_CLEAREXCEPTION; CAF_CM_EXCEPTIONEX_VA1( ListenerExecutionFailedException, 0, "Listener threw exception: %s", orig.c_str()); } } void SimpleMessageListenerContainer::restart() { CAF_CM_FUNCNAME_VALIDATE("restart"); CAF_CM_LOG_DEBUG_VA0("Restarting Rabbit listener container"); _isRunning = false; start(30000); } #if (1) // AsyncMessageProcessingConsumer SimpleMessageListenerContainer::AsyncMessageProcessingConsumer::AsyncMessageProcessingConsumer() : _parent(NULL), _timeout(0), _recoveryInterval(0), _isCanceled(false), CAF_CM_INIT_LOG("SimpleMessageListenerContainer::AsyncMessageProcessingConsumer") { } SimpleMessageListenerContainer::AsyncMessageProcessingConsumer::~AsyncMessageProcessingConsumer() { } void SimpleMessageListenerContainer::AsyncMessageProcessingConsumer::init( SimpleMessageListenerContainer *parent, SmartPtrBlockingQueueConsumer consumer, SmartPtrStartupExceptionHandoff startupException, const uint32 timeout, const uint32 recoveryInterval) { _parent = parent; _consumer = consumer; _startupException = startupException; _timeout = timeout; _recoveryInterval = recoveryInterval; } void SimpleMessageListenerContainer::AsyncMessageProcessingConsumer::run() { CAF_CM_FUNCNAME("run"); bool isAborted = false; try { try { _consumer->start(_timeout); _startupException->set(NULL); _startupException = NULL; } catch (FatalListenerStartupException *ex) { ex->throwSelf(); } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { _startupException->set(NULL); _startupException = NULL; CAF_CM_LOG_ERROR_CAFEXCEPTION; handleStartupFailure(); CAF_CM_THROWEXCEPTION; } bool isContinuable = false; while (!_isCanceled && (_parent->isActive() || isContinuable)) { try { isContinuable = _parent->receiveAndExecute(_consumer); } catch (ListenerExecutionFailedException *ex) { // ignore _logger.log( log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, ex); ex->Release(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_ERROR_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } } catch (FatalListenerStartupException *ex) { CAF_CM_LOG_ERROR_VA1( "Consumer received fatal exception on startup: %s", ex->getFullMsg().c_str()); ex->Release(); isAborted = true; } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_WARN_VA1( "Consumer raised exception. Processing will restart if the connection " "factory supports it. Exception: %s", (CAF_CM_EXCEPTION_GET_FULLMSG).c_str()); CAF_CM_CLEAREXCEPTION; } if (_startupException) { _startupException->set(NULL); _startupException = NULL; } if (_isCanceled) { CAF_CM_LOG_DEBUG_VA0("Canceling due to TaskContainer->cancel()"); } else { if (!_parent->isActive() || isAborted) { CAF_CM_LOG_DEBUG_VA0("Canceling consumer"); try { _consumer->stop(_timeout); } CAF_CM_CATCH_ALL; CAF_CM_LOG_ERROR_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (isAborted) { CAF_CM_LOG_INFO_VA0("Stopping parent container because of aborted consumer"); _parent->stop(_timeout); } } else { CAF_CM_LOG_INFO_VA0("Restarting consumer"); _parent->restart(); } } } void SimpleMessageListenerContainer::AsyncMessageProcessingConsumer::cancel() { _isCanceled = true; } void SimpleMessageListenerContainer::AsyncMessageProcessingConsumer::handleError( const SmartPtrIThrowable& throwable, const SmartPtrIIntMessage& message) const { } void SimpleMessageListenerContainer::AsyncMessageProcessingConsumer::handleStartupFailure() { uint64 start = CDateTimeUtils::getTimeMs(); while (!_isCanceled && CDateTimeUtils::calcRemainingTime(start, _recoveryInterval)) { CThreadUtils::sleep(100); } } #endif amqpIntegrationCoreLink.h000066400000000000000000000014371321503522500372060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AMQPINTEGRATIONCORELINK_H_ #define AMQPINTEGRATIONCORELINK_H_ #ifndef AMQPINTEGRATIONCORE_LINKAGE #ifdef WIN32 #ifdef AMQP_CLIENT #define AMQPINTEGRATIONCORE_LINKAGE __declspec(dllexport) #else #define AMQPINTEGRATIONCORE_LINKAGE __declspec(dllimport) #endif #else #define AMQPINTEGRATIONCORE_LINKAGE #endif #endif #include "AmqpIntegrationCoreDefines.h" #include "AmqpIntegrationCoreFunc.h" #include "AmqpIntegrationExceptions.h" #include "amqpCore/AmqpOutboundEndpoint.h" #include "AutoChannelClose.h" #include "HeaderUtils.h" #endif /* AMQPINTEGRATIONCORELINK_H_ */ stdafx.h000066400000000000000000000010401321503522500336740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpCore/src/amqpCore/* * Created on: Jun 12, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifndef AMQPINTEGRATIONCORE_LINKAGE #ifdef WIN32 #define AMQPINTEGRATIONCORE_LINKAGE __declspec(dllexport) #else #define AMQPINTEGRATIONCORE_LINKAGE #endif #endif #include #include #include "AmqpIntegrationCoreFunc.h" #include "AmqpIntegrationCoreDefines.h" #include "AmqpIntegrationExceptions.h" #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpListener/000077500000000000000000000000001321503522500306555ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpListener/include/000077500000000000000000000000001321503522500323005ustar00rootroot00000000000000AmqpListenerWorker.h000066400000000000000000000012241321503522500361670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpListener/include/* * Created on: Aug 20, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AmqpListenerWorker_h #define AmqpListenerWorker_h #include "Common/CThreadSignal.h" #include "Common/IWork.h" namespace Caf { class AmqpListenerWorker : public IWork { public: AmqpListenerWorker(); virtual ~AmqpListenerWorker(); void doWork(); void stopWork(); private: CThreadSignal _stopSignal; CAF_THREADSIGNAL_CREATE; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(AmqpListenerWorker); }; CAF_DECLARE_SMART_POINTER(AmqpListenerWorker); } #endif /* AmqpListenerWorker_h */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpListener/src/000077500000000000000000000000001321503522500314445ustar00rootroot00000000000000AmqpListenerWorker.cpp000066400000000000000000000064261321503522500356770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpListener/src/* * Created on: Aug 20, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ // NOTE: windows.h defines macros for min and max. Specifying NOMINMAX to prevent // macro definition. Must be specified before windows.h is included. #define NOMINMAX #include "stdafx.h" #include "Integration/Core/CIntegrationAppContext.h" #include "AmqpListenerWorker.h" #include "Common/CLoggingUtils.h" #include "amqpClient/api/AMQExceptions.h" using namespace Caf; AmqpListenerWorker::AmqpListenerWorker() : CAF_CM_INIT_LOG("AmqpListenerWorker") { CAF_THREADSIGNAL_INIT; _stopSignal.initialize("AmqpListenerWorker::stopSignal"); } AmqpListenerWorker::~AmqpListenerWorker() { } void AmqpListenerWorker::doWork() { CAF_CM_FUNCNAME("run"); const std::string monitorDir = AppConfigUtils::getRequiredString("monitor_dir"); const std::string listenerConfiguredStage2Path = FileSystemUtils::buildPath( monitorDir, "listenerConfiguredStage2.txt"); if (FileSystemUtils::doesFileExist(listenerConfiguredStage2Path)) { uint32 intShutdownTimeout = AppConfigUtils::getOptionalUint32( "communication_amqp", "shutdown_timeout"); intShutdownTimeout = std::max(intShutdownTimeout, static_cast(5000)); SmartPtrCIntegrationAppContext intAppContext; try { CLoggingUtils::setStartupConfigFile( AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile), AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogDir)); uint32 intStartupTimeout = AppConfigUtils::getOptionalUint32( "communication_amqp", "startup_timeout"); intStartupTimeout = std::max(intStartupTimeout, static_cast(5000)); uint32 connectionRetryInterval = AppConfigUtils::getOptionalUint32( "communication_amqp", "connection_retry_interval"); connectionRetryInterval = std::max(connectionRetryInterval, static_cast(5000)); bool isSignaled = false; do { try { CAF_CM_LOG_DEBUG_VA0("***** Initializing context"); intAppContext.CreateInstance(); intAppContext->initialize( intStartupTimeout, AppConfigUtils::getRequiredString("communication_amqp", "context_file")); CAF_CM_LOG_DEBUG_VA0("***** Started. Waiting for stop signal."); { CAF_THREADSIGNAL_LOCK_UNLOCK; _stopSignal.wait(CAF_THREADSIGNAL_MUTEX, 0); } CAF_CM_LOG_DEBUG_VA0("***** Received stop signal."); break; } catch (AmqpClient::AmqpExceptions::AmqpTimeoutException *ex) { _logger.log( log4cpp::Priority::WARN, _cm_funcName_, __LINE__, ex); ex->Release(); CThreadUtils::sleep(connectionRetryInterval); } CAF_CM_CATCH_ALL; CAF_CM_THROWEXCEPTION; { CAF_THREADSIGNAL_LOCK_UNLOCK; isSignaled = _stopSignal.waitOrTimeout(CAF_THREADSIGNAL_MUTEX, 100); } } while (!isSignaled); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; try { if (intAppContext) { intAppContext->terminate(intShutdownTimeout); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } else { CAF_CM_LOG_WARN_VA0("Listener not configured"); } } void AmqpListenerWorker::stopWork() { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_LOG_DEBUG_VA0("***** Setting stop signal."); _stopSignal.signal(); } amqpListenerMain.cpp000066400000000000000000000100701321503522500353400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpListener/src/* * Created on: Aug 20, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "AmqpListenerWorker.h" #include "Common/CLoggingUtils.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #ifndef WIN32 #include #endif bool _gDaemonized = true; bool _gSysLogInfos = false; SmartPtrAmqpListenerWorker _gAmqpListenerWorker; using namespace Caf; #ifndef WIN32 extern "C" void TermHandler(int32 signum); #endif int32 main(int32 argc, char** argv) { HRESULT hr = CafInitialize::init(); if (hr != S_OK) { #ifndef WIN32 ::syslog(LOG_ERR, "CommAmqpListener: CafInitialize::init() failed 0x%08X.", hr); #endif ::fprintf(stderr, "CommAmqpListener: CafInitialize::init() failed 0x%08X\n", hr); return 1; } CafInitialize::serviceConfig(); CAF_CM_STATIC_FUNC_LOG( "CommAmqpListener", "main" ); SmartPtrIAppConfig appConfig; try { std::string appConfigEnv; CEnvironmentUtils::readEnvironmentVar("CAF_APPCONFIG", appConfigEnv); if (appConfigEnv.empty()) { Cdeqstr deqstr; deqstr.push_back("cafenv-appconfig"); deqstr.push_back("persistence-appconfig"); deqstr.push_back("CommAmqpListener-appconfig"); deqstr.push_back("custom-appconfig"); appConfig = getAppConfig(deqstr); } else { appConfig = getAppConfig(); } } catch(CCafException *ex) { #ifndef WIN32 ::syslog( LOG_ERR, "CommAmqpListener: getAppConfig() failed . %s", ex->getFullMsg().c_str()); #endif ::fprintf( stderr, "CommAmqpListener: getAppConfig() failed . %s\n", ex->getFullMsg().c_str()); ex->Release(); } catch (std::exception ex) { #ifndef WIN32 ::syslog( LOG_ERR, "CommAmqpListener: getAppConfig() failed . %s", ex.what()); #endif ::fprintf( stderr, "CommAmqpListener: getAppConfig() failed . %s\n", ex.what()); } catch (...) { #ifndef WIN32 ::syslog( LOG_ERR, "CommAmqpListener: getAppConfig() failed . unknown exception"); #endif ::fprintf( stderr, "CommAmqpListener: getAppConfig() failed . unknown exception\n"); } if (!appConfig) { CafInitialize::term(); return 1; } int32 iRc = 0; try { _gAmqpListenerWorker.CreateInstance(); const uint32 maxStrLen = 4096; if ((argc < 1) || (NULL == argv) || (NULL == argv[0]) || (::strnlen(argv[0], maxStrLen) >= maxStrLen)) { CAF_CM_EXCEPTION_VA0(E_INVALIDARG, "argc/argv are invalid"); } #ifdef WIN32 CWinService::initialize(_gAmqpListenerWorker); CWinService::execute(argc, argv); #else const std::string procPath(reinterpret_cast(argv[0])); Cdeqstr parts = CStringUtils::split(procPath, G_DIR_SEPARATOR); std::string procName = "CommAmqpListener"; if (parts.size()) { procName = parts.back(); } CDaemonUtils::MakeDaemon( argc, argv, procPath, procName, TermHandler, _gDaemonized, _gSysLogInfos); CLoggingUtils::setStartupConfigFile( AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile), AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogDir)); _gAmqpListenerWorker->doWork(); #endif } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; if (CAF_CM_ISEXCEPTION) { const std::string msg = CAF_CM_EXCEPTION_GET_FULLMSG; #ifndef WIN32 ::syslog( LOG_ERR, "CommAmqpListener: %s", msg.c_str()); #endif ::fprintf( stderr, "CommAmqpListener: %s\n", msg.c_str()); iRc = 1; } CAF_CM_CLEAREXCEPTION; _gAmqpListenerWorker = NULL; CafInitialize::term(); return iRc; } extern "C" void TermHandler(int32 signum) { CAF_CM_STATIC_FUNC_LOG_ONLY( "CommAmqpListener", "TermHandler" ); CAF_CM_ENTER { switch (signum) { case SIGTERM: CAF_CM_LOG_INFO_VA0( "Received SIGTERM" ); if (_gAmqpListenerWorker) { _gAmqpListenerWorker->stopWork(); } break; case SIGINT: CAF_CM_LOG_INFO_VA0( "Received SIGINT" ); if (_gAmqpListenerWorker) { _gAmqpListenerWorker->stopWork(); } break; default: CAF_CM_LOG_ERROR_VA1( "Ignoring Unexpected signal %d", signum); break; } } CAF_CM_EXIT; } open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Communication/amqpListener/src/stdafx.h000066400000000000000000000004641321503522500331120ustar00rootroot00000000000000/* * Created on: Aug 20, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h #define stdafx_h #include #include #ifdef WIN32 #include "CWinService.h" #endif #endif /* stdafx_h */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/000077500000000000000000000000001321503522500253415ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/000077500000000000000000000000001321503522500272765ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/000077500000000000000000000000001321503522500307215ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/BaseDefines.h000066400000000000000000000026561321503522500332530ustar00rootroot00000000000000/* * Author: mdonahue * Created: Jan 12, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef SYS_INC_BASEDEFINES_H_ #define SYS_INC_BASEDEFINES_H_ #ifdef ECM_SUB_SYSTEM #error "The ECM_SUB_SYSTEM define has been deprecated. Use CAF_SUB_SYSTEM instead." #endif #ifdef WIN32 // Disable compiler warning 4275: non dll-interface used as base for dll-interface class #pragma warning(disable: 4275) #endif #include const gboolean GLIB_FALSE = (gboolean)0; const gboolean GLIB_TRUE = !GLIB_FALSE; // Windows includes #if defined( WIN32 ) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0502 #endif #include #endif #include #if defined( WIN32 ) typedef __int8 int8; typedef unsigned __int8 uint8; typedef __int16 int16; typedef unsigned __int16 uint16; typedef __int32 int32; typedef unsigned __int32 uint32; typedef __int64 int64; typedef unsigned __int64 uint64; struct timezone { int32 tz_minuteswest; int32 tz_dsttime; }; #else #include typedef signed char int8; typedef unsigned char uint8; typedef int16_t int16; typedef uint16_t uint16; typedef int32_t int32; typedef uint32_t uint32; typedef int64_t int64; typedef uint64_t uint64; #endif #include #include #include "BasePlatformLink.h" #endif /* SYS_INC_BASEDEFINES_H_ */ BasePlatformInc.h000066400000000000000000000014061321503522500340250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BasePlatformInc_h_ #define BasePlatformInc_h_ #ifndef BASEPLATFORM_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define BASEPLATFORM_LINKAGE __declspec(dllexport) #else #define BASEPLATFORM_LINKAGE __declspec(dllimport) #endif #else #define BASEPLATFORM_LINKAGE #endif #endif #include "PlatformTypes.h" #include "PlatformDefines.h" #include "PlatformErrors.h" #include "PlatformIID.h" #include "PlatformStringFunc.h" #include "ICafObject.h" #include "TCafObject.h" #include "TCafQIObject.h" #include "TCafSmartPtr.h" #include "TCafStackObject.h" CAF_DECLARE_SMART_INTERFACE_POINTER(ICafObject); #endif BasePlatformLink.h000066400000000000000000000036561321503522500342220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef BasePlatformLink_h_ #define BasePlatformLink_h_ #include "BasePlatformInc.h" #include #include #include #include #include namespace Caf { // Basic string containers typedef std::deque Cdeqstr; typedef std::set Csetstr; typedef std::vector Cvecstr; typedef std::map Cmapstrstr; typedef std::multimap Cmmapstrstr; CAF_DECLARE_SMART_POINTER(Cdeqstr); CAF_DECLARE_SMART_POINTER(Csetstr); CAF_DECLARE_SMART_POINTER(Cvecstr); CAF_DECLARE_SMART_POINTER(Cmapstrstr); CAF_DECLARE_SMART_POINTER(Cmmapstrstr); // GUID containers typedef std::vector Cvecguid; typedef std::deque Cdeqguid; CAF_DECLARE_SMART_POINTER(Cvecguid); CAF_DECLARE_SMART_POINTER(Cdeqguid); struct SGuidLessThan { bool operator()(const GUID clhs, const GUID crhs) const { return ::memcmp(&clhs, &crhs, sizeof(GUID)) < 0; } }; typedef std::set Csetguid; CAF_DECLARE_SMART_POINTER(Csetguid); // class to extract first part of a pair template struct select1st { typename T::first_type operator()(const T & p) const { return p.first; } }; // template function to make use of select1st easy. // T is a container whose value_type is a pair template select1st make_select1st(const T &) { return select1st(); }; // class to extract second part of a pair template struct select2nd { typename T::second_type operator()(const T & p) const { return p.second; } }; // template function to make use of select2nd easy. // T is a container whose value_type is a pair template select2nd make_select2nd(const T &) { return select2nd(); }; } #ifdef WIN32 #include "PlatformApi.h" #endif #endif CafCppUnitSupport.h000066400000000000000000000000001321503522500343720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/includeopen-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Collections.h000066400000000000000000000004751321503522500333560ustar00rootroot00000000000000/* * Author: mdonahue * Created: Jan 25, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef ITERATORS_H_ #define ITERATORS_H_ #include "../src/Collections/Iterators/IteratorsInc.h" #include "../src/Collections/Graphs/GraphsInc.h" #endif /* ITERATORS_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/000077500000000000000000000000001321503522500321515ustar00rootroot00000000000000CApplicationContext.h000066400000000000000000000046231321503522500361630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CApplicationContext_h_ #define CApplicationContext_h_ #include "Common/IAppContext.h" #include "IBean.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER( CApplicationContext); class COMMONAGGREGATOR_LINKAGE CApplicationContext : public IAppContext { private: // Bean constructor arguments struct CBeanCtorArg { typedef enum { NOT_SET, REFERENCE, VALUE } ARG_TYPE; CBeanCtorArg(const ARG_TYPE type, const std::string& value) : _type(type), _value(value) {} ARG_TYPE _type; std::string _value; }; // key=constructor-arg index typedef std::map CBeanCtorArgCollection; struct CBeanNode { CBeanNode() : _isInitialized(false) {} std::string _id; std::string _class; SmartPtrIBean _bean; CBeanCtorArgCollection _ctorArgs; Cmapstrstr _properties; bool _isInitialized; }; CAF_DECLARE_SMART_POINTER(CBeanNode); struct CBeanNodeLess { bool operator()( const SmartPtrCBeanNode& lhs, const SmartPtrCBeanNode& rhs) const { return std::less()(lhs->_id, rhs->_id); } }; typedef TEdgeListGraph CBeanGraph; // key=bean id typedef std::map CBeanCollection; public: CApplicationContext(); virtual ~CApplicationContext(); public: void initialize(); void initialize(const Cdeqstr& filenameCollection); void terminate(); SmartPtrCBeans getBeans() const; public: // IApplicationContext SmartPtrIBean getBean(const std::string& name) const; private: bool m_isInitialized; CBeanCollection _beanCollection; CBeanGraph::ClistVertexEdges _beanTopologySort; Cdeqstr _filenameCollection; private: std::string getDefaultBeanConfigFile() const; void parseBeanConfig( const std::string& beanConfigFile, CBeanCollection& beanCollection) const; void createBeanGraph( CBeanCollection& beanCollection, CBeanGraph& beanGraph, CBeanGraph::ClistVertexEdges& beanTopologySort) const; void initializeBeans( CBeanCollection& beanCollection, CBeanGraph::ClistVertexEdges& beanTopologySort) const; void terminateBeans(CBeanGraph::ClistVertexEdges& beanTopologySort) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CApplicationContext); }; } #endif // #ifndef CApplicationContext_h_ CAutoCondition.h000066400000000000000000000014761321503522500351350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Oct 29, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAUTOCONDITION_H_ #define CAUTOCONDITION_H_ #include "Common/CAutoCondition.h" #include "Common/CAutoMutex.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE CAutoCondition { public: CAutoCondition(); ~CAutoCondition(); void initialize(const std::string& name); bool isInitialized() const; void close(); std::string getName() const; void signal(); void wait(SmartPtrCAutoMutex& mutex); bool waitUntil(SmartPtrCAutoMutex& mutex, gint64 endTime); private: GCond _condition; std::string _name; bool _isInitialized; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAutoCondition); }; CAF_DECLARE_SMART_POINTER(CAutoCondition); } #endif /* CAUTOCONDITION_H_ */ CAutoMutex.h000066400000000000000000000013571321503522500343070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Oct 29, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAUTOMUTEX_H_ #define CAUTOMUTEX_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CAutoMutex { public: CAutoMutex(); ~CAutoMutex(); void initialize(); bool isInitialized() const; void lock(const char* className = NULL, const char* funcName = NULL, const int32 lineNumber = 0); void unlock(const char* className = NULL, const char* funcName = NULL, const int32 lineNumber = 0); GMutex* getNonConstPtr(); private: GMutex _mutex; bool _isInitialized; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAutoMutex); }; CAF_DECLARE_SMART_POINTER(CAutoMutex); } #endif /* CAUTOMUTEX_H_ */ CAutoRecMutex.h000066400000000000000000000014151321503522500347340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Oct 29, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAUTORECMUTEX_H_ #define CAUTORECMUTEX_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CAutoRecMutex { public: CAutoRecMutex(); ~CAutoRecMutex(); void initialize(); bool isInitialized() const; void lock(const char* className = NULL, const char* funcName = NULL, const int32 lineNumber = 0); void unlock(const char* className = NULL, const char* funcName = NULL, const int32 lineNumber = 0); GRecMutex* getNonConstPtr(); private: GRecMutex _mutex; bool _isInitialized; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAutoRecMutex); }; CAF_DECLARE_SMART_POINTER(CAutoRecMutex); } #endif /* CAUTORECMUTEX_H_ */ CCafRegex.h000066400000000000000000000022121321503522500340270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCAFREGEX_H_ #define CCAFREGEX_H_ #include "Common/CCafRegex.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE CCafRegex { public: CCafRegex(); virtual ~CCafRegex(); public: void initialize(const std::string& regex); bool isMatched(const std::string& source); std::map matchNames( const std::string& source, const std::set& names); std::deque matchName( const std::string& source, const std::string& name); std::string match( const std::string& source, const int32 matchNum); std::string replaceLiteral( const std::string& source, const std::string& replacement); public: static std::string replaceLiteral( const std::string& regex, const std::string& source, const std::string& replacement); private: bool _isInitialized; GRegex* _gRegex; std::string _regex; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CCafRegex); }; CAF_DECLARE_SMART_POINTER(CCafRegex); } #endif /* CCAFREGEX_H_ */ CCmdLineOptions.h000066400000000000000000000036051321503522500352410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCmdLineOptions_h_ #define CCmdLineOptions_h_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CCmdLineOptions { private: typedef std::map CStringOptions; typedef std::map CIntOptions; typedef std::map CBoolOptions; public: CCmdLineOptions(); virtual ~CCmdLineOptions(); public: void initialize(const std::string& cmdDescription, const uint32 maxOptions); void parse(int32 argc, char* argv[]); void addStringOption(const std::string& longName, const char shortName, const std::string& optionDescription); void addIntOption(const std::string& longName, const char shortName, const std::string& optionDescription); void addBoolOption(const std::string& longName, const char shortName, const std::string& optionDescription); std::string findStringOption(const std::string& longName); int32 findIntOption(const std::string& longName); bool findBoolOption(const std::string& longName); private: bool _isInitialized; uint32 _optionCnt; std::string _cmdDescription; uint32 _maxOptions; GOptionEntry* _gOptions; CStringOptions _stringOptions; CIntOptions _intOptions; CBoolOptions _boolOptions; // Temporary for storing longNames and optionDescription for addFooOption() methods above. std::vector _longNames, _optionDescriptions; private: void checkOptionCnt( const std::string& longName, const uint32 optionCnt, const uint32 maxOptions) const; void populateOption( GOptionEntry& optionEntry, const std::string& longName, const char shortName, const std::string& optionDescription); private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CCmdLineOptions); }; CAF_DECLARE_SMART_POINTER( CCmdLineOptions); } #endif // #ifndef CCmdLineOptions_h_ CConfigParams.h000066400000000000000000000032531321503522500347220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: mdonahue * Created: Jan 17, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCONFIGPARAMS_H_ #define CCONFIGPARAMS_H_ #include "Common/IConfigParams.h" namespace Caf { /* * This class wraps a GHashTable object where the key is a const char* and * the value is a GVariant*. * * The key and value pointers inserted must exist for the lifetime of this object. * Use the EKeyManagement and EValueMangement flags to control how this * object destroys the contained hash table. * */ class COMMONAGGREGATOR_LINKAGE CConfigParams : public IConfigParams { public: typedef enum { EKeysUnmanaged, // Set if the caller will manage the lifetime of the keys EKeysManaged // Set if this object is to detroy the keys upon destruction } EKeyManagement; typedef enum { EValuesUnmanaged, // Set if the caller will manage the lifetime of the values EValuesManaged // Set if this object is to detroy the values upon destruction } EValueManagement; CConfigParams(); virtual ~CConfigParams(); void initialize( const std::string& sectionName, EKeyManagement keyManagement, EValueManagement valueManagement); public: // IConfigParams GVariant* lookup( const char* key, const EParamDisposition disposition = PARAM_REQUIRED) const; std::string getSectionName() const; void insert(const char* key, GVariant* value); private: static void destroyKeyCallback(gpointer ptr); static void destroyValueCallback(gpointer ptr); private: std::string _sectionName; GHashTable* _table; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CConfigParams); }; CAF_DECLARE_SMART_POINTER(CConfigParams); } #endif /* CCONFIGPARAMS_H_ */ CConfigParamsChain.h000066400000000000000000000021061321503522500356610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: mdonahue * Created: Jan 17, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCONFIGPARAMSCHAIN_H_ #define CCONFIGPARAMSCHAIN_H_ #include "Common/IConfigParams.h" #include "Common/CConfigParams.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE CConfigParamsChain : public IConfigParams { public: CConfigParamsChain(); virtual ~CConfigParamsChain(); void initialize(CConfigParams::EKeyManagement keyManagement, CConfigParams::EValueManagement valueManagement, const SmartPtrIConfigParams& baseParams); void insert(const char* key, GVariant* value); public: // IConfigParams GVariant* lookup(const char* key, const EParamDisposition disposition = PARAM_REQUIRED) const; std::string getSectionName() const; private: static void destroyValueCallback(gpointer ptr); private: SmartPtrCConfigParams _theseParams; SmartPtrIConfigParams _baseParams; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CConfigParamsChain); }; CAF_DECLARE_SMART_POINTER(CConfigParamsChain); } #endif /* CCONFIGPARAMSCHAIN_H_ */ CFileLock.h000066400000000000000000000020411321503522500340330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CFileLock_h_ #define CFileLock_h_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CFileLock { public: enum ELockLevel { UNLOCK, SHARED_LOCK, EXCLUSIVE_LOCK }; public: // Ctor CFileLock(); // dtor ~CFileLock(); // initialize the lock for the specified file void initialize(int32 iFileDescriptor); // initialize the lock for the specified file void initialize(const char * cszFileName, bool bCreateFile = true); // Set the lock to the specified scope void setLockLevel(ELockLevel eLockLevel, bool bDowngradeLock = false); // Set the lock to the specified if possible bool attemptSetLockLevel(ELockLevel eLockLevel, bool bDowngradeLock = false); // Get the current lock level ELockLevel getLockLevel() const; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CFileLock); bool _isInitialized; bool _isFileDescriptorLocal; int32 _fileDescriptor; ELockLevel _lockLevel; }; CAF_DECLARE_SMART_POINTER(CFileLock); } #endif CIniFile.h000066400000000000000000000046631321503522500336760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: May 18, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CINIFILE_H_ #define CINIFILE_H_ #include "Common/CCafRegex.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE CIniFile { public: struct SIniEntry { std::string _name; std::string _valueRaw; std::string _valueExpanded; }; CAF_DECLARE_SMART_POINTER(SIniEntry); struct SIniSection { std::string _sectionName; std::deque _entryCollection; }; CAF_DECLARE_SMART_POINTER(SIniSection); public: CIniFile(); virtual ~CIniFile(); public: void initialize(const std::string& configFilePath); std::deque getSectionCollection(); std::deque getEntryCollection( const std::string& sectionName); SmartPtrSIniEntry findOptionalEntry( const std::string& sectionName, const std::string& keyName); SmartPtrSIniEntry findRequiredEntry( const std::string& sectionName, const std::string& keyName); std::string findOptionalString( const std::string& sectionName, const std::string& keyName); std::string findRequiredString( const std::string& sectionName, const std::string& keyName); std::string findOptionalRawString( const std::string& sectionName, const std::string& keyName); std::string findRequiredRawString( const std::string& sectionName, const std::string& keyName); void log(); void setValue( const std::string& sectionName, const std::string& keyName, const std::string& value); void deleteValue( const std::string& sectionName, const std::string& keyName); private: struct SReplacement { SmartPtrCCafRegex _regex; std::string _value; }; CAF_DECLARE_SMART_POINTER(SReplacement); private: std::deque parse( const std::string& configFilePath) const; SmartPtrSReplacement createReplacement( const std::string& keyName, const std::string& value) const; SmartPtrSIniEntry createIniEntry( const std::string& keyName, const std::string& valueRaw, const std::string& valueExpanded) const; void parseValuePath( const std::string& valuePath, std::string& valueName, std::string& valueValue); private: bool _isInitialized; std::string _configFilePath; std::deque _sectionCollection; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CIniFile); }; CAF_DECLARE_SMART_POINTER(CIniFile); } #endif /* CINIFILE_H_ */ CLoggingSetter.h000066400000000000000000000010151321503522500351200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CLoggingSetter_h_ #define CLoggingSetter_h_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CLoggingSetter { public: CLoggingSetter(); virtual ~CLoggingSetter(); public: void initialize(const std::string& logDir); private: bool _isInitialized; bool _remapLoggingLocation; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CLoggingSetter); }; CAF_DECLARE_SMART_POINTER(CLoggingSetter); } #endif CLoggingUtils.h000066400000000000000000000022501321503522500347540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CLoggingUtils_H_ #define CLoggingUtils_H_ #ifndef WIN32 #include #include "Common/CLoggingUtils.h" #endif namespace Caf { class CLoggingUtils; CAF_DECLARE_SMART_POINTER(CLoggingUtils); class COMMONAGGREGATOR_LINKAGE CLoggingUtils { private: typedef std::map PropertyMap; public: static bool isConsoleAppenderUsed(); static void setStartupConfigFile( const std::string& configFile = "log4cpp_config", const std::string& logDir = std::string()); static std::string getConfigFile(); static void resetConfigFile(); static void setLogDir(const std::string& logDir); public: CLoggingUtils(); private: static SmartPtrCLoggingUtils getInstance(); static void loadConfig(const std::string& configFile); void loadProperties(); private: static GRecMutex _sOpMutex; static SmartPtrCLoggingUtils _sInstance; std::string _configFile; PropertyMap _properties; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CLoggingUtils); }; } #endif /* CLoggingUtils_H_ */ CManagedThreadPool.h000066400000000000000000000061301321503522500356640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Created on: May 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMANAGEDTHREADPOOL_H_ #define CMANAGEDTHREADPOOL_H_ #include "ICafObject.h" namespace Caf { /** * @author mdonahue * @brief This class wraps a GThreadPool and makes it a bit more friendly to use. It * also allows tasks to partially complete and be requeued. * The shutdown behavior is to wait for all active tasks to finish. Inactive * (unscheduled) tasks will be aborted. */ class COMMONAGGREGATOR_LINKAGE CManagedThreadPool { public: /** * @brief Interface for task objects */ struct __declspec(novtable) IThreadTask : public ICafObject { /** * @brief execute task * @retval true the task has completed its work and will be removed from the pool * @retval false the task has not completed its work and will be requeued in the pool */ virtual bool run() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IThreadTask); typedef std::deque TaskDeque; public: CManagedThreadPool(); virtual ~CManagedThreadPool(); /** * @brief initialize the thread pool * @param poolName a friendly name for the pool to aid in debugging * @param threadCount the number of task threads * @param taskUpdateInterval optional task queue refresh rate in milliseconds */ void init( const std::string& poolName, uint32 threadCount, uint32 taskUpdateInterval = 0); /** * @brief terminate the thread pool * All active tasks will be allowed to finish before this method returns */ void term(); /** * @brief add a task to the pool * @param task the task to add */ void enqueue(const SmartPtrIThreadTask& task); /** * @brief add a collection of tasks to the pool * @param tasks the tasks to add */ void enqueue(const TaskDeque& tasks); /** @brief A simple structure to report some statistics * */ struct Stats { /** The number of tasks under management */ uint32 taskCount; /** The number of tasks waiting to be assigned to threads for execution */ uint32 inactiveTaskCount; /** The number of tasks assigned to threads for execution */ uint32 activeTaskCount; /** The number of tasks that have completed execution */ uint32 completeTaskCount; /** The number of tasks that have executed but need to be requeued */ uint32 incompleteTaskCount; }; /** @return the current statistics */ Stats getStats() const; private: static gpointer poolWorkerFunc(gpointer context); static void taskWorkerFunc(gpointer threadContext, gpointer NOT_USED); private: void runPool(); private: /** Default task update interval in milliseconds */ static uint32 DEFAULT_TASK_UPDATE_INTERVAL; private: bool _isInitialized; volatile bool _isShuttingDown; std::string _poolName; GThreadPool *_threadPool; typedef std::set TaskSet; TaskSet _tasks; GThread* _workerThread; uint32 _taskUpdateInterval; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CManagedThreadPool); }; CAF_DECLARE_SMART_POINTER(CManagedThreadPool); } #endif /* CMANAGEDTHREADPOOL_H_ */ CThreadPool.h000066400000000000000000000034071321503522500344130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * CThreadPool.h * * Created on: May 9, 2012 * Author: mdonahue * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CTHREADPOOL_H_ #define CTHREADPOOL_H_ #include "ICafObject.h" #include "Common/CManagedThreadPool.h" namespace Caf { /** * @author mdonahue * @brief This class wraps a GThreadPool and makes it a bit more friendly to use. * This class wraps up a GThreadPool as a lifetime-managed object that can be shared. * The shutdown behavior is to wait for all tasks to finish. */ class COMMONAGGREGATOR_LINKAGE CThreadPool { public: /** * @brief This is the interface for tasks queued in this thread pool */ struct __declspec(novtable) IThreadTask : public ICafObject { /** * @brief execute task * @param userData the userData passed into the thread pool init() method */ virtual void run(gpointer userData) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IThreadTask); public: CThreadPool(); virtual ~CThreadPool(); /** * @brief Initialize the thread pool * @param userData opaque data to be passed to each thread * @param maxThreads the number of threads to create */ void init(gpointer userData, gint maxThreads); /** * @brief Terminate the thread pool * All tasks will be allowed to finish before this method returns */ void term(); /** * @brief Add a task to the thread pool * @param task interface to the task to add */ void addTask(const SmartPtrIThreadTask& task); private: static void ThreadFunc(gpointer data, gpointer userData); private: bool _isInitialized; GThreadPool *_threadPool; gpointer _userData; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CThreadPool); }; CAF_DECLARE_SMART_POINTER(CThreadPool); } #endif /* CTHREADPOOL_H_ */ CThreadSignal.h000066400000000000000000000027321321503522500347170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CThreadSignal_h_ #define CThreadSignal_h_ #include "Common/CThreadSignal.h" #include "Common/CAutoMutex.h" #include "Common/CAutoCondition.h" namespace Caf { // Class-level thread safety macros #define CAF_THREADSIGNAL_CREATE \ private: \ mutable SmartPtrCAutoMutex _threadsync_mutex_ #define CAF_THREADSIGNAL_INIT \ _threadsync_mutex_.CreateInstance(); \ _threadsync_mutex_->initialize() #define CAF_THREADSIGNAL_MUTEX \ _threadsync_mutex_ #define CAF_THREADSIGNAL_LOCK_UNLOCK \ Caf::CAutoMutexLockUnlock _threadsync_auto_lock(CAF_THREADSIGNAL_MUTEX) #define CAF_THREADSIGNAL_LOCK_UNLOCK_LOG \ Caf::CAutoMutexLockUnlock _threadsync_auto_lock(CAF_THREADSIGNAL_MUTEX, CAF_CM_GET_CLASSNAME, CAF_CM_GET_FUNCNAME) class COMMONAGGREGATOR_LINKAGE CThreadSignal { public: CThreadSignal(); virtual ~CThreadSignal(); public: void initialize(const std::string& conditionName); bool isInitialized() const; void signal(); void wait(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs); bool waitOrTimeout(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs); std::string getName() const; void close(); private: bool _isInitialized; CAutoCondition _condition; private: CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CThreadSignal); }; CAF_DECLARE_SMART_POINTER( CThreadSignal); } #endif // #ifndef CThreadSignal_h_ CVariant.h000066400000000000000000000027111321503522500337530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Created on: Jun 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVARIANT_H_ #define CVARIANT_H_ #include "IVariant.h" namespace Caf { /** * @brief A class that holds a GVariant* to manage its lifetime */ CAF_DECLARE_CLASS_AND_SMART_POINTER(CVariant); class COMMONAGGREGATOR_LINKAGE CVariant : public IVariant { public: CVariant(); virtual ~CVariant(); void set(GVariant *variant); public: // IVariant GVariant *get() const; std::string toString() const; bool isString() const; bool isBool() const; bool isUint8() const; bool isInt16() const; bool isUint16() const; bool isInt32() const; bool isUint32() const; bool isInt64() const; bool isUint64() const; public: static SmartPtrCVariant createString(const std::string& value); static SmartPtrCVariant createBool(const bool value); static SmartPtrCVariant createUint8(const uint8 value); static SmartPtrCVariant createInt16(const int16 value); static SmartPtrCVariant createUint16(const uint16 value); static SmartPtrCVariant createInt32(const int32 value); static SmartPtrCVariant createUint32(const uint32 value); static SmartPtrCVariant createInt64(const int64 value); static SmartPtrCVariant createUint64(const uint64 value); private: bool isType(const GVariantType * varType) const; private: GVariant *_variant; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CVariant); }; } #endif /* CVARIANT_H_ */ IAppConfig.h000066400000000000000000000051211321503522500342210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: mdonahue * Created: Jan 19, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef IAPPCONFIG_H_ #define IAPPCONFIG_H_ #include "Common/IConfigParams.h" #include "ICafObject.h" #include "Common/IAppConfig.h" namespace Caf { struct __declspec(novtable) IAppConfig : public ICafObject { CAF_DECL_UUID("e57f2252-ce11-4d15-9338-aa928333f7a3") virtual SmartPtrIConfigParams getParameters(const std::string& sectionName) = 0; virtual bool getString( const std::string& sectionName, const std::string& parameterName, std::string& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0; virtual bool getUint32( const std::string& sectionName, const std::string& parameterName, uint32& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0; virtual bool getInt32( const std::string& sectionName, const std::string& parameterName, int32& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0; virtual bool getBoolean( const std::string& sectionName, const std::string& parameterName, bool& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0; virtual bool getGlobalString( const std::string& parameterName, std::string& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0; virtual bool getGlobalUint32( const std::string& parameterName, uint32& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0; virtual bool getGlobalInt32( const std::string& parameterName, int32& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0; virtual bool getGlobalBoolean( const std::string& parameterName, bool& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED) = 0; virtual std::string resolveValue(const std::string& value) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IAppConfig); SmartPtrIAppConfig COMMONAGGREGATOR_LINKAGE getAppConfig(); SmartPtrIAppConfig COMMONAGGREGATOR_LINKAGE getAppConfig(const std::string& configFile); SmartPtrIAppConfig COMMONAGGREGATOR_LINKAGE getAppConfig(const Cdeqstr& configFileCollection); SmartPtrIAppConfig COMMONAGGREGATOR_LINKAGE getAppConfigAppend(const std::string& configFile); SmartPtrIAppConfig COMMONAGGREGATOR_LINKAGE getAppConfigAppend(const Cdeqstr& configFileCollection); } #endif /* IAPPCONFIG_H_ */ IAppConfigWrite.h000066400000000000000000000032111321503522500352320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: Jan 28, 2015 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef IAPPCONFIGWRITE_H_ #define IAPPCONFIGWRITE_H_ #include "Common/IAppConfigWrite.h" #include "ICafObject.h" namespace Caf { struct __declspec(novtable) IAppConfigWrite : public ICafObject { CAF_DECL_UUID("3cf708c6-b92d-46c3-83d8-edeccecf5ba4") virtual void setString( const std::string& sectionName, const std::string& parameterName, const std::string& value) = 0; virtual void setUint32( const std::string& sectionName, const std::string& parameterName, const uint32& value) = 0; virtual void setInt32( const std::string& sectionName, const std::string& parameterName, const int32& value) = 0; virtual void setBoolean( const std::string& sectionName, const std::string& parameterName, const bool& value) = 0; virtual void setGlobalString( const std::string& parameterName, const std::string& value) = 0; virtual void setGlobalUint32( const std::string& parameterName, const uint32& value) = 0; virtual void setGlobalInt32( const std::string& parameterName, const int32& value) = 0; virtual void setGlobalBoolean( const std::string& parameterName, const bool& value) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IAppConfigWrite); SmartPtrIAppConfigWrite COMMONAGGREGATOR_LINKAGE getAppConfigWrite(); SmartPtrIAppConfigWrite COMMONAGGREGATOR_LINKAGE getAppConfigWrite(const std::string& configFile); SmartPtrIAppConfigWrite COMMONAGGREGATOR_LINKAGE getAppConfigWrite(const Cdeqstr& configFileCollection); } #endif /* IAPPCONFIGWRITE_H_ */ IAppContext.h000066400000000000000000000012171321503522500344420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: mdonahue * Created: Jan 28, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef IAPPLICATIONCONTEXT_H_ #define IAPPLICATIONCONTEXT_H_ #include "ICafObject.h" #include "IBean.h" namespace Caf { struct __declspec(novtable) IAppContext : public ICafObject { CAF_DECL_UUID("f1d65e47-0f12-4301-861c-6a8c90099dae") // key=bean id typedef std::map CBeans; CAF_DECLARE_SMART_POINTER(CBeans); virtual SmartPtrIBean getBean(const std::string& name) const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IAppContext); } #endif /* IAPPLICATIONCONTEXT_H_ */ IConfigParams.h000066400000000000000000000012721321503522500347270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: mdonahue * Created: Jan 17, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef ICONFIGPARAMS_H_ #define ICONFIGPARAMS_H_ #include "Common/IConfigParams.h" namespace Caf { struct __declspec(novtable) IConfigParams : public ICafObject { typedef enum { PARAM_REQUIRED, PARAM_OPTIONAL } EParamDisposition; virtual GVariant* lookup( const char* key, const EParamDisposition disposition = PARAM_REQUIRED) const = 0; virtual std::string getSectionName() const = 0; virtual void insert(const char* key, GVariant* value) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IConfigParams); } #endif /* ICONFIGPARAMS_H_ */ IWork.h000066400000000000000000000011111321503522500332700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Common/* * Author: bwilliams * Created: June 29, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _CommonAggregator_IWork_h_ #define _CommonAggregator_IWork_h_ #include "ICafObject.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IWork : public ICafObject { CAF_DECL_UUID("76c269db-691f-439d-b47d-87ce55639c8f") public: // Read operations virtual void doWork() = 0; virtual void stopWork() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IWork); } #endif // #ifndef _CommonAggregator_IWork_h_ CommonDefines.h000066400000000000000000000022171321503522500335430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef COMMON_SYS_INC_COMMONDEFINES_H_ #define COMMON_SYS_INC_COMMONDEFINES_H_ #include namespace Caf { } // Aggregator #include "../src/Common/CommonAggregatorLink.h" //////////////////////////////////////////////////////////////////////// // endian ordering repair macros //////////////////////////////////////////////////////////////////////// #define CAF_FIX_16BIT_ENDIAN(x) x = (((x) >> 8) & 0xff) | ((x) << 8) #define CAF_FIX_32BIT_ENDIAN(x) x = (((x) >> 24) & 0xff) | (((x) >> 8) & 0xff00) | (((x) & 0xff00) << 8) | ((x) << 24) #define CAF_FIX_64BIT_ENDIAN(x) x = (((x) >> 56) & 0xff) | (((x) >> 40) & 0xff00) | (((x) >> 24) & 0xff0000) | \ (((x) >> 8) & 0xff000000) | (((x) & 0xff000000) << 8) | \ (((x) & 0xff0000) << 24) | (((x) & 0xff00) << 40) | \ ((x) << 56) #define CAF_FIX_GUID_ENDIAN(guid) CAF_FIX_32BIT_ENDIAN(guid.Data1); \ CAF_FIX_16BIT_ENDIAN(guid.Data2); \ CAF_FIX_16BIT_ENDIAN(guid.Data3) #endif /* COMMON_SYS_INC_COMMONDEFINES_H_ */ CommonGlobals.h000066400000000000000000000043361321503522500335550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include#ifndef CommonGlobals_h_ #define CommonGlobals_h_ #include "FrameworkLink.h" namespace Caf { extern FRAMEWORK_LINKAGE const char* _sConfigTmpDir; extern FRAMEWORK_LINKAGE const char* _sConfigInputDir; extern FRAMEWORK_LINKAGE const char* _sConfigOutputDir; extern FRAMEWORK_LINKAGE const char* _sConfigSchemaCacheDir; extern FRAMEWORK_LINKAGE const char* _sConfigProviderRegDir; extern FRAMEWORK_LINKAGE const char* _sConfigInstallDir; extern FRAMEWORK_LINKAGE const char* _sConfigInvokersDir; extern FRAMEWORK_LINKAGE const char* _sConfigProvidersDir; extern FRAMEWORK_LINKAGE const char* _sConfigCommonPackagesDir; extern FRAMEWORK_LINKAGE const char* _sConfigWorkingDir; extern FRAMEWORK_LINKAGE const char* _sConfigPrivateKeyFile; extern FRAMEWORK_LINKAGE const char* _sConfigCertFile; extern FRAMEWORK_LINKAGE const char* _sProviderHostArea; extern FRAMEWORK_LINKAGE const char* _sManagementAgentArea; extern FRAMEWORK_LINKAGE const char* _sSchemaSummaryFilename; extern FRAMEWORK_LINKAGE const char* _sProviderResponseFilename; extern FRAMEWORK_LINKAGE const char* _sStdoutFilename; extern FRAMEWORK_LINKAGE const char* _sStderrFilename; extern FRAMEWORK_LINKAGE const char* _sPayloadRequestFilename; extern FRAMEWORK_LINKAGE const char* _sResponseFilename; extern FRAMEWORK_LINKAGE const char* _sErrorResponseFilename; extern FRAMEWORK_LINKAGE const char* _sProviderRequestFilename; extern FRAMEWORK_LINKAGE const char* _sInfraErrFilename; // AppConfig common parameter names extern FRAMEWORK_LINKAGE const char* _sAppConfigGlobalParamRootDir; extern FRAMEWORK_LINKAGE const char* _sAppConfigGlobalParamDataDir; extern FRAMEWORK_LINKAGE const char* _sAppConfigGlobalParamLogDir; extern FRAMEWORK_LINKAGE const char* _sAppConfigGlobalParamLogConfigFile; extern FRAMEWORK_LINKAGE const char* _sAppConfigGlobalParamInputDir; extern FRAMEWORK_LINKAGE const char* _sAppConfigGlobalParamOutputDir; extern FRAMEWORK_LINKAGE const char* _sAppConfigGlobalParamDbDir; extern FRAMEWORK_LINKAGE const char* _sAppConfigGlobalThreadStackSizeKb; extern FRAMEWORK_LINKAGE const GUID CAFCOMMON_GUID_NULL; extern FRAMEWORK_LINKAGE const char* CAFCOMMON_PATH_DELIM; extern FRAMEWORK_LINKAGE const char CAFCOMMON_PATH_DELIM_CHAR; } #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/000077500000000000000000000000001321503522500326615ustar00rootroot00000000000000CafContracts.h000066400000000000000000000000001321503522500353130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/ContractsDoc/000077500000000000000000000000001321503522500333075ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/ContractsCafCoreTypesDoc/000077500000000000000000000000001321503522500362645ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCAddInCollectionDoc.h000066400000000000000000000000001321503522500421470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCAddInsDoc.h000066400000000000000000000000001321503522500403160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCAttachmentCollectionDoc.h000066400000000000000000000000001321503522500432600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCAttachmentDoc.h000066400000000000000000000000001321503522500412440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCAttachmentNameCollectionDoc.h000066400000000000000000000000001321503522500440610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCAuthnAuthzCollectionDoc.h000066400000000000000000000000001321503522500432630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCAuthnAuthzDoc.h000066400000000000000000000000001321503522500412470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCClassFiltersDoc.h000066400000000000000000000000001321503522500415520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCClassSpecifierDoc.h000066400000000000000000000000001321503522500420530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCFullyQualifiedClassGroupDoc.h000066400000000000000000000000001321503522500440760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCInlineAttachmentCollectionDoc.h000066400000000000000000000000001321503522500444170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCInlineAttachmentDoc.h000066400000000000000000000000001321503522500424030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCLoggingLevelCollectionDoc.h000066400000000000000000000000001321503522500435460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCLoggingLevelElemDoc.h000066400000000000000000000000001321503522500423350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCOperationDoc.h000066400000000000000000000000001321503522500411140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCParameterCollectionDoc.h000066400000000000000000000000001321503522500431100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCPropertyCollectionDoc.h000066400000000000000000000000001321503522500430140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCPropertyDoc.h000066400000000000000000000000001321503522500410000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCProtocolCollectionDoc.h000066400000000000000000000000001321503522500427710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCProtocolDoc.h000066400000000000000000000000001321503522500407550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCRequestConfigDoc.h000066400000000000000000000000001321503522500417320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCRequestHeaderDoc.h000066400000000000000000000000001321503522500417150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCRequestInstanceParameterDoc.h000066400000000000000000000000001321503522500441320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCRequestParameterDoc.h000066400000000000000000000000001321503522500424450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCStatisticsDoc.h000066400000000000000000000000001321503522500413060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCafCoreTypesDocInc.h000066400000000000000000000000001321503522500420320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafCoreTypesDocCafInstallRequestDoc/000077500000000000000000000000001321503522500373265ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCFullPackageElemDoc.h000066400000000000000000000000001321503522500431770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCGetInventoryJobDoc.h000066400000000000000000000000001321503522500433060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCInstallBatchDoc.h000066400000000000000000000000001321503522500425660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCInstallPackageSpecDoc.h000066400000000000000000000000001321503522500437130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCInstallProviderJobDoc.h000066400000000000000000000000001321503522500437720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCInstallProviderSpecDoc.h000066400000000000000000000000001321503522500441520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCInstallRequestDoc.h000066400000000000000000000000001321503522500431750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCMinPackageElemDoc.h000066400000000000000000000000001321503522500430200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCPackageDefnDoc.h000066400000000000000000000000001321503522500423460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCUninstallProviderJobDoc.h000066400000000000000000000000001321503522500443350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocCafInstallRequestDocInc.h000066400000000000000000000000001321503522500441360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/CafInstallRequestDocDiagRequestDoc/000077500000000000000000000000001321503522500361525ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCDiagRequestDoc.h000066400000000000000000000000001321503522500412570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagRequestDocDiagRequestDocInc.h000066400000000000000000000000001321503522500416060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagRequestDocDiagTypesDoc/000077500000000000000000000000001321503522500356265ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCDiagBatchDoc.h000066400000000000000000000000001321503522500403240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagTypesDocCDiagCollectInstancesDoc.h000066400000000000000000000000001321503522500425400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagTypesDocCDiagDeleteValueCollectionDoc.h000066400000000000000000000000001321503522500435160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagTypesDocCDiagDeleteValueDoc.h000066400000000000000000000000001321503522500415020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagTypesDocCDiagSetValueCollectionDoc.h000066400000000000000000000000001321503522500430470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagTypesDocCDiagSetValueDoc.h000066400000000000000000000000001321503522500410330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagTypesDocDiagTypesDocInc.h000066400000000000000000000000001321503522500407360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/DiagTypesDocMgmtRequestDoc/000077500000000000000000000000001321503522500362125ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCMgmtRequestDoc.h000066400000000000000000000000001321503522500413570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtRequestDocMgmtRequestDocInc.h000066400000000000000000000000001321503522500417060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtRequestDocMgmtTypesDoc/000077500000000000000000000000001321503522500356665ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCMgmtBatchDoc.h000066400000000000000000000000001321503522500404240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtTypesDocCMgmtCollectInstancesCollectionDoc.h000066400000000000000000000000001321503522500446540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtTypesDocCMgmtCollectInstancesDoc.h000066400000000000000000000000001321503522500426400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtTypesDocCMgmtCollectSchemaDoc.h000066400000000000000000000000001321503522500421110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtTypesDocCMgmtInvokeOperationCollectionDoc.h000066400000000000000000000000001321503522500445330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtTypesDocCMgmtInvokeOperationDoc.h000066400000000000000000000000001321503522500425170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtTypesDocMgmtTypesDocInc.h000066400000000000000000000000001321503522500410360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MgmtTypesDocMultiPmeMgmtRequestDoc/000077500000000000000000000000001321503522500376675ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCMultiPmeMgmtBatchCollectionDoc.h000066400000000000000000000000001321503522500461160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MultiPmeMgmtRequestDocCMultiPmeMgmtBatchDoc.h000066400000000000000000000000001321503522500441020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MultiPmeMgmtRequestDocCMultiPmeMgmtRequestDoc.h000066400000000000000000000000001321503522500445110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MultiPmeMgmtRequestDocCPmeIdCollectionDoc.h000066400000000000000000000000001321503522500435710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MultiPmeMgmtRequestDocMultiPmeMgmtRequestDocInc.h000066400000000000000000000000001321503522500450400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/MultiPmeMgmtRequestDocPayloadEnvelopeDoc/000077500000000000000000000000001321503522500370245ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCPayloadEnvelopeDoc.h000066400000000000000000000000001321503522500430030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PayloadEnvelopeDocPayloadEnvelopeDocInc.h000066400000000000000000000000001321503522500433320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PayloadEnvelopeDocPersistenceDoc/000077500000000000000000000000001321503522500362215ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCAmqpBrokerCollectionDoc.h000066400000000000000000000000001321503522500431700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocCAmqpBrokerDoc.h000066400000000000000000000000001321503522500411540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocCCertCollectionDoc.h000066400000000000000000000000001321503522500420220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocCCertPathCollectionDoc.h000066400000000000000000000000001321503522500426370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocCLocalSecurityDoc.h000066400000000000000000000000001321503522500416730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocCPersistenceDoc.h000066400000000000000000000000001321503522500413750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocCPersistenceProtocolDoc.h000066400000000000000000000000001321503522500431170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocCRemoteSecurityCollectionDoc.h000066400000000000000000000000001321503522500441100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocCRemoteSecurityDoc.h000066400000000000000000000000001321503522500420740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocPersistenceDocInc.h000066400000000000000000000000001321503522500417240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/PersistenceDocProviderInfraDoc/000077500000000000000000000000001321503522500365075ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCClassCollectionDoc.h000066400000000000000000000000001321503522500424600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderInfraDocCProviderRegDoc.h000066400000000000000000000000001321503522500416270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderInfraDocCSchemaSummaryDoc.h000066400000000000000000000000001321503522500421550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderInfraDocProviderInfraDocInc.h000066400000000000000000000000001321503522500425000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderInfraDocProviderRequestDoc/000077500000000000000000000000001321503522500371005ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCProviderBatchDoc.h000066400000000000000000000000001321503522500425240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocCProviderCollectInstancesCollectionDoc.h000066400000000000000000000000001321503522500467540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocCProviderCollectInstancesDoc.h000066400000000000000000000000001321503522500447400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocCProviderCollectSchemaRequestDoc.h000066400000000000000000000000001321503522500455620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocCProviderInvokeOperationCollectionDoc.h000066400000000000000000000000001321503522500466330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocCProviderInvokeOperationDoc.h000066400000000000000000000000001321503522500446170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocCProviderRequestConfigDoc.h000066400000000000000000000000001321503522500442610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocCProviderRequestDoc.h000066400000000000000000000000001321503522500431330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocCProviderRequestHeaderDoc.h000066400000000000000000000000001321503522500442440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocProviderRequestDocInc.h000066400000000000000000000000001321503522500434620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderRequestDocProviderResultsDoc/000077500000000000000000000000001321503522500371115ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCCdifDoc.h000066400000000000000000000000001321503522500406460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderResultsDocCDefinitionObjectCollectionDoc.h000066400000000000000000000000001321503522500452340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderResultsDocCRequestIdentifierDoc.h000066400000000000000000000000001321503522500434340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderResultsDocCSchemaDoc.h000066400000000000000000000000001321503522500412010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderResultsDocProviderResultsDocInc.h000066400000000000000000000000001321503522500435040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ProviderResultsDocResponseDoc/000077500000000000000000000000001321503522500355335ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCErrorResponseDoc.h000066400000000000000000000000001321503522500412330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCEventKeyCollectionDoc.h000066400000000000000000000000001321503522500421710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCEventKeyDoc.h000066400000000000000000000000001321503522500401550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCEventManifestDoc.h000066400000000000000000000000001321503522500411730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCManifestCollectionDoc.h000066400000000000000000000000001321503522500422050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCManifestDoc.h000066400000000000000000000000001321503522500401710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCProviderEventResponseDoc.h000066400000000000000000000000001321503522500427360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCProviderResponseDoc.h000066400000000000000000000000001321503522500417340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCResponseDoc.h000066400000000000000000000000001321503522500402210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocCResponseHeaderDoc.h000066400000000000000000000000001321503522500413320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocResponseDocInc.h000066400000000000000000000000001321503522500405500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/ResponseDocSchemaTypesDoc/000077500000000000000000000000001321503522500361625ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/DocCActionClassDoc.h000066400000000000000000000000001321503522500412550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCActionClassInstanceCollectionDoc.h000066400000000000000000000000001321503522500447560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCActionClassInstanceDoc.h000066400000000000000000000000001321503522500427420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCClassCardinalityDoc.h000066400000000000000000000000001321503522500423030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCClassFieldDoc.h000066400000000000000000000000001321503522500410630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCClassIdentifierDoc.h000066400000000000000000000000001321503522500421220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCClassInstancePropertyDoc.h000066400000000000000000000000001321503522500433510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCClassPropertyDoc.h000066400000000000000000000000001321503522500416640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCCmdlMetadataDoc.h000066400000000000000000000000001321503522500413720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCCmdlUnionDoc.h000066400000000000000000000000001321503522500407420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCCollectMethodDoc.h000066400000000000000000000000001321503522500416000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCDataClassDoc.h000066400000000000000000000000001321503522500407110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCDataClassInstanceCollectionDoc.h000066400000000000000000000000001321503522500444120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCDataClassInstanceDoc.h000066400000000000000000000000001321503522500423760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCDataClassPropertyDoc.h000066400000000000000000000000001321503522500424560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCDataClassSubInstanceDoc.h000066400000000000000000000000001321503522500430500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCInstanceOperationCollectionDoc.h000066400000000000000000000000001321503522500445130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCInstanceOperationDoc.h000066400000000000000000000000001321503522500424770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCInstanceParameterDoc.h000066400000000000000000000000001321503522500424570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCJoinTypeDoc.h000066400000000000000000000000001321503522500406130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCLogicalRelationshipDoc.h000066400000000000000000000000001321503522500430060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCMethodDoc.h000066400000000000000000000000001321503522500402720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCMethodParameterDoc.h000066400000000000000000000000001321503522500421330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCPhysicalRelationshipDoc.h000066400000000000000000000000001321503522500432100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocCRelationshipDoc.h000066400000000000000000000000001321503522500415130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocSchemaTypesDocInc.h000066400000000000000000000000001321503522500416260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Doc/SchemaTypesDocDocContracts.h000066400000000000000000000000001321503522500353270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contractsopen-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Fx/000077500000000000000000000000001321503522500332365ustar00rootroot00000000000000IBean.h000066400000000000000000000000001321503522500342740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/FxIVariant.h000066400000000000000000000000001321503522500350330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/FxFxContracts.h000066400000000000000000000000001321503522500351770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/ContractsIntegration/000077500000000000000000000000001321503522500350655ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/ContractsDependencies/000077500000000000000000000000001321503522500374535ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationCPollerMetadata.h000066400000000000000000000000001321503522500426130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Integration/DependenciesIChannelInterceptor.h000066400000000000000000000000001321503522500411240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIChannelInterceptorInstance.h000066400000000000000000000000001321503522500426110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIChannelInterceptorSupport.h000066400000000000000000000000001321503522500425210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIChannelResolver.h000066400000000000000000000000001321503522500404270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIDocument.h000066400000000000000000000000001321503522500371130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIErrorHandler.h000066400000000000000000000000001321503522500377240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIErrorProcessor.h000066400000000000000000000000001321503522500403260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIExpressionInvoker.h000066400000000000000000000000001321503522500410320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIIntMessage.h000066400000000000000000000000001321503522500373740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIIntegrationAppContext.h000066400000000000000000000000001321503522500416260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIIntegrationAppContextAware.h000066400000000000000000000000001321503522500426060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIIntegrationComponent.h000066400000000000000000000000001321503522500415030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIIntegrationComponentInstance.h000066400000000000000000000000001321503522500431700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIIntegrationObject.h000066400000000000000000000000001321503522500407470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationILifecycle.h000066400000000000000000000000001321503522500372340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIMessageChannel.h000066400000000000000000000000001321503522500402120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIMessageDispatcher.h000066400000000000000000000000001321503522500407300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIMessageHandler.h000066400000000000000000000000001321503522500402170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIMessageProcessor.h000066400000000000000000000000001321503522500406210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIMessageProducer.h000066400000000000000000000000001321503522500404250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIMessageRouter.h000066400000000000000000000000001321503522500401220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIMessageSplitter.h000066400000000000000000000000001321503522500404500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIPhased.h000066400000000000000000000000001321503522500365410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIPollableChannel.h000066400000000000000000000000001321503522500403600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIRunnable.h000066400000000000000000000000001321503522500371030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationISmartLifecycle.h000066400000000000000000000000001321503522500402430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationISubscribableChannel.h000066400000000000000000000000001321503522500412260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationITaskExecutor.h000066400000000000000000000000001321503522500377560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIThrowable.h000066400000000000000000000000001321503522500372640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationITransformer.h000066400000000000000000000000001321503522500376370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/IntegrationIntegrationContracts.h000066400000000000000000000000001321503522500371050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/ContractsIntegrationContractsDefines.h000066400000000000000000000000001321503522500404030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contractsopen-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/Ma/000077500000000000000000000000001321503522500332165ustar00rootroot00000000000000IConfigEnv.h000066400000000000000000000000001321503522500352650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/MaIPersistence.h000066400000000000000000000000001321503522500356730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contracts/MaMaContracts.h000066400000000000000000000000001321503522500351570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Contractsopen-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/000077500000000000000000000000001321503522500314265ustar00rootroot00000000000000CafCoreTypesDoc/000077500000000000000000000000001321503522500343245ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCAddInCollectionDoc.h000066400000000000000000000016671321503522500402330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CAddInCollectionDoc_h_ #define CAddInCollectionDoc_h_ namespace Caf { /// A simple container for objects of type AddInCollection class CAFCORETYPESDOC_LINKAGE CAddInCollectionDoc { public: CAddInCollectionDoc(); virtual ~CAddInCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque addInCollection = std::deque()); public: /// Accessor for the AddIn std::deque getAddInCollection() const; private: bool _isInitialized; std::deque _addInCollection; private: CAF_CM_DECLARE_NOCOPY(CAddInCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CAddInCollectionDoc); } #endif CAddInsDoc.h000066400000000000000000000017601321503522500363740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CAddInsDoc_h_ #define CAddInsDoc_h_ #include "Doc/CafCoreTypesDoc/CAddInCollectionDoc.h" namespace Caf { /// A simple container for objects of type AddIns class CAFCORETYPESDOC_LINKAGE CAddInsDoc { public: CAddInsDoc(); virtual ~CAddInsDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque addInCollection = std::deque()); public: /// Accessor for the AddInCollection std::deque getAddInCollection() const; private: bool _isInitialized; std::deque _addInCollection; private: CAF_CM_DECLARE_NOCOPY(CAddInsDoc); }; CAF_DECLARE_SMART_POINTER(CAddInsDoc); } #endif CAttachmentCollectionDoc.h000066400000000000000000000026051321503522500413350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CAttachmentCollectionDoc_h_ #define CAttachmentCollectionDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" namespace Caf { /// A simple container for objects of type AttachmentCollection class CAFCORETYPESDOC_LINKAGE CAttachmentCollectionDoc { public: CAttachmentCollectionDoc(); virtual ~CAttachmentCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque attachment = std::deque(), const std::deque inlineAttachment = std::deque()); public: /// Accessor for the Attachment std::deque getAttachment() const; /// Accessor for the InlineAttachment std::deque getInlineAttachment() const; private: bool _isInitialized; std::deque _attachment; std::deque _inlineAttachment; private: CAF_CM_DECLARE_NOCOPY(CAttachmentCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CAttachmentCollectionDoc); } #endif CAttachmentDoc.h000066400000000000000000000024741321503522500373250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CAttachmentDoc_h_ #define CAttachmentDoc_h_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" namespace Caf { /// A simple container for objects of type Attachment class CAFCORETYPESDOC_LINKAGE CAttachmentDoc { public: CAttachmentDoc(); virtual ~CAttachmentDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::string type, const std::string uri, const bool isReference, const CMS_POLICY cmsPolicy = CMS_POLICY_CAF_ENCRYPTED_AND_SIGNED); public: /// Accessor for the Name std::string getName() const; /// Accessor for the Type std::string getType() const; /// Accessor for the Uri std::string getUri() const; /// Accessor for the IsReference bool getIsReference() const; /// Accessor for the CMS Policy CMS_POLICY getCmsPolicy() const; private: bool _isInitialized; std::string _name; std::string _type; std::string _uri; bool _isReference; CMS_POLICY _cmsPolicy; private: CAF_CM_DECLARE_NOCOPY(CAttachmentDoc); }; CAF_DECLARE_SMART_POINTER(CAttachmentDoc); } #endif CAttachmentNameCollectionDoc.h000066400000000000000000000017351321503522500421410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CAttachmentNameCollectionDoc_h_ #define CAttachmentNameCollectionDoc_h_ namespace Caf { /// A simple container for objects of type AttachmentNameCollection class CAFCORETYPESDOC_LINKAGE CAttachmentNameCollectionDoc { public: CAttachmentNameCollectionDoc(); virtual ~CAttachmentNameCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque name = std::deque()); public: /// Accessor for the Name std::deque getName() const; private: bool _isInitialized; std::deque _name; private: CAF_CM_DECLARE_NOCOPY(CAttachmentNameCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CAttachmentNameCollectionDoc); } #endif CAuthnAuthzCollectionDoc.h000066400000000000000000000021041321503522500413320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CAuthnAuthzCollectionDoc_h_ #define CAuthnAuthzCollectionDoc_h_ #include "Doc/CafCoreTypesDoc/CAuthnAuthzDoc.h" namespace Caf { /// Set of logging levels for different components class CAFCORETYPESDOC_LINKAGE CAuthnAuthzCollectionDoc { public: CAuthnAuthzCollectionDoc(); virtual ~CAuthnAuthzCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque authnAuthz = std::deque()); public: /// Used to change the logging level for a specific component std::deque getAuthnAuthz() const; private: bool _isInitialized; std::deque _authnAuthz; private: CAF_CM_DECLARE_NOCOPY(CAuthnAuthzCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CAuthnAuthzCollectionDoc); } #endif CAuthnAuthzDoc.h000066400000000000000000000022171321503522500373230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: May 24, 2015 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CAuthnAuthzDoc_h_ #define CAuthnAuthzDoc_h_ namespace Caf { /// A simple container for objects of type AuthnAuthz class CAFCORETYPESDOC_LINKAGE CAuthnAuthzDoc { public: CAuthnAuthzDoc(); virtual ~CAuthnAuthzDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string type, const std::string value, const std::string name = std::string(), const int32 sequenceNumber = 0); public: /// Accessor for the Type std::string getType() const; /// Accessor for the Value std::string getValue() const; /// Accessor for the Name std::string getName() const; /// Accessor for the SequenceNumber int32 getSequenceNumber() const; private: bool _isInitialized; std::string _type; std::string _value; std::string _name; int32 _sequenceNumber; private: CAF_CM_DECLARE_NOCOPY(CAuthnAuthzDoc); }; CAF_DECLARE_SMART_POINTER(CAuthnAuthzDoc); } #endif CClassFiltersDoc.h000066400000000000000000000020351321503522500376240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CClassFiltersDoc_h_ #define CClassFiltersDoc_h_ namespace Caf { /// A simple container for objects of type ClassFilters class CAFCORETYPESDOC_LINKAGE CClassFiltersDoc { public: CClassFiltersDoc(); virtual ~CClassFiltersDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string dialect = std::string(), const std::deque classFilter = std::deque()); public: /// Accessor for the Dialect std::string getDialect() const; /// Accessor for the ClassFilter std::deque getClassFilter() const; private: bool _isInitialized; std::string _dialect; std::deque _classFilter; private: CAF_CM_DECLARE_NOCOPY(CClassFiltersDoc); }; CAF_DECLARE_SMART_POINTER(CClassFiltersDoc); } #endif CClassSpecifierDoc.h000066400000000000000000000024731321503522500401330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CClassSpecifierDoc_h_ #define CClassSpecifierDoc_h_ #include "Doc/CafCoreTypesDoc/CClassFiltersDoc.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" namespace Caf { /// A simple container for objects of type ClassSpecifier class CAFCORETYPESDOC_LINKAGE CClassSpecifierDoc { public: CClassSpecifierDoc(); virtual ~CClassSpecifierDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClass = SmartPtrCFullyQualifiedClassGroupDoc(), const SmartPtrCClassFiltersDoc classFilters = SmartPtrCClassFiltersDoc()); public: /// Accessor for the FullyQualifiedClass SmartPtrCFullyQualifiedClassGroupDoc getFullyQualifiedClass() const; /// Accessor for the ClassFilters SmartPtrCClassFiltersDoc getClassFilters() const; private: bool _isInitialized; SmartPtrCFullyQualifiedClassGroupDoc _fullyQualifiedClass; SmartPtrCClassFiltersDoc _classFilters; private: CAF_CM_DECLARE_NOCOPY(CClassSpecifierDoc); }; CAF_DECLARE_SMART_POINTER(CClassSpecifierDoc); } #endif CFullyQualifiedClassGroupDoc.h000066400000000000000000000023111321503522500421450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CFullyQualifiedClassGroupDoc_h_ #define CFullyQualifiedClassGroupDoc_h_ namespace Caf { /// A simple container for objects of type FullyQualifiedClassGroup class CAFCORETYPESDOC_LINKAGE CFullyQualifiedClassGroupDoc { public: CFullyQualifiedClassGroupDoc(); virtual ~CFullyQualifiedClassGroupDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string classNamespace, const std::string className, const std::string classVersion); public: /// Accessor for the ClassNamespace std::string getClassNamespace() const; /// Accessor for the ClassName std::string getClassName() const; /// Accessor for the ClassVersion std::string getClassVersion() const; private: bool _isInitialized; std::string _classNamespace; std::string _className; std::string _classVersion; private: CAF_CM_DECLARE_NOCOPY(CFullyQualifiedClassGroupDoc); }; CAF_DECLARE_SMART_POINTER(CFullyQualifiedClassGroupDoc); } #endif CInlineAttachmentCollectionDoc.h000066400000000000000000000022151321503522500424710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInlineAttachmentCollectionDoc_h_ #define CInlineAttachmentCollectionDoc_h_ #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" namespace Caf { /// A simple container for objects of type InlineAttachmentCollection class CAFCORETYPESDOC_LINKAGE CInlineAttachmentCollectionDoc { public: CInlineAttachmentCollectionDoc(); virtual ~CInlineAttachmentCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque attachment = std::deque()); public: /// Accessor for the InlineAttachment std::deque getInlineAttachment() const; private: bool _isInitialized; std::deque _attachment; private: CAF_CM_DECLARE_NOCOPY(CInlineAttachmentCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CInlineAttachmentCollectionDoc); } #endif CInlineAttachmentDoc.h000066400000000000000000000020611321503522500404540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInlineAttachmentDoc_h_ #define CInlineAttachmentDoc_h_ namespace Caf { /// A simple container for objects of type InlineAttachment class CAFCORETYPESDOC_LINKAGE CInlineAttachmentDoc { public: CInlineAttachmentDoc(); virtual ~CInlineAttachmentDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::string type, const std::string value); public: /// Accessor for the Name std::string getName() const; /// Accessor for the Type std::string getType() const; /// Accessor for the Value std::string getValue() const; private: bool _isInitialized; std::string _name; std::string _type; std::string _value; private: CAF_CM_DECLARE_NOCOPY(CInlineAttachmentDoc); }; CAF_DECLARE_SMART_POINTER(CInlineAttachmentDoc); } #endif CLoggingLevelCollectionDoc.h000066400000000000000000000021661321503522500416250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CLoggingLevelCollectionDoc_h_ #define CLoggingLevelCollectionDoc_h_ #include "Doc/CafCoreTypesDoc/CLoggingLevelElemDoc.h" namespace Caf { /// Set of logging levels for different components class CAFCORETYPESDOC_LINKAGE CLoggingLevelCollectionDoc { public: CLoggingLevelCollectionDoc(); virtual ~CLoggingLevelCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque loggingLevel = std::deque()); public: /// Used to change the logging level for a specific component std::deque getLoggingLevel() const; private: bool _isInitialized; std::deque _loggingLevel; private: CAF_CM_DECLARE_NOCOPY(CLoggingLevelCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CLoggingLevelCollectionDoc); } #endif CLoggingLevelElemDoc.h000066400000000000000000000021641321503522500404120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CLoggingLevelElemDoc_h_ #define CLoggingLevelElemDoc_h_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" namespace Caf { /// Logging level for a component class CAFCORETYPESDOC_LINKAGE CLoggingLevelElemDoc { public: CLoggingLevelElemDoc(); virtual ~CLoggingLevelElemDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const LOGGINGCOMPONENT_TYPE component = LOGGINGCOMPONENT_NONE, const LOGGINGLEVEL_TYPE level = LOGGINGLEVEL_NONE); public: /// The logging level applies to this component LOGGINGCOMPONENT_TYPE getComponent() const; /// Set the logging level to this value LOGGINGLEVEL_TYPE getLevel() const; private: LOGGINGCOMPONENT_TYPE _component; LOGGINGLEVEL_TYPE _level; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CLoggingLevelElemDoc); }; CAF_DECLARE_SMART_POINTER(CLoggingLevelElemDoc); } #endif COperationDoc.h000066400000000000000000000021441321503522500371670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef COperationDoc_h_ #define COperationDoc_h_ #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" namespace Caf { /// A simple container for objects of type Operation class CAFCORETYPESDOC_LINKAGE COperationDoc { public: COperationDoc(); virtual ~COperationDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const SmartPtrCParameterCollectionDoc parameterCollection = SmartPtrCParameterCollectionDoc()); public: /// Accessor for the Name std::string getName() const; /// Accessor for the ParameterCollection SmartPtrCParameterCollectionDoc getParameterCollection() const; private: bool _isInitialized; std::string _name; SmartPtrCParameterCollectionDoc _parameterCollection; private: CAF_CM_DECLARE_NOCOPY(COperationDoc); }; CAF_DECLARE_SMART_POINTER(COperationDoc); } #endif CParameterCollectionDoc.h000066400000000000000000000027031321503522500411640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CParameterCollectionDoc_h_ #define CParameterCollectionDoc_h_ #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" namespace Caf { /// A simple container for objects of type ParameterCollection class CAFCORETYPESDOC_LINKAGE CParameterCollectionDoc { public: CParameterCollectionDoc(); virtual ~CParameterCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque parameter = std::deque(), const std::deque instanceParameter = std::deque()); public: /// Accessor for the Parameter std::deque getParameter() const; /// Accessor for the InstanceParameter std::deque getInstanceParameter() const; private: bool _isInitialized; std::deque _parameter; std::deque _instanceParameter; private: CAF_CM_DECLARE_NOCOPY(CParameterCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CParameterCollectionDoc); } #endif CPropertyCollectionDoc.h000066400000000000000000000020211321503522500410610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CPropertyCollectionDoc_h_ #define CPropertyCollectionDoc_h_ #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" namespace Caf { /// A simple container for objects of type PropertyCollection class CAFCORETYPESDOC_LINKAGE CPropertyCollectionDoc { public: CPropertyCollectionDoc(); virtual ~CPropertyCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque property = std::deque()); public: /// Accessor for the Property std::deque getProperty() const; private: bool _isInitialized; std::deque _property; private: CAF_CM_DECLARE_NOCOPY(CPropertyCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CPropertyCollectionDoc); } #endif CPropertyDoc.h000066400000000000000000000021561321503522500370560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CPropertyDoc_h_ #define CPropertyDoc_h_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" namespace Caf { /// A simple container for objects of type Property class CAFCORETYPESDOC_LINKAGE CPropertyDoc { public: CPropertyDoc(); virtual ~CPropertyDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const PROPERTY_TYPE type, const std::deque value = std::deque()); public: /// Accessor for the Name std::string getName() const; /// Accessor for the Type PROPERTY_TYPE getType() const; /// Accessor for the Value std::deque getValue() const; private: PROPERTY_TYPE _type; bool _isInitialized; std::string _name; std::deque _value; private: CAF_CM_DECLARE_NOCOPY(CPropertyDoc); }; CAF_DECLARE_SMART_POINTER(CPropertyDoc); } #endif CProtocolCollectionDoc.h000066400000000000000000000020071321503522500410420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProtocolCollectionDoc_h_ #define CProtocolCollectionDoc_h_ #include "Doc/CafCoreTypesDoc/CProtocolDoc.h" namespace Caf { /// Set of protocol class CAFCORETYPESDOC_LINKAGE CProtocolCollectionDoc { public: CProtocolCollectionDoc(); virtual ~CProtocolCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque protocol = std::deque()); public: /// Used to change the logging level for a specific component std::deque getProtocol() const; private: bool _isInitialized; std::deque _protocol; private: CAF_CM_DECLARE_NOCOPY(CProtocolCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CProtocolCollectionDoc); } #endif CProtocolDoc.h000066400000000000000000000020051321503522500370240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProtocolDoc_h_ #define CProtocolDoc_h_ namespace Caf { /// A simple container for objects of Protocol class CAFCORETYPESDOC_LINKAGE CProtocolDoc { public: CProtocolDoc(); virtual ~CProtocolDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string uri, const std::string name = std::string(), const int32 sequenceNumber = 0); public: /// Accessor for the Uri std::string getUri() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Value int32 getSequenceNumber() const; private: int32 _sequenceNumber; bool _isInitialized; std::string _uri; std::string _name; private: CAF_CM_DECLARE_NOCOPY(CProtocolDoc); }; CAF_DECLARE_SMART_POINTER(CProtocolDoc); } #endif CRequestConfigDoc.h000066400000000000000000000032771321503522500400150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CRequestConfigDoc_h_ #define CRequestConfigDoc_h_ #include "Doc/CafCoreTypesDoc/CAddInsDoc.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" namespace Caf { /// A simple container for objects of type RequestConfig class CAFCORETYPESDOC_LINKAGE CRequestConfigDoc { public: CRequestConfigDoc(); virtual ~CRequestConfigDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string responseFormatType, const SmartPtrCAddInsDoc requestProcessorAddIns = SmartPtrCAddInsDoc(), const SmartPtrCAddInsDoc responseProcessorAddIns = SmartPtrCAddInsDoc(), const SmartPtrCLoggingLevelCollectionDoc loggingLevelCollection = SmartPtrCLoggingLevelCollectionDoc()); public: /// Accessor for the ResponseFormatType std::string getResponseFormatType() const; /// Accessor for the RequestProcessorAddIns SmartPtrCAddInsDoc getRequestProcessorAddIns() const; /// Accessor for the ResponseProcessorAddIns SmartPtrCAddInsDoc getResponseProcessorAddIns() const; /// Accessor for the LoggingLevelCollection SmartPtrCLoggingLevelCollectionDoc getLoggingLevelCollection() const; private: bool _isInitialized; std::string _responseFormatType; SmartPtrCAddInsDoc _requestProcessorAddIns; SmartPtrCAddInsDoc _responseProcessorAddIns; SmartPtrCLoggingLevelCollectionDoc _loggingLevelCollection; private: CAF_CM_DECLARE_NOCOPY(CRequestConfigDoc); }; CAF_DECLARE_SMART_POINTER(CRequestConfigDoc); } #endif CRequestHeaderDoc.h000066400000000000000000000045141321503522500377730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CRequestHeaderDoc_h_ #define CRequestHeaderDoc_h_ #include "Doc/CafCoreTypesDoc/CAuthnAuthzCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestConfigDoc.h" namespace Caf { /// A simple container for objects of type RequestHeader class CAFCORETYPESDOC_LINKAGE CRequestHeaderDoc { public: CRequestHeaderDoc(); virtual ~CRequestHeaderDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCRequestConfigDoc requestConfig, const SmartPtrCAuthnAuthzCollectionDoc authnAuthzCollection = SmartPtrCAuthnAuthzCollectionDoc(), const SmartPtrCProtocolCollectionDoc protocolCollection = SmartPtrCProtocolCollectionDoc(), const SmartPtrCPropertyCollectionDoc echoPropertyBag = SmartPtrCPropertyCollectionDoc(), const std::string version = "1.0", const std::string createdDateTime = CDateTimeUtils::getCurrentDateTime(), const UUID sessionId = CAFCOMMON_GUID_NULL); public: /// Accessor for the RequestConfig SmartPtrCRequestConfigDoc getRequestConfig() const; /// Accessor for the Authentication / Authorization Collection SmartPtrCAuthnAuthzCollectionDoc getAuthnAuthzCollection() const; /// Accessor for the Protocol Collection SmartPtrCProtocolCollectionDoc getProtocolCollection() const; /// Accessor for the EchoPropertyBag SmartPtrCPropertyCollectionDoc getEchoPropertyBag() const; /// Accessor for the version std::string getVersion() const; /// Accessor for the date/time when the request was created std::string getCreatedDateTime() const; /// Accessor for the session ID UUID getSessionId() const; private: bool _isInitialized; SmartPtrCRequestConfigDoc _requestConfig; SmartPtrCAuthnAuthzCollectionDoc _authnAuthzCollection; SmartPtrCProtocolCollectionDoc _protocolCollection; SmartPtrCPropertyCollectionDoc _echoPropertyBag; std::string _version; std::string _createdDateTime; UUID _sessionId; private: CAF_CM_DECLARE_NOCOPY(CRequestHeaderDoc); }; CAF_DECLARE_SMART_POINTER(CRequestHeaderDoc); } #endif CRequestInstanceParameterDoc.h000066400000000000000000000027011321503522500422040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CRequestInstanceParameterDoc_h_ #define CRequestInstanceParameterDoc_h_ namespace Caf { /// A simple container for objects of type RequestInstanceParameter class CAFCORETYPESDOC_LINKAGE CRequestInstanceParameterDoc { public: CRequestInstanceParameterDoc(); virtual ~CRequestInstanceParameterDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::string classNamespace, const std::string className, const std::string classVersion, const std::deque value); public: /// Accessor for the Name std::string getName() const; /// Accessor for the ClassNamespace std::string getClassNamespace() const; /// Accessor for the ClassName std::string getClassName() const; /// Accessor for the ClassVersion std::string getClassVersion() const; /// Accessor for the Value std::deque getValue() const; private: bool _isInitialized; std::string _name; std::string _classNamespace; std::string _className; std::string _classVersion; std::deque _value; private: CAF_CM_DECLARE_NOCOPY(CRequestInstanceParameterDoc); }; CAF_DECLARE_SMART_POINTER(CRequestInstanceParameterDoc); } #endif CRequestParameterDoc.h000066400000000000000000000022251321503522500405200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CRequestParameterDoc_h_ #define CRequestParameterDoc_h_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" namespace Caf { /// A simple container for objects of type RequestParameter class CAFCORETYPESDOC_LINKAGE CRequestParameterDoc { public: CRequestParameterDoc(); virtual ~CRequestParameterDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const PARAMETER_TYPE type, const std::deque value); public: /// Accessor for the Name std::string getName() const; /// Accessor for the Type PARAMETER_TYPE getType() const; /// Accessor for the Value std::deque getValue() const; private: PARAMETER_TYPE _type; bool _isInitialized; std::string _name; std::deque _value; private: CAF_CM_DECLARE_NOCOPY(CRequestParameterDoc); }; CAF_DECLARE_SMART_POINTER(CRequestParameterDoc); } #endif CStatisticsDoc.h000066400000000000000000000033031321503522500373570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CStatisticsDoc_h_ #define CStatisticsDoc_h_ #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" namespace Caf { /// A simple container for objects of type Statistics class CAFCORETYPESDOC_LINKAGE CStatisticsDoc { public: CStatisticsDoc(); virtual ~CStatisticsDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCPropertyCollectionDoc propertyCollection, const int32 providerJobNum, const int32 providerJobTotal, const int32 providerJobDurationSecs, const int32 pmeNum, const int32 pmeTotal, const int32 pmeDurationSecs); public: /// Accessor for the PropertyCollection SmartPtrCPropertyCollectionDoc getPropertyCollection() const; /// Accessor for the ProviderJobNum int32 getProviderJobNum() const; /// Accessor for the ProviderJobTotal int32 getProviderJobTotal() const; /// Accessor for the ProviderJobDurationSecs int32 getProviderJobDurationSecs() const; /// Accessor for the PmeNum int32 getPmeNum() const; /// Accessor for the PmeTotal int32 getPmeTotal() const; /// Accessor for the PmeDurationSecs int32 getPmeDurationSecs() const; private: SmartPtrCPropertyCollectionDoc _propertyCollection; int32 _providerJobNum; int32 _providerJobTotal; int32 _providerJobDurationSecs; int32 _pmeNum; int32 _pmeTotal; int32 _pmeDurationSecs; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CStatisticsDoc); }; CAF_DECLARE_SMART_POINTER(CStatisticsDoc); } #endif CafCoreTypesDocLink.h000066400000000000000000000010611321503522500402660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CafCoreTypesDoc_Link_h_ #define CafCoreTypesDoc_Link_h_ #ifndef CAFCORETYPESDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define CAFCORETYPESDOC_LINKAGE __declspec(dllexport) #else #define CAFCORETYPESDOC_LINKAGE __declspec(dllimport) #endif #else #define CAFCORETYPESDOC_LINKAGE #endif #endif #endif /* CafCoreTypesDoc_Link_h_ */ CafCoreTypesDocTypes.h000066400000000000000000000026131321503522500405010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAFCORETYPESDOCTYPES_H_ #define CAFCORETYPESDOCTYPES_H_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" namespace Caf { typedef enum { PROPERTY_NONE, PROPERTY_STRING, PROPERTY_SINT32, PROPERTY_UINT32, PROPERTY_SINT64, PROPERTY_UINT64, PROPERTY_DECIMAL, PROPERTY_DOUBLE, PROPERTY_BOOLEAN, PROPERTY_DATETIME } PROPERTY_TYPE; typedef enum { PARAMETER_NONE, PARAMETER_STRING, PARAMETER_SINT32, PARAMETER_UINT32, PARAMETER_SINT64, PARAMETER_UINT64, PARAMETER_DECIMAL, PARAMETER_DOUBLE, PARAMETER_BOOLEAN, PARAMETER_DATETIME } PARAMETER_TYPE; typedef enum { LOGGINGLEVEL_NONE, LOGGINGLEVEL_DEBUG, LOGGINGLEVEL_INFO, LOGGINGLEVEL_WARN, LOGGINGLEVEL_ERROR, LOGGINGLEVEL_CRITICAL } LOGGINGLEVEL_TYPE; typedef enum { LOGGINGCOMPONENT_NONE, LOGGINGCOMPONENT_COMMUNICATIONS, LOGGINGCOMPONENT_MANAGEMENTAGENT, LOGGINGCOMPONENT_UINT32, LOGGINGCOMPONENT_PROVIDERFRAMEWORK, LOGGINGCOMPONENT_PROVIDER } LOGGINGCOMPONENT_TYPE; typedef enum { CMS_POLICY_NONE, CMS_POLICY_CAF_ENCRYPTED, CMS_POLICY_CAF_SIGNED, CMS_POLICY_CAF_ENCRYPTED_AND_SIGNED, CMS_POLICY_APP_SIGNED, CMS_POLICY_APP_ENCRYPTED, CMS_POLICY_APP_ENCRYPTED_AND_SIGNED } CMS_POLICY; } #endif /* CAFCORETYPESDOCTYPES_H_ */ CafInstallRequestDoc/000077500000000000000000000000001321503522500353665ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCFullPackageElemDoc.h000066400000000000000000000032371321503522500412560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CFullPackageElemDoc_h_ #define CFullPackageElemDoc_h_ #include "Doc/CafInstallRequestDoc/CPackageDefnDoc.h" namespace Caf { /// A simple container for objects of type FullPackageElem class CAFINSTALLREQUESTDOC_LINKAGE CFullPackageElemDoc { public: CFullPackageElemDoc(); virtual ~CFullPackageElemDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const int32 index, const std::string packageNamespace, const std::string packageName, const std::string packageVersion, const SmartPtrCPackageDefnDoc installPackage, const SmartPtrCPackageDefnDoc uninstallPackage); public: /// Accessor for the Index int32 getIndex() const; /// Accessor for the PackageNamespace std::string getPackageNamespace() const; /// Accessor for the PackageName std::string getPackageName() const; /// Accessor for the PackageVersion std::string getPackageVersion() const; /// Accessor for the InstallPackage SmartPtrCPackageDefnDoc getInstallPackage() const; /// Accessor for the UninstallPackage SmartPtrCPackageDefnDoc getUninstallPackage() const; private: int32 _index; std::string _packageNamespace; std::string _packageName; std::string _packageVersion; SmartPtrCPackageDefnDoc _installPackage; SmartPtrCPackageDefnDoc _uninstallPackage; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CFullPackageElemDoc); }; CAF_DECLARE_SMART_POINTER(CFullPackageElemDoc); } #endif CGetInventoryJobDoc.h000066400000000000000000000015101321503522500413550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CGetInventoryJobDoc_h_ #define CGetInventoryJobDoc_h_ namespace Caf { /// A simple container for objects of type GetInventoryJob class CAFINSTALLREQUESTDOC_LINKAGE CGetInventoryJobDoc { public: CGetInventoryJobDoc(); virtual ~CGetInventoryJobDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID jobId); public: /// Accessor for the JobId UUID getJobId() const; private: UUID _jobId; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CGetInventoryJobDoc); }; CAF_DECLARE_SMART_POINTER(CGetInventoryJobDoc); } #endif CInstallBatchDoc.h000066400000000000000000000027621321503522500406470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInstallBatchDoc_h_ #define CInstallBatchDoc_h_ #include "Doc/CafInstallRequestDoc/CGetInventoryJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" namespace Caf { /// A simple container for objects of type InstallBatch class CAFINSTALLREQUESTDOC_LINKAGE CInstallBatchDoc { public: CInstallBatchDoc(); virtual ~CInstallBatchDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCGetInventoryJobDoc getInventory, const SmartPtrCInstallProviderJobDoc installProvider, const SmartPtrCUninstallProviderJobDoc uninstallProvider); public: /// Accessor for the GetInventory SmartPtrCGetInventoryJobDoc getGetInventory() const; /// Accessor for the InstallProvider SmartPtrCInstallProviderJobDoc getInstallProvider() const; /// Accessor for the UninstallProvider SmartPtrCUninstallProviderJobDoc getUninstallProvider() const; private: bool _isInitialized; SmartPtrCGetInventoryJobDoc _getInventory; SmartPtrCInstallProviderJobDoc _installProvider; SmartPtrCUninstallProviderJobDoc _uninstallProvider; private: CAF_CM_DECLARE_NOCOPY(CInstallBatchDoc); }; CAF_DECLARE_SMART_POINTER(CInstallBatchDoc); } #endif CInstallPackageSpecDoc.h000066400000000000000000000043701321503522500417710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInstallPackageSpecDoc_h_ #define CInstallPackageSpecDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" namespace Caf { /// A simple container for objects of type InstallPackageSpec class CAFINSTALLREQUESTDOC_LINKAGE CInstallPackageSpecDoc { public: CInstallPackageSpecDoc(); virtual ~CInstallPackageSpecDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string packageNamespace, const std::string packageName, const std::string packageVersion, const std::string startupAttachmentName, const std::string packageAttachmentName, const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection, const SmartPtrCAttachmentCollectionDoc attachmentCollection, const std::string arguments); public: /// Accessor for the PackageNamespace std::string getPackageNamespace() const; /// Accessor for the PackageName std::string getPackageName() const; /// Accessor for the PackageVersion std::string getPackageVersion() const; /// Accessor for the StartupAttachmentName std::string getStartupAttachmentName() const; /// Accessor for the PackageAttachmentName std::string getPackageAttachmentName() const; /// Accessor for the AttachmentNameCollection SmartPtrCAttachmentNameCollectionDoc getSupportingAttachmentNameCollection() const; /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc getAttachmentCollection() const; /// Accessor for the Arguments std::string getArguments() const; private: bool _isInitialized; std::string _packageNamespace; std::string _packageName; std::string _packageVersion; std::string _startupAttachmentName; std::string _packageAttachmentName; SmartPtrCAttachmentNameCollectionDoc _attachmentNameCollection; SmartPtrCAttachmentCollectionDoc _attachmentCollection; std::string _arguments; private: CAF_CM_DECLARE_NOCOPY(CInstallPackageSpecDoc); }; CAF_DECLARE_SMART_POINTER(CInstallPackageSpecDoc); } #endif CInstallProviderJobDoc.h000066400000000000000000000035701321503522500420510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInstallProviderJobDoc_h_ #define CInstallProviderJobDoc_h_ #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" namespace Caf { /// A simple container for objects of type InstallProviderJob class CAFINSTALLREQUESTDOC_LINKAGE CInstallProviderJobDoc { public: CInstallProviderJobDoc(); virtual ~CInstallProviderJobDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID jobId, const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const PACKAGE_OS_TYPE packageOSType, const std::deque packageCollection); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the JobId UUID getJobId() const; /// Accessor for the ProviderNamespace std::string getProviderNamespace() const; /// Accessor for the ProviderName std::string getProviderName() const; /// Accessor for the ProviderVersion std::string getProviderVersion() const; /// Accessor for the PackageOSType PACKAGE_OS_TYPE getPackageOSType() const; /// Accessor for the PackageVal std::deque getPackageCollection() const; private: UUID _clientId; UUID _jobId; std::string _providerNamespace; std::string _providerName; std::string _providerVersion; PACKAGE_OS_TYPE _packageOSType; std::deque _packageCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CInstallProviderJobDoc); }; CAF_DECLARE_SMART_POINTER(CInstallProviderJobDoc); } #endif CInstallProviderSpecDoc.h000066400000000000000000000031151321503522500422240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInstallProviderSpecDoc_h_ #define CInstallProviderSpecDoc_h_ #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" namespace Caf { /// A simple container for objects of type InstallProviderSpec class CAFINSTALLREQUESTDOC_LINKAGE CInstallProviderSpecDoc { public: CInstallProviderSpecDoc(); virtual ~CInstallProviderSpecDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const std::deque packageCollection); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the ProviderNamespace std::string getProviderNamespace() const; /// Accessor for the ProviderName std::string getProviderName() const; /// Accessor for the ProviderVersion std::string getProviderVersion() const; /// Accessor for the PackageVal std::deque getPackageCollection() const; private: UUID _clientId; std::string _providerNamespace; std::string _providerName; std::string _providerVersion; std::deque _packageCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CInstallProviderSpecDoc); }; CAF_DECLARE_SMART_POINTER(CInstallProviderSpecDoc); } #endif CInstallRequestDoc.h000066400000000000000000000033651321503522500412560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInstallRequestDoc_h_ #define CInstallRequestDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/CafInstallRequestDoc/CInstallBatchDoc.h" namespace Caf { /// A simple container for objects of type InstallRequest class CAFINSTALLREQUESTDOC_LINKAGE CInstallRequestDoc { public: CInstallRequestDoc(); virtual ~CInstallRequestDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCRequestHeaderDoc requestHeader, const SmartPtrCInstallBatchDoc batch, const SmartPtrCAttachmentCollectionDoc attachmentCollection); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the RequestHeader SmartPtrCRequestHeaderDoc getRequestHeader() const; /// Accessor for the Batch SmartPtrCInstallBatchDoc getBatch() const; /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc getAttachmentCollection() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; SmartPtrCRequestHeaderDoc _requestHeader; SmartPtrCInstallBatchDoc _batch; SmartPtrCAttachmentCollectionDoc _attachmentCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CInstallRequestDoc); }; CAF_DECLARE_SMART_POINTER(CInstallRequestDoc); } #endif CMinPackageElemDoc.h000066400000000000000000000023571321503522500411010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMinPackageElemDoc_h_ #define CMinPackageElemDoc_h_ namespace Caf { /// A simple container for objects of type MinPackageElem class CAFINSTALLREQUESTDOC_LINKAGE CMinPackageElemDoc { public: CMinPackageElemDoc(); virtual ~CMinPackageElemDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const int32 index, const std::string packageNamespace, const std::string packageName, const std::string packageVersion); public: /// Accessor for the Index int32 getIndex() const; /// Accessor for the PackageNamespace std::string getPackageNamespace() const; /// Accessor for the PackageName std::string getPackageName() const; /// Accessor for the PackageVersion std::string getPackageVersion() const; private: int32 _index; std::string _packageNamespace; std::string _packageName; std::string _packageVersion; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CMinPackageElemDoc); }; CAF_DECLARE_SMART_POINTER(CMinPackageElemDoc); } #endif CPackageDefnDoc.h000066400000000000000000000027631321503522500404300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CPackageDefnDoc_h_ #define CPackageDefnDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" namespace Caf { /// A simple container for objects of type PackageDefn class CAFINSTALLREQUESTDOC_LINKAGE CPackageDefnDoc { public: CPackageDefnDoc(); virtual ~CPackageDefnDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string startupAttachmentName, const std::string packageAttachmentName, const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection, const std::string arguments); public: /// Accessor for the StartupAttachmentName std::string getStartupAttachmentName() const; /// Accessor for the PackageAttachmentName std::string getPackageAttachmentName() const; /// Accessor for the AttachmentNameCollection SmartPtrCAttachmentNameCollectionDoc getSupportingAttachmentNameCollection() const; /// Accessor for the Arguments std::string getArguments() const; private: bool _isInitialized; std::string _startupAttachmentName; std::string _packageAttachmentName; SmartPtrCAttachmentNameCollectionDoc _attachmentNameCollection; std::string _arguments; private: CAF_CM_DECLARE_NOCOPY(CPackageDefnDoc); }; CAF_DECLARE_SMART_POINTER(CPackageDefnDoc); } #endif CUninstallProviderJobDoc.h000066400000000000000000000031441321503522500424110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CUninstallProviderJobDoc_h_ #define CUninstallProviderJobDoc_h_ #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" namespace Caf { /// A simple container for objects of type UninstallProviderJob class CAFINSTALLREQUESTDOC_LINKAGE CUninstallProviderJobDoc { public: CUninstallProviderJobDoc(); virtual ~CUninstallProviderJobDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID jobId, const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const PACKAGE_OS_TYPE packageOSType); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the JobId UUID getJobId() const; /// Accessor for the ProviderNamespace std::string getProviderNamespace() const; /// Accessor for the ProviderName std::string getProviderName() const; /// Accessor for the ProviderVersion std::string getProviderVersion() const; /// Accessor for the PackageOSType PACKAGE_OS_TYPE getPackageOSType() const; private: UUID _clientId; UUID _jobId; std::string _providerNamespace; std::string _providerName; std::string _providerVersion; PACKAGE_OS_TYPE _packageOSType; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CUninstallProviderJobDoc); }; CAF_DECLARE_SMART_POINTER(CUninstallProviderJobDoc); } #endif CafInstallRequestDocLink.h000066400000000000000000000011241321503522500423720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CafInstallRequestDoc_Link_h_ #define CafInstallRequestDoc_Link_h_ #ifndef CAFINSTALLREQUESTDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define CAFINSTALLREQUESTDOC_LINKAGE __declspec(dllexport) #else #define CAFINSTALLREQUESTDOC_LINKAGE __declspec(dllimport) #endif #else #define CAFINSTALLREQUESTDOC_LINKAGE #endif #endif #endif /* CafInstallRequestDoc_Link_h_ */ CafInstallRequestDocTypes.h000066400000000000000000000007031321503522500426030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAFINSTALLREQUESTDOCTYPES_H_ #define CAFINSTALLREQUESTDOCTYPES_H_ #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" namespace Caf { typedef enum { PACKAGE_OS_NONE, PACKAGE_OS_ALL, PACKAGE_OS_NIX, PACKAGE_OS_WIN } PACKAGE_OS_TYPE; } #endif /* CAFINSTALLREQUESTTYPES_H_ */ DiagRequestDoc/000077500000000000000000000000001321503522500342125ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCDiagRequestDoc.h000066400000000000000000000026421321503522500373350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDiagRequestDoc_h_ #define CDiagRequestDoc_h_ #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/DiagTypesDoc/CDiagBatchDoc.h" namespace Caf { /// A simple container for objects of type DiagRequest class DIAGREQUESTDOC_LINKAGE CDiagRequestDoc { public: CDiagRequestDoc(); virtual ~CDiagRequestDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCRequestHeaderDoc requestHeader, const SmartPtrCDiagBatchDoc batch); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the RequestHeader SmartPtrCRequestHeaderDoc getRequestHeader() const; /// Accessor for the Batch SmartPtrCDiagBatchDoc getBatch() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; SmartPtrCRequestHeaderDoc _requestHeader; SmartPtrCDiagBatchDoc _batch; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CDiagRequestDoc); }; CAF_DECLARE_SMART_POINTER(CDiagRequestDoc); } #endif DiagRequestDocLink.h000066400000000000000000000010521321503522500400420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef DiagRequestDoc_Link_h_ #define DiagRequestDoc_Link_h_ #ifndef DIAGREQUESTDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define DIAGREQUESTDOC_LINKAGE __declspec(dllexport) #else #define DIAGREQUESTDOC_LINKAGE __declspec(dllimport) #endif #else #define DIAGREQUESTDOC_LINKAGE #endif #endif #endif /* DiagRequestDoc_Link_h_ */ DiagTypesDoc/000077500000000000000000000000001321503522500336665ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCDiagBatchDoc.h000066400000000000000000000030361321503522500364000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDiagBatchDoc_h_ #define CDiagBatchDoc_h_ #include "Doc/DiagTypesDoc/CDiagCollectInstancesDoc.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueCollectionDoc.h" namespace Caf { /// A simple container for objects of type DiagBatch class DIAGTYPESDOC_LINKAGE CDiagBatchDoc { public: CDiagBatchDoc(); virtual ~CDiagBatchDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCDiagCollectInstancesDoc collectInstances, const SmartPtrCDiagSetValueCollectionDoc setValueCollection, const SmartPtrCDiagDeleteValueCollectionDoc deleteValueCollection); public: /// Accessor for the CollectInstances SmartPtrCDiagCollectInstancesDoc getCollectInstances() const; /// Accessor for the SetValueCollection SmartPtrCDiagSetValueCollectionDoc getSetValueCollection() const; /// Accessor for the DeleteValueCollection SmartPtrCDiagDeleteValueCollectionDoc getDeleteValueCollection() const; private: bool _isInitialized; SmartPtrCDiagCollectInstancesDoc _collectInstances; SmartPtrCDiagSetValueCollectionDoc _setValueCollection; SmartPtrCDiagDeleteValueCollectionDoc _deleteValueCollection; private: CAF_CM_DECLARE_NOCOPY(CDiagBatchDoc); }; CAF_DECLARE_SMART_POINTER(CDiagBatchDoc); } #endif CDiagCollectInstancesDoc.h000066400000000000000000000015501321503522500406130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDiagCollectInstancesDoc_h_ #define CDiagCollectInstancesDoc_h_ namespace Caf { /// A simple container for objects of type DiagCollectInstances class DIAGTYPESDOC_LINKAGE CDiagCollectInstancesDoc { public: CDiagCollectInstancesDoc(); virtual ~CDiagCollectInstancesDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID jobId); public: /// Accessor for the JobId UUID getJobId() const; private: UUID _jobId; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CDiagCollectInstancesDoc); }; CAF_DECLARE_SMART_POINTER(CDiagCollectInstancesDoc); } #endif CDiagDeleteValueCollectionDoc.h000066400000000000000000000021441321503522500415710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDiagDeleteValueCollectionDoc_h_ #define CDiagDeleteValueCollectionDoc_h_ #include "Doc/DiagTypesDoc/CDiagDeleteValueDoc.h" namespace Caf { /// A simple container for objects of type DiagDeleteValueCollection class DIAGTYPESDOC_LINKAGE CDiagDeleteValueCollectionDoc { public: CDiagDeleteValueCollectionDoc(); virtual ~CDiagDeleteValueCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque deleteValueCollection); public: /// Accessor for the DeleteValue std::deque getDeleteValueCollection() const; private: bool _isInitialized; std::deque _deleteValueCollection; private: CAF_CM_DECLARE_NOCOPY(CDiagDeleteValueCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CDiagDeleteValueCollectionDoc); } #endif CDiagDeleteValueDoc.h000066400000000000000000000020701321503522500375530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDiagDeleteValueDoc_h_ #define CDiagDeleteValueDoc_h_ namespace Caf { /// A simple container for objects of type DiagDeleteValue class DIAGTYPESDOC_LINKAGE CDiagDeleteValueDoc { public: CDiagDeleteValueDoc(); virtual ~CDiagDeleteValueDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID jobId, const std::string fileAlias, const std::string valueName); public: /// Accessor for the JobId UUID getJobId() const; /// Accessor for the FileAlias std::string getFileAlias() const; /// Accessor for the ValueName std::string getValueName() const; private: UUID _jobId; std::string _fileAlias; std::string _valueName; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CDiagDeleteValueDoc); }; CAF_DECLARE_SMART_POINTER(CDiagDeleteValueDoc); } #endif CDiagSetValueCollectionDoc.h000066400000000000000000000020641321503522500411230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDiagSetValueCollectionDoc_h_ #define CDiagSetValueCollectionDoc_h_ #include "Doc/DiagTypesDoc/CDiagSetValueDoc.h" namespace Caf { /// A simple container for objects of type DiagSetValueCollection class DIAGTYPESDOC_LINKAGE CDiagSetValueCollectionDoc { public: CDiagSetValueCollectionDoc(); virtual ~CDiagSetValueCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque setValueCollection); public: /// Accessor for the SetValue std::deque getSetValueCollection() const; private: bool _isInitialized; std::deque _setValueCollection; private: CAF_CM_DECLARE_NOCOPY(CDiagSetValueCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CDiagSetValueCollectionDoc); } #endif CDiagSetValueDoc.h000066400000000000000000000021331321503522500371040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDiagSetValueDoc_h_ #define CDiagSetValueDoc_h_ #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" namespace Caf { /// A simple container for objects of type DiagSetValue class DIAGTYPESDOC_LINKAGE CDiagSetValueDoc { public: CDiagSetValueDoc(); virtual ~CDiagSetValueDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID jobId, const std::string fileAlias, const SmartPtrCPropertyDoc value); public: /// Accessor for the JobId UUID getJobId() const; /// Accessor for the FileAlias std::string getFileAlias() const; /// Accessor for the Value SmartPtrCPropertyDoc getValue() const; private: UUID _jobId; std::string _fileAlias; SmartPtrCPropertyDoc _value; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CDiagSetValueDoc); }; CAF_DECLARE_SMART_POINTER(CDiagSetValueDoc); } #endif DiagTypesDocLink.h000066400000000000000000000010341321503522500371720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DiagTypesDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef DiagTypesDoc_Link_h_ #define DiagTypesDoc_Link_h_ #ifndef DIAGTYPESDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define DIAGTYPESDOC_LINKAGE __declspec(dllexport) #else #define DIAGTYPESDOC_LINKAGE __declspec(dllimport) #endif #else #define DIAGTYPESDOC_LINKAGE #endif #endif #endif /* DiagTypesDoc_Link_h_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocUtils/000077500000000000000000000000001321503522500331545ustar00rootroot00000000000000EnumConvertersXml.h000066400000000000000000000057411321503522500367150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef EnumConvertersXml_h_ #define EnumConvertersXml_h_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" namespace Caf { namespace EnumConvertersXml { /// Converts the parameter type to a string std::string DOCUTILS_LINKAGE convertParameterTypeToString( const PARAMETER_TYPE parameterType); /// Converts the string to a parameter type PARAMETER_TYPE DOCUTILS_LINKAGE convertStringToParameterType( const std::string parameterType); /// Converts the property type to a string std::string DOCUTILS_LINKAGE convertPropertyTypeToString( const PROPERTY_TYPE propertyType); /// Converts the string to a property type PROPERTY_TYPE DOCUTILS_LINKAGE convertStringToPropertyType( const std::string propertyType); /// Converts the validator type to a string std::string DOCUTILS_LINKAGE convertValidatorTypeToString( const VALIDATOR_TYPE validatorType); /// Converts the string to a validator type VALIDATOR_TYPE DOCUTILS_LINKAGE convertStringToValidatorType( const std::string validatorType); /// Converts the operator type to a string std::string DOCUTILS_LINKAGE convertOperatorTypeToString( const OPERATOR_TYPE operatorType); /// Converts the string to a operator type OPERATOR_TYPE DOCUTILS_LINKAGE convertStringToOperatorType( const std::string operatorType); /// Converts the arity type to a string std::string DOCUTILS_LINKAGE convertArityTypeToString( const ARITY_TYPE arityType); /// Converts the string to an arity type ARITY_TYPE DOCUTILS_LINKAGE convertStringToArityType( const std::string arityType); /// Converts the parameter type to a string std::string DOCUTILS_LINKAGE convertPackageOSTypeToString( const PACKAGE_OS_TYPE packageOSType); /// Converts the string to a parameter type PACKAGE_OS_TYPE DOCUTILS_LINKAGE convertStringToPackageOSType( const std::string packageOSType); /// Converts the logging level enum type to a string std::string DOCUTILS_LINKAGE convertLoggingLevelTypeToString( const LOGGINGLEVEL_TYPE loggingLevelType); /// Converts the string to a logging level enum LOGGINGLEVEL_TYPE DOCUTILS_LINKAGE convertStringToLoggingLevelType( const std::string loggingLevelType); /// Converts the logging component enum type to a string std::string DOCUTILS_LINKAGE convertLoggingComponentTypeToString( const LOGGINGCOMPONENT_TYPE loggingComponentType); /// Converts the string to a logging component enum type LOGGINGCOMPONENT_TYPE DOCUTILS_LINKAGE convertStringToLoggingComponentType( const std::string loggingComponentType); std::string DOCUTILS_LINKAGE convertCmsPolicyToString( const CMS_POLICY cmsPolicy); CMS_POLICY DOCUTILS_LINKAGE convertStringToCmsPolicy( const std::string cmsPolicy); } } #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/000077500000000000000000000000001321503522500326145ustar00rootroot00000000000000CafCoreTypesXml/000077500000000000000000000000001321503522500355455ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlAddInCollectionXml.h000066400000000000000000000016571321503522500414030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef AddInCollectionXml_h_ #define AddInCollectionXml_h_ #include "Doc/CafCoreTypesDoc/CAddInCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the AddInCollection class to/from XML namespace AddInCollectionXml { /// Adds the AddInCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCAddInCollectionDoc addInCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the AddInCollectionDoc from the XML. SmartPtrCAddInCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif AddInsXml.h000066400000000000000000000015251321503522500375440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef AddInsXml_h_ #define AddInsXml_h_ #include "Doc/CafCoreTypesDoc/CAddInsDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the AddIns class to/from XML namespace AddInsXml { /// Adds the AddInsDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCAddInsDoc addInsDoc, const SmartPtrCXmlElement thisXml); /// Parses the AddInsDoc from the XML. SmartPtrCAddInsDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif AttachmentCollectionXml.h000066400000000000000000000017411321503522500425060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef AttachmentCollectionXml_h_ #define AttachmentCollectionXml_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the AttachmentCollection class to/from XML namespace AttachmentCollectionXml { /// Adds the AttachmentCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCAttachmentCollectionDoc attachmentCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the AttachmentCollectionDoc from the XML. SmartPtrCAttachmentCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif AttachmentNameCollectionXml.h000066400000000000000000000020111321503522500432760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef AttachmentNameCollectionXml_h_ #define AttachmentNameCollectionXml_h_ #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the AttachmentNameCollection class to/from XML namespace AttachmentNameCollectionXml { /// Adds the AttachmentNameCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the AttachmentNameCollectionDoc from the XML. SmartPtrCAttachmentNameCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif AttachmentXml.h000066400000000000000000000015751321503522500404770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef AttachmentXml_h_ #define AttachmentXml_h_ #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Attachment class to/from XML namespace AttachmentXml { /// Adds the AttachmentDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCAttachmentDoc attachmentDoc, const SmartPtrCXmlElement thisXml); /// Parses the AttachmentDoc from the XML. SmartPtrCAttachmentDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif AuthnAuthzCollectionXml.h000066400000000000000000000017411321503522500425110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef AuthnAuthzCollectionXml_h_ #define AuthnAuthzCollectionXml_h_ #include "Doc/CafCoreTypesDoc/CAuthnAuthzCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the AuthnAuthzCollection class to/from XML namespace AuthnAuthzCollectionXml { /// Adds the AuthnAuthzCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCAuthnAuthzCollectionDoc authnAuthzCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the AuthnAuthzCollectionDoc from the XML. SmartPtrCAuthnAuthzCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif AuthnAuthzXml.h000066400000000000000000000015751321503522500405020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef AuthnAuthzXml_h_ #define AuthnAuthzXml_h_ #include "Doc/CafCoreTypesDoc/CAuthnAuthzDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the AuthnAuthz class to/from XML namespace AuthnAuthzXml { /// Adds the AuthnAuthzDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCAuthnAuthzDoc authnAuthzDoc, const SmartPtrCXmlElement thisXml); /// Parses the AuthnAuthzDoc from the XML. SmartPtrCAuthnAuthzDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif CafCoreTypesXmlLink.h000066400000000000000000000012701321503522500415440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef CafCoreTypesXml_Link_h_ #define CafCoreTypesXml_Link_h_ #ifndef CAFCORETYPESXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define CAFCORETYPESXML_LINKAGE __declspec(dllexport) #else #define CAFCORETYPESXML_LINKAGE __declspec(dllimport) #endif #else #define CAFCORETYPESXML_LINKAGE #endif #endif #endif /* CafCoreTypesXml_Link_h_ */ ClassFiltersXml.h000066400000000000000000000016211321503522500407750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ClassFiltersXml_h_ #define ClassFiltersXml_h_ #include "Doc/CafCoreTypesDoc/CClassFiltersDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ClassFilters class to/from XML namespace ClassFiltersXml { /// Adds the ClassFiltersDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCClassFiltersDoc classFiltersDoc, const SmartPtrCXmlElement thisXml); /// Parses the ClassFiltersDoc from the XML. SmartPtrCClassFiltersDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ClassSpecifierXml.h000066400000000000000000000016451321503522500413040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ClassSpecifierXml_h_ #define ClassSpecifierXml_h_ #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ClassSpecifier class to/from XML namespace ClassSpecifierXml { /// Adds the ClassSpecifierDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCClassSpecifierDoc classSpecifierDoc, const SmartPtrCXmlElement thisXml); /// Parses the ClassSpecifierDoc from the XML. SmartPtrCClassSpecifierDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif FullyQualifiedClassGroupXml.h000066400000000000000000000020111321503522500433130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef FullyQualifiedClassGroupXml_h_ #define FullyQualifiedClassGroupXml_h_ #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the FullyQualifiedClassGroup class to/from XML namespace FullyQualifiedClassGroupXml { /// Adds the FullyQualifiedClassGroupDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClassGroupDoc, const SmartPtrCXmlElement thisXml); /// Parses the FullyQualifiedClassGroupDoc from the XML. SmartPtrCFullyQualifiedClassGroupDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif LoggingLevelCollectionXml.h000066400000000000000000000017651321503522500430020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef LoggingLevelCollectionXml_h_ #define LoggingLevelCollectionXml_h_ #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the LoggingLevelCollection class to/from XML namespace LoggingLevelCollectionXml { /// Adds the LoggingLevelCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCLoggingLevelCollectionDoc loggingLevelCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the LoggingLevelCollectionDoc from the XML. SmartPtrCLoggingLevelCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif LoggingLevelElemXml.h000066400000000000000000000016711321503522500415650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef LoggingLevelElemXml_h_ #define LoggingLevelElemXml_h_ #include "Doc/CafCoreTypesDoc/CLoggingLevelElemDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the LoggingLevelElem class to/from XML namespace LoggingLevelElemXml { /// Adds the LoggingLevelElemDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCLoggingLevelElemDoc loggingLevelElemDoc, const SmartPtrCXmlElement thisXml); /// Parses the LoggingLevelElemDoc from the XML. SmartPtrCLoggingLevelElemDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif OperationXml.h000066400000000000000000000015631321503522500403440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef OperationXml_h_ #define OperationXml_h_ #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Operation class to/from XML namespace OperationXml { /// Adds the OperationDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCOperationDoc operationDoc, const SmartPtrCXmlElement thisXml); /// Parses the OperationDoc from the XML. SmartPtrCOperationDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ParameterCollectionXml.h000066400000000000000000000017271321503522500423420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ParameterCollectionXml_h_ #define ParameterCollectionXml_h_ #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ParameterCollection class to/from XML namespace ParameterCollectionXml { /// Adds the ParameterCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCParameterCollectionDoc parameterCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the ParameterCollectionDoc from the XML. SmartPtrCParameterCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PropertyCollectionXml.h000066400000000000000000000017151321503522500422430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef PropertyCollectionXml_h_ #define PropertyCollectionXml_h_ #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the PropertyCollection class to/from XML namespace PropertyCollectionXml { /// Adds the PropertyCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCPropertyCollectionDoc propertyCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the PropertyCollectionDoc from the XML. SmartPtrCPropertyCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PropertyXml.h000066400000000000000000000015511321503522500402250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef PropertyXml_h_ #define PropertyXml_h_ #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Property class to/from XML namespace PropertyXml { /// Adds the PropertyDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCPropertyDoc propertyDoc, const SmartPtrCXmlElement thisXml); /// Parses the PropertyDoc from the XML. SmartPtrCPropertyDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProtocolCollectionXml.h000066400000000000000000000017151321503522500422200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProtocolCollectionXml_h_ #define ProtocolCollectionXml_h_ #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProtocolCollection class to/from XML namespace ProtocolCollectionXml { /// Adds the ProtocolCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCProtocolCollectionDoc protocolCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProtocolCollectionDoc from the XML. SmartPtrCProtocolCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProtocolXml.h000066400000000000000000000015511321503522500402020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProtocolXml_h_ #define ProtocolXml_h_ #include "Doc/CafCoreTypesDoc/CProtocolDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Protocol class to/from XML namespace ProtocolXml { /// Adds the ProtocolDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCProtocolDoc protocolDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProtocolDoc from the XML. SmartPtrCProtocolDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif RequestConfigXml.h000066400000000000000000000016341321503522500411610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef RequestConfigXml_h_ #define RequestConfigXml_h_ #include "Doc/CafCoreTypesDoc/CRequestConfigDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the RequestConfig class to/from XML namespace RequestConfigXml { /// Adds the RequestConfigDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCRequestConfigDoc requestConfigDoc, const SmartPtrCXmlElement thisXml); /// Parses the RequestConfigDoc from the XML. SmartPtrCRequestConfigDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif RequestHeaderXml.h000066400000000000000000000016331321503522500411430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef RequestHeaderXml_h_ #define RequestHeaderXml_h_ #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the RequestHeader class to/from XML namespace RequestHeaderXml { /// Adds the RequestHeaderDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCRequestHeaderDoc requestHeaderDoc, const SmartPtrCXmlElement thisXml); /// Parses the RequestHeaderDoc from the XML. SmartPtrCRequestHeaderDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif RequestInstanceParameterXml.h000066400000000000000000000020111321503522500433470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef RequestInstanceParameterXml_h_ #define RequestInstanceParameterXml_h_ #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the RequestInstanceParameter class to/from XML namespace RequestInstanceParameterXml { /// Adds the RequestInstanceParameterDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCRequestInstanceParameterDoc requestInstanceParameterDoc, const SmartPtrCXmlElement thisXml); /// Parses the RequestInstanceParameterDoc from the XML. SmartPtrCRequestInstanceParameterDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif RequestParameterXml.h000066400000000000000000000016711321503522500416750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef RequestParameterXml_h_ #define RequestParameterXml_h_ #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the RequestParameter class to/from XML namespace RequestParameterXml { /// Adds the RequestParameterDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCRequestParameterDoc requestParameterDoc, const SmartPtrCXmlElement thisXml); /// Parses the RequestParameterDoc from the XML. SmartPtrCRequestParameterDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif RequestXml.h000066400000000000000000000011121321503522500400220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: Nov 21, 2014 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef RequestXml_h_ #define RequestXml_h_ #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" namespace Caf { namespace RequestXml { SmartPtrCXmlElement CAFCORETYPESXML_LINKAGE parseString( const std::string& xml, const std::string& rootName); SmartPtrCXmlElement CAFCORETYPESXML_LINKAGE parseFile( const std::string& xml, const std::string& rootName); } } #endif StatisticsXml.h000066400000000000000000000015751321503522500405410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef StatisticsXml_h_ #define StatisticsXml_h_ #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Statistics class to/from XML namespace StatisticsXml { /// Adds the StatisticsDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCStatisticsDoc statisticsDoc, const SmartPtrCXmlElement thisXml); /// Parses the StatisticsDoc from the XML. SmartPtrCStatisticsDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif CafInstallRequestXml/000077500000000000000000000000001321503522500366075ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlCafInstallRequestXmlLink.h000066400000000000000000000013331321503522500436500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef CafInstallRequestXml_Link_h_ #define CafInstallRequestXml_Link_h_ #ifndef CAFINSTALLREQUESTXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define CAFINSTALLREQUESTXML_LINKAGE __declspec(dllexport) #else #define CAFINSTALLREQUESTXML_LINKAGE __declspec(dllimport) #endif #else #define CAFINSTALLREQUESTXML_LINKAGE #endif #endif #endif /* CafInstallRequestXml_Link_h_ */ CafInstallRequestXmlRoots.h000066400000000000000000000056151321503522500440700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef CafInstallRequestXmlRoots_h_ #define CafInstallRequestXmlRoots_h_ #include "Doc/CafInstallRequestDoc/CInstallPackageSpecDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" namespace Caf { namespace XmlRoots { /// Saves the InstallRequestDoc to a string. std::string CAFINSTALLREQUESTXML_LINKAGE saveInstallRequestToString( const SmartPtrCInstallRequestDoc installRequestDoc); /// Parses the InstallPackageSpecDoc from the string. SmartPtrCInstallRequestDoc CAFINSTALLREQUESTXML_LINKAGE parseInstallRequestFromString( const std::string xml); /// Saves the InstallRequestDoc to a file. void CAFINSTALLREQUESTXML_LINKAGE saveInstallRequestToFile( const SmartPtrCInstallRequestDoc installRequestDoc, const std::string filePath); /// Parses the InstallPackageSpecDoc from the file. SmartPtrCInstallRequestDoc CAFINSTALLREQUESTXML_LINKAGE parseInstallRequestFromFile( const std::string filePath); /// Saves the InstallProviderSpecDoc to a string. std::string CAFINSTALLREQUESTXML_LINKAGE saveInstallProviderSpecToString( const SmartPtrCInstallProviderSpecDoc installProviderSpecDoc); /// Parses the InstallPackageSpecDoc from the string. SmartPtrCInstallProviderSpecDoc CAFINSTALLREQUESTXML_LINKAGE parseInstallProviderSpecFromString( const std::string xml); /// Saves the InstallProviderSpecDoc to a file. void CAFINSTALLREQUESTXML_LINKAGE saveInstallProviderSpecToFile( const SmartPtrCInstallProviderSpecDoc installProviderSpecDoc, const std::string filePath); /// Parses the InstallPackageSpecDoc from the file. SmartPtrCInstallProviderSpecDoc CAFINSTALLREQUESTXML_LINKAGE parseInstallProviderSpecFromFile( const std::string filePath); /// Saves the InstallPackageSpecDoc to a string. std::string CAFINSTALLREQUESTXML_LINKAGE saveInstallPackageSpecToString( const SmartPtrCInstallPackageSpecDoc installPackageSpecDoc); /// Parses the InstallPackageSpecDoc from the string. SmartPtrCInstallPackageSpecDoc CAFINSTALLREQUESTXML_LINKAGE parseInstallPackageSpecFromString( const std::string xml); /// Saves the InstallPackageSpecDoc to a file. void CAFINSTALLREQUESTXML_LINKAGE saveInstallPackageSpecToFile( const SmartPtrCInstallPackageSpecDoc installPackageSpecDoc, const std::string filePath); /// Parses the InstallPackageSpecDoc from the file. SmartPtrCInstallPackageSpecDoc CAFINSTALLREQUESTXML_LINKAGE parseInstallPackageSpecFromFile( const std::string filePath); } } #endif /* CafInstallRequestXmlRoots_h_ */ FullPackageElemXml.h000066400000000000000000000017101321503522500424210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef FullPackageElemXml_h_ #define FullPackageElemXml_h_ #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the FullPackageElem class to/from XML namespace FullPackageElemXml { /// Adds the FullPackageElemDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCFullPackageElemDoc fullPackageElemDoc, const SmartPtrCXmlElement thisXml); /// Parses the FullPackageElemDoc from the XML. SmartPtrCFullPackageElemDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif GetInventoryJobXml.h000066400000000000000000000017101321503522500425300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef GetInventoryJobXml_h_ #define GetInventoryJobXml_h_ #include "Doc/CafInstallRequestDoc/CGetInventoryJobDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the GetInventoryJob class to/from XML namespace GetInventoryJobXml { /// Adds the GetInventoryJobDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCGetInventoryJobDoc getInventoryJobDoc, const SmartPtrCXmlElement thisXml); /// Parses the GetInventoryJobDoc from the XML. SmartPtrCGetInventoryJobDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif InstallBatchXml.h000066400000000000000000000016521321503522500420150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef InstallBatchXml_h_ #define InstallBatchXml_h_ #include "Doc/CafInstallRequestDoc/CInstallBatchDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the InstallBatch class to/from XML namespace InstallBatchXml { /// Adds the InstallBatchDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCInstallBatchDoc installBatchDoc, const SmartPtrCXmlElement thisXml); /// Parses the InstallBatchDoc from the XML. SmartPtrCInstallBatchDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif InstallPackageSpecXml.h000066400000000000000000000017461321503522500431460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef InstallPackageSpecXml_h_ #define InstallPackageSpecXml_h_ #include "Doc/CafInstallRequestDoc/CInstallPackageSpecDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the InstallPackageSpec class to/from XML namespace InstallPackageSpecXml { /// Adds the InstallPackageSpecDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCInstallPackageSpecDoc installPackageSpecDoc, const SmartPtrCXmlElement thisXml); /// Parses the InstallPackageSpecDoc from the XML. SmartPtrCInstallPackageSpecDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif InstallProviderJobXml.h000066400000000000000000000017461321503522500432250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef InstallProviderJobXml_h_ #define InstallProviderJobXml_h_ #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the InstallProviderJob class to/from XML namespace InstallProviderJobXml { /// Adds the InstallProviderJobDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCInstallProviderJobDoc installProviderJobDoc, const SmartPtrCXmlElement thisXml); /// Parses the InstallProviderJobDoc from the XML. SmartPtrCInstallProviderJobDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif InstallProviderSpecXml.h000066400000000000000000000017601321503522500434010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef InstallProviderSpecXml_h_ #define InstallProviderSpecXml_h_ #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the InstallProviderSpec class to/from XML namespace InstallProviderSpecXml { /// Adds the InstallProviderSpecDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCInstallProviderSpecDoc installProviderSpecDoc, const SmartPtrCXmlElement thisXml); /// Parses the InstallProviderSpecDoc from the XML. SmartPtrCInstallProviderSpecDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif InstallRequestXml.h000066400000000000000000000016761321503522500424320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef InstallRequestXml_h_ #define InstallRequestXml_h_ #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the InstallRequest class to/from XML namespace InstallRequestXml { /// Adds the InstallRequestDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCInstallRequestDoc installRequestDoc, const SmartPtrCXmlElement thisXml); /// Parses the InstallRequestDoc from the XML. SmartPtrCInstallRequestDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MinPackageElemXml.h000066400000000000000000000016761321503522500422550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MinPackageElemXml_h_ #define MinPackageElemXml_h_ #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MinPackageElem class to/from XML namespace MinPackageElemXml { /// Adds the MinPackageElemDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCMinPackageElemDoc minPackageElemDoc, const SmartPtrCXmlElement thisXml); /// Parses the MinPackageElemDoc from the XML. SmartPtrCMinPackageElemDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PackageDefnXml.h000066400000000000000000000016401321503522500415720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef PackageDefnXml_h_ #define PackageDefnXml_h_ #include "Doc/CafInstallRequestDoc/CPackageDefnDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the PackageDefn class to/from XML namespace PackageDefnXml { /// Adds the PackageDefnDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCPackageDefnDoc packageDefnDoc, const SmartPtrCXmlElement thisXml); /// Parses the PackageDefnDoc from the XML. SmartPtrCPackageDefnDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif UninstallProviderJobXml.h000066400000000000000000000017721321503522500435670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef UninstallProviderJobXml_h_ #define UninstallProviderJobXml_h_ #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the UninstallProviderJob class to/from XML namespace UninstallProviderJobXml { /// Adds the UninstallProviderJobDoc into the XML. void CAFINSTALLREQUESTXML_LINKAGE add( const SmartPtrCUninstallProviderJobDoc uninstallProviderJobDoc, const SmartPtrCXmlElement thisXml); /// Parses the UninstallProviderJobDoc from the XML. SmartPtrCUninstallProviderJobDoc CAFINSTALLREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DiagRequestXml/000077500000000000000000000000001321503522500354335ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlDiagRequestXml.h000066400000000000000000000016021321503522500405010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagRequestXml_h_ #define DiagRequestXml_h_ #include "Doc/DiagRequestDoc/CDiagRequestDoc.h" #include "Doc/DocXml/DiagRequestXml/DiagRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DiagRequest class to/from XML namespace DiagRequestXml { /// Adds the DiagRequestDoc into the XML. void DIAGREQUESTXML_LINKAGE add( const SmartPtrCDiagRequestDoc diagRequestDoc, const SmartPtrCXmlElement thisXml); /// Parses the DiagRequestDoc from the XML. SmartPtrCDiagRequestDoc DIAGREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DiagRequestXmlLink.h000066400000000000000000000012611321503522500413200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagRequestXml_Link_h_ #define DiagRequestXml_Link_h_ #ifndef DIAGREQUESTXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define DIAGREQUESTXML_LINKAGE __declspec(dllexport) #else #define DIAGREQUESTXML_LINKAGE __declspec(dllimport) #endif #else #define DIAGREQUESTXML_LINKAGE #endif #endif #endif /* DiagRequestXml_Link_h_ */ DiagRequestXmlRoots.h000066400000000000000000000022331321503522500415310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagRequestXmlRoots_h_ #define DiagRequestXmlRoots_h_ #include "Doc/DiagRequestDoc/CDiagRequestDoc.h" #include "Doc/DocXml/DiagRequestXml/DiagRequestXmlLink.h" namespace Caf { namespace XmlRoots { /// Saves the DiagRequestDoc to a string. std::string DIAGREQUESTXML_LINKAGE saveDiagRequestToString( const SmartPtrCDiagRequestDoc diagRequestDoc); /// Parses the DiagRequestDoc from the string. SmartPtrCDiagRequestDoc DIAGREQUESTXML_LINKAGE parseDiagRequestFromString( const std::string xml); /// Saves the DiagRequestDoc to a file. void DIAGREQUESTXML_LINKAGE saveDiagRequestToFile( const SmartPtrCDiagRequestDoc diagRequestDoc, const std::string filePath); /// Parses the DiagRequestDoc from the file. SmartPtrCDiagRequestDoc DIAGREQUESTXML_LINKAGE parseDiagRequestFromFile( const std::string filePath); } } #endif /* DiagRequestXmlRoots_h_ */ DiagTypesXml/000077500000000000000000000000001321503522500351075ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlDiagBatchXml.h000066400000000000000000000015441321503522500375530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagBatchXml_h_ #define DiagBatchXml_h_ #include "Doc/DiagTypesDoc/CDiagBatchDoc.h" #include "Doc/DocXml/DiagTypesXml/DiagTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DiagBatch class to/from XML namespace DiagBatchXml { /// Adds the DiagBatchDoc into the XML. void DIAGTYPESXML_LINKAGE add( const SmartPtrCDiagBatchDoc diagBatchDoc, const SmartPtrCXmlElement thisXml); /// Parses the DiagBatchDoc from the XML. SmartPtrCDiagBatchDoc DIAGTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DiagCollectInstancesXml.h000066400000000000000000000017221321503522500417650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagCollectInstancesXml_h_ #define DiagCollectInstancesXml_h_ #include "Doc/DiagTypesDoc/CDiagCollectInstancesDoc.h" #include "Doc/DocXml/DiagTypesXml/DiagTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DiagCollectInstances class to/from XML namespace DiagCollectInstancesXml { /// Adds the DiagCollectInstancesDoc into the XML. void DIAGTYPESXML_LINKAGE add( const SmartPtrCDiagCollectInstancesDoc diagCollectInstancesDoc, const SmartPtrCXmlElement thisXml); /// Parses the DiagCollectInstancesDoc from the XML. SmartPtrCDiagCollectInstancesDoc DIAGTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DiagDeleteValueCollectionXml.h000066400000000000000000000020041321503522500427350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagDeleteValueCollectionXml_h_ #define DiagDeleteValueCollectionXml_h_ #include "Doc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.h" #include "Doc/DocXml/DiagTypesXml/DiagTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DiagDeleteValueCollection class to/from XML namespace DiagDeleteValueCollectionXml { /// Adds the DiagDeleteValueCollectionDoc into the XML. void DIAGTYPESXML_LINKAGE add( const SmartPtrCDiagDeleteValueCollectionDoc diagDeleteValueCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the DiagDeleteValueCollectionDoc from the XML. SmartPtrCDiagDeleteValueCollectionDoc DIAGTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DiagDeleteValueXml.h000066400000000000000000000016401321503522500407260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagDeleteValueXml_h_ #define DiagDeleteValueXml_h_ #include "Doc/DiagTypesDoc/CDiagDeleteValueDoc.h" #include "Doc/DocXml/DiagTypesXml/DiagTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DiagDeleteValue class to/from XML namespace DiagDeleteValueXml { /// Adds the DiagDeleteValueDoc into the XML. void DIAGTYPESXML_LINKAGE add( const SmartPtrCDiagDeleteValueDoc diagDeleteValueDoc, const SmartPtrCXmlElement thisXml); /// Parses the DiagDeleteValueDoc from the XML. SmartPtrCDiagDeleteValueDoc DIAGTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DiagSetValueCollectionXml.h000066400000000000000000000017461321503522500423020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagSetValueCollectionXml_h_ #define DiagSetValueCollectionXml_h_ #include "Doc/DiagTypesDoc/CDiagSetValueCollectionDoc.h" #include "Doc/DocXml/DiagTypesXml/DiagTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DiagSetValueCollection class to/from XML namespace DiagSetValueCollectionXml { /// Adds the DiagSetValueCollectionDoc into the XML. void DIAGTYPESXML_LINKAGE add( const SmartPtrCDiagSetValueCollectionDoc diagSetValueCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the DiagSetValueCollectionDoc from the XML. SmartPtrCDiagSetValueCollectionDoc DIAGTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DiagSetValueXml.h000066400000000000000000000016021321503522500402550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagSetValueXml_h_ #define DiagSetValueXml_h_ #include "Doc/DiagTypesDoc/CDiagSetValueDoc.h" #include "Doc/DocXml/DiagTypesXml/DiagTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DiagSetValue class to/from XML namespace DiagSetValueXml { /// Adds the DiagSetValueDoc into the XML. void DIAGTYPESXML_LINKAGE add( const SmartPtrCDiagSetValueDoc diagSetValueDoc, const SmartPtrCXmlElement thisXml); /// Parses the DiagSetValueDoc from the XML. SmartPtrCDiagSetValueDoc DIAGTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DiagTypesXmlLink.h000066400000000000000000000012431321503522500404500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DiagTypesXml_Link_h_ #define DiagTypesXml_Link_h_ #ifndef DIAGTYPESXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define DIAGTYPESXML_LINKAGE __declspec(dllexport) #else #define DIAGTYPESXML_LINKAGE __declspec(dllimport) #endif #else #define DIAGTYPESXML_LINKAGE #endif #endif #endif /* DiagTypesXml_Link_h_ */ MgmtRequestXml/000077500000000000000000000000001321503522500354735ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlMgmtRequestXml.h000066400000000000000000000016021321503522500406010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtRequestXml_h_ #define MgmtRequestXml_h_ #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MgmtRequest class to/from XML namespace MgmtRequestXml { /// Adds the MgmtRequestDoc into the XML. void MGMTREQUESTXML_LINKAGE add( const SmartPtrCMgmtRequestDoc mgmtRequestDoc, const SmartPtrCXmlElement thisXml); /// Parses the MgmtRequestDoc from the XML. SmartPtrCMgmtRequestDoc MGMTREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MgmtRequestXmlLink.h000066400000000000000000000012611321503522500414200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtRequestXml_Link_h_ #define MgmtRequestXml_Link_h_ #ifndef MGMTREQUESTXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define MGMTREQUESTXML_LINKAGE __declspec(dllexport) #else #define MGMTREQUESTXML_LINKAGE __declspec(dllimport) #endif #else #define MGMTREQUESTXML_LINKAGE #endif #endif #endif /* MgmtRequestXml_Link_h_ */ MgmtRequestXmlRoots.h000066400000000000000000000022331321503522500416310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtRequestXmlRoots_h_ #define MgmtRequestXmlRoots_h_ #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXmlLink.h" namespace Caf { namespace XmlRoots { /// Saves the MgmtRequestDoc to a string. std::string MGMTREQUESTXML_LINKAGE saveMgmtRequestToString( const SmartPtrCMgmtRequestDoc mgmtRequestDoc); /// Parses the MgmtRequestDoc from the string. SmartPtrCMgmtRequestDoc MGMTREQUESTXML_LINKAGE parseMgmtRequestFromString( const std::string xml); /// Saves the MgmtRequestDoc to a file. void MGMTREQUESTXML_LINKAGE saveMgmtRequestToFile( const SmartPtrCMgmtRequestDoc mgmtRequestDoc, const std::string filePath); /// Parses the MgmtRequestDoc from the file. SmartPtrCMgmtRequestDoc MGMTREQUESTXML_LINKAGE parseMgmtRequestFromFile( const std::string filePath); } } #endif /* MgmtRequestXmlRoots_h_ */ MgmtTypesXml/000077500000000000000000000000001321503522500351475ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlMgmtBatchXml.h000066400000000000000000000015441321503522500376530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtBatchXml_h_ #define MgmtBatchXml_h_ #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/DocXml/MgmtTypesXml/MgmtTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MgmtBatch class to/from XML namespace MgmtBatchXml { /// Adds the MgmtBatchDoc into the XML. void MGMTTYPESXML_LINKAGE add( const SmartPtrCMgmtBatchDoc mgmtBatchDoc, const SmartPtrCXmlElement thisXml); /// Parses the MgmtBatchDoc from the XML. SmartPtrCMgmtBatchDoc MGMTTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MgmtCollectInstancesCollectionXml.h000066400000000000000000000020661321503522500441030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtCollectInstancesCollectionXml_h_ #define MgmtCollectInstancesCollectionXml_h_ #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/DocXml/MgmtTypesXml/MgmtTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MgmtCollectInstancesCollection class to/from XML namespace MgmtCollectInstancesCollectionXml { /// Adds the MgmtCollectInstancesCollectionDoc into the XML. void MGMTTYPESXML_LINKAGE add( const SmartPtrCMgmtCollectInstancesCollectionDoc mgmtCollectInstancesCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the MgmtCollectInstancesCollectionDoc from the XML. SmartPtrCMgmtCollectInstancesCollectionDoc MGMTTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MgmtCollectInstancesXml.h000066400000000000000000000017221321503522500420650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtCollectInstancesXml_h_ #define MgmtCollectInstancesXml_h_ #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Doc/DocXml/MgmtTypesXml/MgmtTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MgmtCollectInstances class to/from XML namespace MgmtCollectInstancesXml { /// Adds the MgmtCollectInstancesDoc into the XML. void MGMTTYPESXML_LINKAGE add( const SmartPtrCMgmtCollectInstancesDoc mgmtCollectInstancesDoc, const SmartPtrCXmlElement thisXml); /// Parses the MgmtCollectInstancesDoc from the XML. SmartPtrCMgmtCollectInstancesDoc MGMTTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MgmtCollectSchemaXml.h000066400000000000000000000016641321503522500413430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtCollectSchemaXml_h_ #define MgmtCollectSchemaXml_h_ #include "Doc/MgmtTypesDoc/CMgmtCollectSchemaDoc.h" #include "Doc/DocXml/MgmtTypesXml/MgmtTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MgmtCollectSchema class to/from XML namespace MgmtCollectSchemaXml { /// Adds the MgmtCollectSchemaDoc into the XML. void MGMTTYPESXML_LINKAGE add( const SmartPtrCMgmtCollectSchemaDoc mgmtCollectSchemaDoc, const SmartPtrCXmlElement thisXml); /// Parses the MgmtCollectSchemaDoc from the XML. SmartPtrCMgmtCollectSchemaDoc MGMTTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MgmtInvokeOperationCollectionXml.h000066400000000000000000000020541321503522500437570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtInvokeOperationCollectionXml_h_ #define MgmtInvokeOperationCollectionXml_h_ #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/DocXml/MgmtTypesXml/MgmtTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MgmtInvokeOperationCollection class to/from XML namespace MgmtInvokeOperationCollectionXml { /// Adds the MgmtInvokeOperationCollectionDoc into the XML. void MGMTTYPESXML_LINKAGE add( const SmartPtrCMgmtInvokeOperationCollectionDoc mgmtInvokeOperationCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the MgmtInvokeOperationCollectionDoc from the XML. SmartPtrCMgmtInvokeOperationCollectionDoc MGMTTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MgmtInvokeOperationXml.h000066400000000000000000000017101321503522500417410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtInvokeOperationXml_h_ #define MgmtInvokeOperationXml_h_ #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Doc/DocXml/MgmtTypesXml/MgmtTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MgmtInvokeOperation class to/from XML namespace MgmtInvokeOperationXml { /// Adds the MgmtInvokeOperationDoc into the XML. void MGMTTYPESXML_LINKAGE add( const SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperationDoc, const SmartPtrCXmlElement thisXml); /// Parses the MgmtInvokeOperationDoc from the XML. SmartPtrCMgmtInvokeOperationDoc MGMTTYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MgmtTypesXmlLink.h000066400000000000000000000012431321503522500405500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MgmtTypesXml_Link_h_ #define MgmtTypesXml_Link_h_ #ifndef MGMTTYPESXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define MGMTTYPESXML_LINKAGE __declspec(dllexport) #else #define MGMTTYPESXML_LINKAGE __declspec(dllimport) #endif #else #define MGMTTYPESXML_LINKAGE #endif #endif #endif /* MgmtTypesXml_Link_h_ */ MultiPmeMgmtRequestXml/000077500000000000000000000000001321503522500371505ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlMultiPmeMgmtBatchCollectionXml.h000066400000000000000000000021121321503522500453350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MultiPmeMgmtBatchCollectionXml_h_ #define MultiPmeMgmtBatchCollectionXml_h_ #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchCollectionDoc.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MultiPmeMgmtBatchCollection class to/from XML namespace MultiPmeMgmtBatchCollectionXml { /// Adds the MultiPmeMgmtBatchCollectionDoc into the XML. void MULTIPMEMGMTREQUESTXML_LINKAGE add( const SmartPtrCMultiPmeMgmtBatchCollectionDoc multiPmeMgmtBatchCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the MultiPmeMgmtBatchCollectionDoc from the XML. SmartPtrCMultiPmeMgmtBatchCollectionDoc MULTIPMEMGMTREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MultiPmeMgmtBatchXml.h000066400000000000000000000017461321503522500433350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MultiPmeMgmtBatchXml_h_ #define MultiPmeMgmtBatchXml_h_ #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchDoc.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MultiPmeMgmtBatch class to/from XML namespace MultiPmeMgmtBatchXml { /// Adds the MultiPmeMgmtBatchDoc into the XML. void MULTIPMEMGMTREQUESTXML_LINKAGE add( const SmartPtrCMultiPmeMgmtBatchDoc multiPmeMgmtBatchDoc, const SmartPtrCXmlElement thisXml); /// Parses the MultiPmeMgmtBatchDoc from the XML. SmartPtrCMultiPmeMgmtBatchDoc MULTIPMEMGMTREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MultiPmeMgmtRequestXml.h000066400000000000000000000017721321503522500437430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MultiPmeMgmtRequestXml_h_ #define MultiPmeMgmtRequestXml_h_ #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtRequestDoc.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MultiPmeMgmtRequest class to/from XML namespace MultiPmeMgmtRequestXml { /// Adds the MultiPmeMgmtRequestDoc into the XML. void MULTIPMEMGMTREQUESTXML_LINKAGE add( const SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc, const SmartPtrCXmlElement thisXml); /// Parses the MultiPmeMgmtRequestDoc from the XML. SmartPtrCMultiPmeMgmtRequestDoc MULTIPMEMGMTREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MultiPmeMgmtRequestXmlLink.h000066400000000000000000000013511321503522500445520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MultiPmeMgmtRequestXml_Link_h_ #define MultiPmeMgmtRequestXml_Link_h_ #ifndef MULTIPMEMGMTREQUESTXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define MULTIPMEMGMTREQUESTXML_LINKAGE __declspec(dllexport) #else #define MULTIPMEMGMTREQUESTXML_LINKAGE __declspec(dllimport) #endif #else #define MULTIPMEMGMTREQUESTXML_LINKAGE #endif #endif #endif /* MultiPmeMgmtRequestXml_Link_h_ */ MultiPmeMgmtRequestXmlRoots.h000066400000000000000000000025431321503522500447670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MultiPmeMgmtRequestXmlRoots_h_ #define MultiPmeMgmtRequestXmlRoots_h_ #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtRequestDoc.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXmlLink.h" namespace Caf { namespace XmlRoots { /// Saves the MultiPmeMgmtRequestDoc to a string. std::string MULTIPMEMGMTREQUESTXML_LINKAGE saveMultiPmeMgmtRequestToString( const SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc); /// Parses the MultiPmeMgmtRequestDoc from the string. SmartPtrCMultiPmeMgmtRequestDoc MULTIPMEMGMTREQUESTXML_LINKAGE parseMultiPmeMgmtRequestFromString( const std::string xml); /// Saves the MultiPmeMgmtRequestDoc to a file. void MULTIPMEMGMTREQUESTXML_LINKAGE saveMultiPmeMgmtRequestToFile( const SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc, const std::string filePath); /// Parses the MultiPmeMgmtRequestDoc from the file. SmartPtrCMultiPmeMgmtRequestDoc MULTIPMEMGMTREQUESTXML_LINKAGE parseMultiPmeMgmtRequestFromFile( const std::string filePath); } } #endif /* MultiPmeMgmtRequestXmlRoots_h_ */ PmeIdCollectionXml.h000066400000000000000000000017221321503522500430160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef PmeIdCollectionXml_h_ #define PmeIdCollectionXml_h_ #include "Doc/MultiPmeMgmtRequestDoc/CPmeIdCollectionDoc.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the PmeIdCollection class to/from XML namespace PmeIdCollectionXml { /// Adds the PmeIdCollectionDoc into the XML. void MULTIPMEMGMTREQUESTXML_LINKAGE add( const SmartPtrCPmeIdCollectionDoc pmeIdCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the PmeIdCollectionDoc from the XML. SmartPtrCPmeIdCollectionDoc MULTIPMEMGMTREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PayloadEnvelopeXml/000077500000000000000000000000001321503522500363055ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlPayloadEnvelopeXml.h000066400000000000000000000016751321503522500422370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PayloadEnvelopeXml/* * Author: bwilliams * Created: July 3, 2015 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef PayloadEnvelopeXml_h_ #define PayloadEnvelopeXml_h_ #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the PayloadEnvelope class to/from XML namespace PayloadEnvelopeXml { /// Adds the PayloadEnvelopeDoc into the XML. void PAYLOADENVELOPEXML_LINKAGE add( const SmartPtrCPayloadEnvelopeDoc payloadEnvelopeDoc, const SmartPtrCXmlElement thisXml); /// Parses the PayloadEnvelopeDoc from the XML. SmartPtrCPayloadEnvelopeDoc PAYLOADENVELOPEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PayloadEnvelopeXmlLink.h000066400000000000000000000013151321503522500430440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PayloadEnvelopeXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef PayloadEnvelopeXml_Link_h_ #define PayloadEnvelopeXml_Link_h_ #ifndef PAYLOADENVELOPEXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PAYLOADENVELOPEXML_LINKAGE __declspec(dllexport) #else #define PAYLOADENVELOPEXML_LINKAGE __declspec(dllimport) #endif #else #define PAYLOADENVELOPEXML_LINKAGE #endif #endif #endif /* PayloadEnvelopeXml_Link_h_ */ PayloadEnvelopeXmlRoots.h000066400000000000000000000025001321503522500432520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PayloadEnvelopeXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef PayloadEnvelopeXmlRoots_h_ #define PayloadEnvelopeXmlRoots_h_ #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXmlLink.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXmlRoots.h" namespace Caf { namespace XmlRoots { /// Saves the PayloadEnvelopeDoc to a string. std::string PAYLOADENVELOPEXML_LINKAGE savePayloadEnvelopeToString( const SmartPtrCPayloadEnvelopeDoc payloadEnvelopeDoc); /// Parses the PayloadEnvelopeDoc from the string. SmartPtrCPayloadEnvelopeDoc PAYLOADENVELOPEXML_LINKAGE parsePayloadEnvelopeFromString( const std::string xml); /// Saves the PayloadEnvelopeDoc to a file. void PAYLOADENVELOPEXML_LINKAGE savePayloadEnvelopeToFile( const SmartPtrCPayloadEnvelopeDoc payloadEnvelopeDoc, const std::string filePath); /// Parses the PayloadEnvelopeDoc from the file. SmartPtrCPayloadEnvelopeDoc PAYLOADENVELOPEXML_LINKAGE parsePayloadEnvelopeFromFile( const std::string filePath); } } #endif /* PayloadEnvelopeXmlRoots_h_ */ PersistenceXml/000077500000000000000000000000001321503522500355025ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlCertCollectionXml.h000066400000000000000000000014351321503522500412500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CertCollectionXml_h_ #define CertCollectionXml_h_ #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the CertCollection class to/from XML namespace CertCollectionXml { /// Adds the CertCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCCertCollectionDoc certCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the CertCollectionDoc from the XML. SmartPtrCCertCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif CertPathCollectionXml.h000066400000000000000000000015051321503522500420630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CertPathCollectionXml_h_ #define CertPathCollectionXml_h_ #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the CertPathCollection class to/from XML namespace CertPathCollectionXml { /// Adds the CertPathCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCCertPathCollectionDoc certPathCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the CertPathCollectionDoc from the XML. SmartPtrCCertPathCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif LocalSecurityXml.h000066400000000000000000000014171321503522500411210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef LocalSecurityXml_h_ #define LocalSecurityXml_h_ #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the LocalSecurity class to/from XML namespace LocalSecurityXml { /// Adds the LocalSecurityDoc into the XML. void PERSISTENCEXML_LINKAGE add( const SmartPtrCLocalSecurityDoc localSecurityDoc, const SmartPtrCXmlElement thisXml); /// Parses the LocalSecurityDoc from the XML. SmartPtrCLocalSecurityDoc PERSISTENCEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PersistenceProtocolCollectionXml.h000066400000000000000000000016631321503522500443640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef PersistenceProtocolCollectionXml_h_ #define PersistenceProtocolCollectionXml_h_ #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the PersistenceProtocolCollection class to/from XML namespace PersistenceProtocolCollectionXml { /// Adds the PersistenceProtocolCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the PersistenceProtocolCollectionDoc from the XML. SmartPtrCPersistenceProtocolCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PersistenceProtocolXml.h000066400000000000000000000015131321503522500423420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef PersistenceProtocolXml_h_ #define PersistenceProtocolXml_h_ #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the PersistenceProtocol class to/from XML namespace PersistenceProtocolXml { /// Adds the PersistenceProtocolDoc into the XML. void PERSISTENCEXML_LINKAGE add( const SmartPtrCPersistenceProtocolDoc persistenceProtocolDoc, const SmartPtrCXmlElement thisXml); /// Parses the PersistenceProtocolDoc from the XML. SmartPtrCPersistenceProtocolDoc PERSISTENCEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PersistenceXml.h000066400000000000000000000013731321503522500406240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef PersistenceXml_h_ #define PersistenceXml_h_ #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Persistence class to/from XML namespace PersistenceXml { /// Adds the PersistenceDoc into the XML. void PERSISTENCEXML_LINKAGE add( const SmartPtrCPersistenceDoc persistenceDoc, const SmartPtrCXmlElement thisXml); /// Parses the PersistenceDoc from the XML. SmartPtrCPersistenceDoc PERSISTENCEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PersistenceXmlLink.h000066400000000000000000000010521321503522500414340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef PersistenceXml_Link_h_ #define PersistenceXml_Link_h_ #ifndef PERSISTENCEXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PERSISTENCEXML_LINKAGE __declspec(dllexport) #else #define PERSISTENCEXML_LINKAGE __declspec(dllimport) #endif #else #define PERSISTENCEXML_LINKAGE #endif #endif #endif /* PersistenceXml_Link_h_ */ PersistenceXmlRoots.h000066400000000000000000000020231321503522500416440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef PersistenceXmlRoots_h_ #define PersistenceXmlRoots_h_ #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlLink.h" namespace Caf { namespace XmlRoots { /// Saves the PersistenceDoc to a string. std::string PERSISTENCEXML_LINKAGE savePersistenceToString( const SmartPtrCPersistenceDoc persistenceDoc); /// Parses the PersistenceDoc from the string. SmartPtrCPersistenceDoc PERSISTENCEXML_LINKAGE parsePersistenceFromString( const std::string xml); /// Saves the PersistenceDoc to a file. void PERSISTENCEXML_LINKAGE savePersistenceToFile( const SmartPtrCPersistenceDoc persistenceDoc, const std::string filePath); /// Parses the PersistenceDoc from the file. SmartPtrCPersistenceDoc PERSISTENCEXML_LINKAGE parsePersistenceFromFile( const std::string filePath); } } #endif /* PersistenceXmlRoots_h_ */ RemoteSecurityCollectionXml.h000066400000000000000000000016011321503522500433310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef RemoteSecurityCollectionXml_h_ #define RemoteSecurityCollectionXml_h_ #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the RemoteSecurityCollection class to/from XML namespace RemoteSecurityCollectionXml { /// Adds the RemoteSecurityCollectionDoc into the XML. void CAFCORETYPESXML_LINKAGE add( const SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the RemoteSecurityCollectionDoc from the XML. SmartPtrCRemoteSecurityCollectionDoc CAFCORETYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif RemoteSecurityXml.h000066400000000000000000000014311321503522500413160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef RemoteSecurityXml_h_ #define RemoteSecurityXml_h_ #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the RemoteSecurity class to/from XML namespace RemoteSecurityXml { /// Adds the RemoteSecurityDoc into the XML. void PERSISTENCEXML_LINKAGE add( const SmartPtrCRemoteSecurityDoc remoteSecurityDoc, const SmartPtrCXmlElement thisXml); /// Parses the RemoteSecurityDoc from the XML. SmartPtrCRemoteSecurityDoc PERSISTENCEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderInfraXml/000077500000000000000000000000001321503522500357705ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlClassCollectionXml.h000066400000000000000000000016641321503522500417120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ClassCollectionXml_h_ #define ClassCollectionXml_h_ #include "Doc/ProviderInfraDoc/CClassCollectionDoc.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ClassCollection class to/from XML namespace ClassCollectionXml { /// Adds the ClassCollectionDoc into the XML. void PROVIDERINFRAXML_LINKAGE add( const SmartPtrCClassCollectionDoc classCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the ClassCollectionDoc from the XML. SmartPtrCClassCollectionDoc PROVIDERINFRAXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderInfraXmlLink.h000066400000000000000000000012771321503522500422210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderInfraXml_Link_h_ #define ProviderInfraXml_Link_h_ #ifndef PROVIDERINFRAXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PROVIDERINFRAXML_LINKAGE __declspec(dllexport) #else #define PROVIDERINFRAXML_LINKAGE __declspec(dllimport) #endif #else #define PROVIDERINFRAXML_LINKAGE #endif #endif #endif /* ProviderInfraXml_Link_h_ */ ProviderInfraXmlRoots.h000066400000000000000000000036161321503522500424310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderInfraXmlRoots_h_ #define ProviderInfraXmlRoots_h_ #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlLink.h" #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" namespace Caf { namespace XmlRoots { /// Saves the ProviderRegDoc to a string. std::string PROVIDERINFRAXML_LINKAGE saveProviderRegToString( const SmartPtrCProviderRegDoc providerRegDoc); /// Parses the SchemaSummaryDoc from the string. SmartPtrCProviderRegDoc PROVIDERINFRAXML_LINKAGE parseProviderRegFromString( const std::string xml); /// Saves the ProviderRegDoc to a file. void PROVIDERINFRAXML_LINKAGE saveProviderRegToFile( const SmartPtrCProviderRegDoc providerRegDoc, const std::string filePath); /// Parses the SchemaSummaryDoc from the file. SmartPtrCProviderRegDoc PROVIDERINFRAXML_LINKAGE parseProviderRegFromFile( const std::string filePath); /// Saves the SchemaSummaryDoc to a string. std::string PROVIDERINFRAXML_LINKAGE saveSchemaSummaryToString( const SmartPtrCSchemaSummaryDoc schemaSummaryDoc); /// Parses the SchemaSummaryDoc from the string. SmartPtrCSchemaSummaryDoc PROVIDERINFRAXML_LINKAGE parseSchemaSummaryFromString( const std::string xml); /// Saves the SchemaSummaryDoc to a file. void PROVIDERINFRAXML_LINKAGE saveSchemaSummaryToFile( const SmartPtrCSchemaSummaryDoc schemaSummaryDoc, const std::string filePath); /// Parses the SchemaSummaryDoc from the file. SmartPtrCSchemaSummaryDoc PROVIDERINFRAXML_LINKAGE parseSchemaSummaryFromFile( const std::string filePath); } } #endif /* ProviderInfraXmlRoots_h_ */ ProviderRegXml.h000066400000000000000000000016141321503522500410540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderRegXml_h_ #define ProviderRegXml_h_ #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderReg class to/from XML namespace ProviderRegXml { /// Adds the ProviderRegDoc into the XML. void PROVIDERINFRAXML_LINKAGE add( const SmartPtrCProviderRegDoc providerRegDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderRegDoc from the XML. SmartPtrCProviderRegDoc PROVIDERINFRAXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif SchemaSummaryXml.h000066400000000000000000000016401321503522500414010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef SchemaSummaryXml_h_ #define SchemaSummaryXml_h_ #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the SchemaSummary class to/from XML namespace SchemaSummaryXml { /// Adds the SchemaSummaryDoc into the XML. void PROVIDERINFRAXML_LINKAGE add( const SmartPtrCSchemaSummaryDoc schemaSummaryDoc, const SmartPtrCXmlElement thisXml); /// Parses the SchemaSummaryDoc from the XML. SmartPtrCSchemaSummaryDoc PROVIDERINFRAXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderRequestXml/000077500000000000000000000000001321503522500363615ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlProviderBatchXml.h000066400000000000000000000016521321503522500417530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderBatchXml_h_ #define ProviderBatchXml_h_ #include "Doc/ProviderRequestDoc/CProviderBatchDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderBatch class to/from XML namespace ProviderBatchXml { /// Adds the ProviderBatchDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderBatchDoc providerBatchDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderBatchDoc from the XML. SmartPtrCProviderBatchDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderCollectInstancesCollectionXml.h000066400000000000000000000021741321503522500462030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderCollectInstancesCollectionXml_h_ #define ProviderCollectInstancesCollectionXml_h_ #include "Doc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderCollectInstancesCollection class to/from XML namespace ProviderCollectInstancesCollectionXml { /// Adds the ProviderCollectInstancesCollectionDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderCollectInstancesCollectionDoc providerCollectInstancesCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderCollectInstancesCollectionDoc from the XML. SmartPtrCProviderCollectInstancesCollectionDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderCollectInstancesXml.h000066400000000000000000000020301321503522500441560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderCollectInstancesXml_h_ #define ProviderCollectInstancesXml_h_ #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderCollectInstances class to/from XML namespace ProviderCollectInstancesXml { /// Adds the ProviderCollectInstancesDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderCollectInstancesDoc providerCollectInstancesDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderCollectInstancesDoc from the XML. SmartPtrCProviderCollectInstancesDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderCollectSchemaRequestXml.h000066400000000000000000000021001321503522500447760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderCollectSchemaRequestXml_h_ #define ProviderCollectSchemaRequestXml_h_ #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderCollectSchemaRequest class to/from XML namespace ProviderCollectSchemaRequestXml { /// Adds the ProviderCollectSchemaRequestDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderCollectSchemaRequestDoc from the XML. SmartPtrCProviderCollectSchemaRequestDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderInvokeOperationCollectionXml.h000066400000000000000000000021621321503522500460570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderInvokeOperationCollectionXml_h_ #define ProviderInvokeOperationCollectionXml_h_ #include "Doc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderInvokeOperationCollection class to/from XML namespace ProviderInvokeOperationCollectionXml { /// Adds the ProviderInvokeOperationCollectionDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderInvokeOperationCollectionDoc providerInvokeOperationCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderInvokeOperationCollectionDoc from the XML. SmartPtrCProviderInvokeOperationCollectionDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderInvokeOperationXml.h000066400000000000000000000020161321503522500440410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderInvokeOperationXml_h_ #define ProviderInvokeOperationXml_h_ #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderInvokeOperation class to/from XML namespace ProviderInvokeOperationXml { /// Adds the ProviderInvokeOperationDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderInvokeOperationDoc providerInvokeOperationDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderInvokeOperationDoc from the XML. SmartPtrCProviderInvokeOperationDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderRequestConfigXml.h000066400000000000000000000017721321503522500435130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderRequestConfigXml_h_ #define ProviderRequestConfigXml_h_ #include "Doc/ProviderRequestDoc/CProviderRequestConfigDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderRequestConfig class to/from XML namespace ProviderRequestConfigXml { /// Adds the ProviderRequestConfigDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderRequestConfigDoc providerRequestConfigDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderRequestConfigDoc from the XML. SmartPtrCProviderRequestConfigDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderRequestHeaderXml.h000066400000000000000000000017721321503522500434760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderRequestHeaderXml_h_ #define ProviderRequestHeaderXml_h_ #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderRequestHeader class to/from XML namespace ProviderRequestHeaderXml { /// Adds the ProviderRequestHeaderDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderRequestHeaderDoc providerRequestHeaderDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderRequestHeaderDoc from the XML. SmartPtrCProviderRequestHeaderDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderRequestXml.h000066400000000000000000000016761321503522500423700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderRequestXml_h_ #define ProviderRequestXml_h_ #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderRequest class to/from XML namespace ProviderRequestXml { /// Adds the ProviderRequestDoc into the XML. void PROVIDERREQUESTXML_LINKAGE add( const SmartPtrCProviderRequestDoc providerRequestDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderRequestDoc from the XML. SmartPtrCProviderRequestDoc PROVIDERREQUESTXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderRequestXmlLink.h000066400000000000000000000013151321503522500431740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderRequestXml_Link_h_ #define ProviderRequestXml_Link_h_ #ifndef PROVIDERREQUESTXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PROVIDERREQUESTXML_LINKAGE __declspec(dllexport) #else #define PROVIDERREQUESTXML_LINKAGE __declspec(dllimport) #endif #else #define PROVIDERREQUESTXML_LINKAGE #endif #endif #endif /* ProviderRequestXml_Link_h_ */ ProviderRequestXmlRoots.h000066400000000000000000000043371321503522500434140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderRequestXmlRoots_h_ #define ProviderRequestXmlRoots_h_ #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" namespace Caf { namespace XmlRoots { /// Saves the ProviderCollectSchemaRequestDoc to a string. std::string PROVIDERREQUESTXML_LINKAGE saveProviderCollectSchemaRequestToString( const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc); /// Parses the ProviderCollectSchemaRequestDoc from the string. SmartPtrCProviderCollectSchemaRequestDoc PROVIDERREQUESTXML_LINKAGE parseProviderCollectSchemaRequestFromString( const std::string xml); /// Saves the ProviderCollectSchemaRequestDoc to a file. void PROVIDERREQUESTXML_LINKAGE saveProviderCollectSchemaRequestToFile( const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc, const std::string filePath); /// Parses the ProviderCollectSchemaRequestDoc from the file. SmartPtrCProviderCollectSchemaRequestDoc PROVIDERREQUESTXML_LINKAGE parseProviderCollectSchemaRequestFromFile( const std::string filePath); /// Saves the ProviderRequestDoc to a string. std::string PROVIDERREQUESTXML_LINKAGE saveProviderRequestToString( const SmartPtrCProviderRequestDoc providerRequestDoc); /// Parses the ProviderCollectSchemaRequestDoc from the string. SmartPtrCProviderRequestDoc PROVIDERREQUESTXML_LINKAGE parseProviderRequestFromString( const std::string xml); /// Saves the ProviderRequestDoc to a file. void PROVIDERREQUESTXML_LINKAGE saveProviderRequestToFile( const SmartPtrCProviderRequestDoc providerRequestDoc, const std::string filePath); /// Parses the ProviderCollectSchemaRequestDoc from the file. SmartPtrCProviderRequestDoc PROVIDERREQUESTXML_LINKAGE parseProviderRequestFromFile( const std::string filePath); } } #endif /* ProviderRequestXmlRoots_h_ */ ProviderResultsXml/000077500000000000000000000000001321503522500363725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlCdifXml.h000066400000000000000000000015201321503522500400670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef CdifXml_h_ #define CdifXml_h_ #include "Doc/ProviderResultsDoc/CCdifDoc.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Cdif class to/from XML namespace CdifXml { /// Adds the CdifDoc into the XML. void PROVIDERRESULTSXML_LINKAGE add( const SmartPtrCCdifDoc cdifDoc, const SmartPtrCXmlElement thisXml); /// Parses the CdifDoc from the XML. SmartPtrCCdifDoc PROVIDERRESULTSXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DefinitionObjectCollectionXml.h000066400000000000000000000020541321503522500444600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DefinitionObjectCollectionXml_h_ #define DefinitionObjectCollectionXml_h_ #include "Doc/ProviderResultsDoc/CDefinitionObjectCollectionDoc.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DefinitionObjectCollection class to/from XML namespace DefinitionObjectCollectionXml { /// Adds the DefinitionObjectCollectionDoc into the XML. void PROVIDERRESULTSXML_LINKAGE add( const SmartPtrCDefinitionObjectCollectionDoc definitionObjectCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the DefinitionObjectCollectionDoc from the XML. SmartPtrCDefinitionObjectCollectionDoc PROVIDERRESULTSXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderResultsXmlLink.h000066400000000000000000000013151321503522500432160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderResultsXml_Link_h_ #define ProviderResultsXml_Link_h_ #ifndef PROVIDERRESULTSXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PROVIDERRESULTSXML_LINKAGE __declspec(dllexport) #else #define PROVIDERRESULTSXML_LINKAGE __declspec(dllimport) #endif #else #define PROVIDERRESULTSXML_LINKAGE #endif #endif #endif /* ProviderResultsXml_Link_h_ */ ProviderResultsXmlRoots.h000066400000000000000000000034521321503522500434330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderResultsXmlRoots_h_ #define ProviderResultsXmlRoots_h_ #include "Doc/ProviderResultsDoc/CCdifDoc.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlLink.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" namespace Caf { namespace XmlRoots { /// Saves the SchemaDoc to a string. std::string PROVIDERRESULTSXML_LINKAGE saveSchemaToString( const SmartPtrCSchemaDoc schemaDoc); /// Parses the DefinitionObjectCollectionDoc from the string. SmartPtrCSchemaDoc PROVIDERRESULTSXML_LINKAGE parseSchemaFromString( const std::string xml); /// Saves the SchemaDoc to a file. void PROVIDERRESULTSXML_LINKAGE saveSchemaToFile( const SmartPtrCSchemaDoc schemaDoc, const std::string filePath); /// Parses the DefinitionObjectCollectionDoc from the file. SmartPtrCSchemaDoc PROVIDERRESULTSXML_LINKAGE parseSchemaFromFile( const std::string filePath); /// Saves the CdifDoc to a string. std::string PROVIDERRESULTSXML_LINKAGE saveCdifToString( const SmartPtrCCdifDoc cdifDoc); /// Parses the DefinitionObjectCollectionDoc from the string. SmartPtrCCdifDoc PROVIDERRESULTSXML_LINKAGE parseCdifFromString( const std::string xml); /// Saves the CdifDoc to a file. void PROVIDERRESULTSXML_LINKAGE saveCdifToFile( const SmartPtrCCdifDoc cdifDoc, const std::string filePath); /// Parses the DefinitionObjectCollectionDoc from the file. SmartPtrCCdifDoc PROVIDERRESULTSXML_LINKAGE parseCdifFromFile( const std::string filePath); } } #endif /* ProviderResultsXmlRoots_h_ */ RequestIdentifierXml.h000066400000000000000000000017221321503522500426610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef RequestIdentifierXml_h_ #define RequestIdentifierXml_h_ #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the RequestIdentifier class to/from XML namespace RequestIdentifierXml { /// Adds the RequestIdentifierDoc into the XML. void PROVIDERRESULTSXML_LINKAGE add( const SmartPtrCRequestIdentifierDoc requestIdentifierDoc, const SmartPtrCXmlElement thisXml); /// Parses the RequestIdentifierDoc from the XML. SmartPtrCRequestIdentifierDoc PROVIDERRESULTSXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif SchemaXml.h000066400000000000000000000015441321503522500404300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef SchemaXml_h_ #define SchemaXml_h_ #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Schema class to/from XML namespace SchemaXml { /// Adds the SchemaDoc into the XML. void PROVIDERRESULTSXML_LINKAGE add( const SmartPtrCSchemaDoc schemaDoc, const SmartPtrCXmlElement thisXml); /// Parses the SchemaDoc from the XML. SmartPtrCSchemaDoc PROVIDERRESULTSXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ResponseXml/000077500000000000000000000000001321503522500350145ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlErrorResponseXml.h000066400000000000000000000016071321503522500404620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ErrorResponseXml_h_ #define ErrorResponseXml_h_ #include "Doc/ResponseDoc/CErrorResponseDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ErrorResponse class to/from XML namespace ErrorResponseXml { /// Adds the ErrorResponseDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCErrorResponseDoc errorResponseDoc, const SmartPtrCXmlElement thisXml); /// Parses the ErrorResponseDoc from the XML. SmartPtrCErrorResponseDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif EventKeyCollectionXml.h000066400000000000000000000016711321503522500414210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef EventKeyCollectionXml_h_ #define EventKeyCollectionXml_h_ #include "Doc/ResponseDoc/CEventKeyCollectionDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the EventKeyCollection class to/from XML namespace EventKeyCollectionXml { /// Adds the EventKeyCollectionDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCEventKeyCollectionDoc eventKeyCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the EventKeyCollectionDoc from the XML. SmartPtrCEventKeyCollectionDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif EventKeyXml.h000066400000000000000000000015251321503522500374030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef EventKeyXml_h_ #define EventKeyXml_h_ #include "Doc/ResponseDoc/CEventKeyDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the EventKey class to/from XML namespace EventKeyXml { /// Adds the EventKeyDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCEventKeyDoc eventKeyDoc, const SmartPtrCXmlElement thisXml); /// Parses the EventKeyDoc from the XML. SmartPtrCEventKeyDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif EventManifestXml.h000066400000000000000000000016071321503522500404220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef EventManifestXml_h_ #define EventManifestXml_h_ #include "Doc/ResponseDoc/CEventManifestDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the EventManifest class to/from XML namespace EventManifestXml { /// Adds the EventManifestDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCEventManifestDoc eventManifestDoc, const SmartPtrCXmlElement thisXml); /// Parses the EventManifestDoc from the XML. SmartPtrCEventManifestDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ManifestCollectionXml.h000066400000000000000000000016711321503522500414350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ManifestCollectionXml_h_ #define ManifestCollectionXml_h_ #include "Doc/ResponseDoc/CManifestCollectionDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ManifestCollection class to/from XML namespace ManifestCollectionXml { /// Adds the ManifestCollectionDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCManifestCollectionDoc manifestCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the ManifestCollectionDoc from the XML. SmartPtrCManifestCollectionDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ManifestXml.h000066400000000000000000000015251321503522500374170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ManifestXml_h_ #define ManifestXml_h_ #include "Doc/ResponseDoc/CManifestDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Manifest class to/from XML namespace ManifestXml { /// Adds the ManifestDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCManifestDoc manifestDoc, const SmartPtrCXmlElement thisXml); /// Parses the ManifestDoc from the XML. SmartPtrCManifestDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderEventResponseXml.h000066400000000000000000000017271321503522500421700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderEventResponseXml_h_ #define ProviderEventResponseXml_h_ #include "Doc/ResponseDoc/CProviderEventResponseDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderEventResponse class to/from XML namespace ProviderEventResponseXml { /// Adds the ProviderEventResponseDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCProviderEventResponseDoc providerEventResponseDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderEventResponseDoc from the XML. SmartPtrCProviderEventResponseDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ProviderResponseXml.h000066400000000000000000000016451321503522500411650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ProviderResponseXml_h_ #define ProviderResponseXml_h_ #include "Doc/ResponseDoc/CProviderResponseDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ProviderResponse class to/from XML namespace ProviderResponseXml { /// Adds the ProviderResponseDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCProviderResponseDoc providerResponseDoc, const SmartPtrCXmlElement thisXml); /// Parses the ProviderResponseDoc from the XML. SmartPtrCProviderResponseDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ResponseHeaderXml.h000066400000000000000000000016211321503522500405550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ResponseHeaderXml_h_ #define ResponseHeaderXml_h_ #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ResponseHeader class to/from XML namespace ResponseHeaderXml { /// Adds the ResponseHeaderDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCResponseHeaderDoc responseHeaderDoc, const SmartPtrCXmlElement thisXml); /// Parses the ResponseHeaderDoc from the XML. SmartPtrCResponseHeaderDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ResponseXml.h000066400000000000000000000015251321503522500374470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ResponseXml_h_ #define ResponseXml_h_ #include "Doc/ResponseDoc/CResponseDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Response class to/from XML namespace ResponseXml { /// Adds the ResponseDoc into the XML. void RESPONSEXML_LINKAGE add( const SmartPtrCResponseDoc responseDoc, const SmartPtrCXmlElement thisXml); /// Parses the ResponseDoc from the XML. SmartPtrCResponseDoc RESPONSEXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ResponseXmlLink.h000066400000000000000000000012341321503522500402620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ResponseXml_Link_h_ #define ResponseXml_Link_h_ #ifndef RESPONSEXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define RESPONSEXML_LINKAGE __declspec(dllexport) #else #define RESPONSEXML_LINKAGE __declspec(dllimport) #endif #else #define RESPONSEXML_LINKAGE #endif #endif #endif /* ResponseXml_Link_h_ */ ResponseXmlRoots.h000066400000000000000000000064571321503522500405070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ResponseXmlRoots_h_ #define ResponseXmlRoots_h_ #include "Doc/ResponseDoc/CErrorResponseDoc.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Doc/ResponseDoc/CProviderEventResponseDoc.h" #include "Doc/ResponseDoc/CProviderResponseDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" namespace Caf { namespace XmlRoots { /// Saves the ErrorResponseDoc to a string. std::string RESPONSEXML_LINKAGE saveErrorResponseToString( const SmartPtrCErrorResponseDoc errorResponseDoc); /// Parses the ErrorResponseDoc from the string. SmartPtrCErrorResponseDoc RESPONSEXML_LINKAGE parseErrorResponseFromString( const std::string xml); /// Saves the ErrorResponseDoc to a file. void RESPONSEXML_LINKAGE saveErrorResponseToFile( const SmartPtrCErrorResponseDoc errorResponseDoc, const std::string filePath); /// Parses the ErrorResponseDoc from the file. SmartPtrCErrorResponseDoc RESPONSEXML_LINKAGE parseErrorResponseFromFile( const std::string filePath); /// Saves the ProviderResponseDoc to a string. std::string RESPONSEXML_LINKAGE saveProviderResponseToString( const SmartPtrCProviderResponseDoc providerResponseDoc); /// Parses the ErrorResponseDoc from the string. SmartPtrCProviderResponseDoc RESPONSEXML_LINKAGE parseProviderResponseFromString( const std::string xml); /// Saves the ProviderResponseDoc to a file. void RESPONSEXML_LINKAGE saveProviderResponseToFile( const SmartPtrCProviderResponseDoc providerResponseDoc, const std::string filePath); /// Parses the ErrorResponseDoc from the file. SmartPtrCProviderResponseDoc RESPONSEXML_LINKAGE parseProviderResponseFromFile( const std::string filePath); /// Saves the ResponseDoc to a string. std::string RESPONSEXML_LINKAGE saveResponseToString( const SmartPtrCResponseDoc responseDoc); /// Parses the ErrorResponseDoc from the string. SmartPtrCResponseDoc RESPONSEXML_LINKAGE parseResponseFromString( const std::string xml); /// Saves the ResponseDoc to a file. void RESPONSEXML_LINKAGE saveResponseToFile( const SmartPtrCResponseDoc responseDoc, const std::string filePath); /// Parses the ErrorResponseDoc from the file. SmartPtrCResponseDoc RESPONSEXML_LINKAGE parseResponseFromFile( const std::string filePath); /// Saves the ProviderEventResponseDoc to a string. std::string RESPONSEXML_LINKAGE saveProviderEventResponseToString( const SmartPtrCProviderEventResponseDoc providerEventResponseDoc); /// Parses the ErrorResponseDoc from the string. SmartPtrCProviderEventResponseDoc RESPONSEXML_LINKAGE parseProviderEventResponseFromString( const std::string xml); /// Saves the ProviderEventResponseDoc to a file. void RESPONSEXML_LINKAGE saveProviderEventResponseToFile( const SmartPtrCProviderEventResponseDoc providerEventResponseDoc, const std::string filePath); /// Parses the ErrorResponseDoc from the file. SmartPtrCProviderEventResponseDoc RESPONSEXML_LINKAGE parseProviderEventResponseFromFile( const std::string filePath); } } #endif /* ResponseXmlRoots_h_ */ SchemaTypesXml/000077500000000000000000000000001321503522500354435ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXmlActionClassInstanceCollectionXml.h000066400000000000000000000020661321503522500442050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ActionClassInstanceCollectionXml_h_ #define ActionClassInstanceCollectionXml_h_ #include "Doc/SchemaTypesDoc/CActionClassInstanceCollectionDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ActionClassInstanceCollection class to/from XML namespace ActionClassInstanceCollectionXml { /// Adds the ActionClassInstanceCollectionDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCActionClassInstanceCollectionDoc actionClassInstanceCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the ActionClassInstanceCollectionDoc from the XML. SmartPtrCActionClassInstanceCollectionDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ActionClassInstanceXml.h000066400000000000000000000017221321503522500421670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ActionClassInstanceXml_h_ #define ActionClassInstanceXml_h_ #include "Doc/SchemaTypesDoc/CActionClassInstanceDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ActionClassInstance class to/from XML namespace ActionClassInstanceXml { /// Adds the ActionClassInstanceDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCActionClassInstanceDoc actionClassInstanceDoc, const SmartPtrCXmlElement thisXml); /// Parses the ActionClassInstanceDoc from the XML. SmartPtrCActionClassInstanceDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ActionClassXml.h000066400000000000000000000016021321503522500404770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ActionClassXml_h_ #define ActionClassXml_h_ #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ActionClass class to/from XML namespace ActionClassXml { /// Adds the ActionClassDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCActionClassDoc actionClassDoc, const SmartPtrCXmlElement thisXml); /// Parses the ActionClassDoc from the XML. SmartPtrCActionClassDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ClassCardinalityXml.h000066400000000000000000000016641321503522500415350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ClassCardinalityXml_h_ #define ClassCardinalityXml_h_ #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ClassCardinality class to/from XML namespace ClassCardinalityXml { /// Adds the ClassCardinalityDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCClassCardinalityDoc classCardinalityDoc, const SmartPtrCXmlElement thisXml); /// Parses the ClassCardinalityDoc from the XML. SmartPtrCClassCardinalityDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ClassFieldXml.h000066400000000000000000000015701321503522500403110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ClassFieldXml_h_ #define ClassFieldXml_h_ #include "Doc/SchemaTypesDoc/CClassFieldDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ClassField class to/from XML namespace ClassFieldXml { /// Adds the ClassFieldDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCClassFieldDoc classFieldDoc, const SmartPtrCXmlElement thisXml); /// Parses the ClassFieldDoc from the XML. SmartPtrCClassFieldDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ClassIdentifierXml.h000066400000000000000000000016521321503522500413510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ClassIdentifierXml_h_ #define ClassIdentifierXml_h_ #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ClassIdentifier class to/from XML namespace ClassIdentifierXml { /// Adds the ClassIdentifierDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCClassIdentifierDoc classIdentifierDoc, const SmartPtrCXmlElement thisXml); /// Parses the ClassIdentifierDoc from the XML. SmartPtrCClassIdentifierDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ClassInstancePropertyXml.h000066400000000000000000000017461321503522500426040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ClassInstancePropertyXml_h_ #define ClassInstancePropertyXml_h_ #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ClassInstanceProperty class to/from XML namespace ClassInstancePropertyXml { /// Adds the ClassInstancePropertyDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCClassInstancePropertyDoc classInstancePropertyDoc, const SmartPtrCXmlElement thisXml); /// Parses the ClassInstancePropertyDoc from the XML. SmartPtrCClassInstancePropertyDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif ClassPropertyXml.h000066400000000000000000000016261321503522500411140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef ClassPropertyXml_h_ #define ClassPropertyXml_h_ #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the ClassProperty class to/from XML namespace ClassPropertyXml { /// Adds the ClassPropertyDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCClassPropertyDoc classPropertyDoc, const SmartPtrCXmlElement thisXml); /// Parses the ClassPropertyDoc from the XML. SmartPtrCClassPropertyDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif CmdlMetadataXml.h000066400000000000000000000016141321503522500406170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef CmdlMetadataXml_h_ #define CmdlMetadataXml_h_ #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the CmdlMetadata class to/from XML namespace CmdlMetadataXml { /// Adds the CmdlMetadataDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCCmdlMetadataDoc cmdlMetadataDoc, const SmartPtrCXmlElement thisXml); /// Parses the CmdlMetadataDoc from the XML. SmartPtrCCmdlMetadataDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif CmdlUnionXml.h000066400000000000000000000015561321503522500401740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef CmdlUnionXml_h_ #define CmdlUnionXml_h_ #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the CmdlUnion class to/from XML namespace CmdlUnionXml { /// Adds the CmdlUnionDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCCmdlUnionDoc cmdlUnionDoc, const SmartPtrCXmlElement thisXml); /// Parses the CmdlUnionDoc from the XML. SmartPtrCCmdlUnionDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif CollectMethodXml.h000066400000000000000000000016261321503522500410300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef CollectMethodXml_h_ #define CollectMethodXml_h_ #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the CollectMethod class to/from XML namespace CollectMethodXml { /// Adds the CollectMethodDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCCollectMethodDoc collectMethodDoc, const SmartPtrCXmlElement thisXml); /// Parses the CollectMethodDoc from the XML. SmartPtrCCollectMethodDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DataClassInstanceCollectionXml.h000066400000000000000000000020421321503522500436330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DataClassInstanceCollectionXml_h_ #define DataClassInstanceCollectionXml_h_ #include "Doc/SchemaTypesDoc/CDataClassInstanceCollectionDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DataClassInstanceCollection class to/from XML namespace DataClassInstanceCollectionXml { /// Adds the DataClassInstanceCollectionDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCDataClassInstanceCollectionDoc dataClassInstanceCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the DataClassInstanceCollectionDoc from the XML. SmartPtrCDataClassInstanceCollectionDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DataClassInstanceXml.h000066400000000000000000000016761321503522500416330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DataClassInstanceXml_h_ #define DataClassInstanceXml_h_ #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DataClassInstance class to/from XML namespace DataClassInstanceXml { /// Adds the DataClassInstanceDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCDataClassInstanceDoc dataClassInstanceDoc, const SmartPtrCXmlElement thisXml); /// Parses the DataClassInstanceDoc from the XML. SmartPtrCDataClassInstanceDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DataClassPropertyXml.h000066400000000000000000000016761321503522500417130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DataClassPropertyXml_h_ #define DataClassPropertyXml_h_ #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DataClassProperty class to/from XML namespace DataClassPropertyXml { /// Adds the DataClassPropertyDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCDataClassPropertyDoc dataClassPropertyDoc, const SmartPtrCXmlElement thisXml); /// Parses the DataClassPropertyDoc from the XML. SmartPtrCDataClassPropertyDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DataClassSubInstanceXml.h000066400000000000000000000017341321503522500423000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DataClassSubInstanceXml_h_ #define DataClassSubInstanceXml_h_ #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DataClassSubInstance class to/from XML namespace DataClassSubInstanceXml { /// Adds the DataClassSubInstanceDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCDataClassSubInstanceDoc dataClassSubInstanceDoc, const SmartPtrCXmlElement thisXml); /// Parses the DataClassSubInstanceDoc from the XML. SmartPtrCDataClassSubInstanceDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif DataClassXml.h000066400000000000000000000015561321503522500401430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DataClassXml_h_ #define DataClassXml_h_ #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the DataClass class to/from XML namespace DataClassXml { /// Adds the DataClassDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCDataClassDoc dataClassDoc, const SmartPtrCXmlElement thisXml); /// Parses the DataClassDoc from the XML. SmartPtrCDataClassDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif InstanceOperationCollectionXml.h000066400000000000000000000020421321503522500437340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef InstanceOperationCollectionXml_h_ #define InstanceOperationCollectionXml_h_ #include "Doc/SchemaTypesDoc/CInstanceOperationCollectionDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the InstanceOperationCollection class to/from XML namespace InstanceOperationCollectionXml { /// Adds the InstanceOperationCollectionDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCInstanceOperationCollectionDoc instanceOperationCollectionDoc, const SmartPtrCXmlElement thisXml); /// Parses the InstanceOperationCollectionDoc from the XML. SmartPtrCInstanceOperationCollectionDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif InstanceOperationXml.h000066400000000000000000000016761321503522500417340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef InstanceOperationXml_h_ #define InstanceOperationXml_h_ #include "Doc/SchemaTypesDoc/CInstanceOperationDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the InstanceOperation class to/from XML namespace InstanceOperationXml { /// Adds the InstanceOperationDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCInstanceOperationDoc instanceOperationDoc, const SmartPtrCXmlElement thisXml); /// Parses the InstanceOperationDoc from the XML. SmartPtrCInstanceOperationDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif InstanceParameterXml.h000066400000000000000000000016761321503522500417140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef InstanceParameterXml_h_ #define InstanceParameterXml_h_ #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the InstanceParameter class to/from XML namespace InstanceParameterXml { /// Adds the InstanceParameterDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCInstanceParameterDoc instanceParameterDoc, const SmartPtrCXmlElement thisXml); /// Parses the InstanceParameterDoc from the XML. SmartPtrCInstanceParameterDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif JoinTypeXml.h000066400000000000000000000015441321503522500400420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef JoinTypeXml_h_ #define JoinTypeXml_h_ #include "Doc/SchemaTypesDoc/CJoinTypeDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the JoinType class to/from XML namespace JoinTypeXml { /// Adds the JoinTypeDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCJoinTypeDoc joinTypeDoc, const SmartPtrCXmlElement thisXml); /// Parses the JoinTypeDoc from the XML. SmartPtrCJoinTypeDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif LogicalRelationshipXml.h000066400000000000000000000017221321503522500422330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef LogicalRelationshipXml_h_ #define LogicalRelationshipXml_h_ #include "Doc/SchemaTypesDoc/CLogicalRelationshipDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the LogicalRelationship class to/from XML namespace LogicalRelationshipXml { /// Adds the LogicalRelationshipDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCLogicalRelationshipDoc logicalRelationshipDoc, const SmartPtrCXmlElement thisXml); /// Parses the LogicalRelationshipDoc from the XML. SmartPtrCLogicalRelationshipDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MethodParameterXml.h000066400000000000000000000016521321503522500413620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MethodParameterXml_h_ #define MethodParameterXml_h_ #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the MethodParameter class to/from XML namespace MethodParameterXml { /// Adds the MethodParameterDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCMethodParameterDoc methodParameterDoc, const SmartPtrCXmlElement thisXml); /// Parses the MethodParameterDoc from the XML. SmartPtrCMethodParameterDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif MethodXml.h000066400000000000000000000015201321503522500375130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef MethodXml_h_ #define MethodXml_h_ #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Method class to/from XML namespace MethodXml { /// Adds the MethodDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCMethodDoc methodDoc, const SmartPtrCXmlElement thisXml); /// Parses the MethodDoc from the XML. SmartPtrCMethodDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif PhysicalRelationshipXml.h000066400000000000000000000017341321503522500424400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef PhysicalRelationshipXml_h_ #define PhysicalRelationshipXml_h_ #include "Doc/SchemaTypesDoc/CPhysicalRelationshipDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the PhysicalRelationship class to/from XML namespace PhysicalRelationshipXml { /// Adds the PhysicalRelationshipDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCPhysicalRelationshipDoc physicalRelationshipDoc, const SmartPtrCXmlElement thisXml); /// Parses the PhysicalRelationshipDoc from the XML. SmartPtrCPhysicalRelationshipDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif RelationshipXml.h000066400000000000000000000016141321503522500407400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef RelationshipXml_h_ #define RelationshipXml_h_ #include "Doc/SchemaTypesDoc/CRelationshipDoc.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Streams the Relationship class to/from XML namespace RelationshipXml { /// Adds the RelationshipDoc into the XML. void SCHEMATYPESXML_LINKAGE add( const SmartPtrCRelationshipDoc relationshipDoc, const SmartPtrCXmlElement thisXml); /// Parses the RelationshipDoc from the XML. SmartPtrCRelationshipDoc SCHEMATYPESXML_LINKAGE parse( const SmartPtrCXmlElement thisXml); } } #endif SchemaTypesXmlLink.h000066400000000000000000000012611321503522500413400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef SchemaTypesXml_Link_h_ #define SchemaTypesXml_Link_h_ #ifndef SCHEMATYPESXML_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define SCHEMATYPESXML_LINKAGE __declspec(dllexport) #else #define SCHEMATYPESXML_LINKAGE __declspec(dllimport) #endif #else #define SCHEMATYPESXML_LINKAGE #endif #endif #endif /* SchemaTypesXml_Link_h_ */ MgmtRequestDoc/000077500000000000000000000000001321503522500342525ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCMgmtRequestDoc.h000066400000000000000000000033031321503522500374300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMgmtRequestDoc_h_ #define CMgmtRequestDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" namespace Caf { /// A simple container for objects of type MgmtRequest class MGMTREQUESTDOC_LINKAGE CMgmtRequestDoc { public: CMgmtRequestDoc(); virtual ~CMgmtRequestDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCRequestHeaderDoc requestHeader, const SmartPtrCMgmtBatchDoc batch, const SmartPtrCAttachmentCollectionDoc attachmentCollection); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the RequestHeader SmartPtrCRequestHeaderDoc getRequestHeader() const; /// Accessor for the Batch SmartPtrCMgmtBatchDoc getBatch() const; /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc getAttachmentCollection() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; SmartPtrCRequestHeaderDoc _requestHeader; SmartPtrCMgmtBatchDoc _batch; SmartPtrCAttachmentCollectionDoc _attachmentCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CMgmtRequestDoc); }; CAF_DECLARE_SMART_POINTER(CMgmtRequestDoc); } #endif MgmtRequestDocLink.h000066400000000000000000000010521321503522500401420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef MgmtRequestDoc_Link_h_ #define MgmtRequestDoc_Link_h_ #ifndef MGMTREQUESTDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define MGMTREQUESTDOC_LINKAGE __declspec(dllexport) #else #define MGMTREQUESTDOC_LINKAGE __declspec(dllimport) #endif #else #define MGMTREQUESTDOC_LINKAGE #endif #endif #endif /* MgmtRequestDoc_Link_h_ */ MgmtTypesDoc/000077500000000000000000000000001321503522500337265ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCMgmtBatchDoc.h000066400000000000000000000031461321503522500365020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMgmtBatchDoc_h_ #define CMgmtBatchDoc_h_ #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectSchemaDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" namespace Caf { /// A simple container for objects of type MgmtBatch class MGMTTYPESDOC_LINKAGE CMgmtBatchDoc { public: CMgmtBatchDoc(); virtual ~CMgmtBatchDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCMgmtCollectSchemaDoc collectSchema, const SmartPtrCMgmtCollectInstancesCollectionDoc collectInstancesCollection, const SmartPtrCMgmtInvokeOperationCollectionDoc invokeOperationCollection); public: /// Accessor for the CollectSchema SmartPtrCMgmtCollectSchemaDoc getCollectSchema() const; /// Accessor for the CollectInstancesCollection SmartPtrCMgmtCollectInstancesCollectionDoc getCollectInstancesCollection() const; /// Accessor for the InvokeOperationCollection SmartPtrCMgmtInvokeOperationCollectionDoc getInvokeOperationCollection() const; private: bool _isInitialized; SmartPtrCMgmtCollectSchemaDoc _collectSchema; SmartPtrCMgmtCollectInstancesCollectionDoc _collectInstancesCollection; SmartPtrCMgmtInvokeOperationCollectionDoc _invokeOperationCollection; private: CAF_CM_DECLARE_NOCOPY(CMgmtBatchDoc); }; CAF_DECLARE_SMART_POINTER(CMgmtBatchDoc); } #endif CMgmtCollectInstancesCollectionDoc.h000066400000000000000000000022641321503522500427320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMgmtCollectInstancesCollectionDoc_h_ #define CMgmtCollectInstancesCollectionDoc_h_ #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" namespace Caf { /// A simple container for objects of type MgmtCollectInstancesCollection class MGMTTYPESDOC_LINKAGE CMgmtCollectInstancesCollectionDoc { public: CMgmtCollectInstancesCollectionDoc(); virtual ~CMgmtCollectInstancesCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque collectInstancesCollection); public: /// Accessor for the CollectInstances std::deque getCollectInstancesCollection() const; private: bool _isInitialized; std::deque _collectInstancesCollection; private: CAF_CM_DECLARE_NOCOPY(CMgmtCollectInstancesCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CMgmtCollectInstancesCollectionDoc); } #endif CMgmtCollectInstancesDoc.h000066400000000000000000000025641321503522500407210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMgmtCollectInstancesDoc_h_ #define CMgmtCollectInstancesDoc_h_ #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" namespace Caf { /// A simple container for objects of type MgmtCollectInstances class MGMTTYPESDOC_LINKAGE CMgmtCollectInstancesDoc { public: CMgmtCollectInstancesDoc(); virtual ~CMgmtCollectInstancesDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID jobId, const SmartPtrCClassSpecifierDoc classSpecifier, const SmartPtrCParameterCollectionDoc parameterCollection); public: /// Accessor for the JobId UUID getJobId() const; /// Accessor for the ClassSpecifier SmartPtrCClassSpecifierDoc getClassSpecifier() const; /// Accessor for the ParameterCollection SmartPtrCParameterCollectionDoc getParameterCollection() const; private: UUID _jobId; SmartPtrCClassSpecifierDoc _classSpecifier; SmartPtrCParameterCollectionDoc _parameterCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CMgmtCollectInstancesDoc); }; CAF_DECLARE_SMART_POINTER(CMgmtCollectInstancesDoc); } #endif CMgmtCollectSchemaDoc.h000066400000000000000000000015201321503522500401610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMgmtCollectSchemaDoc_h_ #define CMgmtCollectSchemaDoc_h_ namespace Caf { /// A simple container for objects of type MgmtCollectSchema class MGMTTYPESDOC_LINKAGE CMgmtCollectSchemaDoc { public: CMgmtCollectSchemaDoc(); virtual ~CMgmtCollectSchemaDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID jobId); public: /// Accessor for the JobId UUID getJobId() const; private: UUID _jobId; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CMgmtCollectSchemaDoc); }; CAF_DECLARE_SMART_POINTER(CMgmtCollectSchemaDoc); } #endif CMgmtInvokeOperationCollectionDoc.h000066400000000000000000000022441321503522500426070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMgmtInvokeOperationCollectionDoc_h_ #define CMgmtInvokeOperationCollectionDoc_h_ #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" namespace Caf { /// A simple container for objects of type MgmtInvokeOperationCollection class MGMTTYPESDOC_LINKAGE CMgmtInvokeOperationCollectionDoc { public: CMgmtInvokeOperationCollectionDoc(); virtual ~CMgmtInvokeOperationCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque invokeOperationCollection); public: /// Accessor for the InvokeOperation std::deque getInvokeOperationCollection() const; private: bool _isInitialized; std::deque _invokeOperationCollection; private: CAF_CM_DECLARE_NOCOPY(CMgmtInvokeOperationCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CMgmtInvokeOperationCollectionDoc); } #endif CMgmtInvokeOperationDoc.h000066400000000000000000000024341321503522500405740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMgmtInvokeOperationDoc_h_ #define CMgmtInvokeOperationDoc_h_ #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" namespace Caf { /// A simple container for objects of type MgmtInvokeOperation class MGMTTYPESDOC_LINKAGE CMgmtInvokeOperationDoc { public: CMgmtInvokeOperationDoc(); virtual ~CMgmtInvokeOperationDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID jobId, const SmartPtrCClassSpecifierDoc classSpecifier, const SmartPtrCOperationDoc operation); public: /// Accessor for the JobId UUID getJobId() const; /// Accessor for the ClassSpecifier SmartPtrCClassSpecifierDoc getClassSpecifier() const; /// Accessor for the Operation SmartPtrCOperationDoc getOperation() const; private: UUID _jobId; SmartPtrCClassSpecifierDoc _classSpecifier; SmartPtrCOperationDoc _operation; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CMgmtInvokeOperationDoc); }; CAF_DECLARE_SMART_POINTER(CMgmtInvokeOperationDoc); } #endif MgmtTypesDocLink.h000066400000000000000000000010341321503522500372720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MgmtTypesDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef MgmtTypesDoc_Link_h_ #define MgmtTypesDoc_Link_h_ #ifndef MGMTTYPESDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define MGMTTYPESDOC_LINKAGE __declspec(dllexport) #else #define MGMTTYPESDOC_LINKAGE __declspec(dllimport) #endif #else #define MGMTTYPESDOC_LINKAGE #endif #endif #endif /* MgmtTypesDoc_Link_h_ */ MultiPmeMgmtRequestDoc/000077500000000000000000000000001321503522500357275ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCMultiPmeMgmtBatchCollectionDoc.h000066400000000000000000000021721321503522500441720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMultiPmeMgmtBatchCollectionDoc_h_ #define CMultiPmeMgmtBatchCollectionDoc_h_ #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchDoc.h" namespace Caf { /// A simple container for objects of type MultiPmeMgmtBatchCollection class MULTIPMEMGMTREQUESTDOC_LINKAGE CMultiPmeMgmtBatchCollectionDoc { public: CMultiPmeMgmtBatchCollectionDoc(); virtual ~CMultiPmeMgmtBatchCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque multiPmeBatch); public: /// Accessor for the MultiPmeBatch std::deque getMultiPmeBatch() const; private: bool _isInitialized; std::deque _multiPmeBatch; private: CAF_CM_DECLARE_NOCOPY(CMultiPmeMgmtBatchCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CMultiPmeMgmtBatchCollectionDoc); } #endif CMultiPmeMgmtBatchDoc.h000066400000000000000000000022741321503522500421610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMultiPmeMgmtBatchDoc_h_ #define CMultiPmeMgmtBatchDoc_h_ #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CPmeIdCollectionDoc.h" namespace Caf { /// A simple container for objects of type MultiPmeMgmtBatch class MULTIPMEMGMTREQUESTDOC_LINKAGE CMultiPmeMgmtBatchDoc { public: CMultiPmeMgmtBatchDoc(); virtual ~CMultiPmeMgmtBatchDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCPmeIdCollectionDoc pmeIdCollection, const SmartPtrCMgmtBatchDoc batch); public: /// Accessor for the PmeIdCollection SmartPtrCPmeIdCollectionDoc getPmeIdCollection() const; /// Accessor for the Batch SmartPtrCMgmtBatchDoc getBatch() const; private: bool _isInitialized; SmartPtrCPmeIdCollectionDoc _pmeIdCollection; SmartPtrCMgmtBatchDoc _batch; private: CAF_CM_DECLARE_NOCOPY(CMultiPmeMgmtBatchDoc); }; CAF_DECLARE_SMART_POINTER(CMultiPmeMgmtBatchDoc); } #endif CMultiPmeMgmtRequestDoc.h000066400000000000000000000030301321503522500425570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMultiPmeMgmtRequestDoc_h_ #define CMultiPmeMgmtRequestDoc_h_ #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchCollectionDoc.h" namespace Caf { /// A simple container for objects of type MultiPmeMgmtRequest class MULTIPMEMGMTREQUESTDOC_LINKAGE CMultiPmeMgmtRequestDoc { public: CMultiPmeMgmtRequestDoc(); virtual ~CMultiPmeMgmtRequestDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const SmartPtrCRequestHeaderDoc requestHeader, const SmartPtrCMultiPmeMgmtBatchCollectionDoc multiPmeBatchCollection); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the RequestHeader SmartPtrCRequestHeaderDoc getRequestHeader() const; /// Accessor for the MultiPmeBatchCollection SmartPtrCMultiPmeMgmtBatchCollectionDoc getMultiPmeBatchCollection() const; private: UUID _clientId; UUID _requestId; SmartPtrCRequestHeaderDoc _requestHeader; SmartPtrCMultiPmeMgmtBatchCollectionDoc _multiPmeBatchCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CMultiPmeMgmtRequestDoc); }; CAF_DECLARE_SMART_POINTER(CMultiPmeMgmtRequestDoc); } #endif CPmeIdCollectionDoc.h000066400000000000000000000016421321503522500416460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CPmeIdCollectionDoc_h_ #define CPmeIdCollectionDoc_h_ namespace Caf { /// A simple container for objects of type PmeIdCollection class MULTIPMEMGMTREQUESTDOC_LINKAGE CPmeIdCollectionDoc { public: CPmeIdCollectionDoc(); virtual ~CPmeIdCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque pmeIdCollection); public: /// Accessor for the PmeId std::deque getPmeIdCollection() const; private: bool _isInitialized; std::deque _pmeIdCollection; private: CAF_CM_DECLARE_NOCOPY(CPmeIdCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CPmeIdCollectionDoc); } #endif MultiPmeMgmtRequestDocLink.h000066400000000000000000000011421321503522500432740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef MultiPmeMgmtRequestDoc_Link_h_ #define MultiPmeMgmtRequestDoc_Link_h_ #ifndef MULTIPMEMGMTREQUESTDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define MULTIPMEMGMTREQUESTDOC_LINKAGE __declspec(dllexport) #else #define MULTIPMEMGMTREQUESTDOC_LINKAGE __declspec(dllimport) #endif #else #define MULTIPMEMGMTREQUESTDOC_LINKAGE #endif #endif #endif /* MultiPmeMgmtRequestDoc_Link_h_ */ PayloadEnvelopeDoc/000077500000000000000000000000001321503522500350645ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCPayloadEnvelopeDoc.h000066400000000000000000000044641321503522500410650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PayloadEnvelopeDoc/* * Author: bwilliams * Created: July 3, 2015 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CPayloadEnvelopeDoc_h_ #define CPayloadEnvelopeDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" namespace Caf { /// A simple container for objects of type PayloadEnvelope class PAYLOADENVELOPEDOC_LINKAGE CPayloadEnvelopeDoc { public: CPayloadEnvelopeDoc(); virtual ~CPayloadEnvelopeDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID& clientId, const UUID& requestId, const std::string& pmeId, const std::string& payloadType, const std::string& payloadVersion, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const SmartPtrCProtocolCollectionDoc& protocolCollection = SmartPtrCProtocolCollectionDoc(), const SmartPtrCPropertyCollectionDoc& headerCollection = SmartPtrCPropertyCollectionDoc(), const std::string version = "1.0"); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the PayloadType std::string getPayloadType() const; /// Accessor for the PayloadVersion std::string getPayloadVersion() const; /// Accessor for the Protocol Collection SmartPtrCProtocolCollectionDoc getProtocolCollection() const; /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc getAttachmentCollection() const; /// Accessor for the Headers SmartPtrCPropertyCollectionDoc getHeaderCollection() const; /// Accessor for the version std::string getVersion() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; std::string _payloadType; std::string _payloadVersion; SmartPtrCAttachmentCollectionDoc _attachmentCollection; SmartPtrCProtocolCollectionDoc _protocolCollection; SmartPtrCPropertyCollectionDoc _headerCollection; std::string _version; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CPayloadEnvelopeDoc); }; CAF_DECLARE_SMART_POINTER(CPayloadEnvelopeDoc); } #endif PayloadEnvelopeDocLink.h000066400000000000000000000011061321503522500415660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PayloadEnvelopeDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef PayloadEnvelopeDoc_Link_h_ #define PayloadEnvelopeDoc_Link_h_ #ifndef PAYLOADENVELOPEDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PAYLOADENVELOPEDOC_LINKAGE __declspec(dllexport) #else #define PAYLOADENVELOPEDOC_LINKAGE __declspec(dllimport) #endif #else #define PAYLOADENVELOPEDOC_LINKAGE #endif #endif #endif /* PayloadEnvelopeDoc_Link_h_ */ PersistenceDoc/000077500000000000000000000000001321503522500342615ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCCertCollectionDoc.h000066400000000000000000000016401321503522500400750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CCertCollectionDoc_h_ #define CCertCollectionDoc_h_ namespace Caf { /// A simple container for objects of type CertCollection class PERSISTENCEDOC_LINKAGE CCertCollectionDoc { public: CCertCollectionDoc(); virtual ~CCertCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque certCollection = std::deque()); public: /// Accessor for the Cert std::deque getCert() const; private: bool _isInitialized; std::deque _certCollection; private: CAF_CM_DECLARE_NOCOPY(CCertCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CCertCollectionDoc); } #endif CCertPathCollectionDoc.h000066400000000000000000000017141321503522500407140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CCertPathCollectionDoc_h_ #define CCertPathCollectionDoc_h_ namespace Caf { /// A simple container for objects of type CertPathCollection class PERSISTENCEDOC_LINKAGE CCertPathCollectionDoc { public: CCertPathCollectionDoc(); virtual ~CCertPathCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque certPathCollection = std::deque()); public: /// Accessor for the Cert std::deque getCertPath() const; private: bool _isInitialized; std::deque _certPathCollection; private: CAF_CM_DECLARE_NOCOPY(CCertPathCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CCertPathCollectionDoc); } #endif CLocalSecurityDoc.h000066400000000000000000000026331321503522500377510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CLocalSecurityDoc_h_ #define CLocalSecurityDoc_h_ namespace Caf { /// A simple container for objects of type CLocalSecurityDoc class PERSISTENCEDOC_LINKAGE CLocalSecurityDoc { public: CLocalSecurityDoc(); virtual ~CLocalSecurityDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string& localId = std::string(), const std::string& privateKey = std::string(), const std::string& cert = std::string(), const std::string& privateKeyPath = std::string(), const std::string& certPath = std::string()); public: /// Accessor for the LocalId std::string getLocalId() const; /// Accessor for the PrivateKey std::string getPrivateKey() const; /// Accessor for the Cert std::string getCert() const; /// Accessor for the PrivateKeyPath std::string getPrivateKeyPath() const; /// Accessor for the CertPath std::string getCertPath() const; private: std::string _localId; std::string _privateKey; std::string _cert; std::string _privateKeyPath; std::string _certPath; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CLocalSecurityDoc); }; CAF_DECLARE_SMART_POINTER(CLocalSecurityDoc); } #endif CPersistenceDoc.h000066400000000000000000000035071321503522500374540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CPersistenceDoc_h_ #define CPersistenceDoc_h_ #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" namespace Caf { /// A simple container for objects of type PersistenceEnvelope class PERSISTENCEDOC_LINKAGE CPersistenceDoc { public: CPersistenceDoc(); virtual ~CPersistenceDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCLocalSecurityDoc& localSecurity = SmartPtrCLocalSecurityDoc(), const SmartPtrCRemoteSecurityCollectionDoc& remoteSecurityCollection = SmartPtrCRemoteSecurityCollectionDoc(), const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollection = SmartPtrCPersistenceProtocolCollectionDoc(), const std::string version = "1.0"); public: /// Accessor for the LocalSecurity SmartPtrCLocalSecurityDoc getLocalSecurity() const; /// Accessor for the Protocol Collection SmartPtrCRemoteSecurityCollectionDoc getRemoteSecurityCollection() const; /// Accessor for the PersistenceProtocol SmartPtrCPersistenceProtocolCollectionDoc getPersistenceProtocolCollection() const; /// Accessor for the version std::string getVersion() const; private: SmartPtrCLocalSecurityDoc _localSecurity; SmartPtrCRemoteSecurityCollectionDoc _remoteSecurityCollection; SmartPtrCPersistenceProtocolCollectionDoc _persistenceProtocolCollection; std::string _version; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CPersistenceDoc); }; CAF_DECLARE_SMART_POINTER(CPersistenceDoc); } #endif CPersistenceProtocolCollectionDoc.h000066400000000000000000000023121321503522500432030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CPersistenceProtocolCollectionDoc_h_ #define CPersistenceProtocolCollectionDoc_h_ #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" namespace Caf { /// A simple container for objects of type PersistenceProtocolCollection class PERSISTENCEDOC_LINKAGE CPersistenceProtocolCollectionDoc { public: CPersistenceProtocolCollectionDoc(); virtual ~CPersistenceProtocolCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque persistenceProtocol = std::deque()); public: /// Accessor for the PersistenceProtocol std::deque getPersistenceProtocol() const; private: bool _isInitialized; std::deque _persistenceProtocol; private: CAF_CM_DECLARE_NOCOPY(CPersistenceProtocolCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CPersistenceProtocolCollectionDoc); } #endif CPersistenceProtocolDoc.h000066400000000000000000000054351321503522500412000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CPersistenceProtocolDoc_h_ #define CPersistenceProtocolDoc_h_ #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" namespace Caf { /// A simple container for objects of type CPersistenceProtocolDoc class PERSISTENCEDOC_LINKAGE CPersistenceProtocolDoc { public: CPersistenceProtocolDoc(); virtual ~CPersistenceProtocolDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string& protocolName = std::string(), const std::string& uri = std::string(), const std::string& uriAmqp = std::string(), const std::string& uriTunnel = std::string(), const std::string& tlsCert = std::string(), const std::string& tlsProtocol = std::string(), const Cdeqstr& tlsCipherCollection = Cdeqstr(), const SmartPtrCCertCollectionDoc& tlsCertCollection = SmartPtrCCertCollectionDoc(), const std::string& uriAmqpPath = std::string(), const std::string& uriTunnelPath = std::string(), const std::string& tlsCertPath = std::string(), const SmartPtrCCertPathCollectionDoc& tlsCertPathCollection = SmartPtrCCertPathCollectionDoc()); public: /// Accessor for the ProtocolName std::string getProtocolName() const; /// Accessor for the Uri std::string getUri() const; /// Accessor for the UriAmqp std::string getUriAmqp() const; /// Accessor for the UriTunnel std::string getUriTunnel() const; /// Accessor for the TlsCert std::string getTlsCert() const; /// Accessor for the TlsProtocol std::string getTlsProtocol() const; /// Accessor for the tlsCipherCollection Cdeqstr getTlsCipherCollection() const; /// Accessor for the TlsCertCollection SmartPtrCCertCollectionDoc getTlsCertCollection() const; /// Accessor for the UriAmqpPath std::string getUriAmqpPath() const; /// Accessor for the UriTunnelPath std::string getUriTunnelPath() const; /// Accessor for the TlsCertPath std::string getTlsCertPath() const; /// Accessor for the TlsCertPathCollection SmartPtrCCertPathCollectionDoc getTlsCertPathCollection() const; private: std::string _protocolName; std::string _uri; std::string _uriAmqp; std::string _uriTunnel; std::string _tlsCert; std::string _tlsProtocol; Cdeqstr _tlsCipherCollection; SmartPtrCCertCollectionDoc _tlsCertCollection; std::string _uriAmqpPath; std::string _uriTunnelPath; std::string _tlsCertPath; SmartPtrCCertPathCollectionDoc _tlsCertPathCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CPersistenceProtocolDoc); }; CAF_DECLARE_SMART_POINTER(CPersistenceProtocolDoc); } #endif CRemoteSecurityCollectionDoc.h000066400000000000000000000021651321503522500421660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CRemoteSecurityCollectionDoc_h_ #define CRemoteSecurityCollectionDoc_h_ #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" namespace Caf { /// A simple container for objects of type RemoteSecurityCollection class PERSISTENCEDOC_LINKAGE CRemoteSecurityCollectionDoc { public: CRemoteSecurityCollectionDoc(); virtual ~CRemoteSecurityCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque remoteSecurity = std::deque()); public: /// Accessor for the RemoteSecurity std::deque getRemoteSecurity() const; private: bool _isInitialized; std::deque _remoteSecurity; private: CAF_CM_DECLARE_NOCOPY(CRemoteSecurityCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CRemoteSecurityCollectionDoc); } #endif CRemoteSecurityDoc.h000066400000000000000000000040221321503522500401440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CRemoteSecurityDoc_h_ #define CRemoteSecurityDoc_h_ #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" namespace Caf { /// A simple container for objects of type CRemoteSecurityDoc class PERSISTENCEDOC_LINKAGE CRemoteSecurityDoc { public: CRemoteSecurityDoc(); virtual ~CRemoteSecurityDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string& remoteId = std::string(), const std::string& protocolName = std::string(), const std::string& cmsCert = std::string(), const std::string& cmsCipherName = std::string(), const SmartPtrCCertCollectionDoc& cmsCertCollection = SmartPtrCCertCollectionDoc(), const std::string& cmsCertPath = std::string(), const SmartPtrCCertPathCollectionDoc& cmsCertPathCollection = SmartPtrCCertPathCollectionDoc()); public: /// Accessor for the RemoteId std::string getRemoteId() const; /// Accessor for the ProtocolName std::string getProtocolName() const; /// Accessor for the cmsCert std::string getCmsCert() const; /// Accessor for the CmsCipher std::string getCmsCipherName() const; /// Accessor for the CertCollection SmartPtrCCertCollectionDoc getCmsCertCollection() const; /// Accessor for the cmsCertPath std::string getCmsCertPath() const; /// Accessor for the CertPathCollection SmartPtrCCertPathCollectionDoc getCmsCertPathCollection() const; private: std::string _remoteId; std::string _protocolName; std::string _cmsCert; std::string _cmsCipherName; SmartPtrCCertCollectionDoc _cmsCertCollection; std::string _cmsCertPath; SmartPtrCCertPathCollectionDoc _cmsCertPathCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CRemoteSecurityDoc); }; CAF_DECLARE_SMART_POINTER(CRemoteSecurityDoc); } #endif PersistenceDocLink.h000066400000000000000000000010521321503522500401600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/PersistenceDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef PersistenceDoc_Link_h_ #define PersistenceDoc_Link_h_ #ifndef PERSISTENCEDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PERSISTENCEDOC_LINKAGE __declspec(dllexport) #else #define PERSISTENCEDOC_LINKAGE __declspec(dllimport) #endif #else #define PERSISTENCEDOC_LINKAGE #endif #endif #endif /* PersistenceDoc_Link_h_ */ ProviderInfraDoc/000077500000000000000000000000001321503522500345475ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCClassCollectionDoc.h000066400000000000000000000021011321503522500405240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderInfraDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CClassCollectionDoc_h_ #define CClassCollectionDoc_h_ #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" namespace Caf { /// A simple container for objects of type ClassCollection class PROVIDERINFRADOC_LINKAGE CClassCollectionDoc { public: CClassCollectionDoc(); virtual ~CClassCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque fullyQualifiedClass); public: /// Accessor for the FullyQualifiedClass std::deque getFullyQualifiedClass() const; private: bool _isInitialized; std::deque _fullyQualifiedClass; private: CAF_CM_DECLARE_NOCOPY(CClassCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CClassCollectionDoc); } #endif CProviderRegDoc.h000066400000000000000000000027721321503522500377110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderInfraDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderRegDoc_h_ #define CProviderRegDoc_h_ namespace Caf { /// A simple container for objects of type ProviderReg class PROVIDERINFRADOC_LINKAGE CProviderRegDoc { public: CProviderRegDoc(); virtual ~CProviderRegDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const int32 staleSec, const bool isSchemaVisible, const std::string invokerRelPath); public: /// Accessor for the ProviderNamespace std::string getProviderNamespace() const; /// Accessor for the ProviderName std::string getProviderName() const; /// Accessor for the ProviderVersion std::string getProviderVersion() const; /// Accessor for the StaleSec int32 getStaleSec() const; /// Accessor for the IsSchemaVisible bool getIsSchemaVisible() const; /// Accessor for the InvokerRelPath std::string getInvokerRelPath() const; private: std::string _providerNamespace; std::string _providerName; std::string _providerVersion; int32 _staleSec; bool _isSchemaVisible; std::string _invokerRelPath; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CProviderRegDoc); }; CAF_DECLARE_SMART_POINTER(CProviderRegDoc); } #endif CSchemaSummaryDoc.h000066400000000000000000000030261321503522500402300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderInfraDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CSchemaSummaryDoc_h_ #define CSchemaSummaryDoc_h_ #include "Doc/ProviderInfraDoc/CClassCollectionDoc.h" namespace Caf { /// A simple container for objects of type SchemaSummary class PROVIDERINFRADOC_LINKAGE CSchemaSummaryDoc { public: CSchemaSummaryDoc(); virtual ~CSchemaSummaryDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const SmartPtrCClassCollectionDoc classCollection, const std::string invokerPath); public: /// Accessor for the ProviderNamespace std::string getProviderNamespace() const; /// Accessor for the ProviderName std::string getProviderName() const; /// Accessor for the ProviderVersion std::string getProviderVersion() const; /// Accessor for the ClassCollection SmartPtrCClassCollectionDoc getClassCollection() const; /// Accessor for the InvokerPath std::string getInvokerPath() const; private: bool _isInitialized; std::string _providerNamespace; std::string _providerName; std::string _providerVersion; SmartPtrCClassCollectionDoc _classCollection; std::string _invokerPath; private: CAF_CM_DECLARE_NOCOPY(CSchemaSummaryDoc); }; CAF_DECLARE_SMART_POINTER(CSchemaSummaryDoc); } #endif ProviderInfraDocLink.h000066400000000000000000000010701321503522500407340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderInfraDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef ProviderInfraDoc_Link_h_ #define ProviderInfraDoc_Link_h_ #ifndef PROVIDERINFRADOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PROVIDERINFRADOC_LINKAGE __declspec(dllexport) #else #define PROVIDERINFRADOC_LINKAGE __declspec(dllimport) #endif #else #define PROVIDERINFRADOC_LINKAGE #endif #endif #endif /* ProviderInfraDoc_Link_h_ */ ProviderRequestDoc/000077500000000000000000000000001321503522500351405ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCProviderBatchDoc.h000066400000000000000000000030761321503522500406040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderBatchDoc_h_ #define CProviderBatchDoc_h_ #include "Doc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.h" namespace Caf { /// A simple container for objects of type ProviderBatch class PROVIDERREQUESTDOC_LINKAGE CProviderBatchDoc { public: CProviderBatchDoc(); virtual ~CProviderBatchDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string outputDir, const SmartPtrCProviderCollectInstancesCollectionDoc collectInstancesCollection, const SmartPtrCProviderInvokeOperationCollectionDoc invokeOperationCollection); public: /// Accessor for the OutputDir std::string getOutputDir() const; /// Accessor for the CollectInstancesCollection SmartPtrCProviderCollectInstancesCollectionDoc getCollectInstancesCollection() const; /// Accessor for the InvokeOperationCollection SmartPtrCProviderInvokeOperationCollectionDoc getInvokeOperationCollection() const; private: bool _isInitialized; std::string _outputDir; SmartPtrCProviderCollectInstancesCollectionDoc _collectInstancesCollection; SmartPtrCProviderInvokeOperationCollectionDoc _invokeOperationCollection; private: CAF_CM_DECLARE_NOCOPY(CProviderBatchDoc); }; CAF_DECLARE_SMART_POINTER(CProviderBatchDoc); } #endif CProviderCollectInstancesCollectionDoc.h000066400000000000000000000023221321503522500450250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderCollectInstancesCollectionDoc_h_ #define CProviderCollectInstancesCollectionDoc_h_ #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" namespace Caf { /// A simple container for objects of type ProviderCollectInstancesCollection class PROVIDERREQUESTDOC_LINKAGE CProviderCollectInstancesCollectionDoc { public: CProviderCollectInstancesCollectionDoc(); virtual ~CProviderCollectInstancesCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque collectInstances); public: /// Accessor for the CollectInstances std::deque getCollectInstances() const; private: bool _isInitialized; std::deque _collectInstances; private: CAF_CM_DECLARE_NOCOPY(CProviderCollectInstancesCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CProviderCollectInstancesCollectionDoc); } #endif CProviderCollectInstancesDoc.h000066400000000000000000000032711321503522500430150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderCollectInstancesDoc_h_ #define CProviderCollectInstancesDoc_h_ #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" namespace Caf { /// A simple container for objects of type ProviderCollectInstances class PROVIDERREQUESTDOC_LINKAGE CProviderCollectInstancesDoc { public: CProviderCollectInstancesDoc(); virtual ~CProviderCollectInstancesDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string classNamespace, const std::string className, const std::string classVersion, const UUID jobId, const std::string outputDir, const SmartPtrCParameterCollectionDoc parameterCollection); public: /// Accessor for the ClassNamespace std::string getClassNamespace() const; /// Accessor for the ClassName std::string getClassName() const; /// Accessor for the ClassVersion std::string getClassVersion() const; /// Accessor for the JobId UUID getJobId() const; /// Accessor for the OutputDir std::string getOutputDir() const; /// Accessor for the ParameterCollection SmartPtrCParameterCollectionDoc getParameterCollection() const; private: std::string _classNamespace; std::string _className; std::string _classVersion; UUID _jobId; std::string _outputDir; SmartPtrCParameterCollectionDoc _parameterCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CProviderCollectInstancesDoc); }; CAF_DECLARE_SMART_POINTER(CProviderCollectInstancesDoc); } #endif CProviderCollectSchemaRequestDoc.h000066400000000000000000000031561321503522500436410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderCollectSchemaRequestDoc_h_ #define CProviderCollectSchemaRequestDoc_h_ #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" namespace Caf { /// A simple container for objects of type ProviderCollectSchemaRequest class PROVIDERREQUESTDOC_LINKAGE CProviderCollectSchemaRequestDoc { public: CProviderCollectSchemaRequestDoc(); virtual ~CProviderCollectSchemaRequestDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const UUID jobId, const std::string outputDir, const SmartPtrCProviderRequestHeaderDoc requestHeader); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the JobId UUID getJobId() const; /// Accessor for the OutputDir std::string getOutputDir() const; /// Accessor for the RequestHeader SmartPtrCProviderRequestHeaderDoc getRequestHeader() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; UUID _jobId; std::string _outputDir; SmartPtrCProviderRequestHeaderDoc _requestHeader; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CProviderCollectSchemaRequestDoc); }; CAF_DECLARE_SMART_POINTER(CProviderCollectSchemaRequestDoc); } #endif CProviderInvokeOperationCollectionDoc.h000066400000000000000000000023021321503522500447020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderInvokeOperationCollectionDoc_h_ #define CProviderInvokeOperationCollectionDoc_h_ #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" namespace Caf { /// A simple container for objects of type ProviderInvokeOperationCollection class PROVIDERREQUESTDOC_LINKAGE CProviderInvokeOperationCollectionDoc { public: CProviderInvokeOperationCollectionDoc(); virtual ~CProviderInvokeOperationCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque invokeOperation); public: /// Accessor for the InvokeOperation std::deque getInvokeOperation() const; private: bool _isInitialized; std::deque _invokeOperation; private: CAF_CM_DECLARE_NOCOPY(CProviderInvokeOperationCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CProviderInvokeOperationCollectionDoc); } #endif CProviderInvokeOperationDoc.h000066400000000000000000000031411321503522500426700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderInvokeOperationDoc_h_ #define CProviderInvokeOperationDoc_h_ #include "Doc/CafCoreTypesDoc/COperationDoc.h" namespace Caf { /// A simple container for objects of type ProviderInvokeOperation class PROVIDERREQUESTDOC_LINKAGE CProviderInvokeOperationDoc { public: CProviderInvokeOperationDoc(); virtual ~CProviderInvokeOperationDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string classNamespace, const std::string className, const std::string classVersion, const UUID jobId, const std::string outputDir, const SmartPtrCOperationDoc operation); public: /// Accessor for the ClassNamespace std::string getClassNamespace() const; /// Accessor for the ClassName std::string getClassName() const; /// Accessor for the ClassVersion std::string getClassVersion() const; /// Accessor for the JobId UUID getJobId() const; /// Accessor for the OutputDir std::string getOutputDir() const; /// Accessor for the Operation SmartPtrCOperationDoc getOperation() const; private: std::string _classNamespace; std::string _className; std::string _classVersion; UUID _jobId; std::string _outputDir; SmartPtrCOperationDoc _operation; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CProviderInvokeOperationDoc); }; CAF_DECLARE_SMART_POINTER(CProviderInvokeOperationDoc); } #endif CProviderRequestConfigDoc.h000066400000000000000000000023631321503522500423370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderRequestConfigDoc_h_ #define CProviderRequestConfigDoc_h_ #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" namespace Caf { /// A simple container for objects of type ProviderRequestConfig class PROVIDERREQUESTDOC_LINKAGE CProviderRequestConfigDoc { public: CProviderRequestConfigDoc(); virtual ~CProviderRequestConfigDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string responseFormatType, const SmartPtrCLoggingLevelCollectionDoc loggingLevelCollection); public: /// Accessor for the ResponseFormatType std::string getResponseFormatType() const; /// Accessor for the LoggingLevelCollection SmartPtrCLoggingLevelCollectionDoc getLoggingLevelCollection() const; private: bool _isInitialized; std::string _responseFormatType; SmartPtrCLoggingLevelCollectionDoc _loggingLevelCollection; private: CAF_CM_DECLARE_NOCOPY(CProviderRequestConfigDoc); }; CAF_DECLARE_SMART_POINTER(CProviderRequestConfigDoc); } #endif CProviderRequestDoc.h000066400000000000000000000034401321503522500412060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderRequestDoc_h_ #define CProviderRequestDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderBatchDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" namespace Caf { /// A simple container for objects of type ProviderRequest class PROVIDERREQUESTDOC_LINKAGE CProviderRequestDoc { public: CProviderRequestDoc(); virtual ~CProviderRequestDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCProviderRequestHeaderDoc requestHeader, const SmartPtrCProviderBatchDoc batch, const SmartPtrCAttachmentCollectionDoc attachmentCollection); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the RequestHeader SmartPtrCProviderRequestHeaderDoc getRequestHeader() const; /// Accessor for the Batch SmartPtrCProviderBatchDoc getBatch() const; /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc getAttachmentCollection() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; SmartPtrCProviderRequestHeaderDoc _requestHeader; SmartPtrCProviderBatchDoc _batch; SmartPtrCAttachmentCollectionDoc _attachmentCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CProviderRequestDoc); }; CAF_DECLARE_SMART_POINTER(CProviderRequestDoc); } #endif CProviderRequestHeaderDoc.h000066400000000000000000000024631321503522500423230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderRequestHeaderDoc_h_ #define CProviderRequestHeaderDoc_h_ #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestConfigDoc.h" namespace Caf { /// A simple container for objects of type ProviderRequestHeader class PROVIDERREQUESTDOC_LINKAGE CProviderRequestHeaderDoc { public: CProviderRequestHeaderDoc(); virtual ~CProviderRequestHeaderDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCProviderRequestConfigDoc requestConfig, const SmartPtrCPropertyCollectionDoc echoPropertyBag); public: /// Accessor for the RequestConfig SmartPtrCProviderRequestConfigDoc getRequestConfig() const; /// Accessor for the EchoPropertyBag SmartPtrCPropertyCollectionDoc getEchoPropertyBag() const; private: bool _isInitialized; SmartPtrCProviderRequestConfigDoc _requestConfig; SmartPtrCPropertyCollectionDoc _echoPropertyBag; private: CAF_CM_DECLARE_NOCOPY(CProviderRequestHeaderDoc); }; CAF_DECLARE_SMART_POINTER(CProviderRequestHeaderDoc); } #endif ProviderRequestDocLink.h000066400000000000000000000011061321503522500417160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef ProviderRequestDoc_Link_h_ #define ProviderRequestDoc_Link_h_ #ifndef PROVIDERREQUESTDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PROVIDERREQUESTDOC_LINKAGE __declspec(dllexport) #else #define PROVIDERREQUESTDOC_LINKAGE __declspec(dllimport) #endif #else #define PROVIDERREQUESTDOC_LINKAGE #endif #endif #endif /* ProviderRequestDoc_Link_h_ */ ProviderResultsDoc/000077500000000000000000000000001321503522500351515ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCCdifDoc.h000066400000000000000000000026561321503522500367310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderResultsDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CCdifDoc_h_ #define CCdifDoc_h_ #include "Doc/ProviderResultsDoc/CDefinitionObjectCollectionDoc.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" namespace Caf { /// A simple container for objects of type Cdif class PROVIDERRESULTSDOC_LINKAGE CCdifDoc { public: CCdifDoc(); virtual ~CCdifDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const SmartPtrCRequestIdentifierDoc requestIdentifier, const SmartPtrCDefinitionObjectCollectionDoc definitionObjectCollection, const SmartPtrCSchemaDoc schema); public: /// Accessor for the RequestIdentifier SmartPtrCRequestIdentifierDoc getRequestIdentifier() const; /// Accessor for the DefinitionObjectCollection SmartPtrCDefinitionObjectCollectionDoc getDefinitionObjectCollection() const; /// Accessor for the Schema SmartPtrCSchemaDoc getSchema() const; private: bool _isInitialized; SmartPtrCRequestIdentifierDoc _requestIdentifier; SmartPtrCDefinitionObjectCollectionDoc _definitionObjectCollection; SmartPtrCSchemaDoc _schema; private: CAF_CM_DECLARE_NOCOPY(CCdifDoc); }; CAF_DECLARE_SMART_POINTER(CCdifDoc); } #endif CDefinitionObjectCollectionDoc.h000066400000000000000000000017561321503522500433170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderResultsDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDefinitionObjectCollectionDoc_h_ #define CDefinitionObjectCollectionDoc_h_ namespace Caf { /// Set of elements containing data returned as a result of a provider collection or action class PROVIDERRESULTSDOC_LINKAGE CDefinitionObjectCollectionDoc { public: CDefinitionObjectCollectionDoc(); virtual ~CDefinitionObjectCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque value); public: /// Accessor for the Value std::deque getValue() const; private: bool _isInitialized; std::deque _value; private: CAF_CM_DECLARE_NOCOPY(CDefinitionObjectCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CDefinitionObjectCollectionDoc); } #endif CRequestIdentifierDoc.h000066400000000000000000000031021321503522500415020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderResultsDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CRequestIdentifierDoc_h_ #define CRequestIdentifierDoc_h_ #include "Doc/SchemaTypesDoc/CActionClassDoc.h" namespace Caf { /// Fields that allow client to determine which request resulted in this response document class PROVIDERRESULTSDOC_LINKAGE CRequestIdentifierDoc { public: CRequestIdentifierDoc(); virtual ~CRequestIdentifierDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const UUID jobId, const SmartPtrCActionClassDoc actionClass, const UUID sessionId); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Identifier of the specific job within the request UUID getJobId() const; /// Accessor for the ActionClass SmartPtrCActionClassDoc getActionClass() const; /// Client-configurable identifier that is opaque (not used) by the Common Agent Framework UUID getSessionId() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; UUID _jobId; SmartPtrCActionClassDoc _actionClass; UUID _sessionId; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CRequestIdentifierDoc); }; CAF_DECLARE_SMART_POINTER(CRequestIdentifierDoc); } #endif CSchemaDoc.h000066400000000000000000000040621321503522500372550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderResultsDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CSchemaDoc_h_ #define CSchemaDoc_h_ #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CLogicalRelationshipDoc.h" #include "Doc/SchemaTypesDoc/CPhysicalRelationshipDoc.h" namespace Caf { /// Set of elements describing the objects that can be generated by the provider class PROVIDERRESULTSDOC_LINKAGE CSchemaDoc { public: CSchemaDoc(); virtual ~CSchemaDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque dataClassCollection, const std::deque actionClassCollection, const std::deque logicalRelationshipCollection = std::deque(), const std::deque physicalRelationshipCollection = std::deque()); public: /// Accessor for the DataClassCollection std::deque getDataClassCollection() const; /// Accessor for the ActionClassCollection std::deque getActionClassCollection() const; /// Accessor for the LogicalRelationshipCollection std::deque getLogicalRelationshipCollection() const; /// Accessor for the PhysicalRelationshipCollection std::deque getPhysicalRelationshipCollection() const; private: bool _isInitialized; std::deque _dataClassCollection; std::deque _actionClassCollection; std::deque _logicalRelationshipCollection; std::deque _physicalRelationshipCollection; private: CAF_CM_DECLARE_NOCOPY(CSchemaDoc); }; CAF_DECLARE_SMART_POINTER(CSchemaDoc); } #endif ProviderResultsDocLink.h000066400000000000000000000011061321503522500417400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ProviderResultsDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef ProviderResultsDoc_Link_h_ #define ProviderResultsDoc_Link_h_ #ifndef PROVIDERRESULTSDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define PROVIDERRESULTSDOC_LINKAGE __declspec(dllexport) #else #define PROVIDERRESULTSDOC_LINKAGE __declspec(dllimport) #endif #else #define PROVIDERRESULTSDOC_LINKAGE #endif #endif #endif /* ProviderResultsDoc_Link_h_ */ ResponseDoc/000077500000000000000000000000001321503522500335735ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCErrorResponseDoc.h000066400000000000000000000026061321503522500373110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CErrorResponseDoc_h_ #define CErrorResponseDoc_h_ #include "Doc/ResponseDoc/CResponseHeaderDoc.h" namespace Caf { /// A simple container for objects of type ErrorResponse class RESPONSEDOC_LINKAGE CErrorResponseDoc { public: CErrorResponseDoc(); virtual ~CErrorResponseDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCResponseHeaderDoc responseHeader, const std::string errorMessage); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the Response Header SmartPtrCResponseHeaderDoc getResponseHeader() const; /// Accessor for the ErrorMessage std::string getErrorMessage() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; SmartPtrCResponseHeaderDoc _responseHeader; std::string _errorMessage; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CErrorResponseDoc); }; CAF_DECLARE_SMART_POINTER(CErrorResponseDoc); } #endif CEventKeyCollectionDoc.h000066400000000000000000000017441321503522500402510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CEventKeyCollectionDoc_h_ #define CEventKeyCollectionDoc_h_ #include "Doc/ResponseDoc/CEventKeyDoc.h" namespace Caf { /// A simple container for objects of type EventKeyCollection class RESPONSEDOC_LINKAGE CEventKeyCollectionDoc { public: CEventKeyCollectionDoc(); virtual ~CEventKeyCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque eventKey); public: /// Accessor for the EventKey std::deque getEventKey() const; private: bool _isInitialized; std::deque _eventKey; private: CAF_CM_DECLARE_NOCOPY(CEventKeyCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CEventKeyCollectionDoc); } #endif CEventKeyDoc.h000066400000000000000000000016051321503522500362310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CEventKeyDoc_h_ #define CEventKeyDoc_h_ namespace Caf { /// A simple container for objects of type EventKey class RESPONSEDOC_LINKAGE CEventKeyDoc { public: CEventKeyDoc(); virtual ~CEventKeyDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::string value); public: /// Accessor for the Name std::string getName() const; /// Accessor for the Value std::string getValue() const; private: bool _isInitialized; std::string _name; std::string _value; private: CAF_CM_DECLARE_NOCOPY(CEventKeyDoc); }; CAF_DECLARE_SMART_POINTER(CEventKeyDoc); } #endif CEventManifestDoc.h000066400000000000000000000030341321503522500372450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CEventManifestDoc_h_ #define CEventManifestDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" namespace Caf { /// A simple container for objects of type EventManifest class RESPONSEDOC_LINKAGE CEventManifestDoc { public: CEventManifestDoc(); virtual ~CEventManifestDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string classNamespace, const std::string className, const std::string classVersion, const std::string operationName, const SmartPtrCAttachmentCollectionDoc attachmentCollection); public: /// Accessor for the ClassNamespace std::string getClassNamespace() const; /// Accessor for the ClassName std::string getClassName() const; /// Accessor for the ClassVersion std::string getClassVersion() const; /// Accessor for the OperationName std::string getOperationName() const; /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc getAttachmentCollection() const; private: bool _isInitialized; std::string _classNamespace; std::string _className; std::string _classVersion; std::string _operationName; SmartPtrCAttachmentCollectionDoc _attachmentCollection; private: CAF_CM_DECLARE_NOCOPY(CEventManifestDoc); }; CAF_DECLARE_SMART_POINTER(CEventManifestDoc); } #endif CManifestCollectionDoc.h000066400000000000000000000017441321503522500402650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CManifestCollectionDoc_h_ #define CManifestCollectionDoc_h_ #include "Doc/ResponseDoc/CManifestDoc.h" namespace Caf { /// A simple container for objects of type ManifestCollection class RESPONSEDOC_LINKAGE CManifestCollectionDoc { public: CManifestCollectionDoc(); virtual ~CManifestCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque manifest); public: /// Accessor for the Manifest std::deque getManifest() const; private: bool _isInitialized; std::deque _manifest; private: CAF_CM_DECLARE_NOCOPY(CManifestCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CManifestCollectionDoc); } #endif CManifestDoc.h000066400000000000000000000031521321503522500362440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CManifestDoc_h_ #define CManifestDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" namespace Caf { /// A simple container for objects of type Manifest class RESPONSEDOC_LINKAGE CManifestDoc { public: CManifestDoc(); virtual ~CManifestDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string classNamespace, const std::string className, const std::string classVersion, const UUID jobId, const std::string operationName, const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection); public: /// Accessor for the ClassNamespace std::string getClassNamespace() const; /// Accessor for the ClassName std::string getClassName() const; /// Accessor for the ClassVersion std::string getClassVersion() const; /// Accessor for the JobId UUID getJobId() const; /// Accessor for the OperationName std::string getOperationName() const; /// Accessor for the AttachmentNameCollection SmartPtrCAttachmentNameCollectionDoc getAttachmentNameCollection() const; private: std::string _classNamespace; std::string _className; std::string _classVersion; UUID _jobId; std::string _operationName; SmartPtrCAttachmentNameCollectionDoc _attachmentNameCollection; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CManifestDoc); }; CAF_DECLARE_SMART_POINTER(CManifestDoc); } #endif CProviderEventResponseDoc.h000066400000000000000000000034431321503522500410140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderEventResponseDoc_h_ #define CProviderEventResponseDoc_h_ #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CEventKeyCollectionDoc.h" #include "Doc/ResponseDoc/CEventManifestDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" namespace Caf { /// A simple container for objects of type ProviderEventResponse class RESPONSEDOC_LINKAGE CProviderEventResponseDoc { public: CProviderEventResponseDoc(); virtual ~CProviderEventResponseDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string pmeId, const SmartPtrCResponseHeaderDoc responseHeader, const SmartPtrCEventManifestDoc manifest, const SmartPtrCEventKeyCollectionDoc eventKeyCollection, const SmartPtrCStatisticsDoc statistics); public: /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the ResponseHeader SmartPtrCResponseHeaderDoc getResponseHeader() const; /// Accessor for the Manifest SmartPtrCEventManifestDoc getManifest() const; /// Accessor for the EventKeyCollection SmartPtrCEventKeyCollectionDoc getEventKeyCollection() const; /// Accessor for the Statistics SmartPtrCStatisticsDoc getStatistics() const; private: bool _isInitialized; std::string _pmeId; SmartPtrCResponseHeaderDoc _responseHeader; SmartPtrCEventManifestDoc _manifest; SmartPtrCEventKeyCollectionDoc _eventKeyCollection; SmartPtrCStatisticsDoc _statistics; private: CAF_CM_DECLARE_NOCOPY(CProviderEventResponseDoc); }; CAF_DECLARE_SMART_POINTER(CProviderEventResponseDoc); } #endif CProviderResponseDoc.h000066400000000000000000000037041321503522500400120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CProviderResponseDoc_h_ #define CProviderResponseDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" namespace Caf { /// A simple container for objects of type ProviderResponse class RESPONSEDOC_LINKAGE CProviderResponseDoc { public: CProviderResponseDoc(); virtual ~CProviderResponseDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCResponseHeaderDoc responseHeader, const SmartPtrCManifestDoc manifest, const SmartPtrCAttachmentCollectionDoc attachmentCollection, const SmartPtrCStatisticsDoc statistics); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the ResponseHeader SmartPtrCResponseHeaderDoc getResponseHeader() const; /// Accessor for the Manifest SmartPtrCManifestDoc getManifest() const; /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc getAttachmentCollection() const; /// Accessor for the Statistics SmartPtrCStatisticsDoc getStatistics() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; SmartPtrCResponseHeaderDoc _responseHeader; SmartPtrCManifestDoc _manifest; SmartPtrCAttachmentCollectionDoc _attachmentCollection; SmartPtrCStatisticsDoc _statistics; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CProviderResponseDoc); }; CAF_DECLARE_SMART_POINTER(CProviderResponseDoc); } #endif CResponseDoc.h000066400000000000000000000037301321503522500362760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CResponseDoc_h_ #define CResponseDoc_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CManifestCollectionDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" namespace Caf { /// A simple container for objects of type Response class RESPONSEDOC_LINKAGE CResponseDoc { public: CResponseDoc(); virtual ~CResponseDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCResponseHeaderDoc responseHeader, const SmartPtrCManifestCollectionDoc manifestCollection, const SmartPtrCAttachmentCollectionDoc attachmentCollection, const SmartPtrCStatisticsDoc statistics); public: /// Accessor for the ClientId UUID getClientId() const; /// Accessor for the RequestId UUID getRequestId() const; /// Accessor for the PmeId std::string getPmeId() const; /// Accessor for the ManifestCollection SmartPtrCResponseHeaderDoc getResponseHeader() const; /// Accessor for the ManifestCollection SmartPtrCManifestCollectionDoc getManifestCollection() const; /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc getAttachmentCollection() const; /// Accessor for the Statistics SmartPtrCStatisticsDoc getStatistics() const; private: UUID _clientId; UUID _requestId; std::string _pmeId; SmartPtrCResponseHeaderDoc _responseHeader; SmartPtrCManifestCollectionDoc _manifestCollection; SmartPtrCAttachmentCollectionDoc _attachmentCollection; SmartPtrCStatisticsDoc _statistics; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CResponseDoc); }; CAF_DECLARE_SMART_POINTER(CResponseDoc); } #endif CResponseHeaderDoc.h000066400000000000000000000026571321503522500374160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CResponseHeaderDoc_h_ #define CResponseHeaderDoc_h_ namespace Caf { /// A simple container for objects of type ResponseHeader class RESPONSEDOC_LINKAGE CResponseHeaderDoc { public: CResponseHeaderDoc(); virtual ~CResponseHeaderDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string version = "1.0", const std::string createdDateTime = CDateTimeUtils::getCurrentDateTime(), const uint32 sequenceNumber = 0, const bool isFinalResponse = true, const UUID sessionId = CAFCOMMON_GUID_NULL); public: /// Accessor for the version std::string getVersion() const; /// Accessor for the date/time when the request was created std::string getCreatedDateTime() const; /// Accessor for the sequenceNumber uint32 getSequenceNumber() const; /// Accessor for the version bool getIsFinalResponse() const; /// Accessor for the session ID UUID getSessionId() const; private: std::string _version; std::string _createdDateTime; uint32 _sequenceNumber; bool _isFinalResponse; UUID _sessionId; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CResponseHeaderDoc); }; CAF_DECLARE_SMART_POINTER(CResponseHeaderDoc); } #endif ResponseDocLink.h000066400000000000000000000010251321503522500370040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/ResponseDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef ResponseDoc_Link_h_ #define ResponseDoc_Link_h_ #ifndef RESPONSEDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define RESPONSEDOC_LINKAGE __declspec(dllexport) #else #define RESPONSEDOC_LINKAGE __declspec(dllimport) #endif #else #define RESPONSEDOC_LINKAGE #endif #endif #endif /* ResponseDoc_Link_h_ */ SchemaTypesDoc/000077500000000000000000000000001321503522500342225ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocCActionClassDoc.h000066400000000000000000000036171321503522500373360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CActionClassDoc_h_ #define CActionClassDoc_h_ #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" namespace Caf { /// Definition of an action class that may be generated by the provider class SCHEMATYPESDOC_LINKAGE CActionClassDoc { public: CActionClassDoc(); virtual ~CActionClassDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const SmartPtrCCollectMethodDoc collectMethod, const std::deque methodCollection, const std::string displayName = std::string(), const std::string description = std::string()); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Accessor for the CollectMethod SmartPtrCCollectMethodDoc getCollectMethod() const; /// Accessor for the Method std::deque getMethodCollection() const; /// A hint as to what this class should be called when displaying it to a human std::string getDisplayName() const; /// A phrase to describe the class for mouse-over text, etc std::string getDescription() const; private: bool _isInitialized; std::string _namespaceVal; std::string _name; std::string _version; SmartPtrCCollectMethodDoc _collectMethod; std::deque _methodCollection; std::string _displayName; std::string _description; private: CAF_CM_DECLARE_NOCOPY(CActionClassDoc); }; CAF_DECLARE_SMART_POINTER(CActionClassDoc); } #endif CActionClassInstanceCollectionDoc.h000066400000000000000000000022701321503522500430310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CActionClassInstanceCollectionDoc_h_ #define CActionClassInstanceCollectionDoc_h_ #include "Doc/SchemaTypesDoc/CActionClassInstanceDoc.h" namespace Caf { /// A simple container for objects of type ActionClassInstanceCollection class SCHEMATYPESDOC_LINKAGE CActionClassInstanceCollectionDoc { public: CActionClassInstanceCollectionDoc(); virtual ~CActionClassInstanceCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque actionClassInstanceCollection); public: /// Accessor for the ActionClassInstance std::deque getActionClassInstanceCollection() const; private: bool _isInitialized; std::deque _actionClassInstanceCollection; private: CAF_CM_DECLARE_NOCOPY(CActionClassInstanceCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CActionClassInstanceCollectionDoc); } #endif CActionClassInstanceDoc.h000066400000000000000000000027121321503522500410160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CActionClassInstanceDoc_h_ #define CActionClassInstanceDoc_h_ #include "Doc/SchemaTypesDoc/CInstanceOperationCollectionDoc.h" namespace Caf { /// A simple container for objects of type ActionClassInstance class SCHEMATYPESDOC_LINKAGE CActionClassInstanceDoc { public: CActionClassInstanceDoc(); virtual ~CActionClassInstanceDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const SmartPtrCInstanceOperationCollectionDoc instanceOperationCollection); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Accessor for the InstanceOperationCollection SmartPtrCInstanceOperationCollectionDoc getInstanceOperationCollection() const; private: bool _isInitialized; std::string _namespaceVal; std::string _name; std::string _version; SmartPtrCInstanceOperationCollectionDoc _instanceOperationCollection; private: CAF_CM_DECLARE_NOCOPY(CActionClassInstanceDoc); }; CAF_DECLARE_SMART_POINTER(CActionClassInstanceDoc); } #endif CClassCardinalityDoc.h000066400000000000000000000023671321503522500403650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CClassCardinalityDoc_h_ #define CClassCardinalityDoc_h_ namespace Caf { /// Class description of one end of a relationship class SCHEMATYPESDOC_LINKAGE CClassCardinalityDoc { public: CClassCardinalityDoc(); virtual ~CClassCardinalityDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const std::string cardinality); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Cardinality of one end relationship, i.e. has one, has many, etc std::string getCardinality() const; private: bool _isInitialized; std::string _namespaceVal; std::string _name; std::string _version; std::string _cardinality; private: CAF_CM_DECLARE_NOCOPY(CClassCardinalityDoc); }; CAF_DECLARE_SMART_POINTER(CClassCardinalityDoc); } #endif CClassFieldDoc.h000066400000000000000000000023431321503522500371370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CClassFieldDoc_h_ #define CClassFieldDoc_h_ namespace Caf { /// Description of a class and the field used to identify one end of a relationship class SCHEMATYPESDOC_LINKAGE CClassFieldDoc { public: CClassFieldDoc(); virtual ~CClassFieldDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const std::string field); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Description of a class field used to identify one end of a relationship std::string getField() const; private: bool _isInitialized; std::string _namespaceVal; std::string _name; std::string _version; std::string _field; private: CAF_CM_DECLARE_NOCOPY(CClassFieldDoc); }; CAF_DECLARE_SMART_POINTER(CClassFieldDoc); } #endif CClassIdentifierDoc.h000066400000000000000000000021061321503522500401730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CClassIdentifierDoc_h_ #define CClassIdentifierDoc_h_ namespace Caf { /// Tuple of values to uniquely identify a class class SCHEMATYPESDOC_LINKAGE CClassIdentifierDoc { public: CClassIdentifierDoc(); virtual ~CClassIdentifierDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; private: bool _isInitialized; std::string _namespaceVal; std::string _name; std::string _version; private: CAF_CM_DECLARE_NOCOPY(CClassIdentifierDoc); }; CAF_DECLARE_SMART_POINTER(CClassIdentifierDoc); } #endif CClassInstancePropertyDoc.h000066400000000000000000000036021321503522500414240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CClassInstancePropertyDoc_h_ #define CClassInstancePropertyDoc_h_ #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" namespace Caf { /// Definition of an attribute (field) of a class class SCHEMATYPESDOC_LINKAGE CClassInstancePropertyDoc { public: CClassInstancePropertyDoc(); virtual ~CClassInstancePropertyDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::deque type, const bool required = false, const bool transientVal = false, const bool list = false, const std::string displayName = std::string(), const std::string description = std::string()); public: /// Property name std::string getName() const; /// Accessor for the Type std::deque getType() const; /// Whether this is a required property, i.e. this property must always be non-empty bool getRequired() const; /// Accessor for the TransientVal bool getTransientVal() const; /// Indicates whether to expect a list of properties in the provider response bool getList() const; /// A hint as to what this property should be called when displaying it to a human std::string getDisplayName() const; /// A phrase to describe the property for mouse-over text, etc std::string getDescription() const; private: std::string _name; std::deque _type; bool _required; bool _transientVal; bool _list; std::string _displayName; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CClassInstancePropertyDoc); }; CAF_DECLARE_SMART_POINTER(CClassInstancePropertyDoc); } #endif CClassPropertyDoc.h000066400000000000000000000062301321503522500377370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CClassPropertyDoc_h_ #define CClassPropertyDoc_h_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" namespace Caf { /// Definition of an attribute (field) of a class class SCHEMATYPESDOC_LINKAGE CClassPropertyDoc { public: CClassPropertyDoc(); virtual ~CClassPropertyDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const PROPERTY_TYPE type, const std::deque value, const bool required = false, const bool key = false, const bool list = false, const bool caseSensitive = false, const bool transientVal = false, const std::string defaultVal = std::string(), const VALIDATOR_TYPE validator = VALIDATOR_NONE, const std::string upperRange = std::string(), const std::string lowerRange = std::string(), const std::string displayName = std::string(), const std::string description = std::string()); public: /// Property name std::string getName() const; /// Describes the data type of the property PROPERTY_TYPE getType() const; /// The contents of a validator used on this property std::deque getValue() const; /// Whether this is a required property, i.e. this property must always be non-empty bool getRequired() const; /// Indicates this property may be used as a key identifying field bool getKey() const; /// Indicates whether to expect a list of properties in the provider response bool getList() const; /// Indicates whether a string field should be treated in a case-sensitive manner bool getCaseSensitive() const; /// Accessor for the TransientVal bool getTransientVal() const; /// Accessor for the DefaultVal std::string getDefaultVal() const; /// The type of validator described in the 'value' sub-elements VALIDATOR_TYPE getValidator() const; /// If a 'range' validator is in use, this describes the upper limit of allowable values for the property. QUESTIONABLE: how do we determine inclusive or exclusive range std::string getUpperRange() const; /// If a 'range' validator is in use, this describes the lower limit of allowable values for the property. QUESTIONABLE: how do we determine inclusive or exclusive range std::string getLowerRange() const; /// A hint as to what this property should be called when displaying it to a human std::string getDisplayName() const; /// A phrase to describe the property for mouse-over text, etc std::string getDescription() const; private: std::string _name; PROPERTY_TYPE _type; std::deque _value; bool _required; bool _key; bool _list; bool _caseSensitive; bool _transientVal; std::string _defaultVal; VALIDATOR_TYPE _validator; std::string _upperRange; std::string _lowerRange; std::string _displayName; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CClassPropertyDoc); }; CAF_DECLARE_SMART_POINTER(CClassPropertyDoc); } #endif CCmdlMetadataDoc.h000066400000000000000000000016501321503522500374460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CCmdlMetadataDoc_h_ #define CCmdlMetadataDoc_h_ namespace Caf { /// A simple container for objects of type CmdlMetadata class SCHEMATYPESDOC_LINKAGE CCmdlMetadataDoc { public: CCmdlMetadataDoc(); virtual ~CCmdlMetadataDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::string value); public: /// Accessor for the Name std::string getName() const; /// Accessor for the Value std::string getValue() const; private: bool _isInitialized; std::string _name; std::string _value; private: CAF_CM_DECLARE_NOCOPY(CCmdlMetadataDoc); }; CAF_DECLARE_SMART_POINTER(CCmdlMetadataDoc); } #endif CCmdlUnionDoc.h000066400000000000000000000020401321503522500370100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CCmdlUnionDoc_h_ #define CCmdlUnionDoc_h_ namespace Caf { /// A simple container for objects of type CmdlUnion class SCHEMATYPESDOC_LINKAGE CCmdlUnionDoc { public: CCmdlUnionDoc(); virtual ~CCmdlUnionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; private: bool _isInitialized; std::string _namespaceVal; std::string _name; std::string _version; private: CAF_CM_DECLARE_NOCOPY(CCmdlUnionDoc); }; CAF_DECLARE_SMART_POINTER(CCmdlUnionDoc); } #endif CCollectMethodDoc.h000066400000000000000000000050531321503522500376550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CCollectMethodDoc_h_ #define CCollectMethodDoc_h_ #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" namespace Caf { /// Definition of a collection method on a class class SCHEMATYPESDOC_LINKAGE CCollectMethodDoc { public: CCollectMethodDoc(); virtual ~CCollectMethodDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::deque parameterCollection = std::deque(), const std::deque instanceParameterCollection = std::deque(), const std::deque returnValCollection = std::deque(), const std::deque eventValCollection = std::deque(), const std::deque errorCollection = std::deque()); public: /// name of the collection method std::string getName() const; /// Definition of a parameter that passes simple types to the collection method std::deque getParameterCollection() const; /// Definition of a parameter passing data class instances to the collection method std::deque getInstanceParameterCollection() const; /// Accessor for the ReturnVal std::deque getReturnValCollection() const; /// Accessor for the EventVal std::deque getEventValCollection() const; /// A class that may be returned to indicate an error occurred during the processing of the collection method std::deque getErrorCollection() const; private: bool _isInitialized; std::string _name; std::deque _parameterCollection; std::deque _instanceParameterCollection; std::deque _returnValCollection; std::deque _eventValCollection; std::deque _errorCollection; private: CAF_CM_DECLARE_NOCOPY(CCollectMethodDoc); }; CAF_DECLARE_SMART_POINTER(CCollectMethodDoc); } #endif CDataClassDoc.h000066400000000000000000000046531321503522500367730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDataClassDoc_h_ #define CDataClassDoc_h_ #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" namespace Caf { /// Definition of a data class that may be generated by the provider class SCHEMATYPESDOC_LINKAGE CDataClassDoc { public: CDataClassDoc(); virtual ~CDataClassDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const std::deque propertyCollection = std::deque(), const std::deque instancePropertyCollection = std::deque(), const bool unique = false, const bool transientVal = false, const std::string displayName = std::string(), const std::string description = std::string()); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Accessor for the Property std::deque getPropertyCollection() const; /// Accessor for the InstanceProperty std::deque getInstancePropertyCollection() const; /// Indicates whether the key properties of this class are enough to guarantee uniqueness from other classes of the same type bool getUnique() const; /// Accessor for the TransientVal bool getTransientVal() const; /// A hint as to what this class should be called when displaying it to a human std::string getDisplayName() const; /// A phrase to describe the class for mouse-over text, etc std::string getDescription() const; private: std::string _namespaceVal; std::string _name; std::string _version; std::deque _propertyCollection; std::deque _instancePropertyCollection; bool _unique; bool _transientVal; std::string _displayName; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CDataClassDoc); }; CAF_DECLARE_SMART_POINTER(CDataClassDoc); } #endif CDataClassInstanceCollectionDoc.h000066400000000000000000000023061321503522500424650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDataClassInstanceCollectionDoc_h_ #define CDataClassInstanceCollectionDoc_h_ #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" namespace Caf { /// A simple container for objects of type DataClassInstanceCollection class SCHEMATYPESDOC_LINKAGE CDataClassInstanceCollectionDoc { public: CDataClassInstanceCollectionDoc(); virtual ~CDataClassInstanceCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque dataClassInstanceCollection = std::deque()); public: /// Accessor for the DataClassInstance std::deque getDataClassInstanceCollection() const; private: bool _isInitialized; std::deque _dataClassInstanceCollection; private: CAF_CM_DECLARE_NOCOPY(CDataClassInstanceCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CDataClassInstanceCollectionDoc); } #endif CDataClassInstanceDoc.h000066400000000000000000000043041321503522500404510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDataClassInstanceDoc_h_ #define CDataClassInstanceDoc_h_ #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" namespace Caf { /// A simple container for objects of type DataClassInstance class SCHEMATYPESDOC_LINKAGE CDataClassInstanceDoc { public: CDataClassInstanceDoc(); virtual ~CDataClassInstanceDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const std::deque cmdlMetadataCollection, const std::deque propertyCollection, const std::deque instancePropertyCollection, const SmartPtrCCmdlUnionDoc cmdlUnion); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Accessor for the CmdlMetadata std::deque getCmdlMetadataCollection() const; /// Accessor for the Property std::deque getPropertyCollection() const; /// Accessor for the InstanceProperty std::deque getInstancePropertyCollection() const; /// Accessor for the CmdlUnion SmartPtrCCmdlUnionDoc getCmdlUnion() const; private: bool _isInitialized; std::string _namespaceVal; std::string _name; std::string _version; std::deque _cmdlMetadataCollection; std::deque _propertyCollection; std::deque _instancePropertyCollection; SmartPtrCCmdlUnionDoc _cmdlUnion; private: CAF_CM_DECLARE_NOCOPY(CDataClassInstanceDoc); }; CAF_DECLARE_SMART_POINTER(CDataClassInstanceDoc); } #endif CDataClassPropertyDoc.h000066400000000000000000000023261321503522500405330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDataClassPropertyDoc_h_ #define CDataClassPropertyDoc_h_ #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" namespace Caf { /// A simple container for objects of type DataClassProperty class SCHEMATYPESDOC_LINKAGE CDataClassPropertyDoc { public: CDataClassPropertyDoc(); virtual ~CDataClassPropertyDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::deque cmdlMetadata, const std::string value); public: /// Accessor for the Name std::string getName() const; /// Accessor for the CmdlMetadata std::deque getCmdlMetadata() const; /// Accessor for the Value std::string getValue() const; private: bool _isInitialized; std::string _name; std::deque _cmdlMetadata; std::string _value; private: CAF_CM_DECLARE_NOCOPY(CDataClassPropertyDoc); }; CAF_DECLARE_SMART_POINTER(CDataClassPropertyDoc); } #endif CDataClassSubInstanceDoc.h000066400000000000000000000037461321503522500411340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CDataClassSubInstanceDoc_h_ #define CDataClassSubInstanceDoc_h_ #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CDataClassSubInstanceDoc); /// A simple container for objects of type DataClassSubInstance class SCHEMATYPESDOC_LINKAGE CDataClassSubInstanceDoc { public: CDataClassSubInstanceDoc(); virtual ~CDataClassSubInstanceDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::deque cmdlMetadataCollection, const std::deque propertyCollection, const std::deque instancePropertyCollection, const SmartPtrCCmdlUnionDoc cmdlUnion); public: /// Accessor for the Name std::string getName() const; /// Accessor for the CmdlMetadata std::deque getCmdlMetadataCollection() const; /// Accessor for the Property std::deque getPropertyCollection() const; /// Accessor for the InstanceProperty std::deque getInstancePropertyCollection() const; /// Accessor for the CmdlUnion SmartPtrCCmdlUnionDoc getCmdlUnion() const; private: bool _isInitialized; std::string _name; std::deque _cmdlMetadataCollection; std::deque _propertyCollection; std::deque _instancePropertyCollection; SmartPtrCCmdlUnionDoc _cmdlUnion; private: CAF_CM_DECLARE_NOCOPY(CDataClassSubInstanceDoc); }; CAF_DECLARE_SMART_POINTER(CDataClassSubInstanceDoc); } #endif CInstanceOperationCollectionDoc.h000066400000000000000000000022301321503522500425620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInstanceOperationCollectionDoc_h_ #define CInstanceOperationCollectionDoc_h_ #include "Doc/SchemaTypesDoc/CInstanceOperationDoc.h" namespace Caf { /// A simple container for objects of type InstanceOperationCollection class SCHEMATYPESDOC_LINKAGE CInstanceOperationCollectionDoc { public: CInstanceOperationCollectionDoc(); virtual ~CInstanceOperationCollectionDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::deque instanceOperationCollection); public: /// Accessor for the InstanceOperation std::deque getInstanceOperationCollection() const; private: bool _isInitialized; std::deque _instanceOperationCollection; private: CAF_CM_DECLARE_NOCOPY(CInstanceOperationCollectionDoc); }; CAF_DECLARE_SMART_POINTER(CInstanceOperationCollectionDoc); } #endif CInstanceOperationDoc.h000066400000000000000000000017741321503522500405620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInstanceOperationDoc_h_ #define CInstanceOperationDoc_h_ namespace Caf { /// A simple container for objects of type InstanceOperation class SCHEMATYPESDOC_LINKAGE CInstanceOperationDoc { public: CInstanceOperationDoc(); virtual ~CInstanceOperationDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string operationName, const std::string moniker); public: /// Accessor for the OperationName std::string getOperationName() const; /// Accessor for the Moniker std::string getMoniker() const; private: bool _isInitialized; std::string _operationName; std::string _moniker; private: CAF_CM_DECLARE_NOCOPY(CInstanceOperationDoc); }; CAF_DECLARE_SMART_POINTER(CInstanceOperationDoc); } #endif CInstanceParameterDoc.h000066400000000000000000000037011321503522500405320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CInstanceParameterDoc_h_ #define CInstanceParameterDoc_h_ namespace Caf { /// A parameter containing a data class instance used by a method to control the outcome class SCHEMATYPESDOC_LINKAGE CInstanceParameterDoc { public: CInstanceParameterDoc(); virtual ~CInstanceParameterDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::string instanceNamespace, const std::string instanceName, const std::string instanceVersion, const bool isOptional = false, const bool isList = false, const std::string displayName = std::string(), const std::string description = std::string()); public: /// Name of parameter std::string getName() const; /// Namespace of instance object type std::string getInstanceNamespace() const; /// Name of instance object type std::string getInstanceName() const; /// Version of instance object type std::string getInstanceVersion() const; /// Indicates this parameter need not be passed bool getIsOptional() const; /// Indicates whether to expect a list of values as opposed to a single value (the default if this attribute is not present) bool getIsList() const; /// Human-readable version of the parameter name std::string getDisplayName() const; /// Short description of what the parameter is for std::string getDescription() const; private: std::string _name; std::string _instanceNamespace; std::string _instanceName; std::string _instanceVersion; bool _isOptional; bool _isList; std::string _displayName; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CInstanceParameterDoc); }; CAF_DECLARE_SMART_POINTER(CInstanceParameterDoc); } #endif CJoinTypeDoc.h000066400000000000000000000030051321503522500366630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CJoinTypeDoc_h_ #define CJoinTypeDoc_h_ #include "Doc/SchemaTypesDoc/CClassFieldDoc.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" namespace Caf { /// A simple container for objects of type JoinType class SCHEMATYPESDOC_LINKAGE CJoinTypeDoc { public: CJoinTypeDoc(); virtual ~CJoinTypeDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const OPERATOR_TYPE operand, const SmartPtrCClassFieldDoc dataClassLeft, const SmartPtrCClassFieldDoc dataClassRight, const std::string description); public: /// Defines the operand used to join the class fields. Restricted to '=' for now OPERATOR_TYPE getOperand() const; /// Identifies the fields on classes that uniquely identify relationship SmartPtrCClassFieldDoc getDataClassLeft() const; /// Identifies the fields on classes that uniquely identify relationship SmartPtrCClassFieldDoc getDataClassRight() const; /// A short human-readable description of the join std::string getDescription() const; private: OPERATOR_TYPE _operand; SmartPtrCClassFieldDoc _dataClassLeft; SmartPtrCClassFieldDoc _dataClassRight; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CJoinTypeDoc); }; CAF_DECLARE_SMART_POINTER(CJoinTypeDoc); } #endif CLogicalRelationshipDoc.h000066400000000000000000000042731321503522500410660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CLogicalRelationshipDoc_h_ #define CLogicalRelationshipDoc_h_ #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CJoinTypeDoc.h" namespace Caf { /// Definition of a relationship between classes that can be described by identifying the fields on the classes that uniquely identify the relationship class SCHEMATYPESDOC_LINKAGE CLogicalRelationshipDoc { public: CLogicalRelationshipDoc(); virtual ~CLogicalRelationshipDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const ARITY_TYPE arity, const SmartPtrCClassCardinalityDoc dataClassLeft, const SmartPtrCClassCardinalityDoc dataClassRight, const std::deque joinCollection, const std::string description = std::string()); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Accessor for the Arity ARITY_TYPE getArity() const; /// Accessor for the DataClassLeft SmartPtrCClassCardinalityDoc getDataClassLeft() const; /// Accessor for the DataClassRight SmartPtrCClassCardinalityDoc getDataClassRight() const; /// Defines a join condition of the relationship std::deque getJoinCollection() const; /// Accessor for the Description std::string getDescription() const; private: std::string _namespaceVal; std::string _name; std::string _version; ARITY_TYPE _arity; SmartPtrCClassCardinalityDoc _dataClassLeft; SmartPtrCClassCardinalityDoc _dataClassRight; std::deque _joinCollection; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CLogicalRelationshipDoc); }; CAF_DECLARE_SMART_POINTER(CLogicalRelationshipDoc); } #endif CMethodDoc.h000066400000000000000000000054361321503522500363540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMethodDoc_h_ #define CMethodDoc_h_ #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" namespace Caf { /// Definition of a method on a class class SCHEMATYPESDOC_LINKAGE CMethodDoc { public: CMethodDoc(); virtual ~CMethodDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const std::deque parameterCollection = std::deque(), const std::deque instanceParameterCollection = std::deque(), const std::deque returnValCollection = std::deque(), const std::deque eventValCollection = std::deque(), const std::deque errorCollection = std::deque(), const std::string displayName = std::string(), const std::string description = std::string()); public: /// name of the method std::string getName() const; /// Definition of a parameter that passes simple types to the method std::deque getParameterCollection() const; /// Definition of a parameter that passes data class instances to the method std::deque getInstanceParameterCollection() const; /// Accessor for the ReturnVal std::deque getReturnValCollection() const; /// Accessor for the EventVal std::deque getEventValCollection() const; /// A class that may be returned to indicate an error occurred during the processing of the collection method std::deque getErrorCollection() const; /// Human-readable version of the method name std::string getDisplayName() const; /// A short phrase describing the purpose of the method std::string getDescription() const; private: bool _isInitialized; std::string _name; std::deque _parameterCollection; std::deque _instanceParameterCollection; std::deque _returnValCollection; std::deque _eventValCollection; std::deque _errorCollection; std::string _displayName; std::string _description; private: CAF_CM_DECLARE_NOCOPY(CMethodDoc); }; CAF_DECLARE_SMART_POINTER(CMethodDoc); } #endif CMethodParameterDoc.h000066400000000000000000000035001321503522500402030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CMethodParameterDoc_h_ #define CMethodParameterDoc_h_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" namespace Caf { /// A parameter containing a simple type used by a method to control the outcome class SCHEMATYPESDOC_LINKAGE CMethodParameterDoc { public: CMethodParameterDoc(); virtual ~CMethodParameterDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string name, const PARAMETER_TYPE type, const bool isOptional = false, const bool isList = false, const std::string defaultVal = std::string(), const std::string displayName = std::string(), const std::string description = std::string()); public: /// Name of parameter std::string getName() const; /// Describes the data type of the property PARAMETER_TYPE getType() const; /// Indicates this parameter need not be passed bool getIsOptional() const; /// Indicates whether to expect a list of values as opposed to a single value (the default if this attribute is not present) bool getIsList() const; /// Accessor for the DefaultVal std::string getDefaultVal() const; /// Human-readable version of the parameter name std::string getDisplayName() const; /// Short description of what the parameter is for std::string getDescription() const; private: std::string _name; PARAMETER_TYPE _type; bool _isOptional; bool _isList; std::string _defaultVal; std::string _displayName; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CMethodParameterDoc); }; CAF_DECLARE_SMART_POINTER(CMethodParameterDoc); } #endif CPhysicalRelationshipDoc.h000066400000000000000000000037101321503522500412630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CPhysicalRelationshipDoc_h_ #define CPhysicalRelationshipDoc_h_ #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" namespace Caf { /// Describes a relationship between dataclass where the key information from data class instances comprising the relationship are listed in an instance of this class class SCHEMATYPESDOC_LINKAGE CPhysicalRelationshipDoc { public: CPhysicalRelationshipDoc(); virtual ~CPhysicalRelationshipDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const ARITY_TYPE arity, const SmartPtrCClassCardinalityDoc dataClassLeft, const SmartPtrCClassCardinalityDoc dataClassRight, const std::string description = std::string()); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Accessor for the Arity ARITY_TYPE getArity() const; /// Accessor for the DataClassLeft SmartPtrCClassCardinalityDoc getDataClassLeft() const; /// Accessor for the DataClassRight SmartPtrCClassCardinalityDoc getDataClassRight() const; /// Accessor for the Description std::string getDescription() const; private: std::string _namespaceVal; std::string _name; std::string _version; ARITY_TYPE _arity; SmartPtrCClassCardinalityDoc _dataClassLeft; SmartPtrCClassCardinalityDoc _dataClassRight; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CPhysicalRelationshipDoc); }; CAF_DECLARE_SMART_POINTER(CPhysicalRelationshipDoc); } #endif CRelationshipDoc.h000066400000000000000000000036561321503522500375770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #ifndef CRelationshipDoc_h_ #define CRelationshipDoc_h_ #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" namespace Caf { /// Definition of a relationship between data classes class SCHEMATYPESDOC_LINKAGE CRelationshipDoc { public: CRelationshipDoc(); virtual ~CRelationshipDoc(); public: /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void initialize( const std::string namespaceVal, const std::string name, const std::string version, const ARITY_TYPE arity, const SmartPtrCClassCardinalityDoc dataClassLeft, const SmartPtrCClassCardinalityDoc dataClassRight, const std::string description = std::string()); public: /// Accessor for the NamespaceVal std::string getNamespaceVal() const; /// Accessor for the Name std::string getName() const; /// Accessor for the Version std::string getVersion() const; /// Number of parts (sides) to relationship. Restricted to a two-sided relationship for now ARITY_TYPE getArity() const; /// Identifies the two classes that make up the relationship SmartPtrCClassCardinalityDoc getDataClassLeft() const; /// Identifies the two classes that make up the relationship SmartPtrCClassCardinalityDoc getDataClassRight() const; /// A short human-readable description of the relationship std::string getDescription() const; private: std::string _namespaceVal; std::string _name; std::string _version; ARITY_TYPE _arity; SmartPtrCClassCardinalityDoc _dataClassLeft; SmartPtrCClassCardinalityDoc _dataClassRight; std::string _description; bool _isInitialized; private: CAF_CM_DECLARE_NOCOPY(CRelationshipDoc); }; CAF_DECLARE_SMART_POINTER(CRelationshipDoc); } #endif SchemaTypesDocLink.h000066400000000000000000000010521321503522500400620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef SchemaTypesDoc_Link_h_ #define SchemaTypesDoc_Link_h_ #ifndef SCHEMATYPESDOC_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define SCHEMATYPESDOC_LINKAGE __declspec(dllexport) #else #define SCHEMATYPESDOC_LINKAGE __declspec(dllimport) #endif #else #define SCHEMATYPESDOC_LINKAGE #endif #endif #endif /* SchemaTypesDoc_Link_h_ */ SchemaTypesDocTypes.h000066400000000000000000000011111321503522500402650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Doc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef SCHEMATYPESDOCTYPES_H_ #define SCHEMATYPESDOCTYPES_H_ #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" namespace Caf { typedef enum { OPERATOR_NONE, OPERATOR_EQUAL } OPERATOR_TYPE; typedef enum { ARITY_NONE, ARITY_UNSIGNED_BYTE = 2 } ARITY_TYPE; typedef enum { VALIDATOR_NONE, VALIDATOR_ENUM, VALIDATOR_RANGE, VALIDATOR_REGEX, VALIDATOR_CUSTOM } VALIDATOR_TYPE; } #endif /* SCHEMATYPESDOCTYPES_H_ */ DocContracts.h000066400000000000000000000017001321503522500333770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef DocContracts_h_ #define DocContracts_h_ #include "Doc/CafCoreTypesDoc/CafCoreTypesDocLink.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocLink.h" #include "Doc/DiagTypesDoc/DiagTypesDocLink.h" #include "Doc/DiagRequestDoc/DiagRequestDocLink.h" #include "Doc/MgmtTypesDoc/MgmtTypesDocLink.h" #include "Doc/MgmtRequestDoc/MgmtRequestDocLink.h" #include "Doc/PayloadEnvelopeDoc/PayloadEnvelopeDocLink.h" #include "Doc/PersistenceDoc/PersistenceDocLink.h" #include "Doc/ProviderInfraDoc/ProviderInfraDocLink.h" #include "Doc/ProviderRequestDoc/ProviderRequestDocLink.h" #include "Doc/ProviderResultsDoc/ProviderResultsDocLink.h" #include "Doc/ResponseDoc/ResponseDocLink.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocLink.h" #include "Doc/MultiPmeMgmtRequestDoc/MultiPmeMgmtRequestDocLink.h" #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocUtils.h000066400000000000000000000005431321503522500326220ustar00rootroot00000000000000/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef COMMON_SYS_INC_DOCUTILS_H_ #define COMMON_SYS_INC_DOCUTILS_H_ #include #include #include "../src/Doc/DocUtils/DocUtilsLink.h" #endif /* COMMON_SYS_INC_DOCUTILS_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/DocXml.h000066400000000000000000000021671321503522500322660ustar00rootroot00000000000000/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef COMMON_SYS_INC_DOCXML_H_ #define COMMON_SYS_INC_DOCXML_H_ #include #include #include "Doc/DocXml/CafCoreTypesXml/CafCoreTypesXmlLink.h" #include "Doc/DocXml/SchemaTypesXml/SchemaTypesXmlLink.h" #include "Doc/DocXml/DiagTypesXml/DiagTypesXmlLink.h" #include "Doc/DocXml/DiagRequestXml/DiagRequestXmlLink.h" #include "Doc/DocXml/MgmtTypesXml/MgmtTypesXmlLink.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXmlLink.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXmlLink.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlLink.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlLink.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlLink.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlLink.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlLink.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXmlLink.h" #endif /* COMMON_SYS_INC_DOCXML_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Exception/000077500000000000000000000000001321503522500326575ustar00rootroot00000000000000CCafException.h000066400000000000000000000030041321503522500354210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Exception/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCAFEXCEPTION_H_ #define CCAFEXCEPTION_H_ #include "ICafObject.h" namespace Caf { class EXCEPTION_LINKAGE CCafException : public ICafObject { public: CCafException(); CCafException(const std::string& exceptionClassName); virtual ~CCafException(); virtual void throwSelf(); virtual void throwAddRefedSelf(); void AddRef(); void Release(); void QueryInterface(const IID&, void**); void populate( const std::string& message, const HRESULT errorCode, const std::string& className, const std::string& funcName); void populateVA(const HRESULT errorCode, const std::string& className, const std::string& funcName, const char* format, ...); bool isPopulated() const; std::string getExceptionClassName() const; virtual std::string getMsg() const; std::string getClassName() const; std::string getFuncName() const; HRESULT getError() const; std::deque* getBacktrace() const; virtual std::string getFullMsg() const; private: gint _refCnt; bool _isPopulated; protected: std::string _exceptionClassName; HRESULT _errorCode; std::string _message; std::string _className; std::string _funcName; std::deque* _backtrace; CCafException(const CCafException&); CCafException& operator=(const CCafException&); }; CAF_DECLARE_SMART_POINTER(CCafException); } #endif /* CCAFEXCEPTION_H_ */ FrameworkLink.h000066400000000000000000000006651321503522500335750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef FrameworkLink_h_ #define FrameworkLink_h_ #ifndef FRAMEWORK_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define FRAMEWORK_LINKAGE __declspec(dllexport) #else #define FRAMEWORK_LINKAGE __declspec(dllimport) #endif #else #define FRAMEWORK_LINKAGE #endif #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/IBean.h000066400000000000000000000017021321503522500320500ustar00rootroot00000000000000/* * Author: bwilliams * Created: Jan 26, 2011 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _FxContracts_IBean_h_ #define _FxContracts_IBean_h_ #include "ICafObject.h" namespace Caf { CAF_FORWARD_DECLARE_SMART_INTERFACE(IBean); /// TODO - describe interface struct __declspec(novtable) IBean : public ICafObject { CAF_DECL_UUID("860C6E41-76E4-404b-913F-C330EE864DCD") struct CArg { CArg(const SmartPtrIBean& ref) : _reference(ref), _type(REFERENCE) {} CArg(const std::string& val) : _value(val), _type(VALUE) {} typedef enum { REFERENCE, VALUE } ARG_TYPE; SmartPtrIBean _reference; std::string _value; ARG_TYPE _type; private: CArg(); }; typedef std::deque Cargs; typedef Cmapstrstr Cprops; virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) = 0; virtual void terminateBean() = 0; }; } #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/ICafObject.h000066400000000000000000000027571321503522500330360ustar00rootroot00000000000000/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _ICafObject_H_ #define _ICafObject_H_ /** * @brief * The base interface all classes must support in order to support lifetime management * and interface retrieval. *

* Object lifetime is managed through the AddRef() and Release() methods. Pointers * to supported interfaces on the object - in the form of TCafSmartPtr - are * retrieved using the QueryInterface() method. *

* Interfaces and classes are candidates for QueryInterface() if they declare * a unique identifier for the interface or class. The identifier is a * UUID and is declared using the CAF_DECL_UUID macro. *

* Example interface declaration: *

 * 
 * struct __declspcec(novtable) IMyInterface {
 *
 * 	CAF_DECL_UUID("6AECA0A4-C6B1-4A43-9769-C5A8F56F0B52")
 *
 * 	virtual void Foo() = 0;
 * };
 * 
 * 
*/ struct __declspec(novtable) ICafObject { CAF_DECL_UUID("d285ff70-2314-11e0-ac64-0800200c9a66") /** @brief Increment the object's reference count */ virtual void AddRef() = 0; /** * @brief Decrement the object's reference count *

* The object will be destroyed when the count reaches zero. */ virtual void Release() = 0; /** * @brief Retrieve an interface on the object * @param IID the interface's UUID * @param ppv the address into which the retrieve interface's pointer * will be stored */ virtual void QueryInterface(const IID&, void** ppv) = 0; }; #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/IVariant.h000066400000000000000000000015001321503522500326030ustar00rootroot00000000000000/* * Created on: Jul 23, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _FxContracts_IVARIANT_H_ #define _FxContracts_IVARIANT_H_ #include "ICafObject.h" namespace Caf { struct __declspec(novtable) IVariant : public ICafObject { CAF_DECL_UUID("05AC7CB8-BBD4-4B3B-AB80-29002DD73747") virtual GVariant *get() const = 0; virtual std::string toString() const = 0; virtual bool isString() const = 0; virtual bool isBool() const = 0; virtual bool isUint8() const = 0; virtual bool isInt16() const = 0; virtual bool isUint16() const = 0; virtual bool isInt32() const = 0; virtual bool isUint32() const = 0; virtual bool isInt64() const = 0; virtual bool isUint64() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IVariant); } #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration.h000066400000000000000000000007121321503522500333550ustar00rootroot00000000000000/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef COMMON_SYS_INC_INTEGRATION_H_ #define COMMON_SYS_INC_INTEGRATION_H_ #include // Dependencies // Interfaces #include "Integration/IThrowable.h" #include "Integration/Caf/IntegrationCafLink.h" #include "Integration/Core/IntegrationCoreLink.h" #endif /* COMMON_SYS_INC_INTEGRATION_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/000077500000000000000000000000001321503522500332045ustar00rootroot00000000000000Caf/000077500000000000000000000000001321503522500336165ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/IntegrationCBeanPropertiesHelper.h000066400000000000000000000021011321503522500401460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CBeanPropertiesHelper_h_ #define CBeanPropertiesHelper_h_ namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CBeanPropertiesHelper); class INTEGRATIONCAF_LINKAGE CBeanPropertiesHelper { public: static SmartPtrCBeanPropertiesHelper create( const IBean::Cprops& properties); public: CBeanPropertiesHelper(); virtual ~CBeanPropertiesHelper(); public: void initialize( const IBean::Cprops& properties); public: std::string getRequiredString( const std::string& key) const; std::string getOptionalString( const std::string& key, const std::string& defaultVal = std::string()) const; bool getRequiredBool( const std::string& key) const; bool getOptionalBool( const std::string& key, const bool defaultVal = false) const; private: bool m_isInitialized; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CBeanPropertiesHelper); }; } #endif // #ifndef CBeanPropertiesHelper_h_ CCafMessageCreator.h000066400000000000000000000105571321503522500374200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCafMessageCreator_h_ #define CCafMessageCreator_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" #include "Doc/DiagRequestDoc/CDiagRequestDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ResponseDoc/CErrorResponseDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CCafMessageCreator); class INTEGRATIONCAF_LINKAGE CCafMessageCreator { public: static SmartPtrIIntMessage createPayloadEnvelope( const SmartPtrCResponseDoc& response, const std::string& relFilename, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); static SmartPtrIIntMessage createPayloadEnvelope( const SmartPtrCErrorResponseDoc& errorResponse, const std::string& relFilename, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); static SmartPtrIIntMessage createPayloadEnvelope( const SmartPtrCMgmtRequestDoc& mgmtRequest, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); static SmartPtrIIntMessage createPayloadEnvelope( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const std::deque& attachmentCollection, const IIntMessage::SmartPtrCHeaders& newHeaders = IIntMessage::SmartPtrCHeaders(), const IIntMessage::SmartPtrCHeaders& origHeaders = IIntMessage::SmartPtrCHeaders()); public: static SmartPtrIIntMessage createFromProviderResponse( const SmartPtrCDynamicByteArray& providerResponse, const std::string& relFilename, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); public: static SmartPtrIIntMessage create( const SmartPtrCDynamicByteArray payload, const std::deque& attachmentCollection, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); public: static SmartPtrIIntMessage create( const SmartPtrCMgmtRequestDoc& mgmtRequest, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); static SmartPtrIIntMessage create( const SmartPtrCDiagRequestDoc& diagRequest, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); static SmartPtrIIntMessage create( const SmartPtrCInstallRequestDoc& installRequest, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); static SmartPtrIIntMessage create( const SmartPtrCProviderRegDoc& providerReg, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); static SmartPtrIIntMessage create( const SmartPtrCProviderCollectSchemaRequestDoc& providerCollectSchemaRequest, const std::string& relFilename, const std::string& relDirectory, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); static SmartPtrIIntMessage create( const SmartPtrCProviderRequestDoc& providerRequest, const std::string& relFilename, const std::string& relDirectory, const std::string& providerUri, const IIntMessage::SmartPtrCHeaders& headers = IIntMessage::SmartPtrCHeaders()); private: static SmartPtrIIntMessage createPayloadEnvelope( const std::string& payloadType, const std::string& payloadStr, const UUID& clientId, const UUID& requestId, const std::string& pmeId, const std::string& payloadVersion, const IIntMessage::SmartPtrCHeaders& newHeaders = IIntMessage::SmartPtrCHeaders(), const IIntMessage::SmartPtrCHeaders& origHeaders = IIntMessage::SmartPtrCHeaders(), const SmartPtrCAttachmentCollectionDoc& attachmentCollection = SmartPtrCAttachmentCollectionDoc(), const SmartPtrCProtocolCollectionDoc& protocolCollection = SmartPtrCProtocolCollectionDoc()); private: CAF_CM_DECLARE_NOCREATE(CCafMessageCreator); }; } #endif // #ifndef CCafMessageCreator_h_ CCafMessageHeaders.h000066400000000000000000000056671321503522500374020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCafMessageHeaders_h_ #define CCafMessageHeaders_h_ #include "IVariant.h" #include "Integration/IIntMessage.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CCafMessageHeaders); class INTEGRATIONCAF_LINKAGE CCafMessageHeaders { public: static SmartPtrCCafMessageHeaders create( const IIntMessage::SmartPtrCHeaders& headers); public: CCafMessageHeaders(); virtual ~CCafMessageHeaders(); public: IIntMessage::SmartPtrCHeaders getHeaders() const; public: std::string getPayloadType() const; std::string getPayloadTypeOpt( const std::string& defaultVal = std::string()) const; public: std::string getVersion() const; std::string getVersionOpt( const std::string& defaultVal = "1.0") const; public: UUID getClientId() const; std::string getClientIdStr() const; UUID getClientIdOpt( const UUID defaultVal = CAFCOMMON_GUID_NULL) const; std::string getClientIdStrOpt( const std::string& defaultVal = std::string()) const; public: UUID getRequestId() const; std::string getRequestIdStr() const; UUID getRequestIdOpt( const UUID defaultVal = CAFCOMMON_GUID_NULL) const; std::string getRequestIdStrOpt( const std::string& defaultVal = std::string()) const; public: std::string getPmeId() const; std::string getPmeIdOpt( const std::string& defaultVal = std::string()) const; public: UUID getSessionId() const; std::string getSessionIdStr() const; UUID getSessionIdOpt( const UUID defaultVal = CAFCOMMON_GUID_NULL) const; std::string getSessionIdStrOpt( const std::string& defaultVal = std::string()) const; public: std::string getRelDirectory() const; std::string getRelDirectoryOpt( const std::string& defaultVal = std::string()) const; public: std::string getRelFilename() const; std::string getRelFilenameOpt( const std::string& defaultVal) const; public: std::string getProviderUri() const; std::string getProviderUriOpt( const std::string& defaultVal) const; public: std::string getFlowDirection() const; std::string getFlowDirectionOpt( const std::string& defaultVal) const; public: std::string getRequiredStr( const std::string& key) const; std::string getOptionalStr( const std::string& key, const std::string& defaultVal = std::string()) const; bool getRequiredBool( const std::string& key) const; bool getOptionalBool( const std::string& key, const bool defaultVal = false) const; private: void initialize( const IIntMessage::SmartPtrCHeaders& headers); private: SmartPtrIVariant findOptionalHeader( const std::string& key) const; SmartPtrIVariant findRequiredHeader( const std::string& key) const; private: bool _isInitialized; IIntMessage::SmartPtrCHeaders _headers; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CCafMessageHeaders); }; } #endif // #ifndef CCafMessageHeaders_h_ CCafMessageHeadersWriter.h000066400000000000000000000035561321503522500405720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCafMessageHeadersWriter_h_ #define CCafMessageHeadersWriter_h_ #include "Integration/IIntMessage.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CCafMessageHeadersWriter); class INTEGRATIONCAF_LINKAGE CCafMessageHeadersWriter { public: static SmartPtrCCafMessageHeadersWriter create(); public: CCafMessageHeadersWriter(); virtual ~CCafMessageHeadersWriter(); public: IIntMessage::SmartPtrCHeaders getHeaders() const; public: void setPayloadType(const std::string& payloadType); void setVersion(const std::string& version); void setPayloadVersion(const std::string& payloadVersion); void setClientId(const UUID& clientId); void setClientId(const std::string& clientIdStr); void setRequestId(const UUID& requestId); void setRequestId(const std::string& requestIdStr); void setPmeId(const std::string& pmeId); void setSessionId(const UUID& sessionId); void setSessionId(const std::string& sessionId); void setRelDirectory(const std::string& relDirectory); void setRelFilename(const std::string& relFilename); void setProviderUri(const std::string& providerUri); void setIsThrowable(const bool& isThrowable); void setIsMultiPart(const bool& isMultiPart); void setProtocol(const std::string& protocol); void setProtocolAddress(const std::string& protocolAddress); void setFlowDirection(const std::string& flowDirection); public: void insertString( const std::string& key, const std::string& value); void insertBool( const std::string& key, const bool& value); private: void initialize(); private: bool _isInitialized; IIntMessage::SmartPtrCHeaders _headers; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CCafMessageHeadersWriter); }; } #endif // #ifndef CCafMessageHeadersWriter_h_ CCafMessagePayload.h000066400000000000000000000043001321503522500373770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCafMessagePayload_h_ #define CCafMessagePayload_h_ #include #include "Integration/Caf/CCafMessagePayload.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/ResponseDoc/CEventKeyDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CCafMessagePayload); class INTEGRATIONCAF_LINKAGE CCafMessagePayload { public: static SmartPtrCCafMessagePayload create( const SmartPtrCDynamicByteArray& payload, const std::string& payloadType = std::string()); static SmartPtrCCafMessagePayload createFromFile( const std::string& payloadFile, const std::string& payloadType = std::string()); static SmartPtrCCafMessagePayload createFromStr( const std::string& payloadStr, const std::string& payloadType = std::string()); public: static SmartPtrCDynamicByteArray createBufferFromStr( const std::string& payloadStr); static SmartPtrCDynamicByteArray createBufferFromFile( const std::string& payloadFile); public: static void saveToFile( const SmartPtrCDynamicByteArray& payload, const std::string& payloadPath); static std::string saveToStr( const SmartPtrCDynamicByteArray& payload); public: CCafMessagePayload(); virtual ~CCafMessagePayload(); public: std::string getPayloadStr() const; SmartPtrCDynamicByteArray getPayload() const; public: std::string getVersion() const; public: SmartPtrCRequestHeaderDoc getRequestHeader() const; SmartPtrCManifestDoc getManifest() const; std::deque getEventKeyCollection() const; private: void initialize( const SmartPtrCDynamicByteArray& payload, const std::string& payloadType = std::string(), const std::string& encoding = "xml"); private: bool _isInitialized; std::string _encoding; SmartPtrCDynamicByteArray _payload; std::string _payloadStr; SmartPtrCXmlElement _payloadXml; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CCafMessagePayload); }; } #endif // #ifndef CCafMessagePayload_h_ CCafMessagePayloadParser.h000066400000000000000000000035531321503522500405650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCafMessagePayloadParser_h_ #define CCafMessagePayloadParser_h_ #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CCafMessagePayloadParser); class INTEGRATIONCAF_LINKAGE CCafMessagePayloadParser { public: static SmartPtrCPayloadEnvelopeDoc getPayloadEnvelope( const SmartPtrCDynamicByteArray& payload); static SmartPtrCInstallProviderJobDoc getInstallProviderJob( const SmartPtrCDynamicByteArray& payload); static SmartPtrCUninstallProviderJobDoc getUninstallProviderJob( const SmartPtrCDynamicByteArray& payload); static SmartPtrCProviderRequestDoc getProviderRequest( const SmartPtrCDynamicByteArray& payload); static SmartPtrCProviderRegDoc getProviderReg( const SmartPtrCDynamicByteArray& payload); static SmartPtrCInstallRequestDoc getInstallRequest( const SmartPtrCDynamicByteArray& payload); static SmartPtrCMgmtRequestDoc getMgmtRequest( const SmartPtrCDynamicByteArray& payload); private: static SmartPtrCXmlElement bufferToXml( const SmartPtrCDynamicByteArray& payload, const std::string& payloadType = std::string()); static std::string bufferToStr( const SmartPtrCDynamicByteArray& payload); private: CAF_CM_DECLARE_NOCREATE(CCafMessagePayloadParser); }; } #endif // #ifndef CCafMessagePayloadParser_h_ IntegrationCafLink.h000066400000000000000000000010411321503522500374760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Caf/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef INTEGRATIONCAFLINK_H_ #define INTEGRATIONCAFLINK_H_ #ifndef INTEGRATIONCAF_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define INTEGRATIONCAF_LINKAGE __declspec(dllexport) #else #define INTEGRATIONCAF_LINKAGE __declspec(dllimport) #endif #else #define INTEGRATIONCAF_LINKAGE #endif #endif #endif /* INTEGRATIONCAFLINK_H_ */ Core/000077500000000000000000000000001321503522500340155ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/IntegrationCAbstractMessageChannel.h000066400000000000000000000034531321503522500406370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Created on: Jan 26, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CABSTRACTMESSAGECHANNEL_H_ #define CABSTRACTMESSAGECHANNEL_H_ #include "Integration/IChannelInterceptorSupport.h" #include "Integration/IChannelInterceptor.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/Core/IntegrationCoreLink.h" namespace Caf { /** * Base class for {@link IMessageChannel} implementations providing common * properties and method implementations including {@link IChannelInterceptor interceptors}. */ class INTEGRATIONCORE_LINKAGE CAbstractMessageChannel : public IMessageChannel, public IChannelInterceptorSupport { public: CAbstractMessageChannel(); virtual ~CAbstractMessageChannel(); public: // IMessageChannel bool send( const SmartPtrIIntMessage& message); bool send( const SmartPtrIIntMessage& message, const int32 timeout); public: // IChannelInterceptorSupport void setInterceptors( const IChannelInterceptorSupport::InterceptorCollection& interceptors); protected: /** * Subclasses must implement this method. A non-negative timeout indicates * how int32 to wait if the channel is at capacity. If the value is 0 it must * return immediately with or without success. A negative timeout value * indicates that the method should block until either the message is accepted * or the blocking thread is interrupted. */ virtual bool doSend( const SmartPtrIIntMessage& message, int32 timeout) = 0; protected: std::list getInterceptors() const; private: std::list _interceptors; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAbstractMessageChannel); }; } #endif /* CABSTRACTMESSAGECHANNEL_H_ */ CAbstractMessageRouter.h000066400000000000000000000022021321503522500405360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Created on: Aug 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAbstractMessageRouter_h #define CAbstractMessageRouter_h #include "Integration/IMessageRouter.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CAbstractMessageRouter : public IMessageRouter { public: CAbstractMessageRouter(); virtual ~CAbstractMessageRouter(); void init(); void init( const SmartPtrIMessageChannel& defaultOutputChannel, const bool ignoreSendFailures, const int32 sendTimeout); virtual void routeMessage( const SmartPtrIIntMessage& message); protected: typedef std::deque ChannelCollection; virtual ChannelCollection getTargetChannels( const SmartPtrIIntMessage& message) = 0; private: SmartPtrIMessageChannel _defaultOutputChannel; bool _ignoreSendFailures; int32 _sendTimeout; private: bool _isInitialized; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CAbstractMessageRouter); }; } #endif /* CAbstractMessageRouter_h */ CAbstractPollableChannel.h000066400000000000000000000030531321503522500410010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Created on: Jan 26, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CABSTRACTPOLLABLECHANNEL_H_ #define CABSTRACTPOLLABLECHANNEL_H_ #include "Integration/Core/CAbstractMessageChannel.h" #include "Integration/Dependencies/CPollerMetadata.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IPollableChannel.h" namespace Caf { /** * Base class for pollable channels */ class INTEGRATIONCORE_LINKAGE CAbstractPollableChannel : public CAbstractMessageChannel, public IPollableChannel { public: CAbstractPollableChannel(); virtual ~CAbstractPollableChannel(); public: SmartPtrIIntMessage receive(); SmartPtrIIntMessage receive(const int32 timeout); SmartPtrCPollerMetadata getPollerMetadata() const; protected: /** * Subclasses must implement this method. A non-negative timeout indicates * how int32 to wait if the channel is empty (if the value is 0, it must * return immediately with or without success). A negative timeout value * indicates that the method should block until either a message is * available or the blocking thread is interrupted. */ virtual SmartPtrIIntMessage doReceive(const int32 timeout) = 0; void setPollerMetadata(const SmartPtrCPollerMetadata& pollerMetadata); void setPollerMetadata(const SmartPtrIDocument& pollerDoc); private: SmartPtrCPollerMetadata _pollerMetadata; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAbstractPollableChannel); }; } #endif /* CABSTRACTPOLLABLECHANNEL_H_ */ CBroadcastingDispatcher.h000066400000000000000000000025561321503522500407100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CBroadcastingDispatcher_h_ #define CBroadcastingDispatcher_h_ #include "Integration/IMessageDispatcher.h" #include "Integration/IErrorHandler.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" namespace Caf { /// Sends responses/errors back to the client. class INTEGRATIONCORE_LINKAGE CBroadcastingDispatcher : public IMessageDispatcher { public: CBroadcastingDispatcher(); virtual ~CBroadcastingDispatcher(); public: void initialize( const SmartPtrIErrorHandler& errorHandler); public: // IMessageDispatcher void addHandler( const SmartPtrIMessageHandler& messageHandler); void removeHandler( const SmartPtrIMessageHandler& messageHandler); bool dispatch( const SmartPtrIIntMessage& message); private: typedef std::map CIntMessageHandlerCollection; CAF_DECLARE_SMART_POINTER(CIntMessageHandlerCollection); private: bool _isInitialized; SmartPtrIErrorHandler _errorHandler; SmartPtrCIntMessageHandlerCollection _messageHandlerCollection; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CBroadcastingDispatcher); }; CAF_DECLARE_SMART_POINTER(CBroadcastingDispatcher); } #endif // #ifndef CBroadcastingDispatcher_h_ CChannelInterceptorAdapter.h000066400000000000000000000023241321503522500413620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Created on: Jan 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCHANNELINTERCEPTORADAPTER_H_ #define CCHANNELINTERCEPTORADAPTER_H_ #include "Integration/IChannelInterceptor.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" namespace Caf { /** * A {@link IChannelInterceptor} with no-op method implementations so that * subclasses do not have to implement all of th einterface's methods. */ class INTEGRATIONCORE_LINKAGE CChannelInterceptorAdapter : public IChannelInterceptor { public: CChannelInterceptorAdapter(); virtual ~CChannelInterceptorAdapter(); public: // IChannelInterceptor virtual SmartPtrIIntMessage& preSend( SmartPtrIIntMessage& message, SmartPtrIMessageChannel& channel); virtual void postSend( SmartPtrIIntMessage& message, SmartPtrIMessageChannel& channel, bool sent); virtual bool preReceive( SmartPtrIMessageChannel& channel); virtual SmartPtrIIntMessage& postReceive( SmartPtrIIntMessage& message, SmartPtrIMessageChannel& channel); private: CAF_CM_DECLARE_NOCOPY(CChannelInterceptorAdapter); }; } #endif /* CCHANNELINTERCEPTORADAPTER_H_ */ CChannelResolver.h000066400000000000000000000020411321503522500373600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CChannelResolver_h_ #define CChannelResolver_h_ #include "Integration/IChannelResolver.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CChannelResolver : public IChannelResolver { public: CChannelResolver(); virtual ~CChannelResolver(); public: void initialize( const SmartPtrCIntegrationObjectCollection& integrationObjectCollection); public: // IChannelResolver SmartPtrIMessageChannel resolveChannelName( const std::string& channelName) const; SmartPtrIIntegrationObject resolveChannelNameToObject( const std::string& channelName) const; private: bool _isInitialized; SmartPtrCIntegrationObjectCollection _integrationObjectCollection; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CChannelResolver); }; CAF_DECLARE_SMART_POINTER(CChannelResolver); } #endif // #ifndef CChannelResolver_h_ CDocument.h000066400000000000000000000026121321503522500360500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CDocument_h_ #define CDocument_h_ #include "Integration/IDocument.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CDocument : public IDocument { public: CDocument(); virtual ~CDocument(); public: void initialize(const SmartPtrCXmlElement& xmlElement); SmartPtrCXmlElement getXmlElement() const; public: // IDocument std::string findRequiredAttribute(const std::string& name) const; std::string findOptionalAttribute(const std::string& name) const; SmartPtrIDocument findRequiredChild(const std::string& name) const; SmartPtrIDocument findOptionalChild(const std::string& name) const; SmartPtrCAttributeCollection getAllAttributes() const; SmartPtrCChildCollection getAllChildren() const; SmartPtrCOrderedChildCollection getAllChildrenInOrder() const; std::string getName() const; std::string getValue() const; std::string getPath() const; public: // IDocument Save operations void saveToFile(const std::string& filename) const; std::string saveToString() const; std::string saveToStringRaw() const; private: bool _isInitialized; SmartPtrCXmlElement _xmlElement; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CDocument); }; CAF_DECLARE_SMART_POINTER(CDocument); } #endif // #ifndef CDocument_h_ CErrorHandler.h000066400000000000000000000020761321503522500366650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CErrorHandler_h_ #define CErrorHandler_h_ #include "Integration/IErrorHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/IThrowable.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CErrorHandler : public IErrorHandler { public: CErrorHandler(); virtual ~CErrorHandler(); public: void initialize( const SmartPtrIChannelResolver& channelResolver, const SmartPtrIMessageChannel& errorMessageChannel); public: // IErrorHandler void handleError( const SmartPtrIThrowable& throwable, const SmartPtrIIntMessage& message) const; private: bool _isInitialized; SmartPtrIChannelResolver _channelResolver; SmartPtrIMessageChannel _errorMessageChannel; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CErrorHandler); }; CAF_DECLARE_SMART_POINTER(CErrorHandler); } #endif // #ifndef CErrorHandler_h_ CExpressionHandler.h000066400000000000000000000021221321503522500377230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Created on: Jul 23, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CEXPRESSIONHANDLER_H_ #define CEXPRESSIONHANDLER_H_ #include "Common/IAppConfig.h" #include "Common/IAppContext.h" #include "IVariant.h" #include "Integration/IExpressionInvoker.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CExpressionHandler { public: CExpressionHandler(); virtual ~CExpressionHandler(); void init( const SmartPtrIAppConfig& appConfig, const SmartPtrIAppContext& appContext, const std::string& expression); SmartPtrIVariant evaluate(const SmartPtrIIntMessage& message); std::string getBeanName() const; std::string getMethodName() const; Cdeqstr getMethodParameters() const; std::string toString() const; private: bool _isInitialized; SmartPtrIExpressionInvoker _invoker; std::string _beanName; std::string _methodName; Cdeqstr _methodParams; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CExpressionHandler); }; CAF_DECLARE_SMART_POINTER(CExpressionHandler); } #endif /* CEXPRESSIONHANDLER_H_ */ CIntException.h000066400000000000000000000032651321503522500367100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CIntException_h_ #define CIntException_h_ #include "Exception/CCafException.h" #include "Integration/IThrowable.h" #include "Integration/Core/CIntException.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CIntException : public IThrowable { public: CIntException(); virtual ~CIntException(); public: void initialize(const CCafException* cafException); public: // IThrowable std::string getExceptionClassName() const; std::string getMsg() const; std::string getClassName() const; std::string getFuncName() const; HRESULT getError() const; std::deque* getBacktrace() const; std::string getFullMsg() const; private: bool _isInitialized; std::string _exceptionClassName; HRESULT _errorCode; std::string _message; std::string _className; std::string _funcName; std::deque* _backtrace; std::string _fullMsg; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CIntException); }; CAF_DECLARE_SMART_POINTER(CIntException); #define CAF_CM_DECLARE_INTEGRATION_EXCEPTION_CLASS(_exclass_) \ class INTEGRATIONCORE_LINKAGE _exclass_ : public Caf::CCafException { \ public: \ _exclass_(); \ virtual ~_exclass_(); \ void throwSelf(); \ private: \ _exclass_(const _exclass_ &); \ _exclass_ & operator=(const _exclass_ &); \ }; // Exceptions specific to integration CAF_CM_DECLARE_INTEGRATION_EXCEPTION_CLASS(FatalListenerStartupException) CAF_CM_DECLARE_INTEGRATION_EXCEPTION_CLASS(ListenerExecutionFailedException) CAF_CM_DECLARE_INTEGRATION_EXCEPTION_CLASS(MessageDeliveryException) } #endif // #ifndef CIntException_h_ CIntMessage.h000066400000000000000000000034301321503522500363300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CIntMessage_h_ #define CIntMessage_h_ #include "Integration/IIntMessage.h" #include "ICafObject.h" #include "IVariant.h" #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CIntMessage : public IIntMessage { public: static SmartPtrCHeaders mergeHeaders( const SmartPtrCHeaders& newHeaders, const SmartPtrCHeaders& origHeaders); public: CIntMessage(); virtual ~CIntMessage(); public: void initializeStr( const std::string& payloadStr, const SmartPtrCHeaders& newHeaders, const SmartPtrCHeaders& origHeaders); void initialize( const SmartPtrCDynamicByteArray& payload, const SmartPtrCHeaders& newHeaders, const SmartPtrCHeaders& origHeaders); public: // IIntMessage SmartPtrCDynamicByteArray getPayload() const; std::string getPayloadStr() const; UUID getMessageId() const; std::string getMessageIdStr() const; SmartPtrCHeaders getHeaders() const; SmartPtrIVariant findOptionalHeader( const std::string& key) const; SmartPtrIVariant findRequiredHeader( const std::string& key) const; std::string findOptionalHeaderAsString( const std::string& key) const; std::string findRequiredHeaderAsString( const std::string& key) const; SmartPtrICafObject findOptionalObjectHeader( const std::string& key) const; SmartPtrICafObject findRequiredObjectHeader( const std::string& key) const; private: bool _isInitialized; UUID _messageId; SmartPtrCDynamicByteArray _payload; SmartPtrCHeaders _headers; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CIntMessage); }; CAF_DECLARE_SMART_POINTER(CIntMessage); } #endif // #ifndef _IntegrationContracts_CIntMessage_h_ CIntMessageHeaders.h000066400000000000000000000032021321503522500376210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CIntMessageHeaders_h_ #define CIntMessageHeaders_h_ #include "Integration/Core/CIntMessageHeaders.h" #include "ICafObject.h" #include "IVariant.h" #include "Integration/IIntMessage.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CIntMessageHeaders { public: CIntMessageHeaders(); virtual ~CIntMessageHeaders(); public: IIntMessage::SmartPtrCHeaders getHeaders() const; void clear(); void insertString( const std::string& key, const std::string& value); void insertStringOpt( const std::string& key, const std::string& value); void insertInt64( const std::string& key, const int64& value); void insertUint64( const std::string& key, const uint64& value); void insertInt32( const std::string& key, const int32& value); void insertUint32( const std::string& key, const uint32& value); void insertInt16( const std::string& key, const int16& value); void insertUint16( const std::string& key, const uint16& value); void insertUint8( const std::string& key, const uint8& value); void insertBool( const std::string& key, const bool& value); void insertVariant( const std::string& key, const SmartPtrIVariant& variant); void insertObject( const std::string& key, const SmartPtrICafObject& cafObject); private: IIntMessage::SmartPtrCHeaders _headers; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CIntMessageHeaders); }; CAF_DECLARE_SMART_POINTER(CIntMessageHeaders); } #endif // #ifndef _IntegrationContracts_CIntMessageHeaders_h_ CIntegrationAppContext.h000066400000000000000000000076531321503522500405750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CIntegrationAppContext_h_ #define CIntegrationAppContext_h_ #include "Common/IAppContext.h" #include "Common/CApplicationContext.h" #include "IBean.h" #include "Integration/Core/CChannelResolver.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" #include "Integration/IMessageChannel.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Integration/IChannelResolver.h" #include "Integration/IIntegrationAppContext.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CIntegrationAppContext : public IIntegrationAppContext, public IAppContext, public IChannelResolver { public: CIntegrationAppContext(); virtual ~CIntegrationAppContext(); public: void initialize(const uint32 timeoutMs); void initialize(const uint32 timeoutMs, const std::string& beanConfigPath); void initializeTwoPhase(const uint32 timeoutMs, const std::string& beanConfigPath); void terminate(const uint32 timeoutMs); public: // IIntegrationAppContext void startLifecycleBeans(); SmartPtrIIntegrationObject getIntegrationObject(const std::string& id) const; void getIntegrationObject(const IID& iid, void **ppv) const; SmartPtrCObjectCollection getIntegrationObjects(const IID& iid) const; public: // IAppContext SmartPtrIBean getBean(const std::string& name) const; public: // IChannelResolver SmartPtrIMessageChannel resolveChannelName( const std::string& channelName) const; SmartPtrIIntegrationObject resolveChannelNameToObject( const std::string& channelName) const; private: typedef std::multimap LifecycleBeans; private: void initializeRaw( const uint32 timeoutMs, const std::string& beanConfigPath, const bool startLifecycleBeans); SmartPtrCIntegrationObjectCollection assign( const IAppContext::SmartPtrCBeans& contextBeans, const Cdeqstr& beanConfigPathCollection) const; void injectChannelInterceptors( const SmartPtrCIntegrationObjectCollection& integrationObjectCollection) const; void wire( const SmartPtrIAppContext& appContext, const SmartPtrCIntegrationObjectCollection& integrationObjectCollection, const SmartPtrCChannelResolver& channelResolver) const; void startStop( const LifecycleBeans& lifecycleBeans, const uint32 timeoutMs, const bool isStart) const; SmartPtrCXmlElement getBeanConfigRoot() const; void addBuiltIn( const std::string& beanId, const IAppContext::SmartPtrCBeans& beans, SmartPtrCIntegrationObjectCollection& integrationObjectCollection) const; std::string getDefaultBeanConfigPath() const; Cdeqstr getBeanConfigFiles( const std::string& beanConfigPath) const; private: class CIntegrationAppContextWeakReference : public IIntegrationAppContext { public: CIntegrationAppContextWeakReference(); void set(CIntegrationAppContext *context); SmartPtrIIntegrationObject getIntegrationObject( const std::string& id) const; void getIntegrationObject( const IID& iid, void **ppv) const; IIntegrationAppContext::SmartPtrCObjectCollection getIntegrationObjects( const IID& iid) const; private: CIntegrationAppContext *_context; CAF_CM_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CIntegrationAppContextWeakReference); }; CAF_DECLARE_SMART_POINTER(CIntegrationAppContextWeakReference); private: bool _isInitialized; bool _isIntegrationObjectCollectionReady; bool _lifecycleBeansStarted; uint32 _timeoutMs; SmartPtrCApplicationContext _applicationContext; SmartPtrCChannelResolver _channelResolver; SmartPtrCIntegrationObjectCollection _integrationObjectCollection; SmartPtrCIntegrationAppContextWeakReference _weakSelfReference; LifecycleBeans _lifecycleBeans; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CIntegrationAppContext); }; CAF_DECLARE_SMART_POINTER(CIntegrationAppContext); } #endif // #ifndef CIntegrationAppContext_h_ CMessageHandler.h000066400000000000000000000031311321503522500371510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessageHandler_h_ #define CMessageHandler_h_ #include "Integration/IMessageHandler.h" #include "ICafObject.h" #include "Integration/IErrorProcessor.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/IMessageProcessor.h" #include "Integration/IMessageRouter.h" #include "Integration/IMessageSplitter.h" #include "Integration/ITransformer.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CMessageHandler : public IMessageHandler { public: CMessageHandler(); virtual ~CMessageHandler(); public: void initialize( const std::string& inputId, const SmartPtrIMessageChannel& outputMessageChannel, const SmartPtrICafObject& messageHandlerObj); public: std::string getInputId() const; public: // IMessageHandler void handleMessage( const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); private: bool _isInitialized; std::string _inputId; SmartPtrIIntMessage _savedMessage; SmartPtrIMessageChannel _outputMessageChannel; SmartPtrITransformer _transformer; SmartPtrIMessageProcessor _messageProcessor; SmartPtrIErrorProcessor _errorProcessor; SmartPtrIMessageSplitter _messageSplitter; SmartPtrIMessageRouter _messageRouter; SmartPtrIMessageHandler _messageHandler; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CMessageHandler); }; CAF_DECLARE_SMART_POINTER(CMessageHandler); } #endif // #ifndef CMessageHandler_h_ CMessageHeaderUtils.h000066400000000000000000000034251321503522500400130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Created on: Nov 19, 2014 * Author: bwilliams * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef CMessageHeaderUtils_h_ #define CMessageHeaderUtils_h_ #include "Integration/IIntMessage.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CMessageHeaderUtils { public: static std::string getStringReq( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static std::string getStringOpt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static uint8 getUint8Req( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static uint8 getUint8Opt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static uint16 getUint16Req( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static uint16 getUint16Opt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static uint32 getUint32Req( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static uint32 getUint32Opt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static uint64 getUint64Req( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static uint64 getUint64Opt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static bool getBoolReq( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static bool getBoolOpt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag); static void log( const IIntMessage::SmartPtrCHeaders& headers, const log4cpp::Priority::PriorityLevel priorityLevel = log4cpp::Priority::DEBUG); private: CAF_CM_DECLARE_NOCREATE(CMessageHeaderUtils); }; } #endif CMessagingTemplate.h000066400000000000000000000035251321503522500377070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagingTemplate_h_ #define CMessagingTemplate_h_ #include "Integration/ILifecycle.h" #include "ICafObject.h" #include "Integration/Core/CMessageHandler.h" #include "Integration/Core/CMessagingTemplateHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" #include "Integration/IPollableChannel.h" #include "Integration/ISubscribableChannel.h" #include "Integration/ITaskExecutor.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CMessagingTemplate : public ILifecycle { public: CMessagingTemplate(); virtual ~CMessagingTemplate(); public: void initialize( const SmartPtrIChannelResolver& channelResolver, const SmartPtrIIntegrationObject& inputIntegrationObject, const SmartPtrIMessageChannel& errorMessageChannel, const SmartPtrIMessageChannel& outputMessageChannel, const SmartPtrICafObject& messageHandlerObj); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; private: bool _isInitialized; bool _isRunning; std::string _inputId; SmartPtrISubscribableChannel _inputSubscribableChannel; SmartPtrCMessagingTemplateHandler _messagingTemplateHandler; SmartPtrITaskExecutor _taskExecutor; private: SmartPtrITaskExecutor createTaskExecutor( const SmartPtrIChannelResolver& channelResolver, const SmartPtrCMessageHandler& messageHandler, const SmartPtrIPollableChannel& inputPollableChannel, const SmartPtrIMessageChannel& errorMessageChannel) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CMessagingTemplate); }; CAF_DECLARE_SMART_POINTER(CMessagingTemplate); } #endif // #ifndef CMessagingTemplate_h_ CMessagingTemplateHandler.h000066400000000000000000000017211321503522500412010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessagingTemplateHandler_h_ #define CMessagingTemplateHandler_h_ #include "Integration/IMessageHandler.h" #include "Integration/IIntMessage.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CMessagingTemplateHandler : public IMessageHandler { public: CMessagingTemplateHandler(); virtual ~CMessagingTemplateHandler(); public: void initialize( const SmartPtrIMessageHandler& messageHandler); public: // IMessageHandler void handleMessage( const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); private: bool _isInitialized; SmartPtrIMessageHandler _messageHandler; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CMessagingTemplateHandler); }; CAF_DECLARE_SMART_POINTER(CMessagingTemplateHandler); } #endif // #ifndef CMessagingTemplateHandler_h_ CSimpleAsyncTaskExecutor.h000066400000000000000000000024601321503522500410640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CSimpleAsyncTaskExecutor_h_ #define CSimpleAsyncTaskExecutor_h_ #include "Common/CThreadSignal.h" #include "Integration/Core/CSimpleAsyncTaskExecutorState.h" #include "Integration/IErrorHandler.h" #include "Integration/IRunnable.h" #include "Integration/ITaskExecutor.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CSimpleAsyncTaskExecutor : public ITaskExecutor { public: CSimpleAsyncTaskExecutor(); virtual ~CSimpleAsyncTaskExecutor(); public: void initialize( const SmartPtrIRunnable& runnable, const SmartPtrIErrorHandler& errorHandler); public: // ITaskExecutor void execute(const uint32 timeoutMs); void cancel(const uint32 timeoutMs); ETaskState getState() const; private: static void* threadFunc(void* data); private: bool _isInitialized; GThread* _thread; SmartPtrCSimpleAsyncTaskExecutorState _state; typedef std::pair CThreadData; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_THREADSIGNAL_CREATE; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CSimpleAsyncTaskExecutor); }; CAF_DECLARE_SMART_POINTER(CSimpleAsyncTaskExecutor); } #endif // #ifndef CSimpleAsyncTaskExecutor_h_ CSimpleAsyncTaskExecutorState.h000066400000000000000000000032001321503522500420560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CSimpleAsyncTaskExecutorState_h_ #define CSimpleAsyncTaskExecutorState_h_ #include "Common/CThreadSignal.h" #include "Common/CAutoMutex.h" #include "Integration/IErrorHandler.h" #include "Integration/IRunnable.h" #include "Integration/ITaskExecutor.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CSimpleAsyncTaskExecutorState { public: CSimpleAsyncTaskExecutorState(); virtual ~CSimpleAsyncTaskExecutorState(); public: void initialize( const SmartPtrIRunnable& runnable, const SmartPtrIErrorHandler& errorHandler); SmartPtrIRunnable getRunnable() const; SmartPtrIErrorHandler getErrorHandler() const; ITaskExecutor::ETaskState getState() const; std::string getStateStr() const; void setState(const ITaskExecutor::ETaskState runnableState); bool getHasThreadExited(); void setThreadExited(); void signalStart(); void waitForStart(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs); void signalStop(); void waitForStop(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs); private: bool _isInitialized; bool _hasThreadExited; ITaskExecutor::ETaskState _runnableState; SmartPtrIRunnable _runnable; SmartPtrIErrorHandler _errorHandler; std::string _exceptionMessage; CThreadSignal _threadSignalStart; CThreadSignal _threadSignalStop; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CSimpleAsyncTaskExecutorState); }; CAF_DECLARE_SMART_POINTER(CSimpleAsyncTaskExecutorState); } #endif // #ifndef CSimpleAsyncTaskExecutorState_h_ CSourcePollingChannelAdapter.h000066400000000000000000000032201321503522500416450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CSourcePollingChannelAdapter_h_ #define CSourcePollingChannelAdapter_h_ #include "Common/CThreadSignal.h" #include "Integration/Dependencies/CPollerMetadata.h" #include "Integration/IErrorHandler.h" #include "Integration/IMessageHandler.h" #include "Integration/IPollableChannel.h" #include "Integration/IRunnable.h" namespace Caf { class INTEGRATIONCORE_LINKAGE CSourcePollingChannelAdapter : public IRunnable { public: CSourcePollingChannelAdapter(); virtual ~CSourcePollingChannelAdapter(); public: void initialize( const SmartPtrIMessageHandler& messageHandler, const SmartPtrIPollableChannel& inputPollableChannel, const SmartPtrIErrorHandler& errorHandler); void initialize( const SmartPtrIMessageHandler& messageHandler, const SmartPtrIPollableChannel& inputPollableChannel, const SmartPtrIErrorHandler& errorHandler, const int32 timeout); public: // IRunnable void run(); void cancel(); private: bool getIsCancelled() const; private: bool _isInitialized; bool _isCancelled; bool _isTimeoutSet; int32 _timeout; SmartPtrIMessageHandler _messageHandler; SmartPtrIPollableChannel _inputPollableChannel; SmartPtrIErrorHandler _errorHandler; SmartPtrCPollerMetadata _pollerMetadata; CThreadSignal _threadSignalCancel; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_THREADSIGNAL_CREATE; CAF_CM_DECLARE_NOCOPY(CSourcePollingChannelAdapter); }; CAF_DECLARE_SMART_POINTER(CSourcePollingChannelAdapter); } #endif // #ifndef CSourcePollingChannelAdapter_h_ CUnicastingDispatcher.h000066400000000000000000000026241321503522500404100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CUnicastingDispatcher_h_ #define CUnicastingDispatcher_h_ #include "Integration/IMessageDispatcher.h" #include "Integration/Core/CBroadcastingDispatcher.h" #include "Integration/IErrorHandler.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" namespace Caf { /// Sends responses/errors back to the client. class INTEGRATIONCORE_LINKAGE CUnicastingDispatcher : public IMessageDispatcher { public: CUnicastingDispatcher(); virtual ~CUnicastingDispatcher(); public: void initialize( const SmartPtrIErrorHandler& errorHandler); public: // IMessageDispatcher void addHandler( const SmartPtrIMessageHandler& messageHandler); void removeHandler( const SmartPtrIMessageHandler& messageHandler); bool dispatch( const SmartPtrIIntMessage& message); private: typedef std::map CIntMessageHandlerCollection; CAF_DECLARE_SMART_POINTER(CIntMessageHandlerCollection); private: bool _isInitialized; SmartPtrIErrorHandler _errorHandler; SmartPtrCIntMessageHandlerCollection _messageHandlerCollection; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CUnicastingDispatcher); }; CAF_DECLARE_SMART_POINTER(CUnicastingDispatcher); } #endif // #ifndef CUnicastingDispatcher_h_ FileHeaders.h000066400000000000000000000006171321503522500363450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef FileHeadersInc_h_ #define FileHeadersInc_h_ namespace Caf { namespace FileHeaders { extern INTEGRATIONCORE_LINKAGE const char* _sFILENAME; extern INTEGRATIONCORE_LINKAGE const char* _sORIGINAL_FILE; } } #endif // #ifndef FileHeadersInc_h_ IntegrationCoreLink.h000066400000000000000000000010501321503522500400740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef INTEGRATIONCORELINK_H_ #define INTEGRATIONCORELINK_H_ #ifndef INTEGRATIONCORE_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define INTEGRATIONCORE_LINKAGE __declspec(dllexport) #else #define INTEGRATIONCORE_LINKAGE __declspec(dllimport) #endif #else #define INTEGRATIONCORE_LINKAGE #endif #endif #endif /* INTEGRATIONCORELINK_H_ */ MessageHeaders.h000066400000000000000000000027101321503522500370460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef MessageHeadersInc_h_ #define MessageHeadersInc_h_ namespace Caf { namespace MessageHeaders { // UUID stored as a string extern INTEGRATIONCORE_LINKAGE const char* _sID; // int64 extern INTEGRATIONCORE_LINKAGE const char* _sTIMESTAMP; // string extern INTEGRATIONCORE_LINKAGE const char* _sCORRELATION_ID; // string extern INTEGRATIONCORE_LINKAGE const char* _sREPLY_CHANNEL; // string extern INTEGRATIONCORE_LINKAGE const char* _sERROR_CHANNEL; // int64 extern INTEGRATIONCORE_LINKAGE const char* _sEXPIRATION_DATE; // int32 extern INTEGRATIONCORE_LINKAGE const char* _sPRIORITY; // int32 extern INTEGRATIONCORE_LINKAGE const char* _sSEQUENCE_NUMBER; // int32 extern INTEGRATIONCORE_LINKAGE const char* _sSEQUENCE_SIZE; extern INTEGRATIONCORE_LINKAGE const char* _sIS_THROWABLE; // string extern INTEGRATIONCORE_LINKAGE const char* _sREQUEST_ID; // boolean extern INTEGRATIONCORE_LINKAGE const char* _sMULTIPART; // string extern INTEGRATIONCORE_LINKAGE const char* _sMULTIPART_WORKING_DIR; // string extern INTEGRATIONCORE_LINKAGE const char* _sMESSAGE_TYPE; // string extern INTEGRATIONCORE_LINKAGE const char* _sPROTOCOL_TYPE; // string extern INTEGRATIONCORE_LINKAGE const char* _sPROTOCOL_CONNSTR; } }; #endif // #ifndef MessageHeadersInc_h_ Dependencies/000077500000000000000000000000001321503522500355135ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/IntegrationCPollerMetadata.h000066400000000000000000000016771321503522500407000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/Dependencies/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_CPollerMetadata_h_ #define _IntegrationContracts_CPollerMetadata_h_ namespace Caf { class CPollerMetadata { public: CPollerMetadata() : _maxMessagesPerPoll(0), _fixedRate(0) {} public: uint32 getMaxMessagesPerPoll() const { return _maxMessagesPerPoll; } void putMaxMessagesPerPoll(const uint32& maxMessagesPerPoll) { _maxMessagesPerPoll = maxMessagesPerPoll; } uint32 getFixedRate() const { return _fixedRate; } void putFixedRate(const uint32& fixedRate) { _fixedRate = fixedRate; } private: uint32 _maxMessagesPerPoll; uint32 _fixedRate; private: CPollerMetadata (const CPollerMetadata&); CPollerMetadata & operator=(const CPollerMetadata&); }; CAF_DECLARE_SMART_POINTER(CPollerMetadata); } #endif // #ifndef _IntegrationContracts_CPollerMetadata_h_ IChannelInterceptor.h000066400000000000000000000033501321503522500371770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Created on: Jan 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_ICHANNELINTERCEPTOR_H_ #define _IntegrationContracts_ICHANNELINTERCEPTOR_H_ #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" namespace Caf { struct __declspec(novtable) IChannelInterceptor : public ICafObject { CAF_DECL_UUID("5002EA10-769B-44A0-AA6B-18ED91B57655") /** * Invoked before the message is sent to the channel. * The message may be modified if necessary. * If this method returns null then the * actual send invocation will not occur. */ virtual SmartPtrIIntMessage& preSend( SmartPtrIIntMessage& message, SmartPtrIMessageChannel& channel) = 0; /** * Invoked immediately after the send invocation. The * boolean value argument represents the return value of * that invocation. */ virtual void postSend( SmartPtrIIntMessage& message, SmartPtrIMessageChannel& channel, bool sent) = 0; /** * Invoked as soon as receive is called and before a message * is actually retrieved. If the return value is 'false' then * no message will be retrieved. This only applies to PollableChannels. */ virtual bool preReceive( SmartPtrIMessageChannel& channel) = 0; /** * Invoked immediately after a message has been retrieved but * before it is returned to the caller. The message may be modified * if necessary. This only applies to PollableChannels. */ virtual SmartPtrIIntMessage& postReceive( SmartPtrIIntMessage& message, SmartPtrIMessageChannel& channel) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IChannelInterceptor); } #endif /* _IntegrationContracts_ICHANNELINTERCEPTOR_H_ */ IChannelInterceptorInstance.h000066400000000000000000000012461321503522500406660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Created on: Jan 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_ICHANNELINTERCEPTORINSTANCE_H_ #define _IntegrationContracts_ICHANNELINTERCEPTORINSTANCE_H_ namespace Caf { struct __declspec(novtable) IChannelInterceptorInstance : public ICafObject { CAF_DECL_UUID("566C38A8-FF13-4E31-814E-A18130C009F6") virtual uint32 getOrder() const = 0; virtual bool isChannelIdMatched(const std::string& channelId) const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IChannelInterceptorInstance); } #endif /* _IntegrationContracts_ICHANNELINTERCEPTORINSTANCE_H_ */ IChannelInterceptorSupport.h000066400000000000000000000014211321503522500405710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Created on: Jan 26, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_ICHANNELINTERCEPTORSUPPORT_H_ #define _IntegrationContracts_ICHANNELINTERCEPTORSUPPORT_H_ #include "ICafObject.h" #include "Integration/IChannelInterceptor.h" namespace Caf { struct __declspec(novtable) IChannelInterceptorSupport : public ICafObject { CAF_DECL_UUID("C8F3CBAF-B1EB-4AD8-920C-EFE5EE25638A") typedef std::list InterceptorCollection; virtual void setInterceptors( const InterceptorCollection& interceptors) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IChannelInterceptorSupport); } #endif /* _IntegrationContracts_ICHANNELINTERCEPTORSUPPORT_H_ */ IChannelResolver.h000066400000000000000000000015031321503522500365000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IChannelResolver_h_ #define _IntegrationContracts_IChannelResolver_h_ #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IChannelResolver : public ICafObject { CAF_DECL_UUID("32361862-a312-4cab-a978-45b7059ca102") virtual SmartPtrIMessageChannel resolveChannelName( const std::string& channelName) const = 0; virtual SmartPtrIIntegrationObject resolveChannelNameToObject( const std::string& channelName) const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IChannelResolver); } #endif // #ifndef _IntegrationContracts_IChannelResolver_h_ IDocument.h000066400000000000000000000033331321503522500351670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IDocument_h_ #define _IntegrationContracts_IDocument_h_ namespace Caf { CAF_FORWARD_DECLARE_SMART_INTERFACE(IDocument); /// TODO - describe interface struct __declspec(novtable) IDocument : public ICafObject { CAF_DECL_UUID("aa95ea11-3ca0-4863-b267-88d38246ff67") public: // Read operations typedef std::map CAttributeCollection; typedef std::multimap CChildCollection; typedef std::deque COrderedChildCollection; CAF_DECLARE_SMART_POINTER(CAttributeCollection); CAF_DECLARE_SMART_POINTER(CChildCollection); CAF_DECLARE_SMART_POINTER(COrderedChildCollection); public: // Read operations virtual std::string findRequiredAttribute(const std::string& name) const = 0; virtual std::string findOptionalAttribute(const std::string& name) const = 0; virtual SmartPtrIDocument findRequiredChild(const std::string& name) const = 0; virtual SmartPtrIDocument findOptionalChild(const std::string& name) const = 0; virtual SmartPtrCAttributeCollection getAllAttributes() const = 0; virtual SmartPtrCChildCollection getAllChildren() const = 0; virtual SmartPtrCOrderedChildCollection getAllChildrenInOrder() const = 0; virtual std::string getName() const = 0; virtual std::string getValue() const = 0; virtual std::string getPath() const = 0; public: // Save operations virtual void saveToFile(const std::string& filename) const = 0; virtual std::string saveToString() const = 0; virtual std::string saveToStringRaw() const = 0; }; } #endif // #ifndef _IntegrationContracts_IDocument_h_ IErrorHandler.h000066400000000000000000000013461321503522500360020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IErrorHandler_h_ #define _IntegrationContracts_IErrorHandler_h_ #include "Integration/IIntMessage.h" #include "Integration/IThrowable.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IErrorHandler : public ICafObject { CAF_DECL_UUID("da0e8646-43fb-4d43-a31b-f736c3978d48") public: // Read operations virtual void handleError( const SmartPtrIThrowable& throwable, const SmartPtrIIntMessage& message) const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IErrorHandler); } #endif // #ifndef _IntegrationContracts_IErrorHandler_h_ IErrorProcessor.h000066400000000000000000000012331321503522500363770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IErrorProcessor_h_ #define _IntegrationContracts_IErrorProcessor_h_ #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IErrorProcessor : public ICafObject { CAF_DECL_UUID("7ed3c23c-609a-4e42-9463-ed98da222d0a") virtual SmartPtrIIntMessage processErrorMessage( const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IErrorProcessor); } #endif // #ifndef _IntegrationContracts_IErrorProcessor_h_ IExpressionInvoker.h000066400000000000000000000012531321503522500371050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Created on: Jul 23, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IEXPRESSIONINVOKER_H_ #define _IntegrationContracts_IEXPRESSIONINVOKER_H_ #include "IVariant.h" #include "Integration/IIntMessage.h" namespace Caf { struct __declspec(novtable) IExpressionInvoker : public ICafObject { CAF_DECL_UUID("EF1DC19E-4DE0-416C-A7CB-D1695FF8D52A") virtual SmartPtrIVariant invokeExpression( const std::string& methodName, const Cdeqstr& methodParams, const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IExpressionInvoker); } #endif IIntMessage.h000066400000000000000000000033461321503522500354540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IIntMessage_h_ #define _IntegrationContracts_IIntMessage_h_ #include "ICafObject.h" #include "IVariant.h" #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IIntMessage : public ICafObject { CAF_DECL_UUID("c9abc77a-ebd1-4203-911f-1b37d9b17d8e") // // Routines dealing with the message // virtual UUID getMessageId() const = 0; virtual std::string getMessageIdStr() const = 0; // // Routines dealing with the payload // typedef std::map > CHeaders; CAF_DECLARE_SMART_POINTER(CHeaders); virtual SmartPtrCDynamicByteArray getPayload() const = 0; virtual std::string getPayloadStr() const = 0; // // Routines dealing with the headers // virtual SmartPtrCHeaders getHeaders() const = 0; virtual SmartPtrIVariant findOptionalHeader( const std::string& key) const = 0; virtual SmartPtrIVariant findRequiredHeader( const std::string& key) const = 0; virtual std::string findOptionalHeaderAsString( const std::string& key) const = 0; virtual std::string findRequiredHeaderAsString( const std::string& key) const = 0; virtual SmartPtrICafObject findOptionalObjectHeader( const std::string& key) const = 0; virtual SmartPtrICafObject findRequiredObjectHeader( const std::string& key) const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IIntMessage); typedef std::deque CMessageCollection; CAF_DECLARE_SMART_POINTER(CMessageCollection); } #endif // #ifndef _IntegrationContracts_IIntMessage_h_ IIntegrationAppContext.h000066400000000000000000000016361321503522500377060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Created on: Jun 13, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IINTEGRATIONAPPCONTEXT_H_ #define _IntegrationContracts_IINTEGRATIONAPPCONTEXT_H_ #include "ICafObject.h" #include "Integration/IIntegrationObject.h" namespace Caf { struct __declspec(novtable) IIntegrationAppContext : public ICafObject { CAF_DECL_UUID("CC12C628-50C1-4E74-998D-3A9C961FA06F") virtual SmartPtrIIntegrationObject getIntegrationObject( const std::string& id) const = 0; virtual void getIntegrationObject( const IID& iid, void **ppv) const = 0; typedef std::deque CObjectCollection; CAF_DECLARE_SMART_POINTER(CObjectCollection); virtual SmartPtrCObjectCollection getIntegrationObjects(const IID& iid) const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IIntegrationAppContext); } #endif IIntegrationAppContextAware.h000066400000000000000000000012341321503522500406600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Created on: Jun 13, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IINTEGRATIONAPPCONTEXTAWARE_H_ #define _IntegrationContracts_IINTEGRATIONAPPCONTEXTAWARE_H_ #include "ICafObject.h" #include "Integration/IIntegrationAppContext.h" namespace Caf { struct __declspec(novtable) IIntegrationAppContextAware : public ICafObject { CAF_DECL_UUID("9BC34EB5-AEFF-4384-86DE-421DE89AB6E8") virtual void setIntegrationAppContext( SmartPtrIIntegrationAppContext context) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IIntegrationAppContextAware); } #endif IIntegrationComponent.h000066400000000000000000000015001321503522500375510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IIntegrationComponent_h_ #define _IntegrationContracts_IIntegrationComponent_h_ #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IIntegrationComponent : public ICafObject { CAF_DECL_UUID("087e1494-4abe-4bb6-ae49-48f4510e057f") virtual bool isResponsible( const SmartPtrIDocument& configSection) const = 0; virtual SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IIntegrationComponent); } #endif // #ifndef _IntegrationContracts_IIntegrationComponent_h_ IIntegrationComponentInstance.h000066400000000000000000000014261321503522500412450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IIntegrationComponentInstance_h_ #define _IntegrationContracts_IIntegrationComponentInstance_h_ #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IIntegrationComponentInstance : public ICafObject { CAF_DECL_UUID("70053165-1e46-4893-8e27-0e6ee8675c44") virtual void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IIntegrationComponentInstance); } #endif // #ifndef _IntegrationContracts_IIntegrationComponent_h_ IIntegrationObject.h000066400000000000000000000016221321503522500370220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IIntegrationObject_h_ #define _IntegrationContracts_IIntegrationObject_h_ #include "Integration/IDocument.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IIntegrationObject : public ICafObject { CAF_DECL_UUID("295fa2c8-01a7-4102-b13e-8fcac00b3e5f") virtual void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) = 0; virtual std::string getId() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IIntegrationObject); typedef std::map CIntegrationObjectCollection; CAF_DECLARE_SMART_POINTER(CIntegrationObjectCollection); } #endif // #ifndef _IntegrationContracts_IIntegrationObject_h_ ILifecycle.h000066400000000000000000000012041321503522500353030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_ILifecycle_h_ #define _IntegrationContracts_ILifecycle_h_ namespace Caf { /// TODO - describe interface struct __declspec(novtable) ILifecycle : public ICafObject { CAF_DECL_UUID("180845f8-c956-46b3-8a1b-ef5061cc927a") virtual void start(const uint32 timeoutMs) = 0; virtual void stop(const uint32 timeoutMs) = 0; virtual bool isRunning() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ILifecycle); } #endif // #ifndef _IntegrationContracts_ILifecycle_h_ IMessageChannel.h000066400000000000000000000013241321503522500362640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IMessageChannel_h_ #define _IntegrationContracts_IMessageChannel_h_ #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IMessageChannel : public ICafObject { CAF_DECL_UUID("d5192d01-9c26-4c1c-8966-66d7a108bcbf") virtual bool send( const SmartPtrIIntMessage& message) = 0; virtual bool send( const SmartPtrIIntMessage& message, const int32 timeout) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IMessageChannel); } #endif // #ifndef _IntegrationContracts_IMessageChannel_h_ IMessageDispatcher.h000066400000000000000000000015361321503522500370070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IMessageDispatcher_h_ #define _IntegrationContracts_IMessageDispatcher_h_ #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IMessageDispatcher : public ICafObject { CAF_DECL_UUID("639d8ead-6406-4c41-9a36-74d065f5dd6b") virtual void addHandler( const SmartPtrIMessageHandler& messageHandler) = 0; virtual void removeHandler( const SmartPtrIMessageHandler& messageHandler) = 0; virtual bool dispatch( const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IMessageDispatcher); } #endif // #ifndef _IntegrationContracts_IMessageDispatcher_h_ IMessageHandler.h000066400000000000000000000013511321503522500362710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IMessageHandler_h_ #define _IntegrationContracts_IMessageHandler_h_ #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IMessageHandler : public ICafObject { CAF_DECL_UUID("39a78b6f-f326-4739-b8ad-9e90a827745a") virtual void handleMessage( const SmartPtrIIntMessage& message) = 0; virtual SmartPtrIIntMessage getSavedMessage() const = 0; virtual void clearSavedMessage() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IMessageHandler); } #endif // #ifndef _IntegrationContracts_IMessageHandler_h_ IMessageProcessor.h000066400000000000000000000012401321503522500366700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IMessageProcessor_h_ #define _IntegrationContracts_IMessageProcessor_h_ #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IMessageProcessor : public ICafObject { CAF_DECL_UUID("68770787-c44e-457e-bf8d-20c64d37bfee") virtual SmartPtrIIntMessage processMessage( const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IMessageProcessor); } #endif // #ifndef _IntegrationContracts_IMessageProcessor_h_ IMessageProducer.h000066400000000000000000000011111321503522500364710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IMessageProducer_h_ #define _IntegrationContracts_IMessageProducer_h_ namespace Caf { /// TODO - describe interface struct __declspec(novtable) IMessageProducer : public ICafObject { CAF_DECL_UUID("14430bc5-8556-48f8-b37f-c2f24a50d8dd") virtual bool isMessageProducer() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IMessageProducer); } #endif // #ifndef _IntegrationContracts_IMessageProducer_h_ IMessageRouter.h000066400000000000000000000011751321503522500362000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IMessageRouter_h_ #define _IntegrationContracts_IMessageRouter_h_ #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IMessageRouter : public ICafObject { CAF_DECL_UUID("27ed0739-e527-469b-882f-196d532be0bd") virtual void routeMessage(const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IMessageRouter); } #endif // #ifndef _IntegrationContracts_IMessageRouter_h_ IMessageSplitter.h000066400000000000000000000014161321503522500365240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IMessageSplitter_h_ #define _IntegrationContracts_IMessageSplitter_h_ #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IMessageSplitter : public ICafObject { CAF_DECL_UUID("89a25ba3-113d-4efc-af46-522feda304ac") typedef std::deque CMessageCollection; CAF_DECLARE_SMART_POINTER(CMessageCollection); virtual SmartPtrCMessageCollection splitMessage( const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IMessageSplitter); } #endif // #ifndef _IntegrationContracts_IMessageSplitter_h_ IPhased.h000066400000000000000000000007461321503522500346220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Created on: Aug 6, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IPhased_h #define _IntegrationContracts_IPhased_h #include "ICafObject.h" namespace Caf { struct __declspec(novtable) IPhased : public ICafObject { CAF_DECL_UUID("CAE354D0-E212-4030-8CB7-23C92D59C6A3") virtual int32 getPhase() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IPhased); }; #endif IPollableChannel.h000066400000000000000000000014441321503522500364350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IPollableChannel_h_ #define _IntegrationContracts_IPollableChannel_h_ #include "Integration/Dependencies/CPollerMetadata.h" #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IPollableChannel : public ICafObject { CAF_DECL_UUID("a7ce8841-f37d-489a-a299-e148c5ff6b11") virtual SmartPtrIIntMessage receive() = 0; virtual SmartPtrIIntMessage receive(const int32 timeout) = 0; virtual SmartPtrCPollerMetadata getPollerMetadata() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IPollableChannel); } #endif // #ifndef _IntegrationContracts_IPollableChannel_h_ IRunnable.h000066400000000000000000000010561321503522500351570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_IRunnable_h_ #define _IntegrationContracts_IRunnable_h_ namespace Caf { /// TODO - describe interface struct __declspec(novtable) IRunnable : public ICafObject { CAF_DECL_UUID("a3ad671c-3d04-4eba-aaa4-8dcc9c43c959") virtual void run() = 0; virtual void cancel() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IRunnable); } #endif // #ifndef _IntegrationContracts_IRunnable_h_ ISmartLifecycle.h000066400000000000000000000010261321503522500363140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Created on: Aug 6, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_ISmartLifecycle_h #define _IntegrationContracts_ISmartLifecycle_h #include "Integration/ILifecycle.h" namespace Caf { struct __declspec(novtable) ISmartLifecycle : public ILifecycle { CAF_DECL_UUID("312B7430-659F-48A1-AAAE-AE44D349132C") virtual bool isAutoStartup() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ISmartLifecycle); }; #endif ISubscribableChannel.h000066400000000000000000000013731321503522500373040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_ISubscribableChannel_h_ #define _IntegrationContracts_ISubscribableChannel_h_ #include "Integration/IMessageHandler.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) ISubscribableChannel : public ICafObject { CAF_DECL_UUID("14d7e980-1b98-4453-b27e-8c058fb705b9") virtual void subscribe( const SmartPtrIMessageHandler& messageHandler) = 0; virtual void unsubscribe( const SmartPtrIMessageHandler& messageHandler) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ISubscribableChannel); } #endif // #ifndef _IntegrationContracts_ISubscribableChannel_h_ ITaskExecutor.h000066400000000000000000000014501321503522500360300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_ITaskExecutor_h_ #define _IntegrationContracts_ITaskExecutor_h_ namespace Caf { /// TODO - describe interface struct __declspec(novtable) ITaskExecutor : public ICafObject { CAF_DECL_UUID("4ab38314-fd31-49fc-bfce-173abc53f1a8") typedef enum { ETaskStateNotStarted, ETaskStateStarted, ETaskStateStopping, ETaskStateFinished, ETaskStateFailed } ETaskState; virtual void execute(const uint32 timeoutMs) = 0; virtual void cancel(const uint32 timeoutMs) = 0; virtual ETaskState getState() const = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ITaskExecutor); } #endif // #ifndef _IntegrationContracts_ITaskExecutor_h_ IThrowable.h000066400000000000000000000013531321503522500353400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct. 25, 2011 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _FxContracts_IThrowable_h_ #define _FxContracts_IThrowable_h_ #include "ICafObject.h" namespace Caf { CAF_FORWARD_DECLARE_SMART_INTERFACE(IThrowable); /// TODO - describe interface struct __declspec(novtable) IThrowable : public ICafObject { CAF_DECL_UUID("5bced55d-06b7-4c4b-b805-90b51311dc9b") virtual std::string getExceptionClassName() const = 0; virtual std::string getMsg() const = 0; virtual std::string getClassName() const = 0; virtual std::string getFuncName() const = 0; virtual HRESULT getError() const = 0; virtual std::string getFullMsg() const = 0; }; } #endif ITransformer.h000066400000000000000000000012111321503522500357040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Integration/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IntegrationContracts_ITransformer_h_ #define _IntegrationContracts_ITransformer_h_ #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) ITransformer : public ICafObject { CAF_DECL_UUID("1f2a6ecb-f842-4e09-82a8-89eaf64ec98b") virtual SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(ITransformer); } #endif // #ifndef _IntegrationContracts_ITransformer_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Memory/000077500000000000000000000000001321503522500321715ustar00rootroot00000000000000DynamicArray/000077500000000000000000000000001321503522500344755ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/MemoryDynamicArrayInc.h000066400000000000000000000024511321503522500376650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Memory/DynamicArray/////////////////////////////////////////////////////////////////////////////////////////// // // Author: Michael Donahue // // Created: 05/03/2004 // // Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // /////////////////////////////////////////////////////////////////////////////////////////// #ifndef DynamicArrayInc_h_ #define DynamicArrayInc_h_ #include "Memory/DynamicArray/SDynamicArrayMallocAllocator.h" namespace Caf { template class TDynamicArray; template class TCharAdapter; template class TWCharAdapter; template class TByteAdapter; typedef TDynamicArray CDynamicByteArray; typedef TCharAdapter > > CDynamicCharArray; typedef TWCharAdapter > > CDynamicWCharArray; } #include "Memory/DynamicArray/TDynamicArray.h" #include "Memory/DynamicArray/TByteAdapter.h" #include "Memory/DynamicArray/TCharAdapter.h" #include "Memory/DynamicArray/TWCharAdapter.h" namespace Caf { CAF_DECLARE_SMART_POINTER(CDynamicByteArray); CAF_DECLARE_SMART_POINTER(CDynamicCharArray); CAF_DECLARE_SMART_POINTER(CDynamicWCharArray); } #endif // #ifdef DynamicArrayInc_h_ SDynamicArrayMallocAllocator.h000066400000000000000000000010161321503522500423430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Memory/DynamicArray/* * Author: mdonahue * Created: Feb 15, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef SDYNAMICARRAYMALLOCALLOCATOR_H_ #define SDYNAMICARRAYMALLOCALLOCATOR_H_ namespace Caf { struct SDynamicArrayMallocAllocator { static void* allocMemory( const uint32 cdwAllocSize ) { return ::malloc( cdwAllocSize ); } static void freeMemory( void* pvFree ) { if ( NULL != pvFree ) { ::free( pvFree ); } } }; } #endif /* SDYNAMICARRAYMALLOCALLOCATOR_H_ */ TByteAdapter.h000066400000000000000000000067441321503522500372110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Memory/DynamicArray////////////////////////////////////////////////////////////////////////////// // // $Workfile: TByteAdapter.h $ // // Author: Phil Smith // // Purpose: This template provides the ability to use a ${TDynamicArray} // or a TStaticArray where a byte pointer is required. It // provides a const byte* pointer conversion operator for use // when read only access is required and a function to get the // pointer for write access. Use the byte adapter as follows: // TByteAdapter > // // Predefined character array objects CEcmCharArray and // CEcmWCharArray which use the byte adapter have been provided // in EcmCommonStaticMinDepInc.h. // // Created: Tuesday, August 20, 2002 10:00:00 AM // // Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // // Modification History: // // $Log: //wpbuild01/PvcsData/ECM_40/archives/ECM_41/WinNT/Source/CommonAgtCol/Cpp/EcmCommonStaticMinDep/TByteAdapter.h-arc $ // // Rev 1.4 17 Sep 2003 09:43:12 Michael.Donahue // Implemented hooks for new library model // // Rev 1.3 31 Oct 2002 13:58:02 Greg.Burk // Modified as per code review recomendations. // // Rev 1.2 15 Oct 2002 17:22:58 Phillip.Smith // Documentation updates. // // Rev 1.0 09 Oct 2002 13:42:12 brian.williams // Initial revision. // ////////////////////////////////////////////////////////////////////////////// #ifndef _TByteAdapter_H_ #define _TByteAdapter_H_ namespace Caf { template class TByteAdapter : public T { public: ////////////////////////////////////////////////////////////////////////// // Default Constructor ////////////////////////////////////////////////////////////////////////// TByteAdapter(const wchar_t * pwszDesc = NULL) {} ////////////////////////////////////////////////////////////////////////// // Destructor ////////////////////////////////////////////////////////////////////////// ~TByteAdapter() {} ////////////////////////////////////////////////////////////////////////// // GetNonConstBytePtr // // Get non-const pointer to internal data converted to btye *. // This function should be used only when you must get a pointer that is // to be written to, and you should always call the ${TDynamicArray::Verify()} // function after modifying the data pointed to by this pointer or passing // the pointer to a function that modifies the data pointed to by this // pointer. ////////////////////////////////////////////////////////////////////////// byte * getNonConstBytePtr() { this->verify(); return reinterpret_cast(this->getNonConstPtr()); } ////////////////////////////////////////////////////////////////////////// // GetBytePtr // // Get const pointer to internal data converted to btye *. ////////////////////////////////////////////////////////////////////////// const byte * getBytePtr() const { this->verify(); return reinterpret_cast(this->getPtr()); } ////////////////////////////////////////////////////////////////////////// // const byte Conversion Operator // // Get const pointer to internal data converted to btye *. ////////////////////////////////////////////////////////////////////////// operator const byte * () const { this->verify(); return reinterpret_cast(this->getPtr()); } private: TByteAdapter(const TByteAdapter & crRhs); TByteAdapter & operator=(const TByteAdapter & crRhs); }; } #endif // _TByteAdapter_H_ TCharAdapter.h000066400000000000000000000243051321503522500371540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Memory/DynamicArray////////////////////////////////////////////////////////////////////////////// // // $Workfile: TCharAdapter.h $ // // Author: Greg Burk // // Purpose: This template provides an adapter for TDynamicArray (or // other types of "safe" array classes) that exposes functions // that are useful when working with an array of type char. // // A typedef of this class is already defined and should be // used instead of explicitly using this class. The typedef // is CEcmCharArray. // // Created: Friday, October 18, 2002 1:50:32 PM // // Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // // Modification History: // // $Log: //wpbuild01/PvcsData/ECM_40/archives/ECM_41/WinNT/Source/CommonAgtCol/Cpp/EcmCommonStaticMinDep/TCharAdapter.h-arc $ // // Rev 1.3 10 Oct 2003 08:49:24 Michael.Donahue // Fixed bug in StrCpy // // Rev 1.2 17 Sep 2003 09:43:12 Michael.Donahue // Implemented hooks for new library model // // Rev 1.1 16 Jan 2003 11:17:52 Greg.Burk // Made changes necessary to accomodate new CEcmBasicString class and changes to CEcmString. // // Rev 1.0 31 Oct 2002 10:43:06 Greg.Burk // Initial Revision // ////////////////////////////////////////////////////////////////////////////// #ifndef _TCharAdapter_H_ #define _TCharAdapter_H_ #include namespace Caf { template class TCharAdapter : public T { public: ////////////////////////////////////////////////////////////////////////// // Default Constructor ////////////////////////////////////////////////////////////////////////// TCharAdapter() {} ////////////////////////////////////////////////////////////////////////// // Conversion Constructor ////////////////////////////////////////////////////////////////////////// TCharAdapter(const wchar_t * rhs) { wideToMultiByte(rhs); } ////////////////////////////////////////////////////////////////////////// // Conversion Constructor ////////////////////////////////////////////////////////////////////////// TCharAdapter(const char * rhs) { (*this) = rhs; } ////////////////////////////////////////////////////////////////////////// // Destructor ////////////////////////////////////////////////////////////////////////// ~TCharAdapter() {} ////////////////////////////////////////////////////////////////////////// // Assignment operator ////////////////////////////////////////////////////////////////////////// TCharAdapter& operator=(const wchar_t * rhs) { wideToMultiByte(rhs); return *this; } ////////////////////////////////////////////////////////////////////////// // Assignment operator ////////////////////////////////////////////////////////////////////////// TCharAdapter& operator=(const char * rhs) { const uint32 culLength = ::strlen(rhs); if(culLength > 0) { this->allocateELements(culLength); strnCpy(rhs, culLength); } return *this; } ////////////////////////////////////////////////////////////////////////////// // MakeLower() // // Converts all of the upper-case characters in this string to lower-case. ////////////////////////////////////////////////////////////////////////////// void makeLower() { // Pre-validation. this->verifySentinal(); if(!this->IsNull()) { strlwr(this->m_ptData); } // Post-validation. this->verifySentinal(); } ////////////////////////////////////////////////////////////////////////// // MakeUpper // // Converts all of the lower-case characters in this array to upper-case. ////////////////////////////////////////////////////////////////////////// void makeUpper() { // Pre-validation. this->verifySentinal(); if(!this->isNull()) { strupr(this->m_ptData); } // Post-validation. this->verifySentinal(); } ////////////////////////////////////////////////////////////////////////// // Reverse // // Reverses the characters in the array. ////////////////////////////////////////////////////////////////////////// void reverse() { // Pre-validation. this->verifySentinal(); if(!this->isNull()) { strrev( this->m_ptData ); } // Post-validation. this->verifySentinal(); } ////////////////////////////////////////////////////////////////////////// // StrLen // // Return the length of the string. ////////////////////////////////////////////////////////////////////////// size_t strLen() const { size_t stRetVal = 0; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Delegate to CEcmCtr. stRetVal = ::strlen(this->m_ptData); // Post-validation. this->verifyLength(static_cast(stRetVal)); return stRetVal; } ////////////////////////////////////////////////////////////////////////// // StrCpy // // Make a copy of the string into the buffer. ////////////////////////////////////////////////////////////////////////// TCharAdapter & strCpy(const char * cpszSource) { // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Get the length of the source string. uint32 dwSourceLength = ::strlen(cpszSource); // Make sure the string will fit if we copy it. this->verifyLength(dwSourceLength); // Copy the string into the buffer. ::strcpy(this->m_ptData, cpszSource); // Post-validation. this->verifySentinal(); return (*this); } ////////////////////////////////////////////////////////////////////////// // StrnCpy // // Make a copy of the string into the buffer upto culCount characters. ////////////////////////////////////////////////////////////////////////// TCharAdapter & strnCpy(const char * cpszSource, const uint32 culCount) { // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Make sure the string will fit if we copy it. this->verifyLength(culCount); // Copy the string into the buffer. ::strncpy(this->m_ptData, cpszSource, culCount); // Post-validation. this->verifySentinal(); return (*this); } ////////////////////////////////////////////////////////////////////////// // StrStr // // Find the substring cpszSubString in the array. Returns the pointer to // the first occurance of the substring in the array or NULL if the // substring is not found. ////////////////////////////////////////////////////////////////////////// const char * strStr(const char * cpszSubString) const { const char * cpszRetVal = NULL; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Find the substring. cpszRetVal = ::strstr(this->m_ptData, cpszSubString); // Post-validation. this->verifySentinal(); return cpszRetVal; } ////////////////////////////////////////////////////////////////////////// // StrCmp // // Compare the cpszString to this array. ////////////////////////////////////////////////////////////////////////// int32 strCmp(const char * cpszString) const { int32 iRetVal = 0; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Compare the strings. iRetVal = ::strcmp(this->m_ptData, cpszString); return iRetVal; } ////////////////////////////////////////////////////////////////////////// // StriCmp // // Compare the cpszString to this array (case insensitive). ////////////////////////////////////////////////////////////////////////// int32 striCmp(const char * cpszString) const { int32 iRetVal = 0; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Compare the strings. iRetVal = stricmp(this->m_ptData, cpszString); return iRetVal; } ////////////////////////////////////////////////////////////////////////// // StrnCmp // // Compare the cpszString to this array up to culCount characters. ////////////////////////////////////////////////////////////////////////// int32 strnCmp(const char * cpszString, const uint32 culCount) const { int32 iRetVal = 0; // Pre-validation. this->erifySentinal(); this->verifyNotNull(); // Make sure the comparison can take place with in our array bounds. this->verifyLength(culCount); // Compare the strings. iRetVal = strncmp(this->m_ptData, cpszString, culCount); return iRetVal; } ////////////////////////////////////////////////////////////////////////// // StrChr // // Find the first occurrence of the specified character in the string. ////////////////////////////////////////////////////////////////////////// const char * strChr(char cCharacter) const { const char * cpszRetVal = 0; // Pre-validation. this->erifySentinal(); this->verifyNotNull(); // Compare the strings. cpszRetVal = ::strchr(this->m_ptData, cCharacter); return cpszRetVal; } private: void wideToMultiByte(const wchar_t* cpwszSource) { // Calculate the length of the source. const uint32 cdwSourceLen = cpwszSource ? ::wcslen( cpwszSource ) : 0; // Convert the wide strings to multibyte. if( cdwSourceLen > 0 ) { // This appears to be allocating twice as much memory as is needed, but // this is the way W2A is implemented and W2A seems to convert some // strings that will not convert where the destination is the same // length (in characters) as the source. this->allocateElements( cdwSourceLen * sizeof( wchar_t ) ); int32 iRet; #ifdef WIN32 iRet = ::WideCharToMultiByte( CP_ACP, 0, cpwszSource, -1, GetNonConstPtr(), GetLength(), NULL, NULL ); #else iRet = ::wcstombs( this->getNonConstPtr(), cpwszSource, this->getByteCount() ); // wcstombs returns -1 for error or the length // not including the NULL, so we must increment // to match the windows version iRet++; #endif if( 0 == iRet ) { this->freeArray(); } else { // // Must ReAllocate in order to have the proper char length // The char array was allocated based on wchar_t // // no need to include the NULL terminator // returned by WideCharToMultiByte() // this->rellocateElements( iRet - 1 ); } } else if( cpwszSource != NULL ) { // This chunk of code is important. If the source // string is empty, return an empty string, not // a NULL pointer! this->allocateElements(0); } // Verify array. this->verifySentinal(); } private: TCharAdapter(const TCharAdapter & crRhs); TCharAdapter & operator=(const TCharAdapter & crRhs); }; } #endif // _TCharAdapter_H_ TDynamicArray.h000066400000000000000000001017041321503522500373600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Memory/DynamicArray////////////////////////////////////////////////////////////////////////////// // // Author: Greg Burk // // Purpose: This template provides a way to create an array that has // certain safety features that help solve some of the problems // often created by arrays in C++. You can create an array of // any type. The safety features of this class include array // bounds checking (indexes out of range), automatic // initialization, and automatic destruction. It also provides // some features to check the integrity of the array. This is // especially useful when you get and pass the raw pointer to // the array into a third party function (i.e. Windows API). // // The ${TDynamicArray::verify()} function is used for this // purpose. It does two primary things: // // 1) When the array is allocated, some extra space is allocated // for some sentinel bytes. These bytes are checked to make // sure they are still intact when verify() is called. // // 2) When the array is allocated, the address of the memory // that was allocated is stored and is XORed with a known // bit pattern and the result is also stored. When verify() // is called, this pattern is XORed again with the address // and the result should be the original pattern. // // If either of the above checks fails, an exception is thrown. // The primary weakness of this strategy is that the call to // verify() is left up to the user. If the raw pointer is passed // and something gets messed up, if verify() was not called, the // problem won't be discovered until the next time a function // that calls verify() (most do) is called. This will cause us // to loose the context in which the problem occurred. // // Created: Wednesday, August 07, 2002 2:27:39 PM // // Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ////////////////////////////////////////////////////////////////////////////// #ifndef _TDynamicArray_H_ #define _TDynamicArray_H_ #include #include "Exception/CCafException.h" namespace Caf { ////////////////////////////////////////////////////////////////////////////// // Define sentinel bit pattern. ////////////////////////////////////////////////////////////////////////////// #ifdef __x86_64__ static const uint64 gs_ulDynamicArraySentinelBitPattern = (0xAAAAAAAAAAAAAAAA); #else static const uint32 gs_ulDynamicArraySentinelBitPattern = (0xAAAAAAAA); #endif static const uint32 gs_ulDynamicArraySentinelElementCount = (3); template class TDynamicArray { public: typedef T Type; ////////////////////////////////////////////////////////////////////////// // Default Constructor ////////////////////////////////////////////////////////////////////////// TDynamicArray() : CAF_CM_INIT("TDynamicArray"), _sentinelBits(gs_ulDynamicArraySentinelBitPattern), _isSentinelSet(false), _elementCount(0), _elementIndex(0), _byteCount(0), _data(NULL) { // Initialize the sentinel buffers. ::memset(_sentinelBytes, 0, sizeof(_sentinelBytes)); } ////////////////////////////////////////////////////////////////////////// // Destructor ////////////////////////////////////////////////////////////////////////// virtual ~TDynamicArray() { CAF_CM_FUNCNAME("~TDynamicArray"); try { freeArray(); } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; } ////////////////////////////////////////////////////////////////////////// // PutDescription // // Assign description to object instance. ////////////////////////////////////////////////////////////////////////// void putDescription(const char * pszDesc) { CAF_CM_FUNCNAME_VALIDATE("putDescription"); CAF_CM_VALIDATE_STRINGPTRA(pszDesc); _description = pszDesc; } ////////////////////////////////////////////////////////////////////////// // GetPtr // // Get const pointer to internal data ////////////////////////////////////////////////////////////////////////// const T * getPtr() const { // Pre-validation. verifySentinel(); // Get pointer. const T * rc = _data; return rc; } ////////////////////////////////////////////////////////////////////////// // GetNonConstPtr // // Get non-const pointer to internal data. This function should be used // only when you must get a pointer that is to be written to, and you // should always call the ${TDynamicArray::verify()} function after modifying the data // pointed to by this pointer or passing the pointer to a function that // modifies the data pointed to by this pointer. ////////////////////////////////////////////////////////////////////////// T * getNonConstPtr() { // Pre-validation. verifySentinel(); // Get pointer. T * rc = _data; return rc; } ////////////////////////////////////////////////////////////////////////// // const Conversion Operator ////////////////////////////////////////////////////////////////////////// operator const T *() const { // Pre-validation. verifySentinel(); // Get pointer. const T * rc = _data; return rc; } ////////////////////////////////////////////////////////////////////////// // GetPtrAt // // Returns a const pointer to the internal array at a given index ////////////////////////////////////////////////////////////////////////// const T * getPtrAt(const uint32 elementIndex) const { // Pre-validation. verifyNotNull(); verifySentinel(); verifyElementCount(elementIndex); // Get the pointer at the index specified. const T * rc = &_data[elementIndex]; return rc; } ////////////////////////////////////////////////////////////////////////// // GetNonConstPtrAt // // Returns a non-const pointer to the internal array at a given index. // This function should be used only when you must get a pointer that is // to be written to, and you should always call the ${TDynamicArray::verify()} // function after modifying the data pointed to by this pointer or passing // the pointer to a function that modifies the data pointed to by this // pointer. ////////////////////////////////////////////////////////////////////////// T * getNonConstPtrAt(const uint32 elementIndex) { // Pre-validation. verifyNotNull(); verifySentinel(); verifyElementCount(elementIndex); // Get the pointer at the index specified. T * rc = &_data[elementIndex]; return rc; } ////////////////////////////////////////////////////////////////////////// // GetAt // // Returns the array element at a given index ////////////////////////////////////////////////////////////////////////// T getAt(const uint32 elementIndex) const { // Pre-validation. verifyNotNull(); verifySentinel(); verifyElementCount(elementIndex); // Get the pointer at the index specified. T tRetVal = _data[elementIndex]; return tRetVal; } ////////////////////////////////////////////////////////////////////////// // getPtrAtCurrentPos // // Returns a const pointer to the internal array at the current position. ////////////////////////////////////////////////////////////////////////// const T * getPtrAtCurrentPos() const { return getPtrAt(_elementIndex); } ////////////////////////////////////////////////////////////////////////// // getNonConstPtrAtCurrentPos // // Returns a non-const pointer to the internal array at the current position. // This function should be used only when you must get a pointer that is // to be written to, and you should always call the ${TDynamicArray::verify()} // function after modifying the data pointed to by this pointer or passing // the pointer to a function that modifies the data pointed to by this // pointer. ////////////////////////////////////////////////////////////////////////// T * getNonConstPtrAtCurrentPos() { return getNonConstPtrAt(_elementIndex); } ////////////////////////////////////////////////////////////////////////// // GetAtCurrentPos // // Returns the array element at the current position ////////////////////////////////////////////////////////////////////////// T getAtCurrentPos() const { return getAt(_elementIndex); } ////////////////////////////////////////////////////////////////////////// // SetAt // // Sets the array element at a given index ////////////////////////////////////////////////////////////////////////// void setAt( const uint32 elementIndex, const T value) { // Pre-validation. verifyNotNull(); verifySentinel(); verifyElementCount(elementIndex); // Set the pointer at the index specified. _data[elementIndex] = value; } ////////////////////////////////////////////////////////////////////////// // getElementCount // // Returns the number of array elements. ////////////////////////////////////////////////////////////////////////// uint32 getElementCount() const { return _elementCount; } ////////////////////////////////////////////////////////////////////////// // getByteCount // // Returns the size of the array in bytes. ////////////////////////////////////////////////////////////////////////// uint32 getByteCount() const { return _byteCount; } ////////////////////////////////////////////////////////////////////////// // getByteCountSize // // Returns the size of the array in bytes. ////////////////////////////////////////////////////////////////////////// size_t getByteCountSize() const { return static_cast(_byteCount); } ////////////////////////////////////////////////////////////////////////// // IsNull // // Returns true if the pointer to the internal array is null or false if // the array is not null ////////////////////////////////////////////////////////////////////////// bool isNull() const { return ((NULL == _data) ? true : false); } ////////////////////////////////////////////////////////////////////////// // verify // // Verifies that the array is still properly bound and in good shape. ////////////////////////////////////////////////////////////////////////// void verify() const { // verify. verifySentinel(); } ////////////////////////////////////////////////////////////////////////// // Allocate // // Allocates a new array on the heap (elementCount = number of elements) ////////////////////////////////////////////////////////////////////////// TDynamicArray & allocateElements(const uint32 elementCount) { // Free the previous array if it exists. freeArray(); // Call internal allocation function to actually allocate the // array buffer. internalAllocate(elementCount); return (*this); } ////////////////////////////////////////////////////////////////////////// // AllocateBytes // // Allocates a new array on the heap. ////////////////////////////////////////////////////////////////////////// TDynamicArray & allocateBytes(const size_t byteCount) { return allocateBytes(static_cast(byteCount)); } ////////////////////////////////////////////////////////////////////////// // AllocateBytes // // Allocates a new array on the heap. ////////////////////////////////////////////////////////////////////////// TDynamicArray & allocateBytes(const uint32 byteCount) { // Calculate actual number of array elements to allocate based on // the byte length. const uint32 elementCount = byteCountToElementCount(byteCount); // Delegate to Allocate(). allocateElements(elementCount); return (*this); } ////////////////////////////////////////////////////////////////////////// // ReAllocate // // Reallocates a array on the heap, keeping original contents. // culLength = number of elements ////////////////////////////////////////////////////////////////////////// TDynamicArray & reallocateElements(const uint32 elementCount) { CAF_CM_FUNCNAME("reallocateElements"); // Declare variables to hold copy of original information. uint32 origElementIndex = 0; uint32 origByteCount = 0; T * origData = NULL; try { // Pre-validation. verifySentinel(); // Create a temporary copy of the original buffer and length. origElementIndex = _elementIndex; origByteCount = _byteCount; origData = _data; // Reset the data pointer, length, and byte length. _data = NULL; _elementCount = 0; _elementIndex = 0; _byteCount = 0; // Reset the sentinel set flag. _isSentinelSet = false; // Call internal allocation function to actually allocate the // array buffer. internalAllocate(elementCount); // Copy the original into the new if it exists. if((origData != NULL) && (origByteCount > 0)) { // Calculate the number of bytes to copy. const uint32 bytesToCopy = (_byteCount < origByteCount) ? _byteCount : origByteCount; // Copy the bytes. ::memcpy(_data, origData, bytesToCopy); const uint32 elementsToCopy = byteCountToElementCount(bytesToCopy); _elementIndex = (elementsToCopy < origElementIndex) ? elementsToCopy : origElementIndex; } // verify the sentinel bytes. verifySentinel(); } CAF_CM_CATCH_ALL; // Delete the original buffer if non-null. if (origData) { Allocator::freeMemory(origData); } CAF_CM_THROWEXCEPTION; return (*this); } ////////////////////////////////////////////////////////////////////////// // Grow // // Increases the size of the array by the length // (number of elements) supplied ////////////////////////////////////////////////////////////////////////// TDynamicArray & grow(const uint32 elementCount) { reallocateElements(_elementCount + elementCount); return (*this); } ////////////////////////////////////////////////////////////////////////// // ReAllocateBytes // // Reallocates a array on the heap, keeping original contents. ////////////////////////////////////////////////////////////////////////// TDynamicArray & reallocateBytes(const size_t byteCount) { return reallocateBytes(static_cast(byteCount)); } ////////////////////////////////////////////////////////////////////////// // ReAllocateBytes // // Reallocates a array on the heap, keeping original contents. ////////////////////////////////////////////////////////////////////////// TDynamicArray & reallocateBytes(const uint32 byteCount) { // Calculate actual number of array elements to allocate based // on the byte length. const uint32 elementCount = byteCountToElementCount(byteCount); // Delegate to ReAllocate() function. reallocateElements(elementCount); return (*this); } ////////////////////////////////////////////////////////////////////////// // Free // // Frees the memory for the array. ////////////////////////////////////////////////////////////////////////// void freeArray() { // Free the buffer if it exists. if (_data) { verifySentinel(); // Zeroize the buffer for cryptographic purposes ::memset(_data, 0, _byteCount); Allocator::freeMemory(_data); _data = NULL; // Reset to initial value. _sentinelBits = gs_ulDynamicArraySentinelBitPattern; } // Reset the length and byte length. _elementCount = 0; _elementIndex = 0; _byteCount = 0; // Reset the sentinel set flag. _isSentinelSet = false; } ////////////////////////////////////////////////////////////////////////// // ArrayCpy // // Copies the array entries from crArray into this array. ////////////////////////////////////////////////////////////////////////// void arrayCpy(const TDynamicArray & crArray) { // Make sure reference is not to this. if (this != &crArray) { // Pre-validation. verifyNotNull(); verifyByteCount(crArray.getByteCount()); verifySentinel(); crArray.verifySentinel(); // Reinitialize this array. memSet(); // Copy the array. memcpy(_data, crArray.getPtr(), crArray.getByteCount()); // Post-validation. verifySentinel(); } } ////////////////////////////////////////////////////////////////////////// // ArrayCmp // // Compare this array with crArray. Compares the entire array, so arrays // must be equal size to evaluate to equal. ////////////////////////////////////////////////////////////////////////// int32 arrayCmp(const TDynamicArray & crArray) const { int32 iRetVal = 0; // Make sure reference is not to this. if (this != &crArray) { // Pre-validation. verifySentinel(); crArray.verifySentinel(); // Make sure the arrays are the same length. if ((_data == NULL) && (crArray._data == NULL)) { iRetVal = 0; } else if (getByteCount() == crArray.getByteCount()) { // Compare the array. iRetVal = ::memcmp(_data, crArray.getPtr(), getByteCount()); } else { iRetVal = (getByteCount() > crArray.getByteCount()) ? 1 : -1; } // Post-validation. verifySentinel(); } return iRetVal; } ////////////////////////////////////////////////////////////////////////// // ArrayPrepend // // Prepend this array with the provided array. This call will grow the // array by the size of the provided array. ////////////////////////////////////////////////////////////////////////// void arrayPrepend(const TDynamicArray & crArray) { CAF_CM_FUNCNAME("arrayPrepend"); // Declare variables to hold copy of original information. uint32 origByteCount = 0; uint32 origElementCount = 0; T * origData = NULL; try { // Pre-validation. verifySentinel(); // Create a temporary copy of the original buffer and length. origData = _data; origByteCount = _byteCount; origElementCount = _elementCount; // Reset the data pointer, length, and byte length. _data = NULL; _elementCount = 0; _elementIndex = 0; _byteCount = 0; // Reset the sentinel set flag. _isSentinelSet = false; // Call internal allocation function to actually allocate the // array buffer. internalAllocate(origElementCount + crArray.getElementCount()); // Get an intermediate pointer to the internal buffer. T * tempData = _data; // Copy the provided data into the new buffer if it exists. if((crArray.getPtr() != NULL) && (crArray.getByteCount() > 0)) { // Copy the bytes. ::memcpy(tempData, crArray.getPtr(), crArray.getByteCount()); // Advance the pointer to the end of the data just copied. tempData += crArray.getElementCount(); } // Copy the original into the new if it exists. if((origData != NULL) && (origByteCount > 0)) { // Copy the bytes. ::memcpy(tempData, origData, origByteCount); } // verify the sentinel bytes. verifySentinel(); } CAF_CM_CATCH_ALL; // Delete the original buffer if non-null. if (origData) { Allocator::freeMemory(origData); } CAF_CM_THROWEXCEPTION; } ////////////////////////////////////////////////////////////////////////// // ArrayAppend // // Append this array with the provided array. This call will grow the // array by the size of the provided array. ////////////////////////////////////////////////////////////////////////// void arrayAppend(const TDynamicArray & crArray) { CAF_CM_FUNCNAME("arrayAppend"); // Declare variables to hold copy of original information. uint32 origByteCount = 0; uint32 origElementCount = 0; uint32 origElementIndex = 0; T * origData = NULL; try { // Pre-validation. verifySentinel(); // Create a temporary copy of the original buffer and length. origData = _data; origByteCount = _byteCount; origElementCount = _elementCount; origElementIndex = _elementIndex; // Reset the data pointer, length, and byte length. _data = NULL; _elementCount = 0; _elementIndex = 0; _byteCount = 0; // Reset the sentinel set flag. _isSentinelSet = false; // Call internal allocation function to actually allocate the // array buffer. internalAllocate(origElementCount + crArray.getElementCount()); // Get an intermediate pointer to the internal buffer. T * tempData = _data; // Copy the original into the new if it exists. if((origData != NULL) && (origByteCount > 0)) { // Copy the bytes. ::memcpy(tempData, origData, origByteCount); // Advance the pointer to the end of the data just copied. tempData += origElementCount; } // Copy the provided data into the new buffer if it exists. if((crArray.getPtr() != NULL) && (crArray.getByteCount() > 0)) { // Copy the bytes. ::memcpy(tempData, crArray.getPtr(), crArray.getByteCount()); } _elementIndex = origElementIndex; // verify the sentinel bytes. verifySentinel(); } CAF_CM_CATCH_ALL; // Delete the original buffer if non-null. if (origData) { Allocator::freeMemory(origData); } } ////////////////////////////////////////////////////////////////////////// // MemSet // // Initializes the array by filling it with the fillValue. ////////////////////////////////////////////////////////////////////////// void memSet(const byte fillValue = 0) { // Pre-validation. verifyNotNull(); verifySentinel(); // Initialize the buffer. ::memset(_data, fillValue, _byteCount); _elementIndex = 0; // Post-validation. verifySentinel(); } ////////////////////////////////////////////////////////////////////////// // MemCpy // // Copy the memory from sourceData into this array up to byteCount bytes. ////////////////////////////////////////////////////////////////////////// void memCpy( const void * sourceData, const size_t byteCount) { memCpy(sourceData, static_cast(byteCount)); } ////////////////////////////////////////////////////////////////////////// // MemCpy // // Copy the memory from sourceData into this array up to byteCount bytes. ////////////////////////////////////////////////////////////////////////// void memCpy( const void * sourceData, const uint32 byteCount) { // Pre-validation. verifyNotNull(); verifySentinel(); // Make sure the data will fit if we copy it. verifyByteCount(byteCount); // Copy the data. ::memcpy(_data, sourceData, byteCount); _elementIndex = 0; // Post-validation. verifySentinel(); } ////////////////////////////////////////////////////////////////////////// // MemAppend // // Append the memory from sourceData into this array up to byteCount bytes. ////////////////////////////////////////////////////////////////////////// void memAppend( const void * sourceData, const size_t byteCount) { memAppend(sourceData, static_cast(byteCount)); } ////////////////////////////////////////////////////////////////////////// // MemAppend // // Append the memory from sourceData into this array up to byteCount bytes. ////////////////////////////////////////////////////////////////////////// void memAppend( const void * sourceData, const uint32 byteCount) { // Pre-validation. verifyNotNull(); verifySentinel(); // Make sure the data will fit if we copy it. const uint32 startingByteCount = elementCountToByteCount(_elementIndex); verifyByteCount(startingByteCount + byteCount); // Copy the data. ::memcpy(_data + _elementIndex, sourceData, byteCount); _elementIndex += byteCountToElementCount(byteCount); // Post-validation. verifySentinel(); } ////////////////////////////////////////////////////////////////////////// // MemCmp // // Compare the memory from sourceData with this array up to byteCount bytes. ////////////////////////////////////////////////////////////////////////// int32 memCmp( const void * sourceData, const size_t byteCount) { return memCmp(sourceData, static_cast(byteCount)); } ////////////////////////////////////////////////////////////////////////// // MemCmp // // Compare the memory from sourceData with this array up to byteCount bytes. ////////////////////////////////////////////////////////////////////////// int32 memCmp( const void * sourceData, const uint32 byteCount) const { CAF_CM_FUNCNAME_VALIDATE("memCmp"); CAF_CM_VALIDATE_PTR(sourceData); CAF_CM_VALIDATE_POSITIVE(byteCount); // Pre-validation. verifySentinel(); // Make sure the comparison can take place within our array bounds. verifyByteCount(byteCount); // Do comparison. int32 iRetVal = 0; if ((_data == NULL) && (sourceData == NULL)) { iRetVal = 0; } else { iRetVal = ::memcmp(_data, sourceData, byteCount); } // Post-validation. verifySentinel(); return iRetVal; } ////////////////////////////////////////////////////////////////////////// // MemiCmp // // Compare the memory from sourceData with this array up to byteCount bytes // (case insensitive). ////////////////////////////////////////////////////////////////////////// int32 memiCmp( const void * sourceData, const size_t byteCount) { return memiCmp(sourceData, static_cast(byteCount)); } ////////////////////////////////////////////////////////////////////////// // MemiCmp // // Compare the memory from sourceData with this array up to byteCount bytes // (case insensitive). ////////////////////////////////////////////////////////////////////////// int32 memiCmp( const void * sourceData, const uint32 byteCount) const { CAF_CM_FUNCNAME_VALIDATE("memiCmp"); CAF_CM_VALIDATE_PTR(sourceData); CAF_CM_VALIDATE_POSITIVE(byteCount); // Pre-validation. verifySentinel(); // Make sure the comparison can take place within our array bounds. verifyByteCount(byteCount); // Do comparison. int32 iRetVal = 0; if ((_data == NULL) && (sourceData == NULL)) { iRetVal = 0; } else { iRetVal = memicmp(_data, sourceData, byteCount); } // Post-validation. verifySentinel(); return iRetVal; } ////////////////////////////////////////////////////////////////////////// // incrementElementIndex // // Increments the current position of the index into the buffer. ////////////////////////////////////////////////////////////////////////// void incrementCurrentPos(const uint32 elementCount) { CAF_CM_FUNCNAME("incrementCurrentPos"); if ((_elementIndex + elementCount) > _elementCount) { CAF_CM_EXCEPTION_VA3(ERROR_INSUFFICIENT_BUFFER, "Current position is longer than the total size for '%s' - currentPos: %d, totalLen: %d", _description.c_str(), _elementIndex + elementCount, _elementCount); } _elementIndex += elementCount; } ////////////////////////////////////////////////////////////////////////// // resetElementIndex // // Resets the current position of the index into the buffer. ////////////////////////////////////////////////////////////////////////// void resetCurrentPos() { _elementIndex = 0; } ////////////////////////////////////////////////////////////////////////// // getByteCountFromCurrentPos // // Returns the size of the array in bytes from the current position. ////////////////////////////////////////////////////////////////////////// uint32 getByteCountFromCurrentPos() const { const uint32 byteIndex = elementCountToByteCount(_elementIndex); return (_byteCount - byteIndex); } private: ////////////////////////////////////////////////////////////////////////// // internalAllocate (Private) // // Set the sentinel bytes at the end of the array. ////////////////////////////////////////////////////////////////////////// void internalAllocate(const uint32 elementCount) { CAF_CM_FUNCNAME("internalAllocate"); // This function assumes the calling function has freed any pre- // existing array. CAF_CM_VALIDATE_NULLPTR(_data); CAF_CM_VALIDATE_ZERO(_elementCount); CAF_CM_VALIDATE_ZERO(_byteCount); // Allocate the new buffer. This buffer is _data = static_cast(Allocator::allocMemory( sizeof(T) * (elementCount + gs_ulDynamicArraySentinelElementCount))); // verify that the allocation succeeded. if (!_data) { CAF_CM_EXCEPTION_VA1(ERROR_OUTOFMEMORY, "Array allocation failed for '%s'", _description.c_str()); } // Set sentinel bits #ifdef __x86_64__ _sentinelBits = reinterpret_cast(_data) ^ gs_ulDynamicArraySentinelBitPattern; #else _sentinelBits = reinterpret_cast(_data) ^ gs_ulDynamicArraySentinelBitPattern; #endif // Initialize the new buffer. ::memset(_data, 0, ((elementCount + gs_ulDynamicArraySentinelElementCount) * sizeof(T))); // Set the length and byte length. _elementCount = elementCount; _elementIndex = 0; _byteCount = elementCountToByteCount(elementCount); // Set the sentinel bytes. setSentinel(); // verify the sentinel bytes. verifySentinel(); } ////////////////////////////////////////////////////////////////////////// // SetSentinel (Private) // // Set the sentinel bytes at the end of the array. ////////////////////////////////////////////////////////////////////////// void setSentinel() { // Set the sentinel characters. for (uint32 ulIndex = 0; ulIndex < (2 * sizeof(T)); ++ulIndex) { // Set the sentinel bytes at the end of the array. reinterpret_cast(_data)[(_byteCount + ulIndex + sizeof(T))] = ((ulIndex % 2) == 0) ? 0xFF : 0xDD; // Make a copy of the sentinel bytes for later comparison. _sentinelBytes[ulIndex + sizeof(T)] = ((ulIndex % 2) == 0) ? 0xFF : 0xDD; } // Set the flag indicating the sentinel is set. _isSentinelSet = true; } ////////////////////////////////////////////////////////////////////////// // verifyByteCount (Private) // // Verifies that the byte length supplied is not longer than the array // byte length. ////////////////////////////////////////////////////////////////////////// void verifyByteCount(const uint32 byteCount) const { CAF_CM_FUNCNAME("verifyByteCount"); if (byteCount > _byteCount) { CAF_CM_EXCEPTION_VA3(ERROR_INVALID_INDEX, "The byte length specified [%d] " "exceeds the array length [%d] for '%s'", byteCount, _byteCount, _description.c_str()); } } ////////////////////////////////////////////////////////////////////////// // verifyElementCount (Private) // // Verifies that the index supplied does not go past end of the array. ////////////////////////////////////////////////////////////////////////// void verifyElementCount(const uint32 elementCount) const { CAF_CM_FUNCNAME("verifyElementCount"); if (elementCount >= _elementCount) { CAF_CM_EXCEPTION_VA3(ERROR_INVALID_INDEX, "The index specified [%d] is " "beyond the array bounds [%d] for '%s'", elementCount, (_elementCount - 1), _description.c_str()); } } uint32 byteCountToElementCount(const uint32 byteCount) const { uint32 rc = 0; if (byteCount > 0) { rc = (byteCount / sizeof(T)) + (byteCount % sizeof(T)); } return rc; } uint32 elementCountToByteCount(const uint32 elementCount) const { return (elementCount * sizeof(T)); } protected: ////////////////////////////////////////////////////////////////////////// // verifySentinel (Private) // // Verifies that the sentinel bytes are still intact. ////////////////////////////////////////////////////////////////////////// void verifySentinel() const { CAF_CM_FUNCNAME("verifySentinel"); if (_isSentinelSet) { #ifdef __x86_64__ if ((_sentinelBits ^ reinterpret_cast(_data)) != gs_ulDynamicArraySentinelBitPattern) #else if ((_sentinelBits ^ reinterpret_cast(_data)) != gs_ulDynamicArraySentinelBitPattern) #endif { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_DATA, "The sentinel BITS for array '%s' are no longer valid.", _description.c_str()); } else if (::memcmp(_sentinelBytes, (reinterpret_cast(_data) + _byteCount), sizeof(_sentinelBytes)) != 0) { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_DATA, "The sential BYTES for array '%s' are no longer valid.", _description.c_str()); } } else if (_sentinelBits != gs_ulDynamicArraySentinelBitPattern) { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_DATA, "The sential BITS for array '%s' are no longer valid.", _description.c_str()); } } ////////////////////////////////////////////////////////////////////////// // verifyNotNull (Private) // // Verifies that the data pointer is not null. ////////////////////////////////////////////////////////////////////////// void verifyNotNull() const { CAF_CM_FUNCNAME("verifyNotNull"); if (NULL == _data) { CAF_CM_EXCEPTION_VA1(E_POINTER, "The pointer to the array is null for '%s'", _description.c_str()); } } private: TDynamicArray(const TDynamicArray & crRhs); TDynamicArray & operator=(const TDynamicArray & crRhs); #ifdef WIN32 ////////////////////////////////////////////////////////////////////////// // Operator[] (Private) // // We need to provide an implementation to satisfy the VC8 compiler // even though we never intend this method to be called. ////////////////////////////////////////////////////////////////////////// T operator[](size_t) { // Yes, this code looks very wrong, however, DO NOT REMOVE it! // It is here to supply an implementation that doesn't generate // compiler warnings. This method will never be called. T* tpRetVal = NULL; return *tpRetVal; } #endif private: CAF_CM_CREATE; byte _sentinelBytes[gs_ulDynamicArraySentinelElementCount * sizeof(T)]; #ifdef __x86_64__ uint64 _sentinelBits; #else uint32 _sentinelBits; #endif bool _isSentinelSet; // NOTE: ...Count are not zero-relative, ...Index are zero-relative. // An element is the template type (e.g. wchar_t), so the element count // is the number of these template types in the array. uint32 _elementCount; uint32 _elementIndex; // The number of bytes consumed by the array of template types. uint32 _byteCount; protected: std::string _description; T * _data; }; } #endif // _TDynamicArray_H_ TWCharAdapter.h000066400000000000000000000231141321503522500373000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Memory/DynamicArray////////////////////////////////////////////////////////////////////////////// // // $Workfile: TWCharAdapter.h $ // // Author: Greg Burk // // Purpose: This template provides an adapter for TDynamicArray (or // other types of "safe" array classes) that exposes functions // that are useful when working with an array of type wchar_t. // // A typedef of this class is already defined and should be // used instead of explicitly using this class. The typedef // is CEcmWCharArray. // // Created: Friday, October 18, 2002 1:59:49 PM // // Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // // Modification History: // // $Log: //wpbuild01/PvcsData/ECM_40/archives/ECM_41/WinNT/Source/CommonAgtCol/Cpp/EcmCommonStaticMinDep/TWCharAdapter.h-arc $ // // Rev 1.2 17 Sep 2003 09:43:16 Michael.Donahue // Implemented hooks for new library model // // Rev 1.1 16 Jan 2003 11:17:54 Greg.Burk // Made changes necessary to accomodate new CEcmBasicString class and changes to CEcmString. // // Rev 1.0 31 Oct 2002 10:43:08 Greg.Burk // Initial Revision // ////////////////////////////////////////////////////////////////////////////// #ifndef _TWCharAdapter_H_ #define _TWCharAdapter_H_ namespace Caf { template class TWCharAdapter : public T { public: ////////////////////////////////////////////////////////////////////////// // Default Constructor ////////////////////////////////////////////////////////////////////////// TWCharAdapter() {} ////////////////////////////////////////////////////////////////////////// // Conversion Constructor ////////////////////////////////////////////////////////////////////////// TWCharAdapter(const char * rhs) { multiByteToWide(rhs); } ////////////////////////////////////////////////////////////////////////// // Conversion Constructor ////////////////////////////////////////////////////////////////////////// TWCharAdapter(const wchar_t * rhs) { (*this) = rhs; } ////////////////////////////////////////////////////////////////////////// // Destructor ////////////////////////////////////////////////////////////////////////// ~TWCharAdapter() {} ////////////////////////////////////////////////////////////////////////// // Assignment operator ////////////////////////////////////////////////////////////////////////// TWCharAdapter& operator=(const char * rhs) { multiByteToWide(rhs); return *this; } ////////////////////////////////////////////////////////////////////////// // Assignment operator ////////////////////////////////////////////////////////////////////////// TWCharAdapter& operator=(const wchar_t * rhs) { const uint32 culLength = ::wcslen(rhs); if(culLength > 0) { this->allocateElements(culLength); wcsnCpy(rhs, culLength); } return *this; } ////////////////////////////////////////////////////////////////////////////// // MakeLower() // // Converts all of the upper-case characters in this string to lower-case. ////////////////////////////////////////////////////////////////////////////// void makeLower() { // Pre-validation. this->verifySentinal(); if(!this->isNull()) { wcslwr(this->m_ptData); } // Post-validation. this->verifySentinal(); } ////////////////////////////////////////////////////////////////////////// // MakeUpper // // Converts all of the lower-case characters in this array to upper-case. ////////////////////////////////////////////////////////////////////////// void makeUpper() { // Pre-validation. this->verifySentinal(); if(!this->isNull()) { wcsupr(this->m_ptData); } // Post-validation. this->verifySentinal(); } ////////////////////////////////////////////////////////////////////////// // Reverse // // Reverses the characters in the array. ////////////////////////////////////////////////////////////////////////// void reverse() { // Pre-validation. this->verifySentinal(); if(!this->isNull()) { wcsrev(this->m_ptData); } // Post-validation. this->verifySentinal(); } ////////////////////////////////////////////////////////////////////////// // WcsLen // // Return the length of the string. ////////////////////////////////////////////////////////////////////////// size_t wcsLen() const { size_t stRetVal = 0; this->verifySentinal(); this->verifyNotNull(); stRetVal = ::wcslen(this->m_ptData, this->m_strDesc); this->verifyLength(static_cast(stRetVal)); return stRetVal; } ////////////////////////////////////////////////////////////////////////// // WcsCpy // // Make a copy of the string into the buffer. ////////////////////////////////////////////////////////////////////////// TWCharAdapter & wcsCpy(const wchar_t * cpwszSource) { // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Get the length of the source string. uint32 dwSourceLength = ::wcslen(cpwszSource); // Make sure the string will fit if we copy it. this->verifyLength(dwSourceLength); // Copy the string into the buffer. ::wcscpy(this->m_ptData, cpwszSource); // Post-validation. this->verifySentinal(); return (*this); } ////////////////////////////////////////////////////////////////////////// // WcsnCpy // // Make a copy of the string into the buffer upto culCount characters. ////////////////////////////////////////////////////////////////////////// TWCharAdapter & wcsnCpy(const wchar_t * cpwszSource, const uint32 culCount) { // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Make sure the string will fit if we copy it. this->verifyLength(culCount); // Copy the string into the buffer. ::wcsncpy(this->m_ptData, cpwszSource, culCount); // Post-validation. this->verifySentinal(); return (*this); } ////////////////////////////////////////////////////////////////////////// // WcsStr // // Find the substring cpwszSubString in the array. Returns the pointer to // the first occurance of the substring in the array or NULL if the // substring is not found. ////////////////////////////////////////////////////////////////////////// const wchar_t * wcsStr(const wchar_t * cpwszSubString) const { wchar_t * pwszRetVal = NULL; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Find the substring. pwszRetVal = ::wcsstr(this->m_ptData, cpwszSubString); // Post-validation. this->verifySentinal(); return pwszRetVal; } ////////////////////////////////////////////////////////////////////////// // WcsCmp // // Compare the cpwszString to this array. ////////////////////////////////////////////////////////////////////////// int32 wcsCmp(const wchar_t * cpwszString) const { int32 iRetVal = 0; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Compare the strings. iRetVal = ::wcscmp(this->m_ptData, cpwszString); return iRetVal; } ////////////////////////////////////////////////////////////////////////// // WcsiCmp // // Compare the cpwszString to this array (case insensitive). ////////////////////////////////////////////////////////////////////////// int32 wcsiCmp(const wchar_t * cpwszString) const { int32 iRetVal = 0; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Compare the strings. iRetVal = wcsicmp(this->m_ptData, cpwszString); return iRetVal; } ////////////////////////////////////////////////////////////////////////// // WcsnCmp // // Compare the cpwszString to this array up to culCount characters. ////////////////////////////////////////////////////////////////////////// int32 wcsnCmp(const wchar_t * cpwszString, const uint32 culCount) const { int32 iRetVal = 0; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Make sure the comparison can take place with in our array bounds. this->verifyLength(culCount); // Compare the strings. iRetVal = wcsncmp(this->m_ptData, cpwszString, culCount); return iRetVal; } ////////////////////////////////////////////////////////////////////////// // WcsChr // // Find the first occurrence of the specified character in the string. ////////////////////////////////////////////////////////////////////////// wchar_t * wcsChr(wchar_t wcCharacter) const { wchar_t * pwszRetVal = 0; // Pre-validation. this->verifySentinal(); this->verifyNotNull(); // Compare the strings. pwszRetVal = ::wcschr(this->m_ptData, wcCharacter); return pwszRetVal; } private: void multiByteToWide(const char* cpszSource) { // Calculate the length of the source. const uint32 cdwSourceLen = cpszSource ? ::strlen( cpszSource ) : 0; // Convert the multibyte strings to wide. if( cdwSourceLen > 0 ) { this->allocateElements(cdwSourceLen); int32 iRet; #ifdef WIN32 iRet = ::MultiByteToWideChar( CP_ACP, 0, cpszSource, cdwSourceLen, GetNonConstPtr(), GetLength() ); #else iRet = ::mbstowcs( this->getNonConstPtr(), cpszSource, cdwSourceLen ); // mbstowcs returns -1 on error or the number of // characters without the null terminator, so // we can increase it by 1 for the null or to 0 for // the error condition below if ( 0 != iRet ) iRet++; #endif if( 0 == iRet ) { this->freeArray(); } } else if( cpszSource != NULL ) { // This chunk of code is important. If the source // string is empty, return an empty string, not // a NULL pointer! this->allocateElements(0); } // Verify array. this->verifySentinal(); } private: TWCharAdapter(const TWCharAdapter & crRhs); TWCharAdapter & operator=(const TWCharAdapter & crRhs); }; } #endif // _TWCharAdapter_H_ PlatformDefines.h000066400000000000000000000014361321503522500341010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef PLATFORM_DEFINES_H #define PLATFORM_DEFINES_H #ifdef WIN32 #ifdef _WIN64 typedef uint64 SUBSYS_INTPTR; const SUBSYS_INTPTR SUBSYS_INTPTR_INVALID = 0xffffffffffffffff; #else typedef uint32 SUBSYS_INTPTR; const SUBSYS_INTPTR SUBSYS_INTPTR_INVALID = 0xffffffff; #endif #else #ifdef __x86_64__ typedef uint64_t SUBSYS_INTPTR; const SUBSYS_INTPTR SUBSYS_INTPTR_INVALID = 0xffffffffffffffff; #else typedef uint32_t SUBSYS_INTPTR; const SUBSYS_INTPTR SUBSYS_INTPTR_INVALID = 0xffffffff; #endif const uint32 DLL_PROCESS_ATTACH = 1; const uint32 DLL_PROCESS_DETACH = 2; #ifndef TRUE #define TRUE true #endif #ifndef FALSE #define FALSE false #endif #endif #endif // #ifndef PLATFORM_DEFINES_H PlatformErrors.h000066400000000000000000000152411321503522500337770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef PLATFORMERRORS_H_ #define PLATFORMERRORS_H_ #ifdef WIN32 #include #else const HRESULT S_OK = 0; const HRESULT S_FALSE = 1; const HRESULT E_FAIL = 0x80004005; const HRESULT E_NOTIMPL = 0x80004001; const HRESULT E_INVALIDARG = 0x80070057; const HRESULT E_OUTOFMEMORY = 0x8007000E; const HRESULT E_POINTER = 0x80004003; const HRESULT E_NOINTERFACE = 0x80004002; const HRESULT E_UNEXPECTED = 0x8000FFFF; const HRESULT OLE_E_BLANK = 0x80040007; const HRESULT ERROR_SUCCESS = 0; const HRESULT NO_ERROR = 0; const HRESULT ERROR_INVALID_FUNCTION= 1; const HRESULT ERROR_FILE_NOT_FOUND = 2; const HRESULT ERROR_PATH_NOT_FOUND = 3; const HRESULT ERROR_ACCESS_DENIED = 5; const HRESULT ERROR_INVALID_HANDLE = 6; const HRESULT ERROR_INVALID_DATA = 13; const HRESULT ERROR_OUTOFMEMORY = 14; const HRESULT ERROR_NOT_SAME_DEVICE= 17; const HRESULT ERROR_HANDLE_EOF = 38; const HRESULT ERROR_NOT_SUPPORTED = 50; const HRESULT ERROR_FILE_EXISTS= 80; const HRESULT ERROR_INVALID_PARAMETER = 87; const HRESULT ERROR_BUFFER_OVERFLOW = 111; const HRESULT ERROR_CALL_NOT_IMPLEMENTED = 120; const HRESULT ERROR_INSUFFICIENT_BUFFER = 122; const HRESULT ERROR_BAD_PATHNAME = 161; const HRESULT ERROR_BUSY = 170; const HRESULT ERROR_ALREADY_EXISTS= 183; const HRESULT ERROR_NOT_FOUND = 1168; const HRESULT ERROR_MORE_DATA = 234; const HRESULT ERROR_NO_MORE_ITEMS = 259; const HRESULT ERROR_SHUTDOWN_IN_PROGRESS = 1115; const HRESULT ERROR_INVALID_INDEX = 1413; const HRESULT ERROR_INTERNAL_ERROR = 1359; const HRESULT ERROR_DISCARDED = 157; const HRESULT ERROR_CLASS_ALREADY_EXISTS = 1410; const HRESULT ERROR_CLASS_DOES_NOT_EXIST = 1411; const HRESULT ERROR_TIMEOUT = 1460; const HRESULT ERROR_UNSUPPORTED_TYPE = 1630; const HRESULT ERROR_TAG_NOT_FOUND =2012; const HRESULT ERROR_TAG_NOT_PRESENT =2013; const HRESULT ERROR_DUPLICATE_TAG =2014; const HRESULT ERROR_INVALID_STATE = 5023; const HRESULT ERROR_FILE_READ_ONLY = 6009; const HRESULT ERROR_REVISION_MISMATCH = 1306; const HRESULT ERROR_ALREADY_INITIALIZED = 1247; const HRESULT DISP_E_BADVARTYPE = 0x80020008; const HRESULT DISP_E_OVERFLOW = 0x8002000A; const HRESULT DISP_E_TYPEMISMATCH = 0x80020005; const HRESULT DISP_E_EXCEPTION = 0x80020009; const HRESULT DISP_E_PARAMNOTOPTIONAL = 0x8002000F; const HRESULT DISP_E_UNKNOWNNAME = 0x80020006; const HRESULT DISP_E_BADPARAMCOUNT = 0x8002000E; const HRESULT NTE_BAD_LEN = 0x80090004; const HRESULT RPC_S_OK = 0; const HRESULT RPC_S_OUT_OF_MEMORY = ERROR_OUTOFMEMORY; const HRESULT RPC_S_INVALID_STRING_BINDING = 1700; const HRESULT RPC_S_WRONG_KIND_OF_BINDING = 1701; const HRESULT RPC_S_INVALID_BINDING = 1702; const HRESULT RPC_S_PROTSEQ_NOT_SUPPORTED = 1703; const HRESULT RPC_S_INVALID_RPC_PROTSEQ = 1704; const HRESULT RPC_S_INVALID_STRING_UUID = 1705; const HRESULT RPC_S_INVALID_ENDPOINT_FORMAT = 1706; const HRESULT RPC_S_INVALID_NET_ADDR = 1707; const HRESULT RPC_S_NO_ENDPOINT_FOUND = 1708; const HRESULT RPC_S_INVALID_TIMEOUT = 1709; const HRESULT RPC_S_OBJECT_NOT_FOUND = 1710; const HRESULT RPC_S_ALREADY_REGISTERED = 1711; const HRESULT RPC_S_TYPE_ALREADY_REGISTERED = 1712; const HRESULT RPC_S_ALREADY_LISTENING = 1713; const HRESULT RPC_S_NO_PROTSEQS_REGISTERED = 1714; const HRESULT RPC_S_NOT_LISTENING = 1715; const HRESULT RPC_S_UNKNOWN_MGR_TYPE = 1716; const HRESULT RPC_S_UNKNOWN_IF = 1717; const HRESULT RPC_S_NO_BINDINGS = 1718; const HRESULT RPC_S_NO_PROTSEQS = 1719; const HRESULT RPC_S_CANT_CREATE_ENDPOINT = 1720; const HRESULT RPC_S_OUT_OF_RESOURCES = 1721; const HRESULT RPC_S_SERVER_UNAVAILABLE = 1722; const HRESULT RPC_S_SERVER_TOO_BUSY = 1723; const HRESULT RPC_S_INVALID_NETWORK_OPTIONS = 1724; const HRESULT RPC_S_NO_CALL_ACTIVE = 1725; const HRESULT RPC_S_CALL_FAILED = 1726; const HRESULT RPC_S_CALL_FAILED_DNE = 1727; const HRESULT RPC_S_PROTOCOL_ERROR = 1728; const HRESULT RPC_S_UNSUPPORTED_TRANS_SYN = 1730; const HRESULT RPC_S_UNSUPPORTED_TYPE = 1732; const HRESULT RPC_S_INVALID_TAG = 1733; const HRESULT RPC_S_INVALID_BOUND = 1734; const HRESULT RPC_S_NO_ENTRY_NAME = 1735; const HRESULT RPC_S_INVALID_NAME_SYNTAX = 1736; const HRESULT RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737; const HRESULT RPC_S_UUID_NO_ADDRESS = 1739; const HRESULT RPC_S_DUPLICATE_ENDPOINT = 1740; const HRESULT RPC_S_UNKNOWN_AUTHN_TYPE = 1741; const HRESULT RPC_S_MAX_CALLS_TOO_SMALL = 1742; const HRESULT RPC_S_STRING_TOO_LONG = 1743; const HRESULT RPC_S_PROTSEQ_NOT_FOUND = 1744; const HRESULT RPC_S_PROCNUM_OUT_OF_RANGE = 1745; const HRESULT RPC_S_BINDING_HAS_NO_AUTH = 1746; const HRESULT RPC_S_UNKNOWN_AUTHN_SERVICE = 1747; const HRESULT RPC_S_UNKNOWN_AUTHN_LEVEL = 1748; const HRESULT RPC_S_INVALID_AUTH_IDENTITY = 1749; const HRESULT RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750; const HRESULT FACILITY_WINDOWS = 8; const HRESULT FACILITY_URT = 19; const HRESULT FACILITY_STORAGE = 3; const HRESULT FACILITY_SSPI = 9; const HRESULT FACILITY_SCARD = 16; const HRESULT FACILITY_SETUPAPI = 15; const HRESULT FACILITY_SECURITY = 9; const HRESULT FACILITY_RPC = 1; const HRESULT FACILITY_WIN32 = 7; const HRESULT FACILITY_CONTROL = 10; const HRESULT FACILITY_NULL = 0; const HRESULT FACILITY_MSMQ = 14; const HRESULT FACILITY_MEDIASERVER = 13; const HRESULT FACILITY_INTERNET = 12; const HRESULT FACILITY_ITF = 4; const HRESULT FACILITY_DISPATCH = 2; const HRESULT FACILITY_COMPLUS = 17; const HRESULT FACILITY_CERT = 11; const HRESULT FACILITY_ACS = 20; const HRESULT FACILITY_AAF = 18; const HRESULT SEVERITY_SUCCESS = 0; const HRESULT SEVERITY_ERROR = 1; #define HRESULT_FROM_WIN32(x) ((HRESULT)(x) <= 0 ? ((HRESULT)(x)) : ((HRESULT) (((x) & 0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000))) #define SUCCEEDED(status) ((HRESULT)(status) >= 0) #define FAILED(status) ((HRESULT)(status) < 0) #define IS_ERROR(status) ((uint32)(status) >> 31 == SEVERITY_ERROR) #define HRESULT_CODE(hr) ((hr) & 0xFFFF) #define SCODE_CODE(sc) ((sc) & 0xFFFF) #define HRESULT_FACILITY(hr) (((hr) >> 16) & 0x1FFF) #define SCODE_FACILITY(sc) (((sc) >> 16) & 0x1FFF) #define HRESULT_SEVERITY(hr) (((hr) >> 31) & 0x1 #define SCODE_SEVERITY(sc) (((sc) >> 31) & 0x1) #define MAKE_HRESULT(sev,fac,code) \ ((HRESULT) (((uint32)(sev)<<31) | ((uint32)(fac)<<16) | ((uint32)(code))) ) #define MAKE_SCODE(sev,fac,code) \ ((HRESULT) (((uint32)(sev)<<31) | ((uint32)(fac)<<16) | ((uint32)(code))) ) #endif #endif /* PLATFORMERRORS_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/PlatformIID.h000066400000000000000000000026121321503522500332050ustar00rootroot00000000000000/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef PLATFORM_IID_H #define PLATFORM_IID_H #ifndef WIN32 #include #include struct GUID { // this must match the Windows GUID structure uint32 Data1; // 4 bytes uint16 Data2; // 2 bytes uint16 Data3; // 2 bytes byte Data4[8]; // 8 bytes }; typedef GUID IID, UUID; inline bool IsEqualGUID(const GUID& rguid1, const GUID& rguid2) { return (!::memcmp(&rguid1,&rguid2,sizeof(GUID))); } #define IsEqualIID(rguid1,rguid2) IsEqualGUID(rguid1,rguid2) #define IsEqualUUID(rguid1,rguid2) IsEqualGUID(rguid1,rguid2) extern HRESULT UuidCreate(UUID* uuid); #endif namespace BasePlatform { BASEPLATFORM_LINKAGE std::string UuidToString(const UUID& uuid); BASEPLATFORM_LINKAGE HRESULT UuidFromString(const char* strGuid, UUID& uuid); // This mutex is used to guard the construction of the IIDs in the IIDOF macro extern BASEPLATFORM_LINKAGE GMutex gs_BaseIIDInitMutex; } #define CAF_DECL_UUID(iid) \ public: \ static const IID & IIDOF() \ { \ static IID ms_oIID; \ static bool m_bIsSet; \ g_mutex_lock(&BasePlatform::gs_BaseIIDInitMutex); \ if ( !m_bIsSet ) \ { \ BasePlatform::UuidFromString( iid , ms_oIID ); \ m_bIsSet = true; \ } \ g_mutex_unlock(&BasePlatform::gs_BaseIIDInitMutex); \ return ms_oIID; \ } #define CAF_IIDOF(type_name) type_name::IIDOF() #endif PlatformStringFunc.h000066400000000000000000000005641321503522500346070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef PLATFORMSTRINGFUNC_H_ #define PLATFORMSTRINGFUNC_H_ namespace BasePlatform { //extern std::wstring A2W(const std::string& str); //extern std::string W2A(const std::wstring& str); } #endif /* PLATFORMSTRINGFUNC_H_ */ PlatformTypes.h000066400000000000000000000012101321503522500336160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef PLATFORM_TYPES_H #define PLATFORM_TYPES_H #ifdef WIN32 #include #else // #include #include #include #if defined (__linux__) || defined (__APPLE__) #include #endif //typedef int32 RPC_STATUS; #define __declspec(value) #define __stdcall #define __cdecl #define APIENTRY #define FAR typedef void * HINSTANCE; typedef void * HMODULE; typedef void * HANDLE; typedef void * LPVOID; typedef bool BOOL; typedef uint8_t byte; typedef int32_t HRESULT; #endif #endif // PLATFORM_TYPES_H open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/TCafObject.h000066400000000000000000000011711321503522500330360ustar00rootroot00000000000000/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _TCafObject_h #define _TCafObject_h template class TCafObject : public Base { public: TCafObject() : _refCnt(0) {} public: // ICafObect Implementations void AddRef() { g_atomic_int_inc(&_refCnt); } void Release() { if (g_atomic_int_dec_and_test(&_refCnt)) { delete this; } } void QueryInterface(const IID&, void**) { throw std::runtime_error("QueryInterface not supported"); } private: gint _refCnt; private: TCafObject(const TCafObject&); TCafObject& operator=(const TCafObject&); }; #endif TCafQIObject.h000066400000000000000000000044731321503522500332210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Created: May 25, 2004 * * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef TCAFQIOBJECT_H_ #define TCAFQIOBJECT_H_ template class TCafQIObject : public TCafObject { public: TCafQIObject () { } virtual ~TCafQIObject () { } public: virtual void QueryInterface( const IID& criid, void** ppv ) { Base::_InternalQueryInterface( criid, ppv ); } }; //////////////////////////////////////////////////////////////////////// // // QI map // //////////////////////////////////////////////////////////////////////// #define CAF_BEGIN_QI() \ protected: \ void _InternalQueryInterface (const IID &criid, void **ppv) \ { \ try \ { \ if (ppv) \ { \ *ppv = NULL; \ bool bUseFirstInterface = (::IsEqualGUID(criid, CAF_IIDOF(::ICafObject)) != 0); \ if (0); #define CAF_QI_ENTRY(Interface) \ else if (bUseFirstInterface || ::IsEqualGUID(criid, CAF_IIDOF(Interface))) \ *ppv = static_cast(this); #define CAF_QI_ENTRY2(Interface, IntermediateInterface) \ else if (bUseFirstInterface || ::IsEqualGUID(criid, CAF_IIDOF(Interface))) \ *ppv = static_cast(static_cast(this)); #define CAF_END_QI() \ if (*ppv) \ reinterpret_cast(this)->AddRef(); \ } \ } \ catch (...) \ { \ } \ } //////////////////////////////////////////////////////////////////////// // // Object Id - required for ISerializableObject // //////////////////////////////////////////////////////////////////////// #define CAF_MAKE_OBJECT_ID(Factory, Class) \ (std::string(Factory) + std::string(":") + std::string( #Class )) #define CAF_DECLARE_OBJECT_ID(Class, Factory) \ public: \ virtual std::string GetObjectId () const \ { \ return CAF_MAKE_OBJECT_ID(Factory, Class); \ } // Declare a smart pointer to a class that supports QI after the class has been declared #define CAF_DECLARE_SMART_QI_POINTER(ClassName) \ typedef TCafSmartPtr > SmartPtr##ClassName; \ typedef TCafSmartPtr > ConstPtr##ClassName // Forward declare a smart pointer to a class that supports QI #define CAF_DECLARE_CLASS_AND_IMPQI_POINTER(ClassName) \ class ClassName; \ CAF_DECLARE_SMART_QI_POINTER(ClassName) #endif /* TCAFQIOBJECT_H_ */ TCafSmartPtr.h000066400000000000000000000302331321503522500333260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _TCafSmartPtr_H #define _TCafSmartPtr_H #ifdef WIN32 // Disable C4800 - performance warning forcing value to 'true' or 'false' #pragma warning(disable: 4800) #endif // Forward declarations for Subsystem calls #ifndef SUBSYSTEMBASE_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define SUBSYSTEMBASE_LINKAGE __declspec(dllexport) #else #define SUBSYSTEMBASE_LINKAGE __declspec(dllimport) #endif #else #define SUBSYSTEMBASE_LINKAGE #endif #endif namespace Caf { extern "C" void SUBSYSTEMBASE_LINKAGE CreateObject(const char* cszObjectId, const IID& criid, void** ppv); //extern "C" void SUBSYSTEMBASE_LINKAGE CreateQIObject(const char* cszFactoryId, const char* cszClassName, const IID& criid, void** ppv); } /** * @brief Template to wrap any interface or class and provide lifetime management. *

* Lifetime is managed through reference counting with counts stored in the object * itself. The reference methods are AddRef() and Release(). When the reference * count reaches zero the object will delete itself. *

* Template instantiation:
* Cl is used for accessing the class. It may or may not be derived from * #ICafObject.
* CreateCl is used for creating the class and reference counting. It must * support the #ICafObject interface. */ // CreateCl is used for creation and reference counting and must support the // ICafObject interface. Cl is used for accessing the class. template class TCafSmartPtr { public: typedef Cl class_type; typedef CreateCl create_type; private: typedef TCafSmartPtr SameSmartType; public: // constructors/destructors // default constructor TCafSmartPtr(void) : m_pCl(0) { } // homogeneous raw constructor TCafSmartPtr(Cl *rhs) { m_pCl = rhs; if (m_pCreateCl) m_pCreateCl->AddRef(); } // derived class smart constructor template TCafSmartPtr(const TCafSmartPtr &rhs) { m_pCl = rhs.GetNonAddRefedInterface(); if (m_pCreateCl) m_pCreateCl->AddRef(); } // homogeneous smart constructor TCafSmartPtr(const SameSmartType& rhs) { m_pCl = rhs.m_pCl; if (m_pCreateCl) m_pCreateCl->AddRef(); } // don't allow construction from bool explicit TCafSmartPtr(const bool &rb) { int32 CantConstructSmartPointerFromBool[0]; } // destructor ~TCafSmartPtr(void) { if (m_pCreateCl) m_pCreateCl->Release(); } public: // assignment operators // homogeneous raw assignment SameSmartType &operator=(Cl *rhs) { Attach(rhs); return *this; } // derived class smart assignment template SameSmartType &operator=(const TCafSmartPtr &rhs) { Attach(rhs.GetNonAddRefedInterface()); return *this; } // homogeneous smart assignment SameSmartType &operator=(const SameSmartType &rhs) { Attach(rhs.m_pCl); return *this; } // don't allow assignment from bool void operator=(bool &rb) { int32 CantAssignSmartPointerFromBool[0]; } private: // This helper class is used to ensure that the old smart object gets // released in a safe manner. It is not safe to touch 'this' in any way // whatsoever after releasing the old smart object because the release // could set off a chain of destruction that results in this smart pointer // being destroyed. Note that this includes the exception macros which // reference the automatically-defined class name member variable. class CSafeAutoRelease { public: CSafeAutoRelease(CreateCl *pOldCreateCl) : m_pOldCreateCl(pOldCreateCl) { } ~CSafeAutoRelease() { if (m_pOldCreateCl) m_pOldCreateCl->Release(); } CreateCl *m_pOldCreateCl; }; public: /** * @brief Retrieve an interface from a ICafObject pointer and assign the result to self * @param piObj the object to be queried * @param cbIsRequired if true then the operation must succeed else an * exception will be thrown. If false then the self value will be NULL * if the operation fails. */ void QueryInterface(ICafObject *piObj, const bool cbIsRequired = true) { CSafeAutoRelease oAutoRelease(m_pCreateCl); m_pCreateCl = NULL; if (piObj) piObj->QueryInterface(GetIID(), reinterpret_cast(&m_pCreateCl)); if (cbIsRequired && !m_pCreateCl) throw std::bad_cast(); } /** * @brief Retrieve an interface from another smart pointer and assign the result to self * @param rhs the object to be queried * @param cbIsRequired if true then the operation must succeed else an * exception will be thrown. If false then the self value will be NULL * if the operation fails. */ template void QueryInterface(const TCafSmartPtr &rhs, const bool cbIsRequired = true) { CSafeAutoRelease oAutoRelease(m_pCreateCl); m_pCreateCl = NULL; if (rhs) rhs.QueryInterface(GetIID(), reinterpret_cast(&m_pCreateCl)); if (cbIsRequired && !m_pCreateCl) throw std::bad_cast(); } // This function is provided so that the delegation can go through m_pCreateCl // rather than m_pCl. This way, if this is a smart pointer to a class that // derives from multiple interfaces the compiler will not get confused about // which QueryInterface function to use. void QueryInterface(const IID &criid, void **ppv) const { *ppv = NULL; m_pCreateCl->QueryInterface(criid, ppv); } /** * @brief Return the UUID of the object * @return the UUID */ static const IID& GetIID() { // Compiler bug workaround (see comments before COpaqueTemplate) // return TEcmSmartPtr_GetIID(static_cast *>(NULL)); return CAF_IIDOF(Cl); } public: // comparison operators bool operator==(const Cl *rhs) const { return m_pCl == rhs; } template bool operator==(const TCafSmartPtr &rhs) const { return m_pCl == rhs.GetNonAddRefedInterface(); } bool operator!=(const Cl *rhs) const { return m_pCl != rhs; } template bool operator!=(const TCafSmartPtr &rhs) const { return m_pCl != rhs.GetNonAddRefedInterface(); } bool operator<(const SameSmartType &rhs) const { return (m_pCl < rhs.m_pCl); } public: // conversion // This takes the place of operator bool. // It turns out that the presence of operator bool // causes the compiler to "get lost" when compiling // comparison operations such as if( spcPtr1 == spcPtr2)... // // This conversion operator will satisfy the compiler when // compiling comparison operations. class PseudoBool { }; operator PseudoBool *() const { return (PseudoBool *) m_pCl; } public: // instance creation /** * @brief Create an instance of the CreateCl object *

* The object will have an initial reference count of 1. */ void CreateInstance() { CSafeAutoRelease oAutoRelease(m_pCreateCl); //////////////////////////////////////////////////////////////////////// // // This code is used to verify that it is safe to use a union of Cl // and CreateCl. An error indicates that it is *not* safe in which // case the smart pointer cannot be used as defined. To solve this // problem, eliminate the second template parameter from the smart // pointer definition which will force Cl and CreateCl to be the // same, e.g.: // // typedef TCafSmartPtr > SmartPtrClass; // //////////////////////////////////////////////////////////////////////// Cl *pCl = static_cast(reinterpret_cast(0x4)); if (pCl != reinterpret_cast(0x4)) throw std::logic_error("Illegal use of TCafSmartPtr<> (See comments in TCafSmartPtr.h)"); m_pCreateCl = new CreateCl; if (!m_pCreateCl) throw std::bad_alloc(); m_pCreateCl->AddRef(); } /** * @brief Create an instance of a subsystem object *

* Objects exposed as subsystems (#Caf::TCafSubSystemSmartCl) are identified * by a string. The Cl and CreateCl template arguments would both be * set to an interface on the subsystem object of interest. *

* The object will have an initial reference count of 1. */ void CreateInstance(const char* cszObjectId) { CSafeAutoRelease oAutoRelease(m_pCreateCl); Caf::CreateObject(cszObjectId, GetIID(), reinterpret_cast(&m_pCreateCl)); } // void CreateInstance (const char *cszFactoryId, const char *cszClassName) // { // CSafeAutoRelease oAutoRelease(m_pCreateCl); // Caf::CreateQIObject(cszFactoryId, cszClassName, GetIID(), reinterpret_cast(&m_pCreateCl)); // } public: // operations Cl *GetAddRefedInterface() const { if (!m_pCl) throw std::runtime_error("TCafSmartPtr: m_pCl is NULL"); if (m_pCreateCl) m_pCreateCl->AddRef(); return m_pCl; } Cl *GetNonAddRefedInterface() const { return m_pCl; } Cl **GetReleasedInterfaceReference(void) { CSafeAutoRelease oAutoRelease(m_pCreateCl); m_pCreateCl = NULL; return &m_pCreateCl; } Cl **GetNonReleasedInterfaceReference(void) { return &m_pCreateCl; } void **GetAsPPVArg(void) { return (void**) GetReleasedInterfaceReference(); } bool IsNull() const { return m_pCl == 0; } // the arrow operator simply returns the pointer Cl *operator->() const { if (!m_pCl) throw std::runtime_error("TCafSmartPtr: m_pCl is NULL"); return m_pCl; } Cl &operator*() const { if (!m_pCl) throw std::runtime_error("TCafSmartPtr: m_pCl is NULL"); return *m_pCl; } private: // m_pCreateCl is used for reference counting; m_pCl is used for object access. union { Cl *m_pCl; CreateCl *m_pCreateCl; }; private: // homogeneous raw attachment void Attach(Cl* rhs) { CSafeAutoRelease oAutoRelease(m_pCreateCl); m_pCl = rhs; if (m_pCreateCl) m_pCreateCl->AddRef(); } }; // These template functions will give you a reference to the // underlying object wraped in a smart class template const Cl& ToObj(const TCafSmartPtr& spcT) { return *(spcT.GetNonAddRefedInterface()); } template Cl& ToNonConstObj(const TCafSmartPtr& spcT) { return *(spcT.GetNonAddRefedInterface()); } //////////////////////////////////////////////////////////////////////// // // Declaration Macros // //////////////////////////////////////////////////////////////////////// // Declare a smart pointer after the class has been declared #define CAF_DECLARE_SMART_POINTER(ClassName) \ typedef TCafSmartPtr > SmartPtr##ClassName; \ // typedef TCafSmartPtr > ConstPtr##ClassName // Forward declare a class smart pointer #define CAF_DECLARE_CLASS_AND_SMART_POINTER(ClassName) \ class ClassName; \ CAF_DECLARE_SMART_POINTER(ClassName) // Forward declare a struct smart pointer #define CAF_DECLARE_STRUCT_AND_SMART_POINTER(StructName) \ struct StructName; \ CAF_DECLARE_SMART_POINTER(StructName) // Helper macro - do not use directly #define CAF_DECLARE_SMART_INTERFACE_HELPER(InterfaceName) \ typedef TCafSmartPtr SmartPtr##InterfaceName; \ // typedef TCafSmartPtr ConstPtr##InterfaceName // Declare a smart pointer to an interface in the interface header file #define CAF_DECLARE_SMART_INTERFACE_POINTER(InterfaceName) \ CAF_DECLARE_SMART_INTERFACE_HELPER(InterfaceName) // Forward declare a smart interface pointer #define CAF_FORWARD_DECLARE_SMART_INTERFACE(InterfaceName) \ struct InterfaceName; \ CAF_DECLARE_SMART_INTERFACE_HELPER(InterfaceName) #endif // #ifndef _TCafSmartPtr_H TCafStackObject.h000066400000000000000000000013141321503522500337440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/* * Created on: Jul 23, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef TCAFSTACKOBJECT_H_ #define TCAFSTACKOBJECT_H_ namespace Caf { template class TCafStackObject : public Base { public: TCafStackObject() {} virtual ~TCafStackObject() {} private: virtual void AddRef() { throw std::runtime_error("TCafStackObj::AddRef not supported"); } virtual void Release() { throw std::runtime_error("TCafStackObj::Release not supported"); } virtual void QueryInterface(const IID&, void** ppv) { throw std::runtime_error("TCafStackObj::QueryInterface not supported"); } }; } #endif /* TCAFSTACKOBJECT_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Xml/000077500000000000000000000000001321503522500314615ustar00rootroot00000000000000MarkupParser/000077500000000000000000000000001321503522500340165ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/XmlCMarkupParser.h000066400000000000000000000033071321503522500367110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Xml/MarkupParser/* * Author: mdonahue * Created: Jan 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMARKUPPARSER_H_ #define CMARKUPPARSER_H_ #include #include namespace Caf { /* * Wrapper around glib GMarkupParser to store results in std containers */ namespace MarkupParser { // attribute name, value typedef std::pair Attribute; typedef std::list Attributes; struct AttributeName : public std::binary_function { bool operator()(const Attribute& attr, const std::string& name) const { return (attr.first.compare(name) == 0); } }; struct Element; CAF_DECLARE_SMART_POINTER(Element); struct Element { Element() {} std::string name; std::string value; Attributes attributes; typedef std::list Children; Children children; CAF_CM_DECLARE_NOCOPY(Element); }; struct ElementName : public std::binary_function { bool operator()(const SmartPtrElement& element, const std::string& name) const { return (element->name.compare(name) == 0); } }; SmartPtrElement MARKUPPARSER_LINKAGE parseString(const std::string& xml); SmartPtrElement MARKUPPARSER_LINKAGE parseFile(const std::string& file); typedef Element::Children::iterator ChildIterator; typedef Attributes::iterator AttributeIterator; ChildIterator MARKUPPARSER_LINKAGE findChild(SmartPtrElement& element, const std::string& name); AttributeIterator MARKUPPARSER_LINKAGE findAttribute(Attributes& attributes, const std::string& name); std::string MARKUPPARSER_LINKAGE getAttributeValue(SmartPtrElement& element, const std::string& name); }} #endif /* CMARKUPPARSER_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Xml/XmlUtils/000077500000000000000000000000001321503522500332425ustar00rootroot00000000000000CXmlElement.h000066400000000000000000000053661321503522500355230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/include/Xml/XmlUtils/* * Author: mdonahue * Created: Dec 3, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _CXmlElement_h #define _CXmlElement_h #include "Integration/IDocument.h" #include "Xml/MarkupParser/CMarkupParser.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CXmlElement); class XMLUTILS_LINKAGE CXmlElement { public: typedef std::map CAttributeCollection; typedef std::multimap CElementCollection; typedef std::deque COrderedElementCollection; CAF_DECLARE_SMART_POINTER(CAttributeCollection); CAF_DECLARE_SMART_POINTER(CElementCollection); CAF_DECLARE_SMART_POINTER(COrderedElementCollection); public: CXmlElement(); virtual ~CXmlElement(); public: void initialize(const MarkupParser::SmartPtrElement& element, const std::string& path); MarkupParser::SmartPtrElement getInternalElement(); public: // Read operations std::string findRequiredAttribute(const std::string& name) const; std::string findOptionalAttribute(const std::string& name) const; SmartPtrCXmlElement findRequiredChild(const std::string& name) const; SmartPtrCXmlElement findOptionalChild(const std::string& name) const; SmartPtrCElementCollection findRequiredChildren(const std::string& name) const; SmartPtrCElementCollection findOptionalChildren(const std::string& name) const; SmartPtrCAttributeCollection getAllAttributes() const; SmartPtrCElementCollection getAllChildren() const; SmartPtrCOrderedElementCollection getAllChildrenInOrder() const; std::string getName() const; std::string getValue() const; std::string getCDataValue() const; std::string getPath() const; public: // Write operations void addAttribute(const std::string& name, const std::string& value); void removeAttribute(const std::string& name); void setAttribute(const std::string& name, const std::string& value); SmartPtrCXmlElement createAndAddElement(const std::string& name); void addChild(const SmartPtrCXmlElement& xmlElement); void removeChild(const std::string& name); void setValue(const std::string& value); void setCDataValue(const std::string& value); void appendValue(const std::string& value); void saveToFile(const std::string& filename) const; std::string saveToString() const; std::string saveToStringRaw() const; private: static const std::string CDATA_BEG; static const std::string CDATA_END; private: bool _isInitialized; mutable MarkupParser::SmartPtrElement _element; std::string _path; private: static void saveToString(const MarkupParser::SmartPtrElement& element, std::string& xml); private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CXmlElement); }; CAF_DECLARE_SMART_POINTER(CXmlElement); } #endif /* _CXmlElement_h */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/000077500000000000000000000000001321503522500300655ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/BasePlatform.cpp000066400000000000000000000003351321503522500331510ustar00rootroot00000000000000/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #ifdef WIN32 extern "C" { BOOL APIENTRY DllMain(HMODULE, uint32, LPVOID) { return TRUE; } } #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/000077500000000000000000000000001321503522500323435ustar00rootroot00000000000000Graphs/000077500000000000000000000000001321503522500335105ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/CollectionsGraphsInc.h000066400000000000000000000003711321503522500355400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Graphs/* * Created on: Sep 30, 2011 * Author: mdonahue * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef GRAPHSINC_H_ #define GRAPHSINC_H_ #include "TEdgeListGraph.h" #endif /* GRAPHSINC_H_ */ TEdgeListGraph.h000066400000000000000000000357321321503522500365010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Graphs/* * Created on: Jul 09, 2003 * Author: Scott VanCamp * * Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef TEDGELISTGRAPH_H_ #define TEDGELISTGRAPH_H_ #include #include "Exception/CCafException.h" #include #include #include ////////////////////////////////////////////////////////////////////////////// // // Simple graph that uses an edge list // // Since we may be using this graph with smart pointers I allow you to specify // you own less than function. See // for smart class less than template functions. ////////////////////////////////////////////////////////////////////////////// using namespace Caf; template < class Item, class CustomLess = std::less< Item > > class TEdgeListGraph { private: typedef TEdgeListGraph< Item, CustomLess > SameGraphType; public: typedef std::set< Item, CustomLess> CsetVertexEdges; typedef std::set< Item* > CsetptrVertexEdges; typedef std::map< Item, CsetptrVertexEdges, CustomLess > CmapVertexEdgeList; typedef std::list< Item > ClistVertexEdges; TEdgeListGraph() : CAF_CM_INIT( "TEdgeListGraph" ) { } Item findVertex( const Item& crItemVertex ) const { return internalFindVertex(crItemVertex, _mapEdgeList); } bool isVertexInGraph( const Item& crItemVertex ) const { return internalIsVertexInGraph(crItemVertex, _mapEdgeList); } bool isEdgeInGraph(const Item& source, const Item& destination) const { return internalIsEdgeInGraph(source, destination, _mapEdgeList); } void addVertex( const Item& crItemVertex ) { internalAddVertex(crItemVertex, _mapEdgeList); } void removeVertices( const CsetVertexEdges& crsetParents) { internalRemoveVertices(crsetParents, _mapEdgeList); } void removeVertex( const Item& crItemVertex ) { return internalRemoveVertex(crItemVertex, _mapEdgeList); } void addEdge( const Item& crItemSource, const Item& crItemDestination ) { internalAddEdge(crItemSource, crItemDestination, _mapEdgeList); } void removeEdge( const Item& crItemSource, const Item& crItemDestination ) { internalRemoveEdge(crItemSource, crItemDestination, _mapEdgeList); } CsetVertexEdges getVertices() const { return internalGetVertices(_mapEdgeList); } uint32 getNumberVertices() const { return static_cast(_mapEdgeList.size()); } ////////////////////////////////////////////////////////////////////// // // getEdges() // // Does not recurse into the dependencies, returns the immediate items // that the item depends on. ////////////////////////////////////////////////////////////////////// CsetVertexEdges getEdges( const Item& crItemVertex ) const { return internalGetEdges(crItemVertex, _mapEdgeList); } ////////////////////////////////////////////////////////////////////// // // getParents() // // Returns the parents of a given vertex // ////////////////////////////////////////////////////////////////////// CsetVertexEdges getParents( const Item& crItemVertex ) const { return internalGetParents(crItemVertex, _mapEdgeList); } ////////////////////////////////////////////////////////////////////// // // getAllParents() // Returns a set of all the parents of a particular vertex // ////////////////////////////////////////////////////////////////////// CsetVertexEdges getAllParents( const Item& crItemVertex ) const { CsetVertexEdges oSetParents; // Get the Parents internalGetAllParents( crItemVertex, _mapEdgeList, oSetParents ); return oSetParents; } void copyGraph(SameGraphType& copy) const { internalCopyGraph(*this, copy); } ////////////////////////////////////////////////////////////////////// // // topologySort() // Returns a topology sort of the entire graph. // The returned list indicates vertices in sorted order // ////////////////////////////////////////////////////////////////////// // Kahn, A. B. (1962), "Topological sorting of large networks", Communications of the ACM 5 (11): 558�562 // // L <- Empty list that will contain the sorted elements // S <- Set of all nodes with no incoming edges // while S is non-empty do // remove a node n from S // insert n into L // for each node m with an edge e from n to m do // remove edge e from the graph // if m has no other incoming edges then // insert m into S // if graph has edges then // output error message (graph has at least one cycle) // else // output message (proposed topologically sorted order: L) ClistVertexEdges topologySort() const { CAF_CM_FUNCNAME("topologySort"); ClistVertexEdges sortedList; // Work with a temporary copy of the graph TEdgeListGraph graphCopy; internalCopyGraph(*this, graphCopy); CsetVertexEdges setNoParents; CsetVertexEdges vertices = graphCopy.getVertices(); for (typename CsetVertexEdges::const_iterator vertex = vertices.begin(); vertex != vertices.end(); ++vertex) { if (graphCopy.getParents(*vertex).size() == 0) { setNoParents.insert(*vertex); } } while (setNoParents.size()) { Item n = *(setNoParents.begin()); setNoParents.erase(setNoParents.begin()); sortedList.push_back(n); CsetVertexEdges edges = graphCopy.getEdges(n); for (typename CsetVertexEdges::const_iterator edge = edges.begin(); edge != edges.end(); ++edge) { graphCopy.removeEdge(n, *edge); bool edgeFound = false; CsetVertexEdges vertices = graphCopy.getVertices(); for (typename CsetVertexEdges::const_iterator vertex = vertices.begin(); !edgeFound && (vertex != vertices.end()); ++vertex) { edgeFound = graphCopy.isEdgeInGraph(*vertex, *edge); } if (!edgeFound) { setNoParents.insert(*edge); } } } // Cycle check vertices = graphCopy.getVertices(); for (typename CsetVertexEdges::const_iterator vertex = vertices.begin(); vertex != vertices.end(); ++vertex) { if (graphCopy.getEdges(*vertex).size()) { CAF_CM_EXCEPTION_VA0(ERROR_INVALID_STATE, "The graph has at least one cycle"); } } return sortedList; } private: Item internalFindVertex( const Item& crItemVertex, const CmapVertexEdgeList& graph ) const { Item FoundVertex; // Find the vertex typename CmapVertexEdgeList::const_iterator imapVertex = graph.find( crItemVertex ); if( imapVertex != graph.end() ) { FoundVertex = ( imapVertex->first ); } return FoundVertex; } bool internalIsVertexInGraph( const Item& crItemVertex, const CmapVertexEdgeList& graph ) const { bool bVertexIsInGraph = false; // Find the vertex typename CmapVertexEdgeList::const_iterator imapVertex = graph.find( crItemVertex ); if( imapVertex != graph.end() ) { bVertexIsInGraph = true; } return bVertexIsInGraph; } bool internalIsEdgeInGraph(const Item& source, const Item& destination, const CmapVertexEdgeList& graph) const { CsetVertexEdges edges = internalGetEdges(source, graph); return (edges.end() != edges.find(destination)); } void internalAddVertex( const Item& crItemVertex, CmapVertexEdgeList& graph ) { CAF_CM_FUNCNAME("internalAddVertex"); // Ensure that the Vertex doesn't already exist in the graph // we do not allow duplicate Vertices to exist. typename CmapVertexEdgeList::const_iterator imapEdgeList = graph.find( crItemVertex ); if ( graph.end() == imapEdgeList ) { graph.insert( std::make_pair( crItemVertex, CsetptrVertexEdges() ) ); } else { CAF_CM_EXCEPTION_VA0( ERROR_DUPLICATE_TAG, "Vertex already exists in the graph, cannot add duplicate Vertices"); } } void internalRemoveVertices( const CsetVertexEdges& crsetParents, CmapVertexEdgeList& graph) { for( typename CsetVertexEdges::const_iterator isetVertex = crsetParents.begin(); isetVertex != crsetParents.end(); ++isetVertex ) { internalRemoveVertex( *isetVertex, graph ); } } void internalRemoveVertex( const Item& crItemVertex, CmapVertexEdgeList& graph ) { CsetVertexEdges osetVerticesAffected; // Find the vertex typename CmapVertexEdgeList::iterator imapVertex = graph.find( crItemVertex ); if( imapVertex != graph.end() ) { // Get an Item pointer to the vertex that we wish to remove Item* pItem = const_cast( &( imapVertex->first ) ); // Iterate over each vertex removing each reference to the vertex being removed for( typename CmapVertexEdgeList::iterator imapEdgeList = graph.begin(); imapEdgeList != graph.end(); ++imapEdgeList ) { // Is the item in the edge list for the current vertex typename CsetptrVertexEdges::iterator isetVertex = imapEdgeList->second.find( pItem ); if( isetVertex != imapEdgeList->second.end() ) { // Remove the reference imapEdgeList->second.erase( isetVertex ); } } // We no longer need the Item pointer pItem = NULL; // Remove the vertex graph.erase( imapVertex ); } } void internalAddEdge( const Item& crItemSource, const Item& crItemDestination, CmapVertexEdgeList& graph ) { CAF_CM_FUNCNAME("internalAddEdge"); // Ensure that you are not trying to add a dependency to yourself if ( crItemSource == crItemDestination ) { CAF_CM_EXCEPTION_VA0( ERROR_INVALID_DATA, "Edges to yourself are not allowed, cannot add edge"); } // Ensure that there is a source vertex typename CmapVertexEdgeList::iterator imapSourceVertex = graph.find( crItemSource ); if( imapSourceVertex == graph.end() ) { CAF_CM_EXCEPTION_VA0( ERROR_TAG_NOT_FOUND, "Unable to find source vertex, cannot add edge"); } // Ensure that there is a destination vertex typename CmapVertexEdgeList::iterator imapDestinationVertex = graph.find( crItemDestination ); if( imapDestinationVertex == graph.end() ) { CAF_CM_EXCEPTION_VA0( ERROR_TAG_NOT_FOUND, "Unable to find destination vertex, cannot add edge"); } // Create the edge Item* pItem = const_cast( &( imapDestinationVertex->first ) ); imapSourceVertex->second.insert( pItem ); } void internalRemoveEdge( const Item& crItemSource, const Item& crItemDestination, CmapVertexEdgeList& graph ) { // Ensure that there is a source vertex typename CmapVertexEdgeList::iterator imapSourceVertex = graph.find( crItemSource ); if( imapSourceVertex != graph.end() ) { // Ensure that there is a destination vertex typename CmapVertexEdgeList::iterator imapDestinationVertex = graph.find( crItemDestination ); if( imapDestinationVertex != graph.end() ) { // Get a pointer to the edge Item* pItem = const_cast( &( imapDestinationVertex->first ) ); // remove the edge imapSourceVertex->second.erase( pItem ); } } } CsetVertexEdges internalGetVertices(const CmapVertexEdgeList& graph) const { CsetVertexEdges osetVertices; for( typename CmapVertexEdgeList::const_iterator imapEdgeList = graph.begin(); imapEdgeList != graph.end(); ++imapEdgeList ) { osetVertices.insert( imapEdgeList->first ); } return osetVertices; } CsetVertexEdges internalGetEdges( const Item& crItemVertex, const CmapVertexEdgeList& graph ) const { CAF_CM_FUNCNAME("getEdges"); CsetVertexEdges osetEdges; // Find the vertex typename CmapVertexEdgeList::const_iterator imapVertex = graph.find( crItemVertex ); if( imapVertex == graph.end() ) { CAF_CM_EXCEPTION_VA0( ERROR_TAG_NOT_FOUND, "Unable to find vertex. Cannot get edges"); } else { for( typename CsetptrVertexEdges::const_iterator isetEdge = imapVertex->second.begin(); isetEdge != imapVertex->second.end(); ++isetEdge ) { if( *isetEdge == NULL ) { CAF_CM_EXCEPTION_VA0( E_FAIL, "Invalid graph, an edge reported pointing to a invalid destination vertex"); } osetEdges.insert( **isetEdge ); } } return osetEdges; } CsetVertexEdges internalGetParents( const Item& crItemVertex, const CmapVertexEdgeList& graph) const { CsetVertexEdges oSetParents; // Find the vertex typename CmapVertexEdgeList::const_iterator cimapVertex = graph.find( crItemVertex ); if( cimapVertex != graph.end() ) { // Get an Item pointer to the vertex that we wish to get parents for Item* pItem = const_cast( &( cimapVertex->first ) ); // Iterate over each vertex in the graph for( typename CmapVertexEdgeList::const_iterator cimapEdgeList = graph.begin(); cimapEdgeList != graph.end(); ++cimapEdgeList ) { // Is the item in the edge list for the current vertex typename CsetptrVertexEdges::const_iterator cisetVertex = cimapEdgeList->second.find( pItem ); if( cisetVertex != cimapEdgeList->second.end() ) { // Add the vertex to the set of parents oSetParents.insert( cimapEdgeList->first ); } } // We no longer need the Item pointer pItem = NULL; } return oSetParents; } void internalGetAllParents( const Item& crItemVertex, const CmapVertexEdgeList& graph, CsetVertexEdges& roSetParents) const { // Find the vertex in the map typename CmapVertexEdgeList::const_iterator imapVertex = graph.find( crItemVertex ); if( imapVertex != graph.end() ) { // Get the parents of this vertex CsetVertexEdges setCurrentParents = internalGetParents( crItemVertex, graph ); // For each parent found that we have not recorded yet find its parents for( typename CsetVertexEdges::iterator isetCurrentParent = setCurrentParents.begin(); isetCurrentParent != setCurrentParents.end(); ++isetCurrentParent ) { // Have we recorded this current parent in the parent set? typename CsetVertexEdges::iterator isetIsCurrentParentRecorded = roSetParents.find( *isetCurrentParent ); if( isetIsCurrentParentRecorded == roSetParents.end() ) { // Since we have not recorded this vertex, record it and get its parents roSetParents.insert( *isetCurrentParent ); // Since we have not recorded this parent, record it and get its parents internalGetAllParents(*isetCurrentParent, graph, roSetParents ); } } } } void internalCopyGraph(const SameGraphType& source, SameGraphType& copy) const { CsetVertexEdges sourceVertices = source.getVertices(); for (typename CsetVertexEdges::const_iterator vertex = sourceVertices.begin(); vertex != sourceVertices.end(); ++vertex) { copy.addVertex(*vertex); } for (typename CsetVertexEdges::const_iterator vertex = sourceVertices.begin(); vertex != sourceVertices.end(); ++vertex) { CsetVertexEdges sourceEdges = source.getEdges(*vertex); for (typename CsetVertexEdges::const_iterator edge = sourceEdges.begin(); edge != sourceEdges.end(); ++edge) { copy.addEdge(*vertex, *edge); } } } CmapVertexEdgeList _mapEdgeList; CAF_CM_CREATE; }; #endif /* TEDGELISTGRAPH_H_ */ Iterators/000077500000000000000000000000001321503522500342405ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/CollectionsIteratorsInc.h000066400000000000000000000014401321503522500370160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef IteratorsInc_h_ #define IteratorsInc_h_ #include "TIterator.h" #include "TMapIterator.h" #include "TConstIterator.h" #include "TConstMapIterator.h" #include "TSmartIterator.h" #include "TSmartMapIterator.h" #include "TSmartConstIterator.h" #include "TSmartConstMapIterator.h" #include "TMultimapIterator.h" #include "TConstMultimapIterator.h" #include "TSmartMultimapIterator.h" #include "TSmartConstMultimapIterator.h" #endif // #ifndef IteratorsInc_h_ TConstIterator.h000066400000000000000000000041271321503522500373410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Purpose: Return a lightweight iterator for an arbitrary container. // The iterator moves in the forward direction only; once // it reaches the end you need a new one. I considered // adding m_citerBegin to allow for a Reset method, but // decided that it was better to have a "use once then // throw away" iterator to prevent the misuse of passing // the iterator around, possibly after the original // container has gone away. This way use of the iterator // is localized, much like the use of standard iterators. // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TConstIterator_h_ #define TConstIterator_h_ namespace Caf { template class TConstIterator { public: TConstIterator () { m_citerCurrent = m_citerEnd; } TConstIterator (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); } TConstIterator (const TConstIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; } TConstIterator &operator= (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); return *this; } TConstIterator &operator= (const TConstIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; return *this; } public: const ValueType &operator* () { return *m_citerCurrent; } const ValueType *operator-> () { return m_citerCurrent.operator->(); } void operator++ () { ++m_citerCurrent; } void operator++ (int32) { m_citerCurrent++; } operator bool () { return m_citerCurrent != m_citerEnd; } private: typename Container::const_iterator m_citerCurrent; typename Container::const_iterator m_citerEnd; }; } #endif // #ifndef TConstIterator_h_ TConstMapIterator.h000066400000000000000000000034631321503522500400010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TConstMapIterator_h_ #define TConstMapIterator_h_ namespace Caf { template class TConstMultimapIterator; template class TConstMapIterator { public: TConstMapIterator () { m_citerCurrent = m_citerEnd; } TConstMapIterator (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); } TConstMapIterator (const TConstMapIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; } TConstMapIterator &operator= (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); return *this; } TConstMapIterator &operator= (const TConstMapIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; return *this; } public: const ValueType &operator* () { return m_citerCurrent->second; } const ValueType *operator-> () { return &m_citerCurrent->second; } void operator++ () { ++m_citerCurrent; } void operator++ (int32) { m_citerCurrent++; } const KeyType &getKey (void) { return m_citerCurrent->first; } operator bool () { return m_citerCurrent != m_citerEnd; } private: typename Container::const_iterator m_citerCurrent; typename Container::const_iterator m_citerEnd; }; } #endif // #ifndef TConstMapIterator_h_ TConstMultimapIterator.h000066400000000000000000000031431321503522500410470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TCONSTMULTIMAPITERATOR_H_ #define TCONSTMULTIMAPITERATOR_H_ namespace Caf { template class TConstMultimapIterator { public: TConstMultimapIterator () { m_citerCurrent = m_citerEnd; } TConstMultimapIterator (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); } TConstMultimapIterator (const TConstMultimapIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; } TConstMultimapIterator &operator= (const TConstMultimapIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; return *this; } public: const KeyType &getKey (void) { return m_citerCurrent->first; } const ValueType &operator* () { return m_citerCurrent->second; } const ValueType *operator-> () { return &m_citerCurrent->second; } void operator++ () { ++m_citerCurrent; } void operator++ (int32) { m_citerCurrent++; } operator bool () { return (m_citerCurrent != m_citerEnd); } private: typename Container::const_iterator m_citerCurrent; typename Container::const_iterator m_citerEnd; }; } #endif // #ifdef TCONSTMULTIMAPITERATOR_H_ TIterator.h000066400000000000000000000027031321503522500363300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TIterator_h_ #define TIterator_h_ namespace Caf { template class TIterator { public: TIterator () { m_iterCurrent = m_iterEnd; } TIterator (Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); } TIterator (const TIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; } TIterator &operator= (const Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); return *this; } TIterator &operator= (const TIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; return *this; } public: ValueType &operator* () { return *m_iterCurrent; } ValueType *operator-> () { return m_iterCurrent.operator->(); } void operator++ () { ++m_iterCurrent; } void operator++ (int32) { m_iterCurrent++; } operator bool () { return m_iterCurrent != m_iterEnd; } private: typename Container::iterator m_iterCurrent; typename Container::iterator m_iterEnd; }; } #endif // #ifndef TIterator_h_ TMapIterator.h000066400000000000000000000032731321503522500367710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TMapIterator_h_ #define TMapIterator_h_ namespace Caf { template class TMultimapIterator; template class TMapIterator { public: TMapIterator () { m_iterCurrent = m_iterEnd; } TMapIterator (Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); } TMapIterator (const TMapIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; } TMapIterator &operator= (const Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); return *this; } TMapIterator &operator= (const TMapIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; return *this; } public: ValueType &operator* () { return m_iterCurrent->second; } ValueType *operator-> () { return &m_iterCurrent->second; } void operator++ () { ++m_iterCurrent; } void operator++ (int32) { m_iterCurrent++; } const KeyType &getKey (void) { return m_iterCurrent->first; } operator bool () { return m_iterCurrent != m_iterEnd; } private: typename Container::iterator m_iterCurrent; typename Container::iterator m_iterEnd; }; } #endif // #ifndef TMapIterator_h_ TMultimapIterator.h000066400000000000000000000027671321503522500400530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TMULTIMAPITERATOR_H_ #define TMULTIMAPITERATOR_H_ namespace Caf { template class TMultimapIterator { public: TMultimapIterator () { m_iterCurrent = m_iterEnd; } TMultimapIterator (Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); } TMultimapIterator (const TMultimapIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; } TMultimapIterator &operator= (const TMultimapIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; return *this; } public: const KeyType &getKey (void) { return m_iterCurrent->first; } ValueType &operator* () { return m_iterCurrent->second; } ValueType *operator-> () { return &m_iterCurrent->second; } void operator++ () { ++m_iterCurrent; } void operator++ (int32) { m_iterCurrent++; } operator bool () { return (m_iterCurrent != m_iterEnd); } private: typename Container::iterator m_iterCurrent; typename Container::iterator m_iterEnd; }; } #endif /* TMULTIMAPITERATOR_H_ */ TSmartConstIterator.h000066400000000000000000000035431321503522500403510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Purpose: Variant of TConstIterator that deals with smart pointers // transparently when the arrow operator is used. ONLY works with // containers that hold smart pointers. // // Created: 10/22/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TSmartConstIterator_h_ #define TSmartConstIterator_h_ namespace Caf { template class TSmartConstIterator { public: TSmartConstIterator () { m_citerCurrent = m_citerEnd; } TSmartConstIterator (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); } TSmartConstIterator (const TSmartConstIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; } TSmartConstIterator &operator= (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); return *this; } TSmartConstIterator &operator= (const TSmartConstIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; return *this; } public: const SmartPtrType &operator* () { return *m_citerCurrent; } const ValueType *operator-> () { return m_citerCurrent->operator->(); } void operator++ () { ++m_citerCurrent; } void operator++ (int32) { m_citerCurrent++; } operator bool () { return m_citerCurrent != m_citerEnd; } private: typename Container::const_iterator m_citerCurrent; typename Container::const_iterator m_citerEnd; }; } #endif // #ifndef TSmartConstIterator_h_ TSmartConstMapIterator.h000066400000000000000000000037161321503522500410110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/22/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TSmartConstMapIterator_h_ #define TSmartConstMapIterator_h_ namespace Caf { template class TSmartConstMultimapIterator; template class TSmartConstMapIterator { public: TSmartConstMapIterator () { m_citerCurrent = m_citerEnd; } TSmartConstMapIterator (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); } TSmartConstMapIterator (const TSmartConstMapIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; } TSmartConstMapIterator &operator= (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); return *this; } TSmartConstMapIterator &operator= (const TSmartConstMapIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; return *this; } public: const SmartPtrType &operator* () { return m_citerCurrent->second; } const ValueType *operator-> () { return m_citerCurrent->second.operator->(); } void operator++ () { ++m_citerCurrent; } void operator++ (int32) { m_citerCurrent++; } const KeyType &getKey (void) { return m_citerCurrent->first; } operator bool () { return m_citerCurrent != m_citerEnd; } private: typename Container::const_iterator m_citerCurrent; typename Container::const_iterator m_citerEnd; }; } #endif // #ifndef TSmartConstMapIterator_h_ TSmartConstMultimapIterator.h000066400000000000000000000033341321503522500420600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TSMARTCONSTMULTIMAPITERATOR_H_ #define TSMARTCONSTMULTIMAPITERATOR_H_ namespace Caf { template class TSmartConstMultimapIterator { public: TSmartConstMultimapIterator () { m_citerCurrent = m_citerEnd; } TSmartConstMultimapIterator (const Container &rcContainer) { m_citerCurrent = rcContainer.begin(); m_citerEnd = rcContainer.end(); } TSmartConstMultimapIterator (const TSmartConstMultimapIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; } TSmartConstMultimapIterator &operator= (const TSmartConstMultimapIterator &rhs) { m_citerCurrent = rhs.m_citerCurrent; m_citerEnd = rhs.m_citerEnd; return *this; } public: const KeyType &getKey (void) { return m_citerCurrent->first; } const SmartPtrType &operator* () { return m_citerCurrent->second; } const ValueType *operator-> () { return m_citerCurrent->second.operator->(); } void operator++ () { ++m_citerCurrent; } void operator++ (int32) { m_citerCurrent++; } operator bool () { return (m_citerCurrent != m_citerEnd); } private: typename Container::const_iterator m_citerCurrent; typename Container::const_iterator m_citerEnd; }; } #endif /* TSMARTCONSTMULTIMAPITERATOR_H_ */ TSmartIterator.h000066400000000000000000000030711321503522500373360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TSmartIterator_h_ #define TSmartIterator_h_ namespace Caf { template class TSmartIterator { public: TSmartIterator () { m_iterCurrent = m_iterEnd; } TSmartIterator (Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); } TSmartIterator (const TSmartIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; } TSmartIterator &operator= (const Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); return *this; } TSmartIterator &operator= (const TSmartIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; return *this; } public: SmartPtrType &operator* () { return *m_iterCurrent; } ValueType *operator-> () { return m_iterCurrent->operator->(); } void operator++ () { ++m_iterCurrent; } void operator++ (int32) { m_iterCurrent++; } operator bool () { return m_iterCurrent != m_iterEnd; } private: typename Container::iterator m_iterCurrent; typename Container::iterator m_iterEnd; }; } #endif // #ifndef TSmartIterator_h_ TSmartMapIterator.h000066400000000000000000000035301321503522500377740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TSmartMapIterator_h_ #define TSmartMapIterator_h_ namespace Caf { template class TSmartMultimapIterator; template class TSmartMapIterator { public: TSmartMapIterator () { m_iterCurrent = m_iterEnd; } TSmartMapIterator (Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); } TSmartMapIterator (const TSmartMapIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; } TSmartMapIterator &operator= (const Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); return *this; } TSmartMapIterator &operator= (const TSmartMapIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; return *this; } public: SmartPtrType &operator* () { return m_iterCurrent->second; } ValueType *operator-> () { return m_iterCurrent->second.operator->(); } void operator++ () { ++m_iterCurrent; } void operator++ (int32) { m_iterCurrent++; } const KeyType &getKey (void) { return m_iterCurrent->first; } operator bool () { return m_iterCurrent != m_iterEnd; } private: typename Container::iterator m_iterCurrent; typename Container::iterator m_iterEnd; }; } #endif // #ifndef TSmartMapIterator_h_ TSmartMultimapIterator.h000066400000000000000000000031641321503522500410520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Collections/Iterators///////////////////////////////////////////////////////////////////////////// // // Author: J.P. Grossman // // Created: 10/16/2003 // // Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential // -- VMware Confidential // ///////////////////////////////////////////////////////////////////////////// #ifndef TSMARTMULTIMAPITERATOR_H_ #define TSMARTMULTIMAPITERATOR_H_ namespace Caf { template class TSmartMultimapIterator { public: TSmartMultimapIterator () { m_iterCurrent = m_iterEnd; } TSmartMultimapIterator (Container &rContainer) { m_iterCurrent = rContainer.begin(); m_iterEnd = rContainer.end(); } TSmartMultimapIterator (const TSmartMultimapIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; } TSmartMultimapIterator &operator= (const TSmartMultimapIterator &rhs) { m_iterCurrent = rhs.m_iterCurrent; m_iterEnd = rhs.m_iterEnd; return *this; } public: const KeyType &getKey (void) { return m_iterCurrent->first; } SmartPtrType &operator* () { return m_iterCurrent->second; } ValueType *operator-> () { return m_iterCurrent->second.operator->(); } void operator++ () { ++m_iterCurrent; } void operator++ (int32) { m_iterCurrent++; } operator bool () { return (m_iterCurrent != m_iterEnd); } private: typename Container::iterator m_iterCurrent; typename Container::iterator m_iterEnd; }; } #endif /* TSMARTMULTIMAPITERATOR_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/000077500000000000000000000000001321503522500313155ustar00rootroot00000000000000AppConfigUtils.cpp000066400000000000000000000071041321503522500346330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppConfig.h" #include "AppConfigUtils.h" using namespace Caf; std::string AppConfigUtils::getRequiredString( const std::string& parameterName) { std::string rc; getAppConfig()->getGlobalString(parameterName, rc, IConfigParams::PARAM_REQUIRED); return rc; } uint32 AppConfigUtils::getRequiredUint32( const std::string& parameterName) { uint32 rc; getAppConfig()->getGlobalUint32(parameterName, rc, IConfigParams::PARAM_REQUIRED); return rc; } int32 AppConfigUtils::getRequiredInt32( const std::string& parameterName) { int32 rc; getAppConfig()->getGlobalInt32(parameterName, rc, IConfigParams::PARAM_REQUIRED); return rc; } bool AppConfigUtils::getRequiredBoolean( const std::string& parameterName) { bool rc; getAppConfig()->getGlobalBoolean(parameterName, rc, IConfigParams::PARAM_REQUIRED); return rc; } std::string AppConfigUtils::getOptionalString( const std::string& parameterName) { std::string rc; getAppConfig()->getGlobalString(parameterName, rc, IConfigParams::PARAM_OPTIONAL); return rc; } uint32 AppConfigUtils::getOptionalUint32( const std::string& parameterName) { uint32 rc = 0; getAppConfig()->getGlobalUint32(parameterName, rc, IConfigParams::PARAM_OPTIONAL); return rc; } int32 AppConfigUtils::getOptionalInt32( const std::string& parameterName) { int32 rc = 0; getAppConfig()->getGlobalInt32(parameterName, rc, IConfigParams::PARAM_OPTIONAL); return rc; } bool AppConfigUtils::getOptionalBoolean( const std::string& parameterName) { bool rc = false; getAppConfig()->getGlobalBoolean(parameterName, rc, IConfigParams::PARAM_OPTIONAL); return rc; } std::string AppConfigUtils::getRequiredString( const std::string& sectionName, const std::string& parameterName) { std::string rc; getAppConfig()->getString(sectionName, parameterName, rc, IConfigParams::PARAM_REQUIRED); return rc; } uint32 AppConfigUtils::getRequiredUint32( const std::string& sectionName, const std::string& parameterName) { uint32 rc; getAppConfig()->getUint32(sectionName, parameterName, rc, IConfigParams::PARAM_REQUIRED); return rc; } int32 AppConfigUtils::getRequiredInt32( const std::string& sectionName, const std::string& parameterName) { int32 rc; getAppConfig()->getInt32(sectionName, parameterName, rc, IConfigParams::PARAM_REQUIRED); return rc; } bool AppConfigUtils::getRequiredBoolean( const std::string& sectionName, const std::string& parameterName) { bool rc; getAppConfig()->getBoolean(sectionName, parameterName, rc, IConfigParams::PARAM_REQUIRED); return rc; } std::string AppConfigUtils::getOptionalString( const std::string& sectionName, const std::string& parameterName) { std::string rc; getAppConfig()->getString(sectionName, parameterName, rc, IConfigParams::PARAM_OPTIONAL); return rc; } uint32 AppConfigUtils::getOptionalUint32( const std::string& sectionName, const std::string& parameterName) { uint32 rc = 0; getAppConfig()->getUint32(sectionName, parameterName, rc, IConfigParams::PARAM_OPTIONAL); return rc; } int32 AppConfigUtils::getOptionalInt32( const std::string& sectionName, const std::string& parameterName) { int32 rc = 0; getAppConfig()->getInt32(sectionName, parameterName, rc, IConfigParams::PARAM_OPTIONAL); return rc; } bool AppConfigUtils::getOptionalBoolean( const std::string& sectionName, const std::string& parameterName) { bool rc = false; getAppConfig()->getBoolean(sectionName, parameterName, rc, IConfigParams::PARAM_OPTIONAL); return rc; } AppConfigUtils.h000066400000000000000000000036531321503522500343050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef AppConfigUtils_H_ #define AppConfigUtils_H_ namespace Caf { namespace AppConfigUtils { std::string COMMONAGGREGATOR_LINKAGE getRequiredString(const std::string& parameterName); uint32 COMMONAGGREGATOR_LINKAGE getRequiredUint32(const std::string& parameterName); int32 COMMONAGGREGATOR_LINKAGE getRequiredInt32(const std::string& parameterName); bool COMMONAGGREGATOR_LINKAGE getRequiredBoolean(const std::string& parameterName); std::string COMMONAGGREGATOR_LINKAGE getOptionalString(const std::string& parameterName); uint32 COMMONAGGREGATOR_LINKAGE getOptionalUint32(const std::string& parameterName); int32 COMMONAGGREGATOR_LINKAGE getOptionalInt32(const std::string& parameterName); bool COMMONAGGREGATOR_LINKAGE getOptionalBoolean(const std::string& parameterName); std::string COMMONAGGREGATOR_LINKAGE getRequiredString( const std::string& sectionName, const std::string& parameterName); uint32 COMMONAGGREGATOR_LINKAGE getRequiredUint32( const std::string& sectionName, const std::string& parameterName); int32 COMMONAGGREGATOR_LINKAGE getRequiredInt32( const std::string& sectionName, const std::string& parameterName); bool COMMONAGGREGATOR_LINKAGE getRequiredBoolean( const std::string& sectionName, const std::string& parameterName); std::string COMMONAGGREGATOR_LINKAGE getOptionalString( const std::string& sectionName, const std::string& parameterName); uint32 COMMONAGGREGATOR_LINKAGE getOptionalUint32( const std::string& sectionName, const std::string& parameterName); int32 COMMONAGGREGATOR_LINKAGE getOptionalInt32( const std::string& sectionName, const std::string& parameterName); bool COMMONAGGREGATOR_LINKAGE getOptionalBoolean( const std::string& sectionName, const std::string& parameterName); }; } #endif /* AppConfigUtils_H_ */ CAppConfig.cpp000066400000000000000000000702001321503522500337120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 19, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CConfigParams.h" #include "Common/CLoggingUtils.h" #include "Exception/CCafException.h" #include "Common/IAppConfigWrite.h" #include "Common/IAppConfig.h" #include "Common/IConfigParams.h" #include "CAppConfig.h" using namespace Caf; SmartPtrIAppConfig Caf::getAppConfig() { return CAppConfig::getInstance(); } SmartPtrIAppConfig Caf::getAppConfig(const std::string& configFile) { return CAppConfig::getInstance(configFile); } SmartPtrIAppConfig Caf::getAppConfig(const Cdeqstr& configFileCollection) { return CAppConfig::getInstance(configFileCollection); } SmartPtrIAppConfig Caf::getAppConfigAppend(const std::string& configFile) { return CAppConfig::getInstanceAppend(configFile); } SmartPtrIAppConfig Caf::getAppConfigAppend(const Cdeqstr& configFileCollection) { return CAppConfig::getInstanceAppend(configFileCollection); } SmartPtrIAppConfigWrite Caf::getAppConfigWrite() { return CAppConfig::getInstanceWrite(); } SmartPtrIAppConfigWrite Caf::getAppConfigWrite(const std::string& configFile) { return CAppConfig::getInstanceWrite(configFile); } SmartPtrIAppConfigWrite Caf::getAppConfigWrite(const Cdeqstr& configFileCollection) { return CAppConfig::getInstanceWrite(configFileCollection); } const char* CAppConfig::_sGlobalsSectionName = "globals"; GRecMutex CAppConfig::_sOpMutex; SmartPtrCAppConfig CAppConfig::_sInstance; CAppConfig::CAppConfig() : _isInitialized(false), _envPattern(NULL), _varPattern(NULL), CAF_CM_INIT("CAppConfig") { } CAppConfig::~CAppConfig() { for (CGlobalReplacements::iterator iter = _globalReplacements.begin(); iter != _globalReplacements.end(); ++iter) { g_regex_unref(iter->first); } if (_envPattern) { g_regex_unref(_envPattern); } if (_varPattern) { g_regex_unref(_varPattern); } } void CAppConfig::initialize() { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAutoMutexLockUnlockRaw oLock(&_sOpMutex); std::string appConfigEnv; CEnvironmentUtils::readEnvironmentVar("CAF_APPCONFIG", appConfigEnv); if (appConfigEnv.empty()) { CAF_CM_EXCEPTION_VA0(ERROR_TAG_NOT_FOUND, "CAF_APPCONFIG env var isn't set."); } const Cdeqstr configFileCollection = CStringUtils::split(appConfigEnv, ';'); initialize(configFileCollection); } void CAppConfig::initialize(const std::string& configFile) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(configFile); Cdeqstr configFileCollection; configFileCollection.push_back(configFile); initialize(configFileCollection); } void CAppConfig::initialize(const Cdeqstr& configFileCollection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL(configFileCollection); CAutoMutexLockUnlockRaw oLock(&_sOpMutex); for (TConstIterator strIter(configFileCollection); strIter; strIter++) { const std::string configFile = *strIter; const std::string configPath = calcConfigPath(configFile); if (! configPath.empty()) { _configFileCollection.push_back(configPath); } } // Add a pattern for environment variable lookup _envPattern = g_regex_new( "\\$\\{env\\:(.+)\\}", (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_UNGREEDY | G_REGEX_RAW), (GRegexMatchFlags)0, NULL); _varPattern = g_regex_new( "\\$\\{var\\:(.+)\\}", (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_UNGREEDY | G_REGEX_RAW), (GRegexMatchFlags)0, NULL); _globals = internalLoadParameters(_sGlobalsSectionName); validateGlobals(_globals); _isInitialized = true; } void CAppConfig::append(const std::string& configFile) { CAF_CM_FUNCNAME_VALIDATE("append"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(configFile); Cdeqstr configFileCollection; configFileCollection.push_back(configFile); append(configFileCollection); } void CAppConfig::append(const Cdeqstr& configFileCollection) { CAF_CM_FUNCNAME_VALIDATE("append"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL(configFileCollection); CAutoMutexLockUnlockRaw oLock(&_sOpMutex); for (TConstIterator strIter(configFileCollection); strIter; strIter++) { const std::string configFile = *strIter; const std::string configPath = calcConfigPath(configFile); if (! configPath.empty()) { _configFileCollection.push_back(configPath); } } } SmartPtrIConfigParams CAppConfig::getParameters(const std::string& sectionName) { CAF_CM_FUNCNAME_VALIDATE("getParameters"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); SmartPtrIConfigParams params; CAutoMutexLockUnlockRaw oLock(&_sOpMutex); CParamSections::const_iterator cachedSection = _cachedSections.find(sectionName); if (_cachedSections.end() == cachedSection) { if (::strcmp(sectionName.c_str(), _sGlobalsSectionName) == 0) { params = _globals; } else { params = internalLoadParameters(sectionName); _cachedSections.insert(CParamSections::value_type(sectionName, params)); } } else { params = cachedSection->second; } return params; } bool CAppConfig::getString( const std::string& sectionName, const std::string& parameterName, std::string& value, const IConfigParams::EParamDisposition disposition) { CAF_CM_FUNCNAME("getString"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(parameterName); bool paramFound = false; SmartPtrIConfigParams params = getParameters(sectionName); GVariant* param = params->lookup( parameterName.c_str(), IConfigParams::PARAM_OPTIONAL); if (param) { if (g_variant_is_of_type(param, G_VARIANT_TYPE_STRING)) { value = g_variant_get_string(param, NULL); paramFound = true; } else { CAF_CM_EXCEPTION_VA1(DISP_E_TYPEMISMATCH, "%s exists but is not a string.", parameterName.c_str()); } } else { if (IConfigParams::PARAM_REQUIRED == disposition) { CAF_CM_EXCEPTION_VA2(ERROR_TAG_NOT_FOUND, "Required config parameter [%s] is missing from section [%s]", parameterName.c_str(), sectionName.c_str()); } } return paramFound; } bool CAppConfig::getUint32( const std::string& sectionName, const std::string& parameterName, uint32& value, const IConfigParams::EParamDisposition disposition) { CAF_CM_FUNCNAME("getUint32"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(parameterName); bool paramFound = false; SmartPtrIConfigParams params = getParameters(sectionName); GVariant* param = params->lookup( parameterName.c_str(), IConfigParams::PARAM_OPTIONAL); if (param) { if (g_variant_is_of_type(param, G_VARIANT_TYPE_INT32)) { value = static_cast(g_variant_get_int32(param)); paramFound = true; } else { std::string valueStr; getString(sectionName, parameterName, valueStr, disposition); value = CStringConv::fromString(valueStr); } } else { if (IConfigParams::PARAM_REQUIRED == disposition) { CAF_CM_EXCEPTION_VA2(ERROR_TAG_NOT_FOUND, "Required config parameter [%s] is missing from section [%s]", parameterName.c_str(), sectionName.c_str()); } } return paramFound; } bool CAppConfig::getInt32( const std::string& sectionName, const std::string& parameterName, int32& value, const IConfigParams::EParamDisposition disposition) { CAF_CM_FUNCNAME("getInt32"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(parameterName); bool paramFound = false; SmartPtrIConfigParams params = getParameters(sectionName); GVariant* param = params->lookup( parameterName.c_str(), IConfigParams::PARAM_OPTIONAL); if (param) { if (g_variant_is_of_type(param, G_VARIANT_TYPE_INT32)) { value = g_variant_get_int32(param); paramFound = true; } else { std::string valueStr; getString(sectionName, parameterName, valueStr, disposition); value = CStringConv::fromString(valueStr); } } else { if (IConfigParams::PARAM_REQUIRED == disposition) { CAF_CM_EXCEPTION_VA2(ERROR_TAG_NOT_FOUND, "Required config parameter [%s] is missing from section [%s]", parameterName.c_str(), sectionName.c_str()); } } return paramFound; } bool CAppConfig::getBoolean( const std::string& sectionName, const std::string& parameterName, bool& value, const IConfigParams::EParamDisposition disposition) { CAF_CM_FUNCNAME("getBoolean"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(parameterName); value = false; std::string tmpValue; bool paramFound = getString( sectionName, parameterName, tmpValue, IConfigParams::PARAM_OPTIONAL); if (paramFound) { if ("true" == tmpValue) { value = true; } else if ("false" == tmpValue) { value = false; } else { CAF_CM_EXCEPTION_VA1(DISP_E_TYPEMISMATCH, "%s exists but is not a boolean (true or false).", parameterName.c_str()); } } else { if (IConfigParams::PARAM_REQUIRED == disposition) { CAF_CM_EXCEPTION_VA2(ERROR_TAG_NOT_FOUND, "Required config parameter [%s] is missing from section [%s]", parameterName.c_str(), sectionName.c_str()); } } return paramFound; } bool CAppConfig::getGlobalString( const std::string& parameterName, std::string& value, const IConfigParams::EParamDisposition disposition) { return getString(_sGlobalsSectionName, parameterName, value, disposition); } bool CAppConfig::getGlobalUint32( const std::string& parameterName, uint32& value, const IConfigParams::EParamDisposition disposition) { return getUint32(_sGlobalsSectionName, parameterName, value, disposition); } bool CAppConfig::getGlobalInt32( const std::string& parameterName, int32& value, const IConfigParams::EParamDisposition disposition) { return getInt32(_sGlobalsSectionName, parameterName, value, disposition); } bool CAppConfig::getGlobalBoolean( const std::string& parameterName, bool& value, const IConfigParams::EParamDisposition disposition) { return getBoolean(_sGlobalsSectionName, parameterName, value, disposition); } void CAppConfig::setString( const std::string& sectionName, const std::string& parameterName, const std::string& value) { CAF_CM_FUNCNAME_VALIDATE("setString"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_STRING(value); SmartPtrIConfigParams params = getParameters(sectionName); params->insert(g_strdup(parameterName.c_str()), g_variant_new_string( value.c_str())); } void CAppConfig::setUint32( const std::string& sectionName, const std::string& parameterName, const uint32& value) { CAF_CM_FUNCNAME_VALIDATE("setUint32"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(parameterName); SmartPtrIConfigParams params = getParameters(sectionName); params->insert(g_strdup(parameterName.c_str()), g_variant_new_int32( value)); } void CAppConfig::setInt32( const std::string& sectionName, const std::string& parameterName, const int32& value) { CAF_CM_FUNCNAME_VALIDATE("setInt32"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(parameterName); SmartPtrIConfigParams params = getParameters(sectionName); params->insert(g_strdup(parameterName.c_str()), g_variant_new_int32( value)); } void CAppConfig::setBoolean( const std::string& sectionName, const std::string& parameterName, const bool& value) { CAF_CM_FUNCNAME_VALIDATE("setBoolean"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(parameterName); SmartPtrIConfigParams params = getParameters(sectionName); params->insert(g_strdup(parameterName.c_str()), g_variant_new_boolean( value)); } void CAppConfig::setGlobalString( const std::string& parameterName, const std::string& value) { setString(_sGlobalsSectionName, parameterName, value); } void CAppConfig::setGlobalUint32( const std::string& parameterName, const uint32& value) { setUint32(_sGlobalsSectionName, parameterName, value); } void CAppConfig::setGlobalInt32( const std::string& parameterName, const int32& value) { setInt32(_sGlobalsSectionName, parameterName, value); } void CAppConfig::setGlobalBoolean( const std::string& parameterName, const bool& value) { setBoolean(_sGlobalsSectionName, parameterName, value); } std::string CAppConfig::resolveValue(const std::string& value) { CAF_CM_FUNCNAME("resolveValue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rc = value; GMatchInfo *matchInfo = NULL; GError* error = NULL; try { if (value.length()) { gchar *match = NULL; if (g_regex_match( _varPattern, rc.c_str(), G_REGEX_MATCH_NOTBOL, &matchInfo)) { match = g_match_info_fetch(matchInfo, 1); CAF_CM_VALIDATE_STRINGPTRA(match); std::string varName(match); g_free(match); match = NULL; size_t pos = varName.find(':', 4); std::string section = _sGlobalsSectionName; if (pos != std::string::npos) { section = varName.substr(0, pos); varName = varName.substr(pos + 1, varName.length() - pos - 1); } std::string configVal; bool resolved = false; // one of these will work - the other two will fail try { getString( section, varName, configVal, IConfigParams::PARAM_REQUIRED); resolved = true; } catch (CCafException *ex) { if (ex->getError() == DISP_E_TYPEMISMATCH) { ex->Release(); } else { throw ex; } } if (!resolved) { try { int32 uval = 0; getInt32( section, varName, uval, IConfigParams::PARAM_REQUIRED); configVal = CStringConv::toString(uval); resolved = true; } catch (CCafException *ex) { if (ex->getError() == DISP_E_TYPEMISMATCH) { ex->Release(); } else { throw ex; } } } if (!resolved) { try { bool bval = false; getBoolean( section, varName, bval, IConfigParams::PARAM_REQUIRED); configVal = bval ? "true" : "false"; resolved = true; } catch (CCafException *ex) { if (ex->getError() == DISP_E_TYPEMISMATCH) { ex->Release(); } else { throw ex; } } } if (!resolved) { CAF_CM_EXCEPTION_VA1( ERROR_INVALID_DATA, "Unable to resolve %s", value.c_str()); } gchar *replaced = g_regex_replace_literal( _varPattern, rc.c_str(), -1, 0, configVal.c_str(), G_REGEX_MATCH_NOTBOL, &error); if (error) { throw error; } rc = replaced; g_free(replaced); } g_match_info_free(matchInfo); matchInfo = NULL; if (g_regex_match( _envPattern, rc.c_str(), G_REGEX_MATCH_NOTBOL, &matchInfo)) { match = g_match_info_fetch(matchInfo, 1); CAF_CM_VALIDATE_STRINGPTRA(match); std::string envVarName(match); g_free(match); match = NULL; #ifdef WIN32 char* dupbuf = NULL; size_t duplen = 0; errno_t duprc = ::_dupenv_s(&dupbuf, &duplen, envVarName.c_str()); const std::string dupval(dupbuf && ::strlen(dupbuf) ? dupbuf : ""); ::free(dupbuf); dupbuf = NULL; const char* envVarValue = dupval.c_str(); #else const char* envVarValue = ::getenv(envVarName.c_str()); #endif if (envVarValue && ::strlen(envVarValue)) { gchar* replaced = g_regex_replace_literal( _envPattern, rc.c_str(), -1, 0, envVarValue, G_REGEX_MATCH_NOTBOL, &error); if (error) { throw error; } rc = replaced; g_free(replaced); } else { CAF_CM_EXCEPTION_VA1( ERROR_TAG_NOT_FOUND, "Referenced environment variable is not set: %s", envVarName.c_str()); } } g_match_info_free(matchInfo); matchInfo = NULL; } } CAF_CM_CATCH_ALL; if (matchInfo) { g_match_info_free(matchInfo); } CAF_CM_THROWEXCEPTION; return rc; } SmartPtrIAppConfig CAppConfig::getInstance() { CAutoMutexLockUnlockRaw oLock(&_sOpMutex); if (!_sInstance) { SmartPtrCAppConfig appConfig; appConfig.CreateInstance(); appConfig->initialize(); _sInstance = appConfig; } return _sInstance; } SmartPtrIAppConfig CAppConfig::getInstance(const std::string& configFile) { CAutoMutexLockUnlockRaw oLock(&_sOpMutex); _sInstance = NULL; SmartPtrCAppConfig appConfig; appConfig.CreateInstance(); appConfig->initialize(configFile); _sInstance = appConfig; return _sInstance; } SmartPtrIAppConfig CAppConfig::getInstance(const Cdeqstr& configFileCollection) { CAutoMutexLockUnlockRaw oLock(&_sOpMutex); _sInstance = NULL; SmartPtrCAppConfig appConfig; appConfig.CreateInstance(); appConfig->initialize(configFileCollection); _sInstance = appConfig; return _sInstance; } SmartPtrIAppConfig CAppConfig::getInstanceAppend( const std::string& configFile) { CAF_CM_STATIC_FUNC_VALIDATE("CAppConfig", "getInstanceAppend"); CAutoMutexLockUnlockRaw oLock(&_sOpMutex); CAF_CM_VALIDATE_SMARTPTR(_sInstance); _sInstance->append(configFile); return _sInstance; } SmartPtrIAppConfig CAppConfig::getInstanceAppend( const Cdeqstr& configFileCollection) { CAF_CM_STATIC_FUNC_VALIDATE("CAppConfig", "getInstanceAppend"); CAutoMutexLockUnlockRaw oLock(&_sOpMutex); CAF_CM_VALIDATE_SMARTPTR(_sInstance); _sInstance->append(configFileCollection); return _sInstance; } SmartPtrIAppConfigWrite CAppConfig::getInstanceWrite() { CAutoMutexLockUnlockRaw oLock(&_sOpMutex); if (!_sInstance) { SmartPtrCAppConfig appConfig; appConfig.CreateInstance(); appConfig->initialize(); _sInstance = appConfig; } return _sInstance; } SmartPtrIAppConfigWrite CAppConfig::getInstanceWrite(const std::string& configFile) { CAutoMutexLockUnlockRaw oLock(&_sOpMutex); _sInstance = NULL; SmartPtrCAppConfig appConfig; appConfig.CreateInstance(); appConfig->initialize(configFile); _sInstance = appConfig; return _sInstance; } SmartPtrIAppConfigWrite CAppConfig::getInstanceWrite(const Cdeqstr& configFileCollection) { CAutoMutexLockUnlockRaw oLock(&_sOpMutex); _sInstance = NULL; SmartPtrCAppConfig appConfig; appConfig.CreateInstance(); appConfig->initialize(configFileCollection); _sInstance = appConfig; return _sInstance; } SmartPtrIConfigParams CAppConfig::internalLoadParameters(const std::string& sectionName) { CAF_CM_FUNCNAME_VALIDATE("internalLoadParameters"); CAF_CM_VALIDATE_STRING(sectionName); // Always return at least an empty collection SmartPtrCConfigParams configParams; configParams.CreateInstance(); configParams->initialize( sectionName, CConfigParams::EKeysManaged, CConfigParams::EValuesManaged); for (TConstIterator strIter(_configFileCollection); strIter; strIter++) { const std::string configFile = *strIter; internalLoadParameters(sectionName, configFile, configParams); } return configParams; } void CAppConfig::internalLoadParameters( const std::string& sectionName, const std::string& configFileName, const SmartPtrCConfigParams& configParams) { CAF_CM_FUNCNAME("internalLoadParameters"); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(configFileName); CAF_CM_VALIDATE_SMARTPTR(configParams); GKeyFile* configFile = NULL; GError* configError = NULL; gchar** keys = NULL; gchar* sValue = NULL; GMatchInfo* matchInfo = NULL; gchar* match = NULL; try { try { configFile = g_key_file_new(); g_key_file_load_from_file( configFile, configFileName.c_str(), G_KEY_FILE_NONE, &configError); if (configError) { throw configError; } gsize numKeys = 0; keys = g_key_file_get_keys( configFile, sectionName.c_str(), &numKeys, &configError); if (numKeys) { bool isGlobals = (::strcmp(sectionName.c_str(), _sGlobalsSectionName) == 0); for (gsize idx = 0; idx < numKeys; idx++) { // There is no way to tell if a value is an integer or string. // We want to insert the value as either string or int32 so // try to read the value as an integer. If it cannot be read // as an integer then insert it as a string. gint iValue = g_key_file_get_integer( configFile, sectionName.c_str(), keys[idx], &configError); if (!configError) { configParams->insert(g_strdup(keys[idx]), g_variant_new_int32( iValue)); if (isGlobals) { // create a regular expression to apply against other // values in other sections std::string pattern("\\$\\{"); pattern += keys[idx]; pattern += "\\}"; GRegex* regex = g_regex_new( pattern.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_UNGREEDY | G_REGEX_RAW), (GRegexMatchFlags)0, &configError); if (configError) { throw configError; } const std::string iValueStr = CStringConv::toString(iValue); _globalReplacements.insert(CGlobalReplacements::value_type( regex, iValueStr)); } } else { if (G_KEY_FILE_ERROR_INVALID_VALUE != configError->code) { throw configError; } else { g_error_free(configError); configError = NULL; sValue = g_key_file_get_string( configFile, sectionName.c_str(), keys[idx], &configError); if (configError) { throw configError; } // Check the value to see if it references an environment variable if (g_regex_match( _envPattern, sValue, G_REGEX_MATCH_NOTBOL, &matchInfo)) { // Replace the reference with the env variable value match = g_match_info_fetch(matchInfo, 1); if (*match) { std::string envVarName(match); g_free(match); match = NULL; #ifdef WIN32 char* dupbuf = NULL; size_t duplen = 0; errno_t duprc = ::_dupenv_s(&dupbuf, &duplen, envVarName.c_str()); const std::string dupval(dupbuf && ::strlen(dupbuf) ? dupbuf : ""); ::free(dupbuf); dupbuf = NULL; const char* envVarValue = dupval.c_str(); #else const char* envVarValue = ::getenv(envVarName.c_str()); #endif if (envVarValue && ::strlen(envVarValue)) { gchar* newValue = g_regex_replace_literal( _envPattern, sValue, -1, 0, envVarValue, G_REGEX_MATCH_NOTBOL, &configError); if (configError) { throw configError; } g_free(sValue); sValue = newValue; } else { CAF_CM_EXCEPTION_VA1(ERROR_TAG_NOT_FOUND, "Referenced environment variable is not set: %s", envVarName.c_str()); } } else { CAF_CM_EXCEPTION_VA0(ERROR_INTERNAL_ERROR, "${env:var} matched but subexpression #1 is null."); } } g_match_info_free(matchInfo); matchInfo = NULL; // Replace occurrences of ${global_var_name} with the appropriate global value for (CGlobalReplacements::const_iterator pattern = _globalReplacements.begin(); pattern != _globalReplacements.end(); ++pattern) { if (g_regex_match( pattern->first, sValue, G_REGEX_MATCH_NOTBOL, NULL)) { gchar* newValue = g_regex_replace_literal( pattern->first, sValue, -1, 0, pattern->second.c_str(), G_REGEX_MATCH_NOTBOL, &configError); if (configError) { throw configError; } g_free(sValue); sValue = newValue; } } // Add the variable to the collection configParams->insert(g_strdup(keys[idx]), g_variant_new_string( sValue)); if (isGlobals) { // create a regular expression to apply against other // values in other sections std::string pattern("\\$\\{"); pattern += keys[idx]; pattern += "\\}"; GRegex* regex = g_regex_new( pattern.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_UNGREEDY | G_REGEX_RAW), (GRegexMatchFlags)0, &configError); if (configError) { throw configError; } _globalReplacements.insert(CGlobalReplacements::value_type( regex, sValue)); } } g_free(sValue); sValue = NULL; } } } } catch (GError *e) { CAF_CM_EXCEPTION_VA0(e->code, e->message); } } catch (CCafException *e) { _cm_exception_ = e; } if (configFile) { g_key_file_free(configFile); } if (configError) { g_error_free(configError); } if (keys) { g_strfreev(keys); } if (sValue) { g_free(sValue); } if (matchInfo) { g_match_info_free(matchInfo); } if (match) { g_free(match); } if (_cm_exception_) { throw _cm_exception_; } } void CAppConfig::validateGlobals(const SmartPtrIConfigParams& globals) { CAF_CM_FUNCNAME("validateGlobals"); CAF_CM_VALIDATE_INTERFACE(globals); GVariant* log_dir = globals->lookup( _sAppConfigGlobalParamLogDir, IConfigParams::PARAM_REQUIRED); CAF_CM_ASSERT(g_variant_is_of_type(log_dir, G_VARIANT_TYPE_STRING)); const char* log_dir_val = g_variant_get_string(log_dir, NULL); CAF_CM_VALIDATE_STRINGPTRA(log_dir_val); GVariant* log_file = globals->lookup( _sAppConfigGlobalParamLogConfigFile, IConfigParams::PARAM_REQUIRED); CAF_CM_ASSERT(g_variant_is_of_type(log_file, G_VARIANT_TYPE_STRING)); const char* log_file_val = g_variant_get_string(log_file, NULL); CAF_CM_VALIDATE_STRINGPTRA(log_file_val); CLoggingUtils::setStartupConfigFile(log_file_val); GVariant* thread_stack_size_kb = globals->lookup( _sAppConfigGlobalThreadStackSizeKb, IConfigParams::PARAM_REQUIRED); CAF_CM_ASSERT(g_variant_is_of_type(thread_stack_size_kb, G_VARIANT_TYPE_INT32)); } std::string CAppConfig::calcConfigPath( const std::string& configFile) const { CAF_CM_FUNCNAME_VALIDATE("calcConfigPath"); CAF_CM_VALIDATE_STRING(configFile); std::string rc; if (g_file_test(configFile.c_str(), G_FILE_TEST_IS_REGULAR)) { rc = configFile; } if (rc.empty()) { const std::string currentConfigPath = calcCurrentConfigPath(configFile); if (g_file_test(currentConfigPath.c_str(), G_FILE_TEST_IS_REGULAR)) { rc = currentConfigPath; } } if (rc.empty()) { const std::string pmeConfigPath = calcDefaultConfigPath("pme", configFile); if (g_file_test(pmeConfigPath.c_str(), G_FILE_TEST_IS_REGULAR)) { rc = pmeConfigPath; } } if (rc.empty()) { const std::string clientConfigPath = calcDefaultConfigPath("client", configFile); if (g_file_test(clientConfigPath.c_str(), G_FILE_TEST_IS_REGULAR)) { rc = clientConfigPath; } } return rc; } std::string CAppConfig::calcCurrentConfigPath( const std::string& configFile) const { CAF_CM_FUNCNAME_VALIDATE("calcCurrentConfigPath"); CAF_CM_VALIDATE_STRING(configFile); const std::string currentDir = FileSystemUtils::getCurrentDir(); const std::string configPath = FileSystemUtils::buildPath( currentDir, configFile); return configPath; } std::string CAppConfig::calcDefaultConfigPath( const std::string& area, const std::string& configFile) const { CAF_CM_FUNCNAME_VALIDATE("calcDefaultConfigPath"); CAF_CM_VALIDATE_STRING(area); CAF_CM_VALIDATE_STRING(configFile); const std::string configDir = calcDefaultConfigDir(area); const std::string configPath = FileSystemUtils::buildPath( configDir, configFile); return configPath; } #ifdef WIN32 std::string CAppConfig::calcDefaultConfigDir( const std::string& area) const { CAF_CM_FUNCNAME("calcDefaultConfigDir"); CAF_CM_VALIDATE_STRING(area); std::string programData; CEnvironmentUtils::readEnvironmentVar("ProgramData", programData); if (programData.empty()) { CAF_CM_EXCEPTION_VA0(ERROR_TAG_NOT_FOUND, "ProgramData env var isn't set."); } const std::string configDir = FileSystemUtils::buildPath( programData, "VMware", "VMware CAF", area, "config"); return configDir; } #else std::string CAppConfig::calcDefaultConfigDir( const std::string& area) const { CAF_CM_FUNCNAME_VALIDATE("calcDefaultConfigDir"); CAF_CM_VALIDATE_STRING(area); const std::string configDir = FileSystemUtils::buildPath( G_DIR_SEPARATOR_S, "etc", "vmware-caf", area, "config"); return configDir; } #endif CAppConfig.h000066400000000000000000000117321321503522500333640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 19, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAPPCONFIG_H_ #define CAPPCONFIG_H_ #include "Common/IConfigParams.h" #include "Common/CConfigParams.h" #include "Common/IAppConfig.h" #include "Common/IAppConfigWrite.h" namespace Caf { CAF_DECLARE_CLASS_AND_SMART_POINTER(CAppConfig); class COMMONAGGREGATOR_LINKAGE CAppConfig : public IAppConfig, public IAppConfigWrite { public: // IAppConfig SmartPtrIConfigParams getParameters(const std::string& sectionName); bool getString( const std::string& sectionName, const std::string& parameterName, std::string& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED); bool getUint32( const std::string& sectionName, const std::string& parameterName, uint32& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED); bool getInt32( const std::string& sectionName, const std::string& parameterName, int32& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED); bool getBoolean( const std::string& sectionName, const std::string& parameterName, bool& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED); bool getGlobalString( const std::string& parameterName, std::string& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED); bool getGlobalUint32( const std::string& parameterName, uint32& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED); bool getGlobalInt32( const std::string& parameterName, int32& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED); bool getGlobalBoolean( const std::string& parameterName, bool& value, const IConfigParams::EParamDisposition disposition = IConfigParams::PARAM_REQUIRED); std::string resolveValue(const std::string& value); static SmartPtrIAppConfig getInstance(); static SmartPtrIAppConfig getInstance(const std::string& configFile); static SmartPtrIAppConfig getInstance(const Cdeqstr& configFileCollection); static SmartPtrIAppConfig getInstanceAppend(const std::string& configFile); static SmartPtrIAppConfig getInstanceAppend(const Cdeqstr& configFileCollection); public: // IAppConfigWrite void setString(const std::string& sectionName, const std::string& parameterName, const std::string& value); void setUint32(const std::string& sectionName, const std::string& parameterName, const uint32& value); void setInt32(const std::string& sectionName, const std::string& parameterName, const int32& value); void setBoolean(const std::string& sectionName, const std::string& parameterName, const bool& value); void setGlobalString(const std::string& parameterName, const std::string& value); void setGlobalUint32(const std::string& parameterName, const uint32& value); void setGlobalInt32(const std::string& parameterName, const int32& value); void setGlobalBoolean(const std::string& parameterName, const bool& value); static SmartPtrIAppConfigWrite getInstanceWrite(); static SmartPtrIAppConfigWrite getInstanceWrite(const std::string& configFile); static SmartPtrIAppConfigWrite getInstanceWrite(const Cdeqstr& configFileCollection); private: CAppConfig(); virtual ~CAppConfig(); private: void initialize(); void initialize(const std::string& configFile); void initialize(const Cdeqstr& configFileCollection); void append(const std::string& configFile); void append(const Cdeqstr& configFileCollection); private: SmartPtrIConfigParams internalLoadParameters( const std::string& sectionName); void internalLoadParameters( const std::string& sectionName, const std::string& configFileName, const SmartPtrCConfigParams& configParams); void validateGlobals(const SmartPtrIConfigParams& globals); private: std::string calcCurrentConfigPath( const std::string& configFile) const; std::string calcConfigPath( const std::string& configFilename) const; std::string calcDefaultConfigPath( const std::string& area, const std::string& configFile) const; std::string calcDefaultConfigDir( const std::string& area) const; private: static const char* _sGlobalsSectionName; static GRecMutex _sOpMutex; static SmartPtrCAppConfig _sInstance; bool _isInitialized; typedef std::map CParamSections; CParamSections _cachedSections; typedef std::map CGlobalReplacements; CGlobalReplacements _globalReplacements; GRegex* _envPattern; GRegex* _varPattern; SmartPtrIConfigParams _globals; Cdeqstr _configFileCollection; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAppConfig); friend class TCafObject; }; } #endif /* CAPPCONFIG_H_ */ CApplicationContext.cpp000066400000000000000000000354131321503522500356630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Common/CApplicationContext.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" using namespace Caf; CApplicationContext::CApplicationContext(void) : m_isInitialized(false), CAF_CM_INIT_LOG("CApplicationContext") { } CApplicationContext::~CApplicationContext(void) { } void CApplicationContext::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(m_isInitialized); const std::string beanConfigFile = getDefaultBeanConfigFile(); Cdeqstr filenameCollection; filenameCollection.push_front(beanConfigFile); initialize(filenameCollection); } void CApplicationContext::initialize(const Cdeqstr& filenameCollection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(m_isInitialized); CAF_CM_VALIDATE_STL(filenameCollection); for (TConstIterator filenameIter(filenameCollection); filenameIter; filenameIter++) { const std::string beanConfigFile = *filenameIter; parseBeanConfig( beanConfigFile, _beanCollection); } CBeanGraph beanGraph; createBeanGraph( _beanCollection, beanGraph, _beanTopologySort); try { initializeBeans( _beanCollection, _beanTopologySort); } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_CRIT_CAFEXCEPTION; CCafException *ex = CAF_CM_GETEXCEPTION; ex->AddRef(); CAF_CM_CLEAREXCEPTION; try { terminateBeans(_beanTopologySort); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; _beanTopologySort.clear(); _beanCollection.clear(); CAF_CM_GETEXCEPTION = ex; CAF_CM_THROWEXCEPTION; } m_isInitialized = true; } void CApplicationContext::terminate() { CAF_CM_FUNCNAME_VALIDATE("terminate"); CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized); terminateBeans(_beanTopologySort); _beanTopologySort.clear(); _beanCollection.clear(); _filenameCollection.clear(); } IAppContext::SmartPtrCBeans CApplicationContext::getBeans() const { CAF_CM_FUNCNAME_VALIDATE("getBeans"); CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized); SmartPtrCBeans beans; beans.CreateInstance(); for (TSmartConstMapIterator beanIter(_beanCollection); beanIter; beanIter++) { beans->insert(CBeans::value_type( beanIter.getKey().c_str(), beanIter->_bean)); } return beans; } SmartPtrIBean CApplicationContext::getBean(const std::string& beanId) const { CAF_CM_FUNCNAME("getBean"); CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized); CAF_CM_VALIDATE_STRING(beanId); CBeanCollection::const_iterator iter = _beanCollection.find(beanId); if (iter == _beanCollection.end()) { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Bean not found - %s", beanId.c_str()); } CAF_CM_LOG_DEBUG_VA1( "Bean Found - %s", beanId.c_str()); return iter->second->_bean; } std::string CApplicationContext::getDefaultBeanConfigFile() const { CAF_CM_FUNCNAME("parseBeanConfig"); // Get the bean config file const std::string beanConfigFile = AppConfigUtils::getRequiredString("bean_config_file"); if (!FileSystemUtils::doesFileExist(beanConfigFile)) { CAF_CM_EXCEPTIONEX_VA1( FileNotFoundException, 0, "The bean config file [%s] does not exist.", beanConfigFile.c_str()); } return beanConfigFile; } void CApplicationContext::parseBeanConfig( const std::string& beanConfigFile, CBeanCollection& beanCollection) const { CAF_CM_FUNCNAME("parseBeanConfig"); CAF_CM_VALIDATE_STRING(beanConfigFile); CAF_CM_LOG_DEBUG_VA1("Parsing bean config file %s", beanConfigFile.c_str()); // We will look up class references early in the process to fail as early // as possible and to make logging better. // Parse the bean config file CXmlElement::SmartPtrCElementCollection rootElements = CXmlUtils::parseFile(beanConfigFile, "caf:beans")->getAllChildren(); for (TSmartConstMultimapIterator rootChild(*rootElements); rootChild; rootChild++) { // if the child is a bean... if (rootChild->getName() == "bean") { // Syntactic sugar const SmartPtrCXmlElement beanElement = *rootChild; // Bean attributes const std::string beanId = beanElement->findRequiredAttribute("id"); CAF_CM_LOG_DEBUG_VA1("Parsing bean [id=%s]", beanId.c_str()); const std::string beanClass = beanElement->findRequiredAttribute("class"); CAF_CM_LOG_DEBUG_VA2( "Checking bean class [id=%s][class=%s]", beanId.c_str(), beanClass.c_str()); if (!CEcmSubSystemRegistry::IsRegistered(beanClass)) { CAF_CM_EXCEPTIONEX_VA3( NoSuchElementException, 0, "Bean class %s is not registered. Fix the AppConfig file. " "[bean id=%s][bean_config_file=%s]", beanClass.c_str(), beanId.c_str(), beanConfigFile.c_str()); } // get optional constructor args and properties CBeanCtorArgCollection beanCtorArgs; Cmapstrstr beanProperties; CAF_CM_LOG_DEBUG_VA1("Parsing bean ctor args and properties [id=%s]", beanId.c_str()); CXmlElement::SmartPtrCElementCollection beanElements = beanElement->getAllChildren(); for (TSmartConstMultimapIterator beanChild(*beanElements); beanChild; beanChild++) { if (beanChild->getName() == "property") { // Syntactic sugar const SmartPtrCXmlElement propArgElement = *beanChild; // property attributes const std::string name = propArgElement->findRequiredAttribute("name"); const std::string value = propArgElement->findRequiredAttribute("value"); if (!beanProperties.insert(std::make_pair(name, value)).second) { CAF_CM_EXCEPTIONEX_VA3( DuplicateElementException, 0, "Bean property name is duplicated. " "[bean id=%s][property name=%s][bean_config_file=%s]", beanId.c_str(), name.c_str(), beanConfigFile.c_str()); } } else if (beanChild->getName() == "constructor-arg") { // Syntactic sugar const SmartPtrCXmlElement ctorArgElement = *beanChild; // ctor attributes const uint32 ctorArgIndex = CStringConv::fromString(ctorArgElement->findRequiredAttribute("index")); CBeanCtorArg::ARG_TYPE ctorArgType = CBeanCtorArg::NOT_SET; std::string ctorArgValue = ctorArgElement->findOptionalAttribute("value"); if (ctorArgValue.length() > 0) { ctorArgType = CBeanCtorArg::VALUE; } else { ctorArgValue = ctorArgElement->findOptionalAttribute("ref"); if (ctorArgValue.length() > 0) { ctorArgType = CBeanCtorArg::REFERENCE; } else { CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, 0, "Bean constructor argument must be of type value or ref and cannot be empty. " "[bean id=%s][bean_config_file=%s]", beanId.c_str(), beanConfigFile.c_str()); } } if (!beanCtorArgs.insert( CBeanCtorArgCollection::value_type( ctorArgIndex, CBeanCtorArg(ctorArgType, ctorArgValue))).second) { CAF_CM_EXCEPTIONEX_VA3( DuplicateElementException, 0, "Bean has a duplicate constructor-arg index. " "[bean id=%s][bean_config_file=%s][arg-index=%d]", beanId.c_str(), beanConfigFile.c_str(), ctorArgIndex); } CAF_CM_LOG_DEBUG_VA4( "Bean ctor arg parsed [id=%s][arg-index=%d][arg-type=%s][arg-value=%s]", beanId.c_str(), ctorArgIndex, (CBeanCtorArg::VALUE == ctorArgType ? "VALUE" : "REFERENCE"), ctorArgValue.c_str()); } } // Add the bean definition to the collection SmartPtrCBeanNode beanNode; beanNode.CreateInstance(); beanNode->_id = beanId; beanNode->_class = beanClass; beanNode->_ctorArgs = beanCtorArgs; beanNode->_properties = beanProperties; if (!beanCollection.insert( CBeanCollection::value_type( beanId, beanNode)).second) { CAF_CM_EXCEPTIONEX_VA3( DuplicateElementException, 0, "Duplicate bean definition detected. " "[bean id=%s][bean class=%s][bean_config_file=%s]", beanId.c_str(), beanNode->_class.c_str(), beanConfigFile.c_str()); } } } CAF_CM_LOG_DEBUG_VA2( "Bean configuration file defined %d beans. " "[file=%s]", beanCollection.size(), beanConfigFile.c_str()); } void CApplicationContext::createBeanGraph( CBeanCollection& beanCollection, CBeanGraph& beanGraph, CBeanGraph::ClistVertexEdges& beanTopologySort) const { CAF_CM_FUNCNAME("createBeanGraph"); // Iterate the bean collection and create the beans. They will not be initialized. // Two name sets will be built: bean names and contstructor-arg ref names. // These two sets will be compared to ensure that all referenced beans exist. Csetstr beanNames; Csetstr beanCtorRefNames; for (TSmartMapIterator beanIter(beanCollection); beanIter; beanIter++) { // Create the bean and add it to the collection CAF_CM_LOG_DEBUG_VA2( "Creating bean [id=%s][class=%s]", beanIter.getKey().c_str(), beanIter->_class.c_str()); beanIter->_bean.CreateInstance(beanIter->_class.c_str()); // Add the bean id to the beanNames set if (!beanNames.insert(beanIter->_id).second) { CAF_CM_LOG_DEBUG_VA1( "Internal logic error: duplicate bean detected. " "[id=%s]", beanIter->_id.c_str()); } // Add ref constructor args to the ctor ref name set for (TConstMapIterator beanCtorArg(beanIter->_ctorArgs); beanCtorArg; beanCtorArg++) { if (CBeanCtorArg::REFERENCE == beanCtorArg->_type) { beanCtorRefNames.insert(beanCtorArg->_value); } } } // Make sure that all beans referenced as ctor args exist Csetstr beanNameDiff; std::set_difference( beanCtorRefNames.begin(), beanCtorRefNames.end(), beanNames.begin(), beanNames.end(), std::inserter(beanNameDiff, beanNameDiff.end())); if (beanNameDiff.size()) { for (TConstIterator missingName(beanNameDiff); missingName; missingName++) { CAF_CM_LOG_ERROR_VA1( "No bean definition exists for constructor-arg referenced bean '%s'", missingName->c_str()); } CAF_CM_EXCEPTIONEX_VA0( NoSuchElementException, 0, "One or more bean constructor-args references beans that are not defined."); } // Create a graph node for each bean for (TSmartConstMapIterator beanIter(beanCollection); beanIter; beanIter++) { beanGraph.addVertex(*beanIter); } // Okay. Now connect the vertices according the constructor-arg references. // The resulting graph will give us the initialization/tear-down order. for (TSmartConstMapIterator beanIter(beanCollection); beanIter; beanIter++) { for (TConstMapIterator ctorArg(beanIter->_ctorArgs); ctorArg; ctorArg++) { if (CBeanCtorArg::REFERENCE == ctorArg->_type) { CBeanCollection::const_iterator ctorBean = beanCollection.find(ctorArg->_value); if (beanCollection.end() == ctorBean) { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Internal error: constructor-arg referenced bean '%s' is missing", ctorArg->_value.c_str()); } beanGraph.addEdge(ctorBean->second, *beanIter); } } } // And finally - compute the bean topology sort order beanTopologySort = beanGraph.topologySort(); // Debugging - you will thank me for this later CAF_CM_LOG_DEBUG_VA0("BEGIN: Bean initialization order") for (TSmartConstIterator beanNode(beanTopologySort); beanNode; beanNode++) { CAF_CM_LOG_DEBUG_VA1("bean id=%s", beanNode->_id.c_str()); } CAF_CM_LOG_DEBUG_VA0("END: Bean initialization order") } void CApplicationContext::initializeBeans( CBeanCollection& beanCollection, CBeanGraph::ClistVertexEdges& beanTopologySort) const { CAF_CM_FUNCNAME("initializeBeans"); for (TSmartIterator beanNode(beanTopologySort); beanNode; beanNode++) { CAF_CM_LOG_DEBUG_VA1("Initializing bean %s", beanNode->_id.c_str()); // The bean should not have been initialized if (beanNode->_isInitialized) { CAF_CM_EXCEPTIONEX_VA1( IllegalStateException, 0, "Internal error: Bean [%s] has already been initialized.", beanNode->_id.c_str()); } // Iterate the contructor-args and build a collection to // pass to the bean initializer IBean::Cargs beanInitArgs; for (TConstMapIterator ctorArg(beanNode->_ctorArgs); ctorArg; ctorArg++) { switch (ctorArg->_type) { case CBeanCtorArg::REFERENCE: { CBeanCollection::const_iterator bean = beanCollection.find(ctorArg->_value); if (!bean->second->_isInitialized) { CAF_CM_EXCEPTIONEX_VA2( NullPointerException, 0, "Internal error: Referenced bean not initialized. " "[bean id=%s][constructor-arg ref=%s]", beanNode->_id.c_str(), ctorArg->_value.c_str()); } beanInitArgs.push_back(IBean::CArg(bean->second->_bean)); CAF_CM_LOG_DEBUG_VA1( "constructor-arg ref=%s", ctorArg->_value.c_str()); } break; case CBeanCtorArg::VALUE: beanInitArgs.push_back(IBean::CArg(ctorArg->_value)); CAF_CM_LOG_DEBUG_VA1( "constructor-arg value=%s", ctorArg->_value.c_str()); break; default: CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, 0, "Internal error: Bean constructor-arg is not a ref or value " "[bean id=%s][constructor-arg index=%d]", beanNode->_id.c_str(), ctorArg.getKey()); } } // Iterate the bean properties and resolve value references SmartPtrIAppConfig appConfig = getAppConfig(); Cmapstrstr properties = beanNode->_properties; for (TMapIterator property(properties); property; property++) { *property = appConfig->resolveValue(*property); } // Initialize the bean beanNode->_bean->initializeBean(beanInitArgs, properties); beanNode->_isInitialized = true; } } void CApplicationContext::terminateBeans(CBeanGraph::ClistVertexEdges& beanTopologySort) const { CAF_CM_FUNCNAME("terminateBeans"); // Important! Iterate in reverse order of initialization // Some beans may not be initialized because of exceptions during init process for (CBeanGraph::ClistVertexEdges::reverse_iterator beanNode = beanTopologySort.rbegin(); beanNode != beanTopologySort.rend(); beanNode++) { if ((*beanNode)->_isInitialized) { CAF_CM_LOG_DEBUG_VA1( "Terminating bean %s", (*beanNode)->_id.c_str()); try { (*beanNode)->_bean->terminateBean(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } else { CAF_CM_LOG_DEBUG_VA1( "Skipping termination of uninitialized bean %s", (*beanNode)->_id.c_str()); } } } CAutoCondition.cpp000066400000000000000000000034061321503522500346270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Oct 29, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CAutoMutex.h" #include "Common/CAutoCondition.h" using namespace Caf; CAutoCondition::CAutoCondition() : _isInitialized (false), CAF_CM_INIT("CAutoCondition") { ::g_cond_init(&_condition); } CAutoCondition::~CAutoCondition() { ::g_cond_clear(&_condition); } void CAutoCondition::initialize(const std::string& name) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _name = name; _isInitialized = true; } bool CAutoCondition::isInitialized() const { return _isInitialized; } void CAutoCondition::close() { CAF_CM_FUNCNAME_VALIDATE("close"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (_isInitialized) { ::g_cond_clear(&_condition); _name.clear(); _isInitialized = false; } } std::string CAutoCondition::getName() const { CAF_CM_FUNCNAME_VALIDATE("getName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _name; } void CAutoCondition::signal() { CAF_CM_FUNCNAME_VALIDATE("signal"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ::g_cond_signal(&_condition); } void CAutoCondition::wait(SmartPtrCAutoMutex& mutex) { CAF_CM_FUNCNAME_VALIDATE("wait"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(mutex); ::g_cond_wait(&_condition, mutex->getNonConstPtr()); } bool CAutoCondition::waitUntil(SmartPtrCAutoMutex& mutex, gint64 endTime) { CAF_CM_FUNCNAME_VALIDATE("waitUntil"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(mutex); gboolean isSignaled = ::g_cond_wait_until(&_condition, mutex->getNonConstPtr(), endTime); return (FALSE == isSignaled) ? false : true; } CAutoFileUnlock.cpp000066400000000000000000000011141321503522500347260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CFileLock.h" #include "Exception/CCafException.h" #include "CAutoFileUnlock.h" using namespace Caf; CAutoFileUnlock::CAutoFileUnlock(SmartPtrCFileLock & rspcManagedLock) { m_spcLock = rspcManagedLock; } CAutoFileUnlock::~CAutoFileUnlock() { CAF_CM_STATIC_FUNC("CAutoFileUnlock", "~CAutoFileUnlock"); try { if (m_spcLock) { m_spcLock->setLockLevel(CFileLock::UNLOCK, true); m_spcLock = 0; } } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; } CAutoFileUnlock.h000066400000000000000000000006511321503522500344000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAutoFileUnlock_h_ #define CAutoFileUnlock_h_ #include "Common/CFileLock.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE CAutoFileUnlock { public: CAutoFileUnlock(SmartPtrCFileLock & rspcManagedLock); ~CAutoFileUnlock(); private: SmartPtrCFileLock m_spcLock; CAF_CM_DECLARE_NOCOPY(CAutoFileUnlock); }; } #endif CAutoMutex.cpp000066400000000000000000000032471321503522500340060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Oct 29, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CAutoMutex.h" using namespace Caf; CAutoMutex::CAutoMutex() : _isInitialized(false), CAF_CM_INIT("CAutoMutex") { } CAutoMutex::~CAutoMutex() { if (_isInitialized) { ::g_mutex_clear(&_mutex); } } void CAutoMutex::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); ::g_mutex_init(&_mutex); _isInitialized = true; } bool CAutoMutex::isInitialized() const { return _isInitialized; } void CAutoMutex::lock( const char* className, const char* funcName, const int32 lineNumber) { CAF_CM_FUNCNAME_VALIDATE("lock"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // if ((NULL != className) && (NULL != funcName)) { // CAF_CM_LOG_DEBUG_VA4("Waiting for lock - %s::%s(%d) - %p", className, funcName, // lineNumber, &_mutex); // } ::g_mutex_lock(&_mutex); // if ((NULL != className) && (NULL != funcName)) { // CAF_CM_LOG_DEBUG_VA4("Got lock - %s::%s(%d) - %p", className, funcName, lineNumber, // &_mutex); // } } void CAutoMutex::unlock( const char* className, const char* funcName, const int32 lineNumber) { CAF_CM_FUNCNAME_VALIDATE("unlock"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // if ((NULL != className) && (NULL != funcName)) { // CAF_CM_LOG_DEBUG_VA4("Unlocking lock - %s::%s(%d) - %p", className, funcName, // lineNumber, &_mutex); // } ::g_mutex_unlock(&_mutex); } GMutex* CAutoMutex::getNonConstPtr() { CAF_CM_FUNCNAME_VALIDATE("getNonConstPtr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return &_mutex; } CAutoMutexLockUnlock.cpp000066400000000000000000000032651321503522500357730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CAutoMutex.h" #include "Common/CAutoRecMutex.h" #include "CAutoMutexLockUnlock.h" using namespace Caf; CAutoMutexLockUnlock::CAutoMutexLockUnlock( SmartPtrCAutoMutex& mutex, const char* className, const char* funcName, const int32 lineNumber) : _lineNumber(0), CAF_CM_INIT("CAutoMutexLockUnlock") { CAF_CM_FUNCNAME_VALIDATE("CAutoMutexLockUnlock"); CAF_CM_VALIDATE_SMARTPTR(mutex); _mutex = mutex; if ((NULL != className) && (NULL != funcName)) { _className = className; _funcName = funcName; _lineNumber = lineNumber; } _mutex->lock(className, funcName, lineNumber); } CAutoMutexLockUnlock::CAutoMutexLockUnlock( SmartPtrCAutoRecMutex& recMutex, const char* className, const char* funcName, const int32 lineNumber) : _lineNumber(0), CAF_CM_INIT("CAutoMutexLockUnlock") { CAF_CM_FUNCNAME_VALIDATE("CAutoMutexLockUnlock"); CAF_CM_VALIDATE_SMARTPTR(recMutex); _recMutex = recMutex; if ((NULL != className) && (NULL != funcName)) { _className = className; _funcName = funcName; _lineNumber = lineNumber; } _recMutex->lock(className, funcName, lineNumber); } CAutoMutexLockUnlock::~CAutoMutexLockUnlock() { if (_className.empty() && _funcName.empty()) { if (!_mutex.IsNull()) { _mutex->unlock(); } if (!_recMutex.IsNull()) { _recMutex->unlock(); } } else { if (!_mutex.IsNull()) { _mutex->unlock(_className.c_str(), _funcName.c_str(), _lineNumber); } if (!_recMutex.IsNull()) { _recMutex->unlock(_className.c_str(), _funcName.c_str(), _lineNumber); } } } CAutoMutexLockUnlock.h000066400000000000000000000016611321503522500354360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAUTOMUTEXLOCKUNLOCK_H_ #define CAUTOMUTEXLOCKUNLOCK_H_ #include "Common/CAutoMutex.h" #include "Common/CAutoRecMutex.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE CAutoMutexLockUnlock { public: CAutoMutexLockUnlock( SmartPtrCAutoMutex& mutex, const char* className = NULL, const char* funcName = NULL, const int32 lineNumber = 0); CAutoMutexLockUnlock( SmartPtrCAutoRecMutex& recMutex, const char* className = NULL, const char* funcName = NULL, const int32 lineNumber = 0); ~CAutoMutexLockUnlock(); private: SmartPtrCAutoMutex _mutex; SmartPtrCAutoRecMutex _recMutex; std::string _className; std::string _funcName; int32 _lineNumber; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAutoMutexLockUnlock); }; } #endif /* CAUTOMUTEXLOCKUNLOCK_H_ */ CAutoMutexLockUnlockRaw.cpp000066400000000000000000000014201321503522500364340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CAutoMutexLockUnlockRaw.h" using namespace Caf; CAutoMutexLockUnlockRaw::CAutoMutexLockUnlockRaw(GMutex* mutex) : CAF_CM_INIT("CAutoMutexLockUnlockRaw") { _mutex = mutex; _recMutex = NULL; if (_mutex) { ::g_mutex_lock(_mutex); } } CAutoMutexLockUnlockRaw::CAutoMutexLockUnlockRaw(GRecMutex* recMutex) : CAF_CM_INIT("CAutoMutexLockUnlockRaw") { _mutex = NULL; _recMutex = recMutex; if (_recMutex) { ::g_rec_mutex_lock(_recMutex); } } CAutoMutexLockUnlockRaw::~CAutoMutexLockUnlockRaw() { if (_mutex) { ::g_mutex_unlock(_mutex); } if (_recMutex) { ::g_rec_mutex_unlock(_recMutex); } } CAutoMutexLockUnlockRaw.h000066400000000000000000000011101321503522500360750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAUTOMUTEXLOCKUNLOCKRAW_H_ #define CAUTOMUTEXLOCKUNLOCKRAW_H_ namespace Caf { class SUBSYSTEMBASE_LINKAGE CAutoMutexLockUnlockRaw { public: CAutoMutexLockUnlockRaw(GMutex* mutex); CAutoMutexLockUnlockRaw(GRecMutex* recMutex); ~CAutoMutexLockUnlockRaw(); private: GMutex* _mutex; GRecMutex* _recMutex; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAutoMutexLockUnlockRaw); }; } #endif /* CAUTOMUTEXLOCKUNLOCKRAW_H_ */ CAutoMutexUnlockLock.cpp000066400000000000000000000032301321503522500357630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Oct 21, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CAutoMutex.h" #include "Common/CAutoRecMutex.h" #include "CAutoMutexUnlockLock.h" using namespace Caf; CAutoMutexUnlockLock::CAutoMutexUnlockLock( SmartPtrCAutoMutex& mutex, const char* className, const char* funcName, const int32 lineNumber) : _lineNumber(lineNumber), CAF_CM_INIT("CAutoMutexUnlockLock") { CAF_CM_FUNCNAME_VALIDATE("CAutoMutexUnlockLock"); CAF_CM_VALIDATE_SMARTPTR(mutex); _mutex = mutex; if ((NULL != className) && (NULL != funcName)) { _className = className; _funcName = funcName; } _mutex->unlock(className, funcName, lineNumber); } CAutoMutexUnlockLock::CAutoMutexUnlockLock( SmartPtrCAutoRecMutex& recMutex, const char* className, const char* funcName, const int32 lineNumber) : _lineNumber(lineNumber), CAF_CM_INIT("CAutoMutexUnlockLock") { CAF_CM_FUNCNAME_VALIDATE("CAutoMutexUnlockLock"); CAF_CM_VALIDATE_SMARTPTR(recMutex); _recMutex = recMutex; if ((NULL != className) && (NULL != funcName)) { _className = className; _funcName = funcName; } _recMutex->unlock(className, funcName, lineNumber); } CAutoMutexUnlockLock::~CAutoMutexUnlockLock() { if (_className.empty() && _funcName.empty()) { if (!_mutex.IsNull()) { _mutex->lock(); } if (!_recMutex.IsNull()) { _recMutex->lock(); } } else { if (!_mutex.IsNull()) { _mutex->lock(_className.c_str(), _funcName.c_str(), _lineNumber); } if (!_recMutex.IsNull()) { _recMutex->lock(_className.c_str(), _funcName.c_str(), _lineNumber); } } } CAutoMutexUnlockLock.h000066400000000000000000000016621321503522500354370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Oct 21, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAUTOMUTEXUNLOCKLOCK_H_ #define CAUTOMUTEXUNLOCKLOCK_H_ #include "Common/CAutoMutex.h" #include "Common/CAutoRecMutex.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE CAutoMutexUnlockLock { public: CAutoMutexUnlockLock( SmartPtrCAutoMutex& mutex, const char* className = NULL, const char* funcName = NULL, const int32 lineNumber = 0); CAutoMutexUnlockLock( SmartPtrCAutoRecMutex& recMutex, const char* className = NULL, const char* funcName = NULL, const int32 lineNumber = 0); ~CAutoMutexUnlockLock(); private: SmartPtrCAutoMutex _mutex; SmartPtrCAutoRecMutex _recMutex; std::string _className; std::string _funcName; int32 _lineNumber; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CAutoMutexUnlockLock); }; } #endif /* CAUTOMUTEXUNLOCKLOCK_H_ */ CAutoRecMutex.cpp000066400000000000000000000033011321503522500344270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Oct 29, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CAutoRecMutex.h" using namespace Caf; CAutoRecMutex::CAutoRecMutex() : _isInitialized(false), CAF_CM_INIT("CAutoRecMutex") { ::g_rec_mutex_init(&_mutex); } CAutoRecMutex::~CAutoRecMutex() { ::g_rec_mutex_clear(&_mutex); } void CAutoRecMutex::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } bool CAutoRecMutex::isInitialized() const { return _isInitialized; } void CAutoRecMutex::lock( const char* className, const char* funcName, const int32 lineNumber) { CAF_CM_FUNCNAME_VALIDATE("lock"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // if ((NULL != className) && (NULL != funcName)) { // CAF_CM_LOG_DEBUG_VA4("Waiting for lock - %s::%s(%d) - %p", className, funcName, // lineNumber, &_mutex); // } ::g_rec_mutex_lock(&_mutex); // if ((NULL != className) && (NULL != funcName)) { // CAF_CM_LOG_DEBUG_VA4("Got lock - %s::%s(%d) - %p", className, funcName, lineNumber, // &_mutex); // } } void CAutoRecMutex::unlock( const char* className, const char* funcName, const int32 lineNumber) { CAF_CM_FUNCNAME_VALIDATE("unlock"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // if ((NULL != className) && (NULL != funcName)) { // CAF_CM_LOG_DEBUG_VA4("Unlocking lock - %s::%s(%d) - %p", className, funcName, // lineNumber, &_mutex); // } ::g_rec_mutex_unlock(&_mutex); } GRecMutex* CAutoRecMutex::getNonConstPtr() { CAF_CM_FUNCNAME_VALIDATE("getNonConstPtr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return &_mutex; } CCafRegex.cpp000066400000000000000000000131321321503522500335310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CCafRegex.h" #include "Exception/CCafException.h" using namespace Caf; CCafRegex::CCafRegex() : _isInitialized(false), _gRegex(NULL), CAF_CM_INIT_LOG("CCafRegex") { } CCafRegex::~CCafRegex() { CAF_CM_FUNCNAME("~CCafRegex"); try { if(NULL != _gRegex) { g_regex_unref(_gRegex); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } void CCafRegex::initialize(const std::string& regex) { CAF_CM_FUNCNAME("initialize"); GError* gError = NULL; try { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(regex); _gRegex = g_regex_new( regex.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_RAW), (GRegexMatchFlags)0, &gError); if(NULL == _gRegex) { const std::string errorMessage = (gError == NULL) ? "" : gError->message; const int32 errorCode = (gError == NULL) ? 0 : gError->code; CAF_CM_EXCEPTION_VA1(errorCode, "g_regex_new Failed: \"%s\"", errorMessage.c_str()); } if(NULL != gError) { g_error_free(gError); } _regex = regex; _isInitialized = true; } catch(...) { if(NULL != gError) { g_error_free(gError); } throw; } } bool CCafRegex::isMatched(const std::string& source) { CAF_CM_FUNCNAME_VALIDATE("isMatched"); bool rc = false; GMatchInfo* gMatchInfo = NULL; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(source); gboolean gIsMatch = g_regex_match(_gRegex, source.c_str(), (GRegexMatchFlags)0, &gMatchInfo); rc = (FALSE == gIsMatch) ? false : true; if(NULL != gMatchInfo) { g_match_info_free(gMatchInfo); } } catch(...) { if(NULL != gMatchInfo) { g_match_info_free(gMatchInfo); } throw; } return rc; } std::map CCafRegex::matchNames( const std::string& source, const std::set& names) { CAF_CM_FUNCNAME_VALIDATE("matchNames"); std::map rc; GMatchInfo* gMatchInfo = NULL; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(source); CAF_CM_VALIDATE_STL(names); gboolean gIsMatch = g_regex_match(_gRegex, source.c_str(), (GRegexMatchFlags)0, &gMatchInfo); if(GLIB_TRUE == gIsMatch) { CAF_CM_VALIDATE_PTR(gMatchInfo); for(TConstIterator > name(names); name; name++) { gchar* gString = g_match_info_fetch_named(gMatchInfo, (*name).c_str()); if(NULL != gString) { rc.insert(std::make_pair(*name, gString)); g_free(gString); } } } if(NULL != gMatchInfo) { g_match_info_free(gMatchInfo); } } catch(...) { if(NULL != gMatchInfo) { g_match_info_free(gMatchInfo); } throw; } return rc; } std::deque CCafRegex::matchName( const std::string& source, const std::string& name) { CAF_CM_FUNCNAME("matchName"); std::deque rc; GMatchInfo* gMatchInfo = NULL; GError* gError = NULL; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(source); CAF_CM_VALIDATE_STRING(name); gboolean gIsMatch = g_regex_match(_gRegex, source.c_str(), (GRegexMatchFlags)0, &gMatchInfo); if(GLIB_TRUE == gIsMatch) { CAF_CM_VALIDATE_PTR(gMatchInfo); while(g_match_info_matches(gMatchInfo)) { gchar* gString = g_match_info_fetch_named(gMatchInfo, name.c_str()); rc.push_back(gString); g_free(gString); g_match_info_next(gMatchInfo, &gError); if(NULL != gError) { CAF_CM_EXCEPTION_VA1(gError->code, "g_match_info_next Failed: \"%s\"", gError->message); } } } if(NULL != gMatchInfo) { g_match_info_free(gMatchInfo); } } catch(...) { if(NULL != gMatchInfo) { g_match_info_free(gMatchInfo); } if(NULL != gError) { g_error_free(gError); } throw; } return rc; } std::string CCafRegex::match( const std::string& source, const int32 matchNum) { CAF_CM_FUNCNAME_VALIDATE("match"); std::string rc; GMatchInfo* gMatchInfo = NULL; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(source); gboolean gIsMatch = g_regex_match(_gRegex, source.c_str(), (GRegexMatchFlags)0, &gMatchInfo); if(GLIB_TRUE == gIsMatch) { CAF_CM_VALIDATE_PTR(gMatchInfo); gchar* gString = g_match_info_fetch(gMatchInfo, matchNum); rc = gString; g_free(gString); } if(NULL != gMatchInfo) { g_match_info_free(gMatchInfo); } } catch(...) { if(NULL != gMatchInfo) { g_match_info_free(gMatchInfo); } } return rc; } std::string CCafRegex::replaceLiteral( const std::string& source, const std::string& replacement) { CAF_CM_FUNCNAME("replaceLiteral"); std::string rc; GError* gError = NULL; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(source); CAF_CM_VALIDATE_STRING(replacement); gchar* gString = g_regex_replace_literal( _gRegex, source.c_str(), -1, 0, replacement.c_str(), G_REGEX_MATCH_NOTBOL, &gError); if(NULL != gError) { CAF_CM_EXCEPTION_VA1(gError->code, "g_regex_replace_literal Failed: \"%s\"", gError->message); } rc = gString; g_free(gString); } catch(...) { if(NULL != gError) { g_error_free(gError); } throw; } return rc; } std::string CCafRegex::replaceLiteral( const std::string& regex, const std::string& source, const std::string& replacement) { CAF_CM_STATIC_FUNC_VALIDATE("CCafRegex", "replaceLiteral"); CAF_CM_VALIDATE_STRING(regex); CAF_CM_VALIDATE_STRING(source); CAF_CM_VALIDATE_STRING(replacement); CCafRegex cafRegex; cafRegex.initialize(regex); return cafRegex.replaceLiteral(source, replacement); } CCmdLineOptions.cpp000066400000000000000000000144631321503522500347440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CCmdLineOptions.h" #include "Exception/CCafException.h" using namespace Caf; CCmdLineOptions::CCmdLineOptions(void) : _isInitialized(false), _optionCnt(0), _maxOptions(0), _gOptions(NULL), CAF_CM_INIT_LOG("CCmdLineOptions") { } CCmdLineOptions::~CCmdLineOptions(void) { CAF_CM_FUNCNAME("~CCmdLineOptions"); try { for(TConstIterator option(_stringOptions); option && (option->second != NULL); option++) { g_free(option->second); } } CAF_CM_CATCH_ALL CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } void CCmdLineOptions::initialize( const std::string& cmdDescription, const uint32 maxOptions) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(cmdDescription); CAF_CM_VALIDATE_POSITIVE(maxOptions); _cmdDescription = cmdDescription; _maxOptions = maxOptions; _gOptions = new GOptionEntry[_maxOptions + 1]; _isInitialized = true; } CAF_CM_EXIT; } void CCmdLineOptions::addStringOption( const std::string& longName, const char shortName, const std::string& optionDescription) { CAF_CM_FUNCNAME_VALIDATE("addStringOption"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(longName); CAF_CM_VALIDATE_STRING(optionDescription); checkOptionCnt(longName, _optionCnt, _maxOptions); populateOption(_gOptions[_optionCnt], longName, shortName, optionDescription); _stringOptions.insert(std::make_pair(longName, static_cast(NULL))); _gOptions[_optionCnt].arg_data = &(_stringOptions.find(longName)->second); _gOptions[_optionCnt].arg = G_OPTION_ARG_STRING; _optionCnt++; } CAF_CM_EXIT; } void CCmdLineOptions::addIntOption( const std::string& longName, const char shortName, const std::string& optionDescription) { CAF_CM_FUNCNAME_VALIDATE("addIntOption"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(longName); CAF_CM_VALIDATE_STRING(optionDescription); checkOptionCnt(longName, _optionCnt, _maxOptions); populateOption(_gOptions[_optionCnt], longName, shortName, optionDescription); _intOptions.insert(std::make_pair(longName, 0)); _gOptions[_optionCnt].arg_data = &(_intOptions.find(longName)->second); _gOptions[_optionCnt].arg = G_OPTION_ARG_INT; _optionCnt++; } CAF_CM_EXIT; } void CCmdLineOptions::addBoolOption( const std::string& longName, const char shortName, const std::string& optionDescription) { CAF_CM_FUNCNAME_VALIDATE("addBoolOption"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(longName); CAF_CM_VALIDATE_STRING(optionDescription); checkOptionCnt(longName, _optionCnt, _maxOptions); populateOption(_gOptions[_optionCnt], longName, shortName, optionDescription); _boolOptions.insert(std::make_pair(longName, FALSE)); _gOptions[_optionCnt].arg_data = &(_boolOptions.find(longName)->second); _gOptions[_optionCnt].arg = G_OPTION_ARG_NONE; _optionCnt++; } CAF_CM_EXIT; } void CCmdLineOptions::parse( int32 argc, char* argv[]) { CAF_CM_FUNCNAME("parse"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _gOptions[_optionCnt] = GOptionEntry(); GError *gError = NULL; GOptionContext *gContext = g_option_context_new(_cmdDescription.c_str()); g_option_context_add_main_entries(gContext, _gOptions, NULL); if(!g_option_context_parse(gContext, &argc, &argv, &gError)) { CAF_CM_VALIDATE_PTR(gError); const std::string errorMessage = gError->message; const int32 errorCode = gError->code; g_error_free(gError); g_option_context_free(gContext); CAF_CM_EXCEPTION_VA1(errorCode, "option parsing failed: %s", errorMessage.c_str()); } g_option_context_free(gContext); } CAF_CM_EXIT; } std::string CCmdLineOptions::findStringOption( const std::string& longName) { CAF_CM_FUNCNAME("findStringOption"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(longName); CStringOptions::const_iterator iter = _stringOptions.find(longName); if(iter == _stringOptions.end()) { CAF_CM_EXCEPTION_VA1(E_FAIL, "String option not found: %s", longName.c_str()); } if(iter->second != NULL) { rc = iter->second; } } CAF_CM_EXIT; return rc; } int32 CCmdLineOptions::findIntOption( const std::string& longName) { CAF_CM_FUNCNAME("findIntOption"); int32 rc = 0; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(longName); CIntOptions::const_iterator iter = _intOptions.find(longName); if(iter == _intOptions.end()) { CAF_CM_EXCEPTION_VA1(E_FAIL, "Int option not found: %s", longName.c_str()); } rc = iter->second; } CAF_CM_EXIT; return rc; } bool CCmdLineOptions::findBoolOption( const std::string& longName) { CAF_CM_FUNCNAME("findBoolOption"); bool rc = false; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(longName); CBoolOptions::const_iterator iter = _boolOptions.find(longName); if(iter == _boolOptions.end()) { CAF_CM_EXCEPTION_VA1(E_FAIL, "Bool option not found: %s", longName.c_str()); } rc = iter->second == GLIB_TRUE ? true : false; } CAF_CM_EXIT; return rc; } void CCmdLineOptions::checkOptionCnt( const std::string& longName, const uint32 optionCnt, const uint32 maxOptions) const { CAF_CM_FUNCNAME("checkOptionCnt"); CAF_CM_ENTER { if(optionCnt >= maxOptions) { CAF_CM_EXCEPTION_VA3(E_INVALIDARG, "\"%s\" exceeded the maximum number of allowed options (%d >= %d)", longName.c_str(), optionCnt, maxOptions); } } CAF_CM_EXIT; } void CCmdLineOptions::populateOption( GOptionEntry& optionEntry, const std::string& longName, const char shortName, const std::string& optionDescription) { CAF_CM_ENTER { // We can't guarantee that longName's and optionDescription's scopes will be sufficient, so store the strings. _longNames.push_back(longName); _optionDescriptions.push_back(optionDescription); optionEntry.long_name = _longNames.back().c_str(); optionEntry.short_name = shortName; optionEntry.flags = 0; optionEntry.description = _optionDescriptions.back().c_str(); optionEntry.arg_description = NULL; } CAF_CM_EXIT; } CConfigParams.cpp000066400000000000000000000041731321503522500344230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 17, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CConfigParams.h" #include "Exception/CCafException.h" #include "Common/IConfigParams.h" using namespace Caf; CConfigParams::CConfigParams() : _table(NULL), CAF_CM_INIT("CConfigParams") { } CConfigParams::~CConfigParams() { if (_table) g_hash_table_unref( _table); } void CConfigParams::initialize( const std::string& sectionName, EKeyManagement keyManagement, EValueManagement valueManagement) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_table); CAF_CM_VALIDATE_STRING(sectionName); _sectionName = sectionName; _table = g_hash_table_new_full( g_str_hash, g_str_equal, EKeysManaged == keyManagement ? destroyKeyCallback : NULL, EValuesManaged == valueManagement ? destroyValueCallback : NULL); } CAF_CM_EXIT; } void CConfigParams::insert(const char* key, GVariant* value) { CAF_CM_FUNCNAME_VALIDATE("insert"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_table); CAF_CM_VALIDATE_STRINGPTRA(key); CAF_CM_VALIDATE_PTR(value); g_hash_table_insert(_table, (void*)key, value); } CAF_CM_EXIT; } GVariant* CConfigParams::lookup( const char* key, const EParamDisposition disposition) const { CAF_CM_FUNCNAME("lookup"); GVariant* value = NULL; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_table); CAF_CM_VALIDATE_STRINGPTRA(key); value = (GVariant*)g_hash_table_lookup(_table, key); if (!value && (disposition == PARAM_REQUIRED)) { CAF_CM_EXCEPTION_VA2( ERROR_TAG_NOT_FOUND, "Required config parameter [%s] is missing from section [%s]", key, _sectionName.c_str()); } } CAF_CM_EXIT; return value; } std::string CConfigParams::getSectionName() const { CAF_CM_FUNCNAME_VALIDATE("getSectionName"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_table); } CAF_CM_EXIT; return _sectionName; } void CConfigParams::destroyKeyCallback(gpointer ptr) { g_free(ptr); } void CConfigParams::destroyValueCallback(gpointer ptr) { g_variant_unref((GVariant*)ptr); } CConfigParamsChain.cpp000066400000000000000000000034211321503522500353610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 17, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CConfigParamsChain.h" #include "Exception/CCafException.h" #include "Common/IConfigParams.h" using namespace Caf; CConfigParamsChain::CConfigParamsChain() : CAF_CM_INIT("CConfigParamsChain") { } CConfigParamsChain::~CConfigParamsChain() { } void CConfigParamsChain::initialize( CConfigParams::EKeyManagement keyManagement, CConfigParams::EValueManagement valueManagement, const SmartPtrIConfigParams& baseParams) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_theseParams); CAF_CM_VALIDATE_INTERFACE(baseParams); _baseParams = baseParams; _theseParams.CreateInstance(); _theseParams->initialize( _baseParams->getSectionName(), keyManagement, valueManagement); } void CConfigParamsChain::insert(const char* key, GVariant* value) { CAF_CM_FUNCNAME_VALIDATE("insert"); CAF_CM_PRECOND_ISINITIALIZED(_theseParams); _theseParams->insert(key, value); } GVariant* CConfigParamsChain::lookup( const char* key, const EParamDisposition disposition) const { CAF_CM_FUNCNAME("lookup"); CAF_CM_PRECOND_ISINITIALIZED(_theseParams); GVariant* value = _theseParams->lookup(key, PARAM_OPTIONAL); if (!value) { value = _baseParams->lookup(key, PARAM_OPTIONAL); } if (!value && (disposition == PARAM_REQUIRED)) { CAF_CM_EXCEPTION_VA2( ERROR_TAG_NOT_FOUND, "Required config parameter [%s] is missing from section [%s]", key, _baseParams->getSectionName().c_str()); } return value; } std::string CConfigParamsChain::getSectionName() const { CAF_CM_FUNCNAME_VALIDATE("lookup"); CAF_CM_PRECOND_ISINITIALIZED(_theseParams); return _theseParams->getSectionName(); } CDaemonUtils.cpp000066400000000000000000000233061321503522500342750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jun 9, 2011 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CLoggingUtils.h" #include "CDaemonUtils.h" #include #include #include #include #include #include #ifndef OPEN_MAX #define OPEN_MAX 256 #endif using namespace Caf; extern "C" void DaemonUtilsCrashHandler(int32 sigNum, siginfo_t *info, void *context); /////////////////////////////////////////////////////////////////////////////// // // MakeDaemon // This function makes the process a daemon process // // NOTE: The following function has numerous coding standard violations that // cannot be/should not be corrected by CAF common classes and macros. // /////////////////////////////////////////////////////////////////////////////// void CDaemonUtils::MakeDaemon( int32 argc, char** argv, const std::string& procPath, const std::string& procName, void(*pfnShutdownHandler)(int32 signalNum), bool& isDaemonized, bool& logInfos) { const std::string logProcName = procName.empty() ? "CDaemonUtils" : procName; ::openlog(logProcName.c_str(), LOG_PID, LOG_USER); ::atexit(::closelog); ::syslog(LOG_INFO, "Initializing %s", logProcName.c_str()); isDaemonized = true; logInfos = false; bool enableCrashHandlers = true; std::string userName; std::string groupName; std::string rootDir; int32 irc = 0; while ((irc = ::getopt(argc, argv, "u:g:r:vnc")) != -1) { switch (irc) { case 'u': userName = optarg; break; case 'g': groupName = optarg; break; case 'r': rootDir = optarg; break; case 'n': isDaemonized = false; break; case 'c': enableCrashHandlers = false; break; case 'v': logInfos = true; break; default: ::syslog(LOG_WARNING, "Unknown option '%c', ignoring", irc); } } if (logInfos) { ::syslog( LOG_INFO, "Got user %s", userName.empty() ? "" : userName.c_str()); ::syslog( LOG_INFO, "Got group %s", groupName.empty() ? "" : groupName.c_str()); } if (isDaemonized) { if (logInfos) { ::syslog(LOG_INFO, "Daemonizing"); } // This bizarre check is necessary because the console appender writes to stdout // when a daemon, which messes up the listener some of the file reads - plus, it // just doesn't make sense for a daemon to write to the console. if (CLoggingUtils::isConsoleAppenderUsed()) { ::syslog(LOG_ERR, "Daemon cannot use console appender"); ::exit(2); } // first fork ourselves off if (logInfos) { ::syslog(LOG_INFO, "Daemon forking"); } ::closelog(); int32 childPid = ::fork(); if (childPid < 0) { ::syslog(LOG_ERR, "Cannot fork child - %s", ::strerror(errno)); ::exit(2); } else if (childPid > 0) { ::exit( 0 ); // we're done because we are the parent } // so we are the child - setsid causes this process to be a new // session leader, process group leader and has no controlling terminal if (static_cast(-1) == ::setsid()) { ::syslog( LOG_ERR, "Unable to become a session leader - %s", ::strerror(errno)); ::exit(2); } // Ignore the signal from this parent terminating ::signal(SIGHUP, SIG_IGN); // and fork again - puts the init process in charge of cleaning us up childPid = ::fork(); if (childPid < 0) { syslog( LOG_ERR, "Cannot fork 2nd child - %s", ::strerror(errno)); ::exit(2); } else if (childPid > 0) { ::exit( 0 ); // we're done because we are the first child } // close any open file descriptors int32 maxFd = ::sysconf(_SC_OPEN_MAX); if (maxFd < 0) { maxFd = OPEN_MAX; } for (int32 fd = 0; fd < maxFd; ++fd) { ::close(fd); } // and re-open syslog ::openlog(logProcName.c_str(), LOG_CONS | LOG_PID, LOG_USER); errno = 0; } // set a signal handler to catch SIGTERM & SIGINT struct sigaction sigActionInfo; if (pfnShutdownHandler) { ::memset(&sigActionInfo, 0, sizeof(struct sigaction)); sigActionInfo.sa_flags = 0; sigActionInfo.sa_handler = pfnShutdownHandler; sigemptyset(&sigActionInfo.sa_mask); if (-1 == ::sigaction(SIGTERM, &sigActionInfo, NULL)) { ::syslog( LOG_ERR, "Unable to setup shutdown signal handler - %s", ::strerror(errno)); ::exit(2); } if (-1 == ::sigaction(SIGINT, &sigActionInfo, NULL)) { ::syslog( LOG_ERR, "Unable to setup interrupt signal handler - %s", ::strerror(errno)); ::exit(2); } } else { ::syslog(LOG_WARNING, "No shutdown handler function was supplied."); } // ignore any terminal signals #ifdef SIGTTOU ::signal(SIGTTOU, SIG_IGN); #endif #ifdef SIGTTIN ::signal(SIGTTIN, SIG_IGN); #endif #ifdef SIGTSTP ::signal(SIGTSTP, SIG_IGN); #endif // set us up as the specified group if (!groupName.empty()) { struct group* groupInfo = ::getgrnam(groupName.c_str()); if (groupInfo) { if (logInfos) { ::syslog(LOG_INFO, "Switching to group %d", groupInfo->gr_gid); } if (0 != ::setgid(groupInfo->gr_gid)) { ::syslog( LOG_ERR, "Unable to become group %s - %s", groupName.c_str(), ::strerror(errno)); ::exit(2); } } else { ::syslog( LOG_ERR, "Unable to find group info for %s - %s", groupName.c_str(), ::strerror(errno)); ::exit(2); } } // set us up as the specified user if (!userName.empty()) { struct passwd * passwdInfo = ::getpwnam(userName.c_str()); if (passwdInfo) { if (logInfos) { ::syslog(LOG_INFO, "Switching to user %d", passwdInfo->pw_uid); } if (0 != ::setuid(passwdInfo->pw_uid)) { ::syslog( LOG_ERR, "Unable to become user %s - %s", userName.c_str(), ::strerror(errno)); ::exit(2); } } else { ::syslog( LOG_ERR, "Unable to find login info for %s - %s", userName.c_str(), ::strerror(errno)); ::exit(2); } } // Move the current directory to the specified directory // to make sure we don't hold a file system open. if (rootDir.empty()) { if (logInfos) { ::syslog(LOG_INFO, "Switching to directory of %s", procPath.c_str()); } const char * lastSlash = ::strrchr(procPath.c_str(), '/'); if (*lastSlash) { std::string directory = procPath; directory.erase(directory.rfind('/')); if (logInfos) { ::syslog(LOG_INFO, "chdir %s", directory.c_str()); } ::chdir(directory.c_str()); } else { if (logInfos) { ::syslog(LOG_INFO, "chdir /"); } ::chdir("/"); } } else { if (logInfos) { ::syslog(LOG_INFO, "Switching to directory %s", rootDir.c_str()); } if (-1 == ::chdir(rootDir.c_str())) { ::syslog( LOG_ERR, "::chdir to %s failed - %s", rootDir.c_str(), ::strerror(errno)); } } // set our umask correctly - disable all world access if (logInfos) { ::syslog(LOG_INFO, "umask 0007"); } ::umask(0007); // boost our open file limit struct rlimit rlimitInfo; ::getrlimit(RLIMIT_NOFILE, &rlimitInfo); if (rlimitInfo.rlim_cur < rlimitInfo.rlim_max) { if (logInfos) { #ifdef __x86_64__ ::syslog( LOG_INFO, "rlimit change #files from %lld to %lld", (long long) rlimitInfo.rlim_cur, (long long) rlimitInfo.rlim_max); #else ::syslog( LOG_INFO, "rlimit change #files from %d to %d", rlimitInfo.rlim_cur, rlimitInfo.rlim_max); #endif } rlimitInfo.rlim_cur = rlimitInfo.rlim_max; ::setrlimit(RLIMIT_NOFILE, &rlimitInfo); } else { if (logInfos) { #ifdef __x86_64__ ::syslog( LOG_INFO, "rlimit #files already at maximum of %lld", (long long) rlimitInfo.rlim_cur); #else ::syslog( LOG_INFO, "rlimit #files already at maximum of %d", rlimitInfo.rlim_cur); #endif } } if (enableCrashHandlers) { // Set up the crash handler struct sigaction newAction; struct sigaction oldAction; ::memset(&newAction, 0, sizeof(struct sigaction)); ::memset(&oldAction, 0, sizeof(struct sigaction)); newAction.sa_sigaction = DaemonUtilsCrashHandler; newAction.sa_flags = SA_SIGINFO | SA_RESETHAND; if (sigfillset(&newAction.sa_mask) == -1) { ::syslog( LOG_ERR, "Unable to fill crash handler signal set - %s", ::strerror(errno)); } else if (::sigaction(SIGILL, &newAction, &oldAction) == -1 || ::sigaction(SIGSEGV, &newAction, &oldAction) == -1 || ::sigaction(SIGFPE, &newAction, &oldAction) == -1 || ::sigaction(SIGBUS, &newAction, &oldAction) == -1) { ::syslog( LOG_ERR, "Unable to set crash handler signal handler %s", ::strerror(errno)); } } if (logInfos) ::syslog(LOG_INFO, "Initialized"); } extern "C" void DaemonUtilsCrashHandler(int32 sigNum, siginfo_t *info, void *context) { CAF_CM_STATIC_FUNC_LOG("CDaemonUtils", "DaemonUtilsCrashHandler"); try { std::string message("Got Signal "); switch (sigNum) { case SIGSEGV: message += "[SEGV"; break; case SIGBUS: message += "[BUS"; break; case SIGFPE: message += "[FPE"; break; case SIGILL: message += "[ILL"; break; default: message += "[UNKNOWN SIGNAL (" + CStringConv::toString(sigNum) + ")"; break; } message += " code=" + CStringConv::toString(info->si_code) + "]"; message += " Fault Addr[" + CStringConv::toString(info->si_addr) + "] "; #if defined ( __linux__ ) || defined ( __APPLE__ ) Dl_info dlInfo; if (0 != ::dladdr(info->si_addr, &dlInfo)) { if (dlInfo.dli_fname != NULL) { message += " Module ["; message += dlInfo.dli_fname; } if (dlInfo.dli_sname != NULL) { message += " Symbol ["; message += dlInfo.dli_sname; } } #else #error "Need to determine if DlInfo is available" #endif ::syslog(LOG_ERR, "%s", message.c_str()); CAF_CM_LOG_ERROR_VA0(message.c_str()); } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; ::exit(-1); } CDaemonUtils.h000066400000000000000000000007701321503522500337420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jun 9, 2011 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CDAEMONUTILS_H_ #define CDAEMONUTILS_H_ class CDaemonUtils { public: static void MakeDaemon( int32 argc, char** argv, const std::string& procPath, const std::string& procName, void(*pfnShutdownHandler)(int32 signalNum), bool& isDaemonized, bool& logInfos); CAF_CM_DECLARE_NOCREATE(CDaemonUtils); }; #endif /* CDAEMONUTILS_H_ */ CDateTimeUtils.cpp000066400000000000000000000044371321503522500345720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/*k * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #ifndef WIN32 #include #endif #include "CDateTimeUtils.h" using namespace Caf; #ifdef WIN32 #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 int32 CDateTimeUtils::getTimeOfDay(struct timeval *tv, struct timezone *tz) { FILETIME ft; unsigned __int64 tmpres = 0; static int32 tzflag; if (NULL != tv) { ::GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; /*converting file time to unix epoch*/ tmpres -= DELTA_EPOCH_IN_MICROSECS; tmpres /= 10; /*convert into microseconds*/ tv->tv_sec = (int32)(tmpres / 1000000UL); tv->tv_usec = (int32)(tmpres % 1000000UL); } if (NULL != tz) { if (!tzflag) { _tzset(); tzflag++; } long minuteswest = 0; ::_get_timezone(&minuteswest); tz->tz_minuteswest = minuteswest / 60; int32 dstHours = 0; ::_get_daylight(&dstHours); tz->tz_dsttime = dstHours == 0 ? 0 : 1; } return 0; } #else int32 CDateTimeUtils::getTimeOfDay(struct timeval *tv, struct timezone *tz) { return ::gettimeofday(tv, tz); } #endif uint64 CDateTimeUtils::getTimeMs() { CAF_CM_STATIC_FUNC("CDateTimeUtils", "getTimeMs"); timeval curTime; if(-1 == getTimeOfDay(&curTime, NULL)) { const int32 errorCode = errno; CAF_CM_EXCEPTION_VA0(errorCode, "getTimeOfDay failed"); } return (curTime.tv_sec * 1000) + (curTime.tv_usec / 1000); } uint64 CDateTimeUtils::calcRemainingTime( const uint64 begTimeMs, const uint64 totalMs) { CAF_CM_STATIC_FUNC_VALIDATE("CDateTimeUtils", "calcRemainingTime"); const uint64 diffTimeMs = CDateTimeUtils::getTimeMs() - begTimeMs; CAF_CM_VALIDATE_NONNEGATIVE_INT64(diffTimeMs); uint64 rc = 0; if(totalMs > diffTimeMs) { rc = totalMs - diffTimeMs; } return rc; } std::string CDateTimeUtils::getCurrentDateTime() { time_t now; ::time(&now); char buf[sizeof "0000-00-00T00:00:00Z"]; tm result; #ifdef WIN32 ::gmtime_s(&result, &now); ::strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", &result); #else ::gmtime_r(&now, &result); ::strftime(buf, sizeof buf, "%FT%TZ", &result); #endif return buf; } CDateTimeUtils.h000066400000000000000000000012221321503522500342240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CDateTimeUtils_H_ #define CDateTimeUtils_H_ #ifndef WIN32 #include #else #include #endif namespace Caf { class COMMONAGGREGATOR_LINKAGE CDateTimeUtils { public: static uint64 getTimeMs(); static uint64 calcRemainingTime( const uint64 begTimeMs, const uint64 totalMs); static int32 getTimeOfDay(struct timeval *tv, struct timezone *tz); static std::string getCurrentDateTime(); private: CAF_CM_DECLARE_NOCREATE(CDateTimeUtils); }; } #endif /* CDateTimeUtils_H_ */ CEnvironmentUtils.cpp000066400000000000000000000022201321503522500353660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: 10/19/2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CEnvironmentUtils.h" using namespace Caf; void CEnvironmentUtils::readEnvironmentVar(const char* varname, std::string& rValue) { CAF_CM_STATIC_FUNC_VALIDATE("CEnvironmentUtils", "readEnvironmentVar"); CAF_CM_VALIDATE_PTR(varname); #ifdef WIN32 char* dupEnvBuf = NULL; size_t dupEnvBufLen = 0; errno_t apiRc = ::_dupenv_s(&dupEnvBuf, &dupEnvBufLen, varname); rValue = std::string(dupEnvBuf && ::strlen(dupEnvBuf) ? dupEnvBuf : ""); ::free(dupEnvBuf); dupEnvBuf = NULL; #else const char *prValue = ::getenv(varname); if (NULL != prValue) { rValue = prValue; } #endif } void CEnvironmentUtils::writeEnvironmentVar(const char* varname, std::string& rValue) { CAF_CM_STATIC_FUNC_VALIDATE("CEnvironmentUtils", "writeEnvironmentVar"); CAF_CM_VALIDATE_PTR(varname); #ifdef WIN32 std::ostringstream formattedStream; formattedStream << std::string(varname) << std::string("=") << rValue; ::_putenv(formattedStream.str().c_str()); #else // Not Implemented #endif } CEnvironmentUtils.h000066400000000000000000000007621321503522500350440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: 10/19/2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CENVIRONMENTUTILS_H_ #define CENVIRONMENTUTILS_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CEnvironmentUtils { public: static void readEnvironmentVar(const char* varname, std::string& rValue); static void writeEnvironmentVar(const char* varname, std::string& rValue); private: CAF_CM_DECLARE_NOCREATE(CEnvironmentUtils); }; } #endif CFileLock.cpp000066400000000000000000000114001321503522500335310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CFileLock.h" #include "Exception/CCafException.h" #include #include #include #include using namespace Caf; //////////////////////////////////////////////////////////////////////// // // CFileLock::CFileLock() // //////////////////////////////////////////////////////////////////////// CFileLock::CFileLock() : CAF_CM_INIT("CFileLock"), _isInitialized(false), _isFileDescriptorLocal(false), _fileDescriptor(-1), _lockLevel(UNLOCK) { } //////////////////////////////////////////////////////////////////////// // // CFileLock::~CFileLock() // //////////////////////////////////////////////////////////////////////// CFileLock::~CFileLock() { CAF_CM_FUNCNAME("~CFileLock"); try { if (_isInitialized) { setLockLevel(UNLOCK, true); if (_isFileDescriptorLocal) ::close(_fileDescriptor); } } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; } //////////////////////////////////////////////////////////////////////// // // CFileLock::Initialize() // //////////////////////////////////////////////////////////////////////// void CFileLock::initialize(int32 iFileDescriptor) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _lockLevel = UNLOCK; _fileDescriptor = iFileDescriptor; _isFileDescriptorLocal = false; _isInitialized = true; } //////////////////////////////////////////////////////////////////////// // // CFileLock::Initialize() // //////////////////////////////////////////////////////////////////////// void CFileLock::initialize(const char* cszFilename, bool bCreateFile) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRINGPTRA(cszFilename); int32 iFlags = bCreateFile ? O_RDWR | O_CREAT : O_RDWR; int32 iFileDescriptor = ::open(cszFilename, iFlags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (-1 != iFileDescriptor) { _lockLevel = UNLOCK; _fileDescriptor = iFileDescriptor; _isFileDescriptorLocal = true; _isInitialized = true; } else { int32 iRc = errno; CAF_CM_EXCEPTION_VA1(iRc, "Unable to open file %s", cszFilename); } } //////////////////////////////////////////////////////////////////////// // // CFileLock::GetLockLevel() // //////////////////////////////////////////////////////////////////////// CFileLock::ELockLevel CFileLock::getLockLevel() const { CAF_CM_FUNCNAME_VALIDATE("getLockLeve"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _lockLevel; } //////////////////////////////////////////////////////////////////////// // // CFileLock::SetLockLevel() // //////////////////////////////////////////////////////////////////////// void CFileLock::setLockLevel(ELockLevel eLockLevel, bool bDowngradeLock) { CAF_CM_FUNCNAME("setLockLeve"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); bool bLockChangeOK = true; // determine if we are attempting to downgrade an existing lock if (!bDowngradeLock) { if (eLockLevel <= _lockLevel) { bLockChangeOK = false; } } if (bLockChangeOK && (eLockLevel != _lockLevel)) { struct flock stFlock; ::memset(&stFlock, 0, sizeof(stFlock)); stFlock.l_whence = SEEK_SET; stFlock.l_start = 0; stFlock.l_len = 1; if (SHARED_LOCK == eLockLevel) stFlock.l_type = F_RDLCK; else if (EXCLUSIVE_LOCK == eLockLevel) stFlock.l_type = F_WRLCK; else stFlock.l_type = F_UNLCK; if (-1 != ::fcntl(_fileDescriptor, F_SETLKW, &stFlock)) { _lockLevel = eLockLevel; } else { CAF_CM_EXCEPTION_VA0(errno, "Unable to modify lock"); } } } //////////////////////////////////////////////////////////////////////// // // CFileLock::AttemptSetLockLevel() // //////////////////////////////////////////////////////////////////////// bool CFileLock::attemptSetLockLevel(ELockLevel eLockLevel, bool bDowngradeLock) { CAF_CM_FUNCNAME("attemptSetLockLeve"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); bool bRet = false; bool bLockChangeOK = true; // determine if we are attempting to downgrade an existing lock if (!bDowngradeLock) { if (eLockLevel <= _lockLevel) { bLockChangeOK = false; } } if (bLockChangeOK && (eLockLevel != _lockLevel)) { struct flock stFlock; ::memset(&stFlock, 0, sizeof(stFlock)); stFlock.l_whence = SEEK_SET; stFlock.l_start = 0; stFlock.l_len = 1; if (SHARED_LOCK == eLockLevel) stFlock.l_type = F_RDLCK; else if (EXCLUSIVE_LOCK == eLockLevel) stFlock.l_type = F_WRLCK; else stFlock.l_type = F_UNLCK; if (-1 != ::fcntl(_fileDescriptor, F_SETLK, &stFlock)) { _lockLevel = eLockLevel; bRet = true; } else if ((EACCES != errno) && (EAGAIN != errno)) { CAF_CM_EXCEPTION_VA0(errno, "Unable to modify lock"); } } return bRet; } CFileSystemUtils.cpp000066400000000000000000000775371321503522500351750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Exception/CCafException.h" #include "CFileSystemUtils.h" #include "../Collections/Iterators/IteratorsInc.h" #ifdef WIN32 #include #endif #ifdef __linux__ #include #include #endif #include #include using namespace Caf; const std::string FileSystemUtils::REGEX_MATCH_ALL; void FileSystemUtils::createDirectory( const std::string& path, const uint32 mode/* = 0770*/) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "createDirectory"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); if(doesDirectoryExist(path)) { CAF_CM_EXCEPTIONEX_VA1( IllegalStateException, ERROR_ALREADY_EXISTS, "Directory exists: %s", path.c_str()); } else { CAF_CM_LOG_DEBUG_VA1("Creating directory - %s", path.c_str()); int32 rc = g_mkdir_with_parents(path.c_str(), mode); if(rc < 0) { rc = errno; CAF_CM_EXCEPTIONEX_VA1( IOException, rc, "Unable to create directory: %s", path.c_str()); } } } CAF_CM_EXIT; } void FileSystemUtils::removeDirectory( const std::string& path) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "removeDirectory"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); if(doesDirectoryExist(path)) { CAF_CM_LOG_DEBUG_VA1("Removing directory - %s", path.c_str()); int32 rc = g_rmdir(path.c_str()); if(rc < 0) { rc = errno; CAF_CM_EXCEPTIONEX_VA1( IOException, rc, "Failed to remove directory: %s", path.c_str()); } } else { CAF_CM_EXCEPTIONEX_VA1( PathNotFoundException, 0, "Directory does not exist: %s", path.c_str()); } } CAF_CM_EXIT; } void FileSystemUtils::recursiveRemoveDirectory(const std::string& path) { CAF_CM_STATIC_FUNC("FileSystemUtils", "recursiveRemoveDirectory"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); if(doesDirectoryExist(path)) { DirectoryItems items = itemsInDirectory(path, REGEX_MATCH_ALL); // Delete subdirs first for (TConstIterator directory(items.directories); directory; directory++) { recursiveRemoveDirectory(path + G_DIR_SEPARATOR_S + *directory); } // Delete files for (TConstIterator file(items.files); file; file++) { removeFile(path + G_DIR_SEPARATOR_S + *file); } // Delete directory removeDirectory(path); } else { CAF_CM_EXCEPTIONEX_VA1( PathNotFoundException, 0, "Directory does not exist: %s", path.c_str()); } } CAF_CM_EXIT; } void FileSystemUtils::removeFile( const std::string& path) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "removeFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); if(doesFileExist(path)) { CAF_CM_LOG_DEBUG_VA1("Removing file - %s", path.c_str()); int32 rc = g_remove(path.c_str()); if(rc < 0) { rc = errno; CAF_CM_EXCEPTIONEX_VA1( IOException, rc,"Failed to remove file: %s", path.c_str()); } } else { CAF_CM_EXCEPTIONEX_VA1( FileNotFoundException, 0, "File does not exist: %s", path.c_str()); } } CAF_CM_EXIT; } FileSystemUtils::Files FileSystemUtils::removeFilesInDirectory( const std::string& path, const std::string& regex) { CAF_CM_STATIC_FUNC("FileSystemUtils", "removeFilesInDirectory"); Files rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); if(doesDirectoryExist(path)) { DirectoryItems items = itemsInDirectory(path, regex); for (TConstIterator file(items.files); file; file++) { removeFile(path + G_DIR_SEPARATOR_S + *file); rc.push_back(*file); } } else { CAF_CM_EXCEPTIONEX_VA1( PathNotFoundException, 0, "Directory does not exist: %s", path.c_str()); } } CAF_CM_EXIT; return rc; } bool FileSystemUtils::doesFileExist( const std::string& path) { CAF_CM_STATIC_FUNC_VALIDATE( "FileSystemUtils", "doesFileExist" ); CAF_CM_VALIDATE_STRING(path); return isRegularFile(path); } bool FileSystemUtils::doesDirectoryExist( const std::string& path) { CAF_CM_STATIC_FUNC_LOG_VALIDATE( "FileSystemUtils", "doesDirectoryExist" ); bool rc = false; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); rc = (GLIB_TRUE == g_file_test(path.c_str(), G_FILE_TEST_IS_DIR)); } CAF_CM_EXIT; return rc; } bool FileSystemUtils::isRegularFile( const std::string& path) { CAF_CM_STATIC_FUNC_VALIDATE( "FileSystemUtils", "isRegularFile" ); bool rc = false; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); // Test to make sure the source is a regular file (or symlink to one), not a directory rc = (g_file_test(path.c_str(), G_FILE_TEST_IS_REGULAR) == GLIB_TRUE); } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::getCurrentDir() { return getDirname(getCurrentFile()); } std::string FileSystemUtils::getCurrentFile() { std::string fileName; CEcmDllManager::GetLibraryNameFromHandle(NULL, fileName); return fileName; } std::string FileSystemUtils::getBasename( const std::string& path) { CAF_CM_STATIC_FUNC( "FileSystemUtils", "getBasename" ); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); gchar* basename = g_path_get_basename(path.c_str()); if(NULL == basename) { CAF_CM_EXCEPTION_EFAIL( "g_path_get_basename Failed: " + path); } rc = basename; g_free(basename); } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::getDirname( const std::string& path) { CAF_CM_STATIC_FUNC( "FileSystemUtils", "getDirname" ); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); gchar* dirname = g_path_get_dirname(path.c_str()); if(NULL == dirname) { CAF_CM_EXCEPTION_EFAIL( "g_path_get_dirname Failed: " + path); } rc = dirname; g_free(dirname); } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::getTmpDir() { CAF_CM_STATIC_FUNC( "FileSystemUtils", "getTmpDir" ); std::string rc; CAF_CM_ENTER { const gchar* tmpDir = g_get_tmp_dir(); if(NULL == tmpDir) { CAF_CM_EXCEPTION_EFAIL( "g_get_tmp_dir Failed"); } else { // Trim trailing slash rc = tmpDir; rc.erase(rc.find_last_not_of(G_DIR_SEPARATOR)+1); } } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::buildPath( const std::string& path, const std::string& newElement) { CAF_CM_STATIC_FUNC( "FileSystemUtils", "buildPath" ); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); CAF_CM_VALIDATE_STRING(newElement); gchar* newPath = g_build_filename(path.c_str(), newElement.c_str(), NULL); if(NULL == newPath) { CAF_CM_EXCEPTION_VA2(E_FAIL, "g_build_filename Failed: %s, %s", path.c_str(), newElement.c_str()); } rc = normalizePathForPlatform(newPath); g_free(newPath); } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::buildPath( const std::string& path, const std::string& newElement1, const std::string& newElement2) { CAF_CM_STATIC_FUNC( "FileSystemUtils", "buildPath" ); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); CAF_CM_VALIDATE_STRING(newElement1); CAF_CM_VALIDATE_STRING(newElement2); gchar* newPath = g_build_filename(path.c_str(), newElement1.c_str(), newElement2.c_str(), NULL); if(NULL == newPath) { CAF_CM_EXCEPTION_VA3(E_FAIL, "g_build_filename Failed: %s, %s, %s", path.c_str(), newElement1.c_str(), newElement2.c_str()); } rc = normalizePathForPlatform(newPath); g_free(newPath); } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::buildPath( const std::string& path, const std::string& newElement1, const std::string& newElement2, const std::string& newElement3) { CAF_CM_STATIC_FUNC( "FileSystemUtils", "buildPath" ); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); CAF_CM_VALIDATE_STRING(newElement1); CAF_CM_VALIDATE_STRING(newElement2); CAF_CM_VALIDATE_STRING(newElement3); gchar* newPath = g_build_filename( path.c_str(), newElement1.c_str(), newElement2.c_str(), newElement3.c_str(), NULL); if(NULL == newPath) { CAF_CM_EXCEPTION_VA4(E_FAIL, "g_build_filename Failed: %s, %s, %s, %s", path.c_str(), newElement1.c_str(), newElement2.c_str(), newElement3.c_str()); } rc = normalizePathForPlatform(newPath); g_free(newPath); } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::buildPath( const std::string& path, const std::string& newElement1, const std::string& newElement2, const std::string& newElement3, const std::string& newElement4) { CAF_CM_STATIC_FUNC( "FileSystemUtils", "buildPath" ); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); CAF_CM_VALIDATE_STRING(newElement1); CAF_CM_VALIDATE_STRING(newElement2); CAF_CM_VALIDATE_STRING(newElement3); CAF_CM_VALIDATE_STRING(newElement4); gchar* newPath = g_build_filename( path.c_str(), newElement1.c_str(), newElement2.c_str(), newElement3.c_str(), newElement4.c_str(), NULL); if(NULL == newPath) { CAF_CM_EXCEPTION_VA5(E_FAIL, "g_build_filename Failed: %s, %s, %s, %s, %s", path.c_str(), newElement1.c_str(), newElement2.c_str(), newElement3.c_str(), newElement4.c_str()); } rc = normalizePathForPlatform(newPath); g_free(newPath); } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::loadTextFile( const std::string& path) { CAF_CM_STATIC_FUNC( "FileSystemUtils", "loadTextFile" ); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); // Throw an exception if the file doesn't exist. if (!doesFileExist(path)) { CAF_CM_EXCEPTIONEX_VA1( FileNotFoundException, 0, "The file '%s' does not exist.", path.c_str()); } // Read in the contents of the file. Since this is a text file, it's terminated with NULL // so we needn't pass the length. GError *gError = NULL; gchar *fileContents = NULL; const bool isSuccessful = g_file_get_contents(path.c_str(), &fileContents, NULL, &gError); // If the call wasn't successful, throw an exception with the error information. if(! isSuccessful) { CAF_CM_VALIDATE_PTR(gError); const std::string errorMessage = gError->message; const int32 errorCode = gError->code; g_error_free(gError); CAF_CM_EXCEPTIONEX_VA2( IOException, errorCode, "g_file_get_contents Failed: %s File: %s", errorMessage.c_str(), path.c_str()); } if (fileContents && ::strlen(fileContents)) { rc = fileContents; } g_free(fileContents); } CAF_CM_EXIT; return rc; } Cdeqstr FileSystemUtils::loadTextFileIntoColl( const std::string& path) { CAF_CM_STATIC_FUNC("FileSystemUtils", "loadTextFileIntoColl"); CAF_CM_VALIDATE_STRING(path); // Throw an exception if the file doesn't exist. if (!doesFileExist(path)) { CAF_CM_EXCEPTIONEX_VA1( FileNotFoundException, 0, "The file '%s' does not exist.", path.c_str()); } std::ifstream fileStream(path.c_str()); if (! fileStream.is_open()) { CAF_CM_EXCEPTION_VA1(E_UNEXPECTED, "Error opening file - %s", path.c_str()); } Cdeqstr rc; std::string line; while(std::getline(fileStream, line)) { rc.push_back(line); } if (fileStream.bad()) { CAF_CM_EXCEPTION_VA1(E_UNEXPECTED, "Error reading file - %s", path.c_str()); } return rc; } SmartPtrCDynamicByteArray FileSystemUtils::loadByteFile( const std::string& path) { CAF_CM_STATIC_FUNC("FileSystemUtils", "loadByteFile"); SmartPtrCDynamicByteArray rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); // Throw an exception if the file doesn't exist. if (!doesFileExist(path)) { CAF_CM_EXCEPTIONEX_VA1( FileNotFoundException, 0, "The file '%s' does not exist.", path.c_str()); } // Read in the contents of the file. Since this is a text file, it's terminated with NULL // so we needn't pass the length. GError *gError = NULL; gchar *fileContents = NULL; gsize fileContentsLen = 0; const bool isSuccessful = g_file_get_contents( path.c_str(), &fileContents, &fileContentsLen, &gError); // If the call wasn't successful, throw an exception with the error information. if(! isSuccessful) { CAF_CM_VALIDATE_PTR(gError); const std::string errorMessage = gError->message; const int32 errorCode = gError->code; g_error_free(gError); CAF_CM_EXCEPTIONEX_VA2( IOException, errorCode, "g_file_get_contents Failed: %s File: %s", errorMessage.c_str(), path.c_str()); } if (fileContents && fileContentsLen) { rc.CreateInstance(); rc->allocateBytes(static_cast(fileContentsLen)); rc->memCpy(fileContents, static_cast(fileContentsLen)); } g_free(fileContents); } CAF_CM_EXIT; return rc; } void FileSystemUtils::saveTextFile( const std::string& outputDir, const std::string& filename, const std::string& contents, const FILE_MODE_TYPE fileMode/* = FILE_MODE_REPLACE*/, const std::string temporaryFileSuffix/* = ".tmp"*/) { CAF_CM_STATIC_FUNC_VALIDATE("FileSystemUtils", "saveTextFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(outputDir); CAF_CM_VALIDATE_STRING(filename); CAF_CM_VALIDATE_STRING(contents); const std::string filePath = buildPath(outputDir, filename); saveTextFile(filePath, contents, fileMode, temporaryFileSuffix); } CAF_CM_EXIT; } void FileSystemUtils::saveTextFile( const std::string& filePath, const std::string& contents, const FILE_MODE_TYPE fileMode/* = FILE_MODE_REPLACE*/, const std::string temporaryFileSuffix/* = ".tmp"*/) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("FileSystemUtils", "saveTextFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); CAF_CM_VALIDATE_STRING(contents); saveByteFile(filePath, reinterpret_cast(contents.c_str()), contents.length(), fileMode, temporaryFileSuffix); } CAF_CM_EXIT; } void FileSystemUtils::saveByteFile( const std::string& filePath, const SmartPtrCDynamicByteArray& contents, const FILE_MODE_TYPE fileMode/* = FILE_MODE_REPLACE*/, const std::string temporaryFileSuffix/* = ".tmp"*/) { CAF_CM_STATIC_FUNC_VALIDATE("FileSystemUtils", "saveByteFile"); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_VALIDATE_SMARTPTR(contents); // temporaryFileSuffix is optional saveByteFile(filePath, contents->getPtr(), contents->getByteCount(), fileMode, temporaryFileSuffix); } void FileSystemUtils::saveByteFile( const std::string& filePath, const byte* contents, const size_t& contentsLen, const FILE_MODE_TYPE fileMode/* = FILE_MODE_REPLACE*/, const std::string temporaryFileSuffix/* = ".tmp"*/) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "saveByteFile"); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_VALIDATE_PTR(contents); // temporaryFileSuffix is optional const std::string fileDir = getDirname(filePath); if (! doesDirectoryExist(fileDir)) { createDirectory(fileDir); } bool fileExists = doesFileExist(filePath); switch (fileMode) { case FILE_MODE_REPLACE: if (fileExists) { CAF_CM_LOG_DEBUG_VA1("Replacing file - %s", filePath.c_str()); } saveFileSafely(filePath, contents, contentsLen, temporaryFileSuffix); break; case FILE_MODE_IGNORE: if (fileExists) { CAF_CM_LOG_WARN_VA1("Ignoring file - %s", filePath.c_str()); } else { saveFileSafely(filePath, contents, contentsLen, temporaryFileSuffix); } break; case FILE_MODE_FAIL: if (fileExists) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_EXISTS, "File exists - %s", filePath.c_str()); } saveFileSafely(filePath, contents, contentsLen, temporaryFileSuffix); break; } } void FileSystemUtils::saveFileSafely( const std::string& filePath, const byte* contents, const size_t& contentsLen, const std::string& temporaryFileSuffix) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("FileSystemUtils", "saveFileSafely"); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_VALIDATE_PTR(contents); // temporaryFileSuffix is optional CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); if (temporaryFileSuffix.empty()) { saveByteFileRaw(filePath, contents, contentsLen); } else { const std::string filePathTmp = filePath + temporaryFileSuffix; saveByteFileRaw(filePathTmp, contents, contentsLen); moveFile(filePathTmp, filePath); } } void FileSystemUtils::saveByteFileRaw( const std::string& path, const byte* contents, const size_t& contentsLen) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "saveByteFileRaw"); CAF_CM_VALIDATE_STRING(path); CAF_CM_VALIDATE_PTR(contents); GError *gError = NULL; const bool isSuccessful = g_file_set_contents( path.c_str(), reinterpret_cast(contents), contentsLen, &gError); // If the call wasn't successful, throw an exception with the error information. if(! isSuccessful) { CAF_CM_VALIDATE_PTR(gError); const std::string errorMessage = gError->message; const int32 errorCode = gError->code; g_error_free(gError); CAF_CM_EXCEPTIONEX_VA2( IOException, errorCode, "g_file_set_contents Failed: %s File: %s", errorMessage.c_str(), path.c_str()); } } FileSystemUtils::DirectoryItems FileSystemUtils::itemsInDirectory( const std::string& path, const std::string& regex) { CAF_CM_STATIC_FUNC( "FileSystemUtils", "itemsInDirectory" ); DirectoryItems rc; GDir *gDir = NULL; GError *gError = NULL; GRegex *gRegex = NULL; try { CAF_CM_VALIDATE_STRING(path); if(! doesDirectoryExist(path)) { CAF_CM_EXCEPTIONEX_VA1( PathNotFoundException, 0, "Directory does not exist: %s", path.c_str()); } gDir = g_dir_open(path.c_str(), 0, &gError); if(NULL == gDir) { const std::string errorMessage = (gError == NULL) ? "" : gError->message; const int32 errorCode = (gError == NULL) ? 0 : gError->code; CAF_CM_EXCEPTIONEX_VA2( IOException, errorCode, "Failed to open directory \"%s\": %s", path.c_str(), errorMessage.c_str()); } if(regex.compare(REGEX_MATCH_ALL) != 0) { gRegex = g_regex_new(regex.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_RAW), (GRegexMatchFlags)0, &gError); if(gError) { const std::string errorMessage = gError->message; const int32 errorCode = gError->code; CAF_CM_EXCEPTIONEX_VA2(IOException, errorCode, "g_regex_new Failed: %s regex: %s", errorMessage.c_str(), regex.c_str()); } } for(const gchar* filename = g_dir_read_name(gDir); filename != NULL; filename = g_dir_read_name(gDir)) { std::string fullPath(path); fullPath += G_DIR_SEPARATOR_S; fullPath += filename; bool isDirectory = g_file_test(fullPath.c_str(), G_FILE_TEST_IS_DIR); if (gRegex) { if (g_regex_match(gRegex, filename, (GRegexMatchFlags)0, NULL)) { if (isDirectory) { rc.directories.push_back(filename); } else { rc.files.push_back(filename); } } } else { if (isDirectory) { rc.directories.push_back(filename); } else { rc.files.push_back(filename); } } } if(gError != NULL) { g_error_free(gError); } if(gDir != NULL) { g_dir_close(gDir); } if(gRegex != NULL) { g_regex_unref(gRegex); } } catch(...) { if(gError != NULL) { g_error_free(gError); } if(gDir != NULL) { g_dir_close(gDir); } if(gRegex != NULL) { g_regex_unref(gRegex); } throw; } return rc; } FileSystemUtils::PathAndDirectoryItemsCollection FileSystemUtils::recursiveItemsInDirectory(const std::string& path, const std::string& regex) { PathAndDirectoryItemsCollection rc; CAF_CM_ENTER { DirectoryItems items = itemsInDirectory(path, regex); rc.push_back(PathAndDirectoryItems(path, items)); for (TConstIterator subdir(items.directories); subdir; subdir++) { std::string subdirPath = buildPath(path, *subdir); PathAndDirectoryItemsCollection subitems = recursiveItemsInDirectory(subdirPath, regex); rc.insert(rc.end(), subitems.begin(), subitems.end()); } } CAF_CM_EXIT; return rc; } void FileSystemUtils::copyFile(const std::string& srcPath, const std::string& dstPath) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "copyFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(srcPath); CAF_CM_VALIDATE_STRING(dstPath); // Test to make sure the source is a regular file (or symlink to one), not a directory if (! isRegularFile(srcPath)) { CAF_CM_EXCEPTIONEX_VA1( UnsupportedOperationException, 0, "Source is not a regular file: %s", srcPath.c_str()); } const std::string dstDir = getDirname(dstPath); if (!doesDirectoryExist(dstDir)) { CAF_CM_EXCEPTIONEX_VA1( PathNotFoundException, 0, "Destination path does not exist: %s", dstDir.c_str()); } #if defined (__linux__) || defined (__APPLE__) int32 infd = -1; int32 outfd = -1; try { // Determine the stats of the source file, for use with output file later struct stat srcStat; if (::stat(srcPath.c_str(), &srcStat) != 0) { int32 rc = errno; CAF_CM_EXCEPTIONEX_VA1( IOException, rc, "::stat %s failed", srcPath.c_str()); } infd = ::open(srcPath.c_str(), O_RDONLY); if (infd == -1) { int32 rc = errno; CAF_CM_EXCEPTIONEX_VA1( IOException, rc, "Unable to open %s for reading", srcPath.c_str()); } // Open output file write-only for user, initially, and set to source file's mode bits later outfd = ::open(dstPath.c_str(), O_WRONLY | O_CREAT, S_IWUSR); if (outfd == -1) { int32 rc = errno; CAF_CM_EXCEPTIONEX_VA1( IOException, rc, "Unable to open %s for writing", dstPath.c_str()); } // Arbitrary size for the data buffer to use for the copy const int32 buff_size = 65536; byte buffer[buff_size]; ssize_t index = 0; // Loop until we've processed the whole file while (index < srcStat.st_size) { ssize_t bytesRead = ::read(infd, buffer, buff_size); if (bytesRead > 0) { ssize_t writeIndex = 0; // Loop until we've written out all the buffer while (writeIndex < bytesRead) { // If we're part way done, write from where we left off, but with a smaller number of bytes left ssize_t bytesWritten = ::write(outfd, buffer + writeIndex, bytesRead - writeIndex); if (bytesWritten < 0) { int32 rc = errno; CAF_CM_EXCEPTIONEX_VA2( IOException, rc, "Unable to write to %s (index = %d)", dstPath.c_str(), writeIndex); } writeIndex += bytesWritten; } index += bytesRead; } else if (bytesRead < 0) { int32 rc = errno; CAF_CM_EXCEPTIONEX_VA2( IOException, rc, "Unable to read from %s at offset %d", srcPath.c_str(), index); } } if (outfd != -1) { // Lastly, update the mode bits on the destination file to be the same as the source ::fchmod(outfd, srcStat.st_mode); } } CAF_CM_CATCH_ALL; if (infd != -1) { ::close(infd); } if (outfd != -1) { ::close(outfd); } CAF_CM_THROWEXCEPTION; #elif defined(WIN32) const std::wstring wSrcPath = CStringUtils::convertNarrowToWide(srcPath); const std::wstring wDstPath = CStringUtils::convertNarrowToWide(dstPath); BOOL bRc = ::CopyFileW( wSrcPath.c_str(), wDstPath.c_str(), TRUE); if (!bRc) { const DWORD lastError = ::GetLastError(); const std::string errorMsg = BasePlatform::PlatformApi::GetApiErrorMessage(lastError); CAF_CM_EXCEPTIONEX_VA3( IOException, lastError, "Failed to copy file %s to %s - %s", srcPath.c_str(), dstPath.c_str(), errorMsg.c_str()); } #else #error not implemented #endif } CAF_CM_EXIT; } void FileSystemUtils::moveFile(const std::string& srcPath, const std::string& dstPath) { CAF_CM_STATIC_FUNC("FileSystemUtils", "moveFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(srcPath); CAF_CM_VALIDATE_STRING(dstPath); if (!doesFileExist(srcPath)) { CAF_CM_EXCEPTIONEX_VA1( FileNotFoundException, 0, "Source file does not exist: %s", srcPath.c_str()); } if (!doesDirectoryExist(getDirname(dstPath))) { createDirectory(getDirname(dstPath)); } if (g_rename(srcPath.c_str(), dstPath.c_str()) == -1) { int32 rc = errno; CAF_CM_EXCEPTIONEX_VA2( IOException, rc, "Unable to move file %s to %s", srcPath.c_str(), dstPath.c_str()); } } CAF_CM_EXIT; } void FileSystemUtils::copyDirectory(const std::string& srcPath, const std::string& dstPath) { CAF_CM_STATIC_FUNC("FileSystemUtils", "copyDirectory"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(srcPath); CAF_CM_VALIDATE_STRING(dstPath); if(doesDirectoryExist(dstPath)) { CAF_CM_EXCEPTIONEX_VA1( IOException, ERROR_ALREADY_EXISTS, "Cannot copy into an existing directory: %s", dstPath.c_str()); } createDirectory(dstPath); if(!doesDirectoryExist(srcPath)) { CAF_CM_EXCEPTIONEX_VA1( PathNotFoundException, 0, "Invalid source directory: %s", srcPath.c_str()); } const DirectoryItems items = itemsInDirectory(srcPath, FileSystemUtils::REGEX_MATCH_ALL); for (TConstIterator srcFile(items.files); srcFile; srcFile++) { copyFile(srcPath + G_DIR_SEPARATOR_S + *srcFile, dstPath + G_DIR_SEPARATOR_S + *srcFile); } } CAF_CM_EXIT; } void FileSystemUtils::recursiveCopyDirectory(const std::string& srcPath, const std::string& dstPath) { CAF_CM_STATIC_FUNC_VALIDATE("FileSystemUtils", "recursiveCopyDirectory"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(srcPath); CAF_CM_VALIDATE_STRING(dstPath); const DirectoryItems items = itemsInDirectory(srcPath, FileSystemUtils::REGEX_MATCH_ALL); // Copy subdirectories first for (TConstIterator srcDir(items.directories); srcDir; srcDir++) { copyDirectory(srcPath + G_DIR_SEPARATOR_S + *srcDir, dstPath + G_DIR_SEPARATOR_S + *srcDir); } // Copy files second for (TConstIterator srcFile(items.files); srcFile; srcFile++) { copyFile(srcPath + G_DIR_SEPARATOR_S + *srcFile, dstPath + G_DIR_SEPARATOR_S + *srcFile); } } CAF_CM_EXIT; } std::string FileSystemUtils::findOptionalFile( const std::string& directory, const std::string& filename) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "findOptionalFile"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(filename); const std::deque files = findOptionalFiles(directory, filename); if (files.size() == 1) { rc = files[0]; } else if (files.size() > 1) { CAF_CM_EXCEPTION_VA2(ERROR_FILE_EXISTS, "Found more than one file - directory: %s, filename: %s", directory.c_str(), filename.c_str()) } } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::findRequiredFile( const std::string& directory, const std::string& filename) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "findRequiredFile"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(filename); rc = findOptionalFile(directory, filename); if (rc.empty()) { CAF_CM_EXCEPTION_VA2(ERROR_FILE_NOT_FOUND, "File not found - directory: %s, filename: %s", directory.c_str(), filename.c_str()) } } CAF_CM_EXIT; return rc; } std::deque FileSystemUtils::findOptionalFiles( const std::string& directory, const std::string& filename) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("FileSystemUtils", "findOptionalFiles"); std::deque rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(filename); PathAndDirectoryItemsCollection pAndDItemsCol = recursiveItemsInDirectory(directory, REGEX_MATCH_ALL); for (TConstIterator pAndDItemsColIter(pAndDItemsCol); pAndDItemsColIter; pAndDItemsColIter++) { const std::string path = pAndDItemsColIter->path; const DirectoryItems directoryItems = pAndDItemsColIter->items; const Files files = directoryItems.files; for (TConstIterator fileIter(files); fileIter; fileIter++) { const std::string filenameCur = *fileIter; if (filenameCur.compare(filename) == 0) { const std::string filePath = buildPath(path, filename); rc.push_back(filePath); } } } } CAF_CM_EXIT; return rc; } std::deque FileSystemUtils::findRequiredFiles( const std::string& directory, const std::string& filename) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "findRequiredFiles"); std::deque rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(filename); rc = findOptionalFiles(directory, filename); if (rc.empty()) { CAF_CM_EXCEPTION_VA2(ERROR_FILE_NOT_FOUND, "File not found - directory: %s, filename: %s", directory.c_str(), filename.c_str()) } } CAF_CM_EXIT; return rc; } void FileSystemUtils::chmod( const std::string &path, const uint32 mode/* = 0770*/) { CAF_CM_STATIC_FUNC_LOG("FileSystemUtils", "chmod"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); if(! doesFileExist(path)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, 0, "File does not exist: %s", path.c_str()); } // Not using g_chmod on Nix because it hangs. #ifdef WIN32 g_chmod(path.c_str(), mode); #else const int32 rc = ::chmod(path.c_str(), mode); if (rc != 0) { CAF_CM_EXCEPTION_VA1(E_INVALIDARG, "chmod failed - file: %s, filename: %s", path.c_str()); } #endif } CAF_CM_EXIT; } std::string FileSystemUtils::normalizePathForPlatform( const std::string &path) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("FileSystemUtils", "normalizePathForPlatform"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); rc = path; #ifdef WIN32 std::replace(rc.begin(), rc.end(), '/', '\\'); #else std::replace(rc.begin(), rc.end(), '\\', '/'); #endif } CAF_CM_EXIT; return rc; } std::string FileSystemUtils::normalizePathWithForward( const std::string &path) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("FileSystemUtils", "normalizePathWithForward"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(path); rc = path; std::replace(rc.begin(), rc.end(), '\\', '/'); } CAF_CM_EXIT; return rc; } int64 FileSystemUtils::getFileSize(const std::string& filename) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("FileSystemUtils", "getFileSize"); CAF_CM_VALIDATE_STRING(filename); struct stat stat_buf; int32 rc = ::stat(filename.c_str(), &stat_buf); return rc == 0 ? stat_buf.st_size : -1; } std::string FileSystemUtils::saveTempTextFile(const std::string& filename_template, const std::string& contents) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("FileSystemUtils", "saveTempTextFile"); std::string filename; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filename_template); CAF_CM_VALIDATE_STRING(contents); filename = FileSystemUtils::getTempFilename(filename_template); FileSystemUtils::saveTextFile(filename, contents); } CAF_CM_EXIT; return filename; } std::string FileSystemUtils::getTempFilename(const std::string& filename_template) { CAF_CM_STATIC_FUNC("FileSystemUtils", "getTempFilename"); std::string filename; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filename_template); gchar* allocatedFilename; GError *gError = NULL; int32 fd = g_file_open_tmp(filename_template.c_str(), &allocatedFilename, &gError); if (fd >= 0) { filename = allocatedFilename; #ifdef WIN32 ::_close(fd); #else ::close(fd); #endif g_free(allocatedFilename); } if (gError != NULL) { const std::string errorMessage = gError->message; const int32 errorCode = gError->code; g_error_free(gError); CAF_CM_EXCEPTIONEX_VA2( IOException, errorCode, "g_file_open_tmp Failed: %s Template: %s", errorMessage.c_str(), filename_template.c_str()); } } CAF_CM_EXIT; CAF_CM_VALIDATE_STRING(filename); return filename; } std::string FileSystemUtils::executeScript( const std::string& scriptPath, const std::string& scriptResultsDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("FileSystemUtils", "executeScript"); CAF_CM_VALIDATE_STRING(scriptPath); CAF_CM_VALIDATE_STRING(scriptResultsDir); Cdeqstr argv; argv.push_back(scriptPath); const std::string basename = FileSystemUtils::getBasename(scriptPath); const std::string stdoutPath = FileSystemUtils::buildPath( scriptResultsDir, basename + ".stdout"); const std::string stderrPath = FileSystemUtils::buildPath( scriptResultsDir, basename + ".stderr"); ProcessUtils::runSyncToFiles(argv, stdoutPath, stderrPath); std::string rc; if (FileSystemUtils::doesFileExist(stdoutPath)) { rc = FileSystemUtils::loadTextFile(stdoutPath); } return rc; } CFileSystemUtils.h000066400000000000000000000127171321503522500346270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CFILESYSTEMUTILS_H_ #define CFILESYSTEMUTILS_H_ #include "Memory/DynamicArray/DynamicArrayInc.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE FileSystemUtils { public: // Helpful typedefs // file or directory name only: no path. typedef std::deque Files; typedef Files Directories; // directory and file names only: no path. struct DirectoryItems { DirectoryItems() {}; DirectoryItems(const Directories& d, const Files& f) : directories(d), files(f) {}; Directories directories; Files files; }; // first is full path to the items in DirectoryItems struct PathAndDirectoryItems { PathAndDirectoryItems() {}; PathAndDirectoryItems(const std::string& p, DirectoryItems& i) : path(p), items(i) {}; std::string path; DirectoryItems items; }; typedef enum { FILE_MODE_REPLACE, FILE_MODE_FAIL, FILE_MODE_IGNORE } FILE_MODE_TYPE; typedef std::deque PathAndDirectoryItemsCollection; // Use this constant to match all item names in a directory static const std::string REGEX_MATCH_ALL; static void createDirectory(const std::string &path, const uint32 mode = 0770); static void removeDirectory(const std::string& path); static void recursiveRemoveDirectory(const std::string& path); static void removeFile(const std::string& path); static Files removeFilesInDirectory(const std::string& path, const std::string& regex); static bool doesFileExist(const std::string& path); static bool doesDirectoryExist(const std::string& path); static bool isRegularFile(const std::string& path); static std::string getCurrentDir(); static std::string getCurrentFile(); static std::string getBasename(const std::string& path); static std::string getDirname(const std::string& path); static std::string getTmpDir(); static std::string buildPath( const std::string& path, const std::string& newElement); static std::string buildPath( const std::string& path, const std::string& newElement1, const std::string& newElement2); static std::string buildPath( const std::string& path, const std::string& newElement1, const std::string& newElement2, const std::string& newElement3); static std::string buildPath( const std::string& path, const std::string& newElement1, const std::string& newElement2, const std::string& newElement3, const std::string& newElement4); static std::string loadTextFile( const std::string& path); static Cdeqstr loadTextFileIntoColl( const std::string& path); static SmartPtrCDynamicByteArray loadByteFile( const std::string& path); static void saveTextFile( const std::string& outputDir, const std::string& filename, const std::string& contents, const FILE_MODE_TYPE fileMode = FILE_MODE_REPLACE, const std::string temporaryFileSuffix = ".tmp"); static void saveTextFile( const std::string& filePath, const std::string& contents, const FILE_MODE_TYPE fileMode = FILE_MODE_REPLACE, const std::string temporaryFileSuffix = ".tmp"); static void saveByteFile( const std::string& filePath, const SmartPtrCDynamicByteArray& contents, const FILE_MODE_TYPE fileMode = FILE_MODE_REPLACE, const std::string temporaryFileSuffix = ".tmp"); static void saveByteFile( const std::string& filePath, const byte* contents, const size_t& contentsLen, const FILE_MODE_TYPE fileMode = FILE_MODE_REPLACE, const std::string temporaryFileSuffix = ".tmp"); static DirectoryItems itemsInDirectory( const std::string& path, const std::string& regex); static PathAndDirectoryItemsCollection recursiveItemsInDirectory( const std::string& path, const std::string& regex); // The caller must ensure that dstPath exists. static void copyFile(const std::string& srcPath, const std::string& dstPath); static void moveFile(const std::string& srcPath, const std::string& dstPath); static void copyDirectory(const std::string& srcPath, const std::string& dstPath); static void recursiveCopyDirectory(const std::string& srcPath, const std::string& dstPath); static std::string findOptionalFile( const std::string& outputDir, const std::string& filename); static std::string findRequiredFile( const std::string& outputDir, const std::string& filename); static std::deque findOptionalFiles( const std::string& outputDir, const std::string& filename); static std::deque findRequiredFiles( const std::string& outputDir, const std::string& filename); static void chmod( const std::string &path, const uint32 mode = 0770); static std::string normalizePathForPlatform( const std::string &path); static std::string normalizePathWithForward( const std::string &path); static int64 getFileSize(const std::string& filename); static std::string saveTempTextFile(const std::string& filename_template, const std::string& contents); static std::string getTempFilename(const std::string& filename_template); static std::string executeScript( const std::string& scriptPath, const std::string& scriptResultsDir); private: static void saveFileSafely( const std::string& filePath, const byte* contents, const size_t& contentsLen, const std::string& temporaryFileSuffix); static void saveByteFileRaw( const std::string& path, const byte* contents, const size_t& contentsLen); private: CAF_CM_DECLARE_NOCREATE(FileSystemUtils); }; } #endif /* CFILESYSTEMUTILS_H_ */ CHexCodec.cpp000066400000000000000000000056641321503522500335420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: May 24, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CHexCodec.h" #include #include using namespace Caf; using namespace std; std::string CHexCodec::Encode( const byte* buffer, const uint32 bufferSize, const uint32 pairSpacing, const uint32 pairsPerLine, const char lineBreakChar) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CHexCodec", "Encode"); stringstream encoding; CAF_CM_ENTER { CAF_CM_VALIDATE_PTR(buffer); CAF_CM_VALIDATE_NOTZERO(bufferSize); string spacing; for (uint32 u = 0; u < pairSpacing; ++u) { spacing += ' '; } uint16 uTest = 1; byte bTest[2] = { 1, 0 }; const bool isLittleEndian = (::memcmp(&uTest, bTest, 2) == 0); uint32 groups = bufferSize >> 2; uint32 remainder = bufferSize % 4; encoding.fill('0'); encoding.setf(ios_base::uppercase); encoding.setf(ios_base::hex, ios_base::basefield); uint8 b[4]; const uint32* uintPtr = reinterpret_cast(buffer); uint32 pairs = 0; for (uint32 u = 0; u < groups; ++u) { if (isLittleEndian) { b[0] = static_cast(*uintPtr); b[1] = static_cast(*uintPtr >> 8); b[2] = static_cast(*uintPtr >> 16); b[3] = static_cast(*uintPtr >> 24); } else { b[0] = static_cast(*uintPtr >> 24); b[1] = static_cast(*uintPtr >> 16); b[2] = static_cast(*uintPtr >> 8); b[3] = static_cast(*uintPtr); } for (uint32 p = 0; p < 4; ++p) { if (pairSpacing && pairs) { encoding << spacing; } encoding << setw(2) << static_cast(b[p]); if (pairsPerLine) { if (0 == (++pairs % pairsPerLine)) { encoding << lineBreakChar; pairs = 0; } } else { ++pairs; } } ++uintPtr; } switch (remainder) { case 0: break; case 1: if (isLittleEndian) { b[0] = static_cast(*uintPtr); } else { b[0] = static_cast(*uintPtr >> 24); } break; case 2: if (isLittleEndian) { b[0] = static_cast(*uintPtr); b[1] = static_cast(*uintPtr >> 8); } else { b[0] = static_cast(*uintPtr >> 24); b[1] = static_cast(*uintPtr >> 16); } break; case 3: if (isLittleEndian) { b[0] = static_cast(*uintPtr); b[1] = static_cast(*uintPtr >> 8); b[2] = static_cast(*uintPtr >> 16); } else { b[0] = static_cast(*uintPtr >> 24); b[1] = static_cast(*uintPtr >> 16); b[2] = static_cast(*uintPtr >> 8); } break; } for (uint32 p = 0; p < remainder; ++p) { if (pairSpacing && pairs) { encoding << spacing; } encoding << setw(2) << static_cast(b[p]); if (pairsPerLine) { if (0 == (++pairs % pairsPerLine)) { encoding << lineBreakChar; pairs = 0; } } else { ++pairs; } } } CAF_CM_EXIT; return encoding.str(); } CHexCodec.h000066400000000000000000000015351321503522500332000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: May 24, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHEXCODEC_H_ #define CHEXCODEC_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CHexCodec { public: /// Encodes a buffer as a 2 digit per byte string. /// /// @param buffer Input buffer /// @param bufferSize Input buffer length /// @param pairSpacing Number of spaces to insert between digit pairs /// @param pairsPerLine Number of pairs to encode per line. 0 = single line output. /// @param lineBreakChar Character to insert between lines /// @return A string containing the hex encoding static std::string Encode( const byte* buffer, const uint32 bufferSize, const uint32 pairSpacing = 0, const uint32 pairsPerLine = 0, const char lineBreakChar = '\n'); }; } #endif /* CHEXCODEC_H_ */ CIniFile.cpp000066400000000000000000000315311321503522500333670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: May 18, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CCafRegex.h" #include "Common/CIniFile.h" #include "Exception/CCafException.h" using namespace Caf; CIniFile::CIniFile() : _isInitialized(false), CAF_CM_INIT_LOG("CIniFile") { } CIniFile::~CIniFile() { } void CIniFile::initialize( const std::string& configFilePath) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(configFilePath); _configFilePath = configFilePath; _isInitialized = true; } std::deque CIniFile::getSectionCollection() { CAF_CM_FUNCNAME_VALIDATE("getSectionCollection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::deque sectionCollection; if (_sectionCollection.empty()) { _sectionCollection = parse(_configFilePath); } sectionCollection = _sectionCollection; return sectionCollection; } std::deque CIniFile::getEntryCollection( const std::string& sectionName) { CAF_CM_FUNCNAME_VALIDATE("getEntryCollection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); std::deque entryCollection; if (_sectionCollection.empty()) { _sectionCollection = parse(_configFilePath); } for (TConstIterator > iniSectionIter(_sectionCollection); iniSectionIter; iniSectionIter++) { const SmartPtrSIniSection iniSection = *iniSectionIter; const std::string sectionNameTmp = iniSection->_sectionName; if (sectionNameTmp.compare(sectionName) == 0) { entryCollection = iniSection->_entryCollection; } } return entryCollection; } CIniFile::SmartPtrSIniEntry CIniFile::findOptionalEntry( const std::string& sectionName, const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findOptionalEntry"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(keyName); CIniFile::SmartPtrSIniEntry iniEntry; if (_sectionCollection.empty()) { _sectionCollection = parse(_configFilePath); } for (TConstIterator > iniSectionIter(_sectionCollection); iniSectionIter; iniSectionIter++) { const SmartPtrSIniSection iniSection = *iniSectionIter; const std::string sectionNameTmp = iniSection->_sectionName; if (sectionNameTmp.compare(sectionName) == 0) { for (TConstIterator > iniEntryIter(iniSection->_entryCollection); iniEntryIter; iniEntryIter++) { const SmartPtrSIniEntry iniEntryTmp = *iniEntryIter; const std::string keyNameTmp = iniEntryTmp->_name; if (keyNameTmp.compare(keyName) == 0) { iniEntry = iniEntryTmp; break; } } } } return iniEntry; } CIniFile::SmartPtrSIniEntry CIniFile::findRequiredEntry( const std::string& sectionName, const std::string& keyName) { CAF_CM_FUNCNAME("findRequiredEntry"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(keyName); const SmartPtrSIniEntry iniEntry = findOptionalEntry(sectionName, keyName); if (iniEntry.IsNull()) { CAF_CM_EXCEPTIONEX_VA2(NoSuchElementException, ERROR_NOT_FOUND, "Value not found - sectionName: %s, keyName: %s", sectionName.c_str(), keyName.c_str()); } return iniEntry; } std::string CIniFile::findOptionalString( const std::string& sectionName, const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findOptionalString"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(keyName); std::string value; const SmartPtrSIniEntry iniEntry = findOptionalEntry(sectionName, keyName); if (! iniEntry.IsNull()) { value = iniEntry->_valueExpanded; } return value; } std::string CIniFile::findRequiredString( const std::string& sectionName, const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findRequiredString"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(keyName); const SmartPtrSIniEntry iniEntry = findRequiredEntry(sectionName, keyName); return iniEntry->_valueExpanded; } std::string CIniFile::findOptionalRawString( const std::string& sectionName, const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findOptionalRawString"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(keyName); std::string value; const SmartPtrSIniEntry iniEntry = findOptionalEntry(sectionName, keyName); if (! iniEntry.IsNull()) { value = iniEntry->_valueRaw; } return value; } std::string CIniFile::findRequiredRawString( const std::string& sectionName, const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findRequiredRawString"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(keyName); const SmartPtrSIniEntry iniEntry = findRequiredEntry(sectionName, keyName); return iniEntry->_valueRaw; } void CIniFile::log() { CAF_CM_FUNCNAME_VALIDATE("log"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (_sectionCollection.empty()) { _sectionCollection = parse(_configFilePath); } for (TConstIterator > iniSectionIter(_sectionCollection); iniSectionIter; iniSectionIter++) { const SmartPtrSIniSection iniSection = *iniSectionIter; CAF_CM_LOG_DEBUG_VA1("Section - %s", iniSection->_sectionName.c_str()); for (TConstIterator > iniEntryIter(iniSection->_entryCollection); iniEntryIter; iniEntryIter++) { const SmartPtrSIniEntry iniEntry = *iniEntryIter; CAF_CM_LOG_DEBUG_VA3(" Entry - %s=%s (%s)", iniEntry->_name.c_str(), iniEntry->_valueRaw.c_str(), iniEntry->_valueExpanded.c_str()); } } } void CIniFile::setValue( const std::string& sectionName, const std::string& keyName, const std::string& value) { CAF_CM_FUNCNAME("setValue"); GKeyFile* gKeyFile = NULL; GError* gError = NULL; gchar* gFileContents = NULL; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(keyName); CAF_CM_VALIDATE_STRING(value); try { gKeyFile = g_key_file_new(); g_key_file_load_from_file( gKeyFile, _configFilePath.c_str(), G_KEY_FILE_NONE, &gError); if (gError != NULL) { throw gError; } g_key_file_set_string( gKeyFile, sectionName.c_str(), keyName.c_str(), value.c_str()); gFileContents = g_key_file_to_data( gKeyFile, NULL, &gError); if (gError != NULL) { throw gError; } if (gKeyFile) { g_key_file_free(gKeyFile); gKeyFile = NULL; } g_file_set_contents( _configFilePath.c_str(), gFileContents, -1, &gError); if (gError != NULL) { throw gError; } _sectionCollection.clear(); } catch (GError *gErrorExc) { CAF_CM_EXCEPTION_VA0(gErrorExc->code, gErrorExc->message); } } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT try { if (gKeyFile) { g_key_file_free(gKeyFile); } if (gError) { g_error_free(gError); } if (gFileContents) { g_free(gFileContents); } } CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } void CIniFile::deleteValue( const std::string& sectionName, const std::string& keyName) { CAF_CM_FUNCNAME("deleteValue"); GKeyFile* gKeyFile = NULL; GError* gError = NULL; gchar* gFileContents = NULL; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sectionName); CAF_CM_VALIDATE_STRING(keyName); try { gKeyFile = g_key_file_new(); g_key_file_load_from_file( gKeyFile, _configFilePath.c_str(), G_KEY_FILE_NONE, &gError); if (gError != NULL) { throw gError; } g_key_file_remove_key( gKeyFile, sectionName.c_str(), keyName.c_str(), &gError); if (gError != NULL) { throw gError; } gFileContents = g_key_file_to_data( gKeyFile, NULL, &gError); if (gError != NULL) { throw gError; } if (gKeyFile) { g_key_file_free(gKeyFile); gKeyFile = NULL; } g_file_set_contents( _configFilePath.c_str(), gFileContents, -1, &gError); if (gError != NULL) { throw gError; } _sectionCollection.clear(); } catch (GError *gErrorExc) { CAF_CM_EXCEPTION_VA0(gErrorExc->code, gErrorExc->message); } } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT try { if (gKeyFile) { g_key_file_free(gKeyFile); } if (gError) { g_error_free(gError); } if (gFileContents) { g_free(gFileContents); } } CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } std::deque CIniFile::parse( const std::string& configFilePath) const { CAF_CM_FUNCNAME("parse"); std::deque iniSectionCollection; std::deque replacementCollection; GKeyFile* gKeyFile = NULL; gchar** gGroupStrCollection = NULL; gchar** gKeyStrCollection = NULL; GError* gError = NULL; gchar* gValueStr = NULL; try { CAF_CM_VALIDATE_STRING(configFilePath); try { gKeyFile = g_key_file_new(); g_key_file_load_from_file( gKeyFile, configFilePath.c_str(), G_KEY_FILE_NONE, &gError); if (gError != NULL) { throw gError; } gsize numGroups = 0; gGroupStrCollection = g_key_file_get_groups(gKeyFile, &numGroups); for (gsize groupNum = 0; groupNum < numGroups; groupNum++) { const gchar* gGroupNameStr = gGroupStrCollection[groupNum]; const std::string groupName = gGroupNameStr; SmartPtrSIniSection iniSection; iniSection.CreateInstance(); iniSection->_sectionName = groupName; gsize numKeys = 0; gKeyStrCollection = g_key_file_get_keys( gKeyFile, gGroupNameStr, &numKeys, &gError); for (gsize keyNum = 0; keyNum < numKeys; keyNum++) { const gchar* gKeyNameStr = gKeyStrCollection[keyNum]; const std::string keyName = gKeyNameStr; gValueStr = g_key_file_get_string( gKeyFile, gGroupNameStr, gKeyNameStr, &gError); if (gError != NULL) { throw gError; } std::string valueRaw = gValueStr; g_free(gValueStr); gValueStr = NULL; std::string valueExpanded; if (valueRaw.empty()) { // TODO: Need a way to represent NULL strings as opposed to empty strings. valueRaw = " "; valueExpanded = " "; } else { valueExpanded = CStringUtils::trim(valueRaw); valueExpanded = CStringUtils::expandEnv(valueExpanded); for (TConstIterator > replacementIter(replacementCollection); replacementIter; replacementIter++ ) { const SmartPtrSReplacement replacement = *replacementIter; if (replacement->_regex->isMatched(valueExpanded)) { valueExpanded = replacement->_regex->replaceLiteral(valueExpanded, replacement->_value); break; } } if (groupName.compare("globals") == 0) { const SmartPtrSReplacement replacement = createReplacement(keyName, valueExpanded); replacementCollection.push_back(replacement); } } const SmartPtrSIniEntry iniEntry = createIniEntry(keyName, valueRaw, valueExpanded); iniSection->_entryCollection.push_back(iniEntry); } iniSectionCollection.push_back(iniSection); } } catch (GError *gErrorExc) { CAF_CM_EXCEPTION_VA0(gErrorExc->code, gErrorExc->message); } } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT try { if (gKeyFile) { g_key_file_free(gKeyFile); } if (gError) { g_error_free(gError); } if (gGroupStrCollection) { g_strfreev(gGroupStrCollection); } if (gKeyStrCollection) { g_strfreev(gKeyStrCollection); } if (gValueStr) { g_free(gValueStr); } } CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; return iniSectionCollection; } CIniFile::SmartPtrSReplacement CIniFile::createReplacement( const std::string& keyName, const std::string& value) const { CAF_CM_FUNCNAME_VALIDATE("createReplacement"); CAF_CM_VALIDATE_STRING(keyName); std::string pattern("\\$\\{"); pattern += keyName; pattern += "\\}"; SmartPtrCCafRegex regex; regex.CreateInstance(); regex->initialize(pattern); SmartPtrSReplacement replacement; replacement.CreateInstance(); replacement->_regex = regex; replacement->_value = value; return replacement; } CIniFile::SmartPtrSIniEntry CIniFile::createIniEntry( const std::string& keyName, const std::string& valueRaw, const std::string& valueExpanded) const { CAF_CM_FUNCNAME_VALIDATE("createIniEntry"); CAF_CM_VALIDATE_STRING(keyName); CAF_CM_VALIDATE_STRING(valueRaw); CAF_CM_VALIDATE_STRING(valueExpanded); SmartPtrSIniEntry iniEntry; iniEntry.CreateInstance(); iniEntry->_name = keyName; iniEntry->_valueRaw = valueRaw; iniEntry->_valueExpanded = valueExpanded; return iniEntry; } CLoggingSetter.cpp000066400000000000000000000033211321503522500346210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CLoggingSetter.h" #include "Common/CLoggingUtils.h" using namespace Caf; //////////////////////////////////////////////////////////////////////// // // CLoggingSetter::CLoggingSetter() // //////////////////////////////////////////////////////////////////////// CLoggingSetter::CLoggingSetter() : _isInitialized(false), _remapLoggingLocation(false), CAF_CM_INIT_LOG("CLoggingSetter") { } //////////////////////////////////////////////////////////////////////// // // CLoggingSetter::~CLoggingSetter() // //////////////////////////////////////////////////////////////////////// CLoggingSetter::~CLoggingSetter() { CAF_CM_FUNCNAME("~CLoggingSetter"); try { if (_isInitialized) { if (_remapLoggingLocation) { CAF_CM_LOG_DEBUG_VA0("Resetting log config dir"); CLoggingUtils::resetConfigFile(); CAF_CM_LOG_DEBUG_VA0("Reset log config dir"); } } } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; } //////////////////////////////////////////////////////////////////////// // // CLoggingSetter::Initialize() // //////////////////////////////////////////////////////////////////////// void CLoggingSetter::initialize(const std::string& logDir) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(logDir); _remapLoggingLocation = AppConfigUtils::getOptionalBoolean("remap_logging_location"); if (_remapLoggingLocation) { CAF_CM_LOG_DEBUG_VA1("Setting log config dir - %s", logDir.c_str()); CLoggingUtils::setLogDir(logDir); CAF_CM_LOG_DEBUG_VA1("Set log config dir - %s", logDir.c_str()); } _isInitialized = true; } CLoggingUtils.cpp000066400000000000000000000140221321503522500344530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/*k * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CLoggingUtils.h" #include "Exception/CCafException.h" #include #include using namespace Caf; GRecMutex CLoggingUtils::_sOpMutex; SmartPtrCLoggingUtils CLoggingUtils::_sInstance; bool CLoggingUtils::isConsoleAppenderUsed() { bool rc = false; const log4cpp::AppenderSet appenders = log4cpp::Category::getRoot().getAllAppenders(); for (log4cpp::AppenderSet::const_iterator iter = appenders.begin(); (iter != appenders.end() && !rc); iter++) { const log4cpp::Appender* appender = *iter; rc = CStringUtils::isEqualIgnoreCase(appender->getName(), "console"); } return rc; } void CLoggingUtils::setStartupConfigFile( const std::string& configFile, const std::string& logDir) { CAF_CM_STATIC_FUNC("CLoggingUtils", "setStartupConfigFile"); CAF_CM_VALIDATE_STRING(configFile); #ifndef WIN32 char configFileFullBuf[ 32768 ]; ::realpath(configFile.c_str(), configFileFullBuf); const std::string configFileFull = configFileFullBuf; #else wchar_t w_configFileFullBuf[ 32768 ]; const std::wstring w_configFile = CStringUtils::convertNarrowToWide(configFile.c_str()); DWORD dwResult = GetFullPathName(w_configFile.c_str(), 32768, w_configFileFullBuf, NULL); // Convert the string back to narrow const std::string configFileFull = CStringUtils::convertWideToNarrow(std::wstring(w_configFileFullBuf, dwResult)); #endif if (!FileSystemUtils::doesFileExist(configFileFull)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "Config file does not exist - %s", configFileFull.c_str()); } CAutoMutexLockUnlockRaw oLock(&_sOpMutex); if (_sInstance.IsNull()) { _sInstance.CreateInstance(); } _sInstance->_configFile = configFileFull; _sInstance->loadProperties(); if (logDir.empty()) { _sInstance->loadConfig(configFileFull); } else { setLogDir(logDir); } } SmartPtrCLoggingUtils CLoggingUtils::getInstance() { CAF_CM_STATIC_FUNC("CLoggingUtils", "getInstance"); CAutoMutexLockUnlockRaw oLock(&_sOpMutex); if (!_sInstance) { CAF_CM_EXCEPTION_VA0(ERROR_INVALID_STATE, "Config file not set"); } return _sInstance; } CLoggingUtils::CLoggingUtils() : CAF_CM_INIT_LOG("CLoggingUtils") { } void CLoggingUtils::loadConfig(const std::string& configFile) { CAF_CM_STATIC_FUNC_LOG("CLoggingUtils", "loadConfig"); CAF_CM_VALIDATE_STRING(configFile); if (!FileSystemUtils::doesFileExist(configFile)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "Config file does not exist - %s", configFile.c_str()); } // Make sure existing unmanaged appenders are cleaned up std::vector* categories = log4cpp::Category::getCurrentCategories(); for (std::vector::const_iterator catIter = categories->begin(); catIter != categories->end(); catIter++) { log4cpp::Category* category = *catIter; log4cpp::AppenderSet appenders = category->getAllAppenders(); for (log4cpp::AppenderSet::const_iterator appIter = appenders.begin(); appIter != appenders.end(); appIter++) { log4cpp::Appender* appender = *appIter; if (!category->ownsAppender(appender)) { // Appender lifecycle is NOT managed by the category...need to manually delete // First remove the appender before another thread attempts to access it during logging category->removeAppender(appender); delete appender; } } } // Use property configurator to load configuration file..to set up configured Categories and Appenders try { log4cpp::PropertyConfigurator::configure(configFile); } catch (log4cpp::ConfigureFailure e) { std::cout << "Log4cpp Error: " << e.what() << std::endl; } CAF_CM_LOG_DEBUG_VA1("Using log config file - %s", configFile.c_str()); } std::string CLoggingUtils::getConfigFile() { return getInstance()->_configFile; } void CLoggingUtils::resetConfigFile() { loadConfig(getInstance()->_configFile); } void CLoggingUtils::setLogDir(const std::string& logDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CLoggingUtils", "setLogDir"); CAF_CM_VALIDATE_STRING(logDir); if (!FileSystemUtils::doesDirectoryExist(logDir)) { CAF_CM_LOG_INFO_VA1("Creating log dir - %s", logDir.c_str()); FileSystemUtils::createDirectory(logDir); } // Create a temporary file for storing the new config std::string tmpFileName = FileSystemUtils::buildPath(logDir, "log4cpp_config_tmp"); static const std::string SRCH_STR = ".fileName"; static const size_t SRCH_STR_SIZE = SRCH_STR.length(); std::ofstream tmpCfg(tmpFileName.c_str(), std::ios_base::out | std::ios_base::trunc); PropertyMap src = getInstance()->_properties; for (PropertyMap::const_iterator iter = src.begin(); iter != src.end(); iter++) { tmpCfg << (*iter).first << "="; if (iter->first.rfind(SRCH_STR) == iter->first.length() - SRCH_STR_SIZE) { const std::string basename = FileSystemUtils::getBasename(iter->second); tmpCfg << FileSystemUtils::buildPath(logDir, basename); } else { tmpCfg << (*iter).second; } tmpCfg << std::endl; } tmpCfg.close(); loadConfig(tmpFileName); FileSystemUtils::removeFile(tmpFileName); } void CLoggingUtils::loadProperties() { CAF_CM_FUNCNAME_VALIDATE("loadProperties"); CAF_CM_VALIDATE_STRING(_configFile); _properties.clear(); static const size_t BUFF_SIZE = 2048; char buffer[BUFF_SIZE]; std::string line, property, name, value, prefix; size_t pos = 0; std::ifstream properties(_configFile.c_str()); while (properties.getline(buffer, BUFF_SIZE)) { line = CStringUtils::trim(buffer); // Check for comment. If at beginning, ignore whole line. If not, extract portion up to comment pos = line.find('#'); if (pos == std::string::npos) { property = line; } else if (pos > 0) { property = line.substr(0, pos); } else { continue; } // Parse the property into name/value pos = property.find('='); if (pos != std::string::npos) { name = CStringUtils::trim(property.substr(0, pos)); value = CStringUtils::trim(property.substr(pos + 1, property.size() - pos)); _properties[name] = value; } else { continue; } } } CManagedThreadPool.cpp000066400000000000000000000245101321503522500353650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Created on: May 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CManagedThreadPool.h" #include "Exception/CCafException.h" namespace Caf { class TaskWrapper : public CManagedThreadPool::IThreadTask { public: typedef enum { StateInactive, StateActive, StateFinishedComplete, StateFinishedIncomplete } EnumState; public: TaskWrapper(); virtual ~TaskWrapper(); void init(const CManagedThreadPool::SmartPtrIThreadTask& task); void setState(EnumState state); EnumState getState() const; public: // IThreadTask bool run(); private: CManagedThreadPool::SmartPtrIThreadTask _task; EnumState _state; private: CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(TaskWrapper); }; CAF_DECLARE_SMART_POINTER(TaskWrapper); } using namespace Caf; uint32 CManagedThreadPool::DEFAULT_TASK_UPDATE_INTERVAL = 333; CManagedThreadPool::CManagedThreadPool() : _isInitialized(false), _isShuttingDown(false), _threadPool(NULL), _workerThread(NULL), _taskUpdateInterval(DEFAULT_TASK_UPDATE_INTERVAL), CAF_CM_INIT_LOG("CManagedThreadPool") { CAF_CM_INIT_THREADSAFE; } CManagedThreadPool::~CManagedThreadPool() { CAF_CM_FUNCNAME_VALIDATE("~CManagedThreadPool"); if (_threadPool || _workerThread || _tasks.size()) { const char* poolName = _poolName.empty() ? "" : _poolName.c_str(); CAF_CM_LOG_ERROR_VA1( "[poolName=%s] Destroying thread pool but it is " "still active. You really should call term() first.", poolName); CAF_CM_LOG_DEBUG_VA1("[poolName=%s] Setting shutdown flag", poolName); _isShuttingDown = true; if (_workerThread) { CAF_CM_LOG_DEBUG_VA1("[poolName=%s] Waiting for worker thread to stop", poolName); g_thread_join(_workerThread); } if (_threadPool) { CAF_CM_LOG_DEBUG_VA1("[poolName=%s] Waiting for thread pool to stop", poolName); g_thread_pool_free( _threadPool, TRUE, /* immediate - do not schedule any more tasks to threads */ TRUE /* wait - wait for currently running tasks to finish */ ); } CAF_CM_LOG_DEBUG_VA2( "[poolName=%s] Pool has shut down. Releasing %d tasks", poolName, _tasks.size()); for (TConstIterator task(_tasks); task; task++) { (*task)->Release(); } } } void CManagedThreadPool::init( const std::string& poolName, uint32 threadCount, uint32 taskUpdateInterval) { CAF_CM_FUNCNAME("init"); CAF_CM_VALIDATE_STRING(poolName); CAF_CM_VALIDATE_NOTZERO(threadCount); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _poolName = poolName; if (taskUpdateInterval) { _taskUpdateInterval = taskUpdateInterval; } GError *error = NULL; _threadPool = g_thread_pool_new( taskWorkerFunc, NULL, threadCount, TRUE, &error); if (error) { CAF_CM_THROW_GERROR(error); } _workerThread = CThreadUtils::startJoinable( poolWorkerFunc, this); _isInitialized = true; } void CManagedThreadPool::term() { CAF_CM_FUNCNAME("term"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOCK_UNLOCK; if (g_thread_self() == _workerThread) { CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, ERROR_INVALID_STATE, "Must terminate the worker thread from a different thread - %p", _workerThread); } CAF_CM_LOG_DEBUG_VA1("[poolName=%s] Setting shutdown flag", _poolName.c_str()); _isShuttingDown = true; CAF_CM_LOG_DEBUG_VA2("[poolName=%s] Waiting for worker thread to stop - workerThread: %p", _poolName.c_str(), _workerThread); GThread* workerThread = _workerThread; { CAF_CM_UNLOCK_LOCK; g_thread_join(workerThread); } _workerThread = NULL; CAF_CM_LOG_DEBUG_VA1("[poolName=%s] Waiting for thread pool to stop", _poolName.c_str()); GThreadPool* threadPool = _threadPool; { CAF_CM_UNLOCK_LOCK; g_thread_pool_free( threadPool, TRUE, /* immediate - do not schedule any more tasks to threads */ TRUE /* wait - wait for currently running tasks to finish */ ); } _threadPool = NULL; CAF_CM_LOG_DEBUG_VA2( "[poolName=%s] Pool has shut down. Releasing %d tasks", _poolName.c_str(), _tasks.size()); const TaskSet tasks = _tasks; { CAF_CM_UNLOCK_LOCK; for (TConstIterator task(tasks); task; task++) { (*task)->Release(); } } _tasks.clear(); } void CManagedThreadPool::enqueue(const SmartPtrIThreadTask& task) { CAF_CM_FUNCNAME("enqueue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(task); CAF_CM_LOCK_UNLOCK; SmartPtrTaskWrapper taskWrapper; taskWrapper.CreateInstance(); taskWrapper->init(task); if (!_tasks.insert(taskWrapper.GetAddRefedInterface()).second) { // This should not be possible! taskWrapper->Release(); CAF_CM_EXCEPTIONEX_VA1( DuplicateElementException, 0, "[poolName=%s] An attempt was made to add a task object with an " "address equal to that of an existing object. " "This should not be possible. Please report this bug.", _poolName.c_str()); } } void CManagedThreadPool::enqueue(const TaskDeque& tasks) { CAF_CM_FUNCNAME("enqueue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOCK_UNLOCK; for (TSmartConstIterator task(tasks); task; task++) { SmartPtrTaskWrapper taskWrapper; taskWrapper.CreateInstance(); taskWrapper->init(*task); if (!_tasks.insert(taskWrapper.GetAddRefedInterface()).second) { // This should not be possible! taskWrapper->Release(); CAF_CM_EXCEPTIONEX_VA1( DuplicateElementException, 0, "[poolName=%s] An attempt was made to add a task object with an " "address equal to that of an existing object. " "This should not be possible. Please report this bug.", _poolName.c_str()); } } } CManagedThreadPool::Stats CManagedThreadPool::getStats() const { CAF_CM_FUNCNAME_VALIDATE("getStats"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOCK_UNLOCK; Stats stats = { 0, 0, 0, 0, 0 }; stats.taskCount = static_cast(_tasks.size()); for (TConstIterator task(_tasks); task; task++) { TaskWrapper *taskWrapper = reinterpret_cast(*task); switch (taskWrapper->getState()) { case TaskWrapper::StateActive: ++stats.activeTaskCount; break; case TaskWrapper::StateInactive: ++stats.inactiveTaskCount; break; case TaskWrapper::StateFinishedComplete: ++stats.completeTaskCount; break; case TaskWrapper::StateFinishedIncomplete: ++stats.incompleteTaskCount; break; } } return stats; } gpointer CManagedThreadPool::poolWorkerFunc(gpointer context) { CAF_CM_STATIC_FUNC_LOG("CManagedThreadPool", "poolWorkerFunc"); try { CAF_CM_VALIDATE_PTR(context); CManagedThreadPool *pool = reinterpret_cast(context); pool->runPool(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; return NULL; } void CManagedThreadPool::runPool() { CAF_CM_FUNCNAME("runPool"); CAF_CM_LOCK_UNLOCK; CAF_CM_LOG_DEBUG_VA1("[poolName=%s] Starting runPool() thread", _poolName.c_str()); while (!_isShuttingDown) { TaskSet tasksToRun; TaskSet tasksRemoved; try { // Move inactive tasks to the thread pool for (TConstIterator task(_tasks); !_isShuttingDown && task; task++) { TaskWrapper* taskWrapper = reinterpret_cast(*task); if (TaskWrapper::StateInactive == taskWrapper->getState()) { taskWrapper->setState(TaskWrapper::StateActive); GError *error = NULL; g_thread_pool_push( _threadPool, taskWrapper, &error); if (error) { taskWrapper->setState(TaskWrapper::StateInactive); CAF_CM_LOG_ERROR_VA3( "[poolName=%s] Unable to add task to tread pool. " "[%d][%s]", _poolName.c_str(), error->code, error->message); g_error_free(error); error = NULL; } } } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; try { // Handle finished tasks. The tasks may switch from Active to // FinishedComplete or FinishedIncomplete while we are reading the // state. That's okay - we'll just catch it on the next go-round. // // The alternative is to protect the state variable in the task wrapper // with a critical section. Seems kind of expensive for something that // isn't really a problem or time-critical. // // Also using naked iterators here since I'm updating the task set. TaskSet::iterator task = _tasks.begin(); while (!_isShuttingDown && (task != _tasks.end())) { TaskWrapper* taskWrapper = reinterpret_cast(*task); if (TaskWrapper::StateFinishedComplete == taskWrapper->getState()) { TaskSet::iterator toErase = task; ++task; _tasks.erase(toErase); taskWrapper->Release(); } else if (TaskWrapper::StateFinishedIncomplete == taskWrapper->getState()) { taskWrapper->setState(TaskWrapper::StateInactive); ++task; } else { ++task; } } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; const uint32 taskUpdateInterval = _taskUpdateInterval; { CAF_CM_UNLOCK_LOCK; CThreadUtils::sleep(taskUpdateInterval); } } CAF_CM_LOG_DEBUG_VA1("[poolName=%s] Leaving runPool() thread", _poolName.c_str()); } void CManagedThreadPool::taskWorkerFunc(gpointer threadContext, gpointer) { CAF_CM_STATIC_FUNC_LOG("TaskWorkerFunc", "taskWorkerFunc"); // Don't want to segfault so I'll test threadContext even though // it *cannot* be NULL. If it is we are in really bad shape! try { CAF_CM_VALIDATE_PTR(threadContext); TaskWrapper *task = reinterpret_cast(threadContext); bool complete = false; try { complete = task->run(); } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; task->setState(TaskWrapper::StateFinishedComplete); } else { task->setState(complete ? TaskWrapper::StateFinishedComplete : TaskWrapper::StateFinishedIncomplete); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } TaskWrapper::TaskWrapper() : _state(StateInactive) { CAF_CM_INIT_THREADSAFE; } TaskWrapper::~TaskWrapper() { } void TaskWrapper::init(const CManagedThreadPool::SmartPtrIThreadTask& task) { _task = task; } void TaskWrapper::setState(EnumState state) { CAF_CM_LOCK_UNLOCK; _state = state; } TaskWrapper::EnumState TaskWrapper::getState() const { CAF_CM_LOCK_UNLOCK; return _state; } bool TaskWrapper::run() { return _task->run(); } CPersistenceUtils.cpp000066400000000000000000000443401321503522500353570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/*k * Author: bwilliams * Created: Nov 25, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" #include "CPersistenceUtils.h" using namespace Caf; SmartPtrCPersistenceDoc CPersistenceUtils::loadPersistence( const std::string& persistenceDir) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "loadPersistence"); CAF_CM_VALIDATE_STRING(persistenceDir); SmartPtrCPersistenceDoc persistence; persistence.CreateInstance(); persistence->initialize( loadLocalSecurity(persistenceDir), loadRemoteSecurityCollection(persistenceDir), loadPersistenceProtocolCollection(persistenceDir), loadTextFile(persistenceDir, "version.txt", "1.0")); return persistence; } SmartPtrCLocalSecurityDoc CPersistenceUtils::loadLocalSecurity( const std::string& persistenceDir) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "loadLocalSecurity"); CAF_CM_VALIDATE_STRING(persistenceDir); const std::string localDir = FileSystemUtils::buildPath(persistenceDir, "local"); SmartPtrCLocalSecurityDoc localSecurity; localSecurity.CreateInstance(); localSecurity->initialize( loadTextFile(localDir, "localId.txt"), loadTextFile(localDir, "privateKey.pem"), loadTextFile(localDir, "cert.pem"), FileSystemUtils::buildPath(localDir, "privateKey.pem"), FileSystemUtils::buildPath(localDir, "cert.pem")); return localSecurity; } SmartPtrCRemoteSecurityCollectionDoc CPersistenceUtils::loadRemoteSecurityCollection( const std::string& persistenceDir) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "loadRemoteSecurityCollection"); CAF_CM_VALIDATE_STRING(persistenceDir); const std::string remoteDir = FileSystemUtils::buildPath(persistenceDir, "remote"); std::deque remoteSecurityCollectionInner; if (FileSystemUtils::doesDirectoryExist(remoteDir)) { FileSystemUtils::DirectoryItems remoteItems = FileSystemUtils::itemsInDirectory( remoteDir, FileSystemUtils::REGEX_MATCH_ALL); for (TConstIterator remoteIter(remoteItems.directories); remoteIter; remoteIter++) { const std::string remoteId = *remoteIter; const std::string remoteIdDir = FileSystemUtils::buildPath(remoteDir, remoteId); const std::string cmsCertCollectionDir = FileSystemUtils::buildPath(remoteIdDir, "cmsCertCollection"); std::deque cmsCertCollectionInner; std::deque cmsCertPathCollectionInner; if (FileSystemUtils::doesDirectoryExist(cmsCertCollectionDir)) { FileSystemUtils::DirectoryItems cmsCertCollectionItems = FileSystemUtils::itemsInDirectory( cmsCertCollectionDir, FileSystemUtils::REGEX_MATCH_ALL); for (TConstIterator cmsCertCollectionIter(cmsCertCollectionItems.files); cmsCertCollectionIter; cmsCertCollectionIter++) { cmsCertCollectionInner.push_back( loadTextFile(cmsCertCollectionDir, *cmsCertCollectionIter)); cmsCertPathCollectionInner.push_back( FileSystemUtils::buildPath(cmsCertCollectionDir, *cmsCertCollectionIter)); } } SmartPtrCCertCollectionDoc cmsCertCollection; cmsCertCollection.CreateInstance(); cmsCertCollection->initialize(cmsCertCollectionInner); SmartPtrCCertPathCollectionDoc cmsCertPathCollection; cmsCertPathCollection.CreateInstance(); cmsCertPathCollection->initialize(cmsCertPathCollectionInner); SmartPtrCRemoteSecurityDoc remoteSecurity; remoteSecurity.CreateInstance(); remoteSecurity->initialize( loadTextFile(remoteIdDir, "remoteId.txt"), loadTextFile(remoteIdDir, "protocolName.txt"), loadTextFile(remoteIdDir, "cmsCert.pem"), loadTextFile(remoteIdDir, "cmsCipherName.txt"), cmsCertCollection, FileSystemUtils::buildPath(remoteIdDir, "cmsCert.pem"), cmsCertPathCollection); remoteSecurityCollectionInner.push_back(remoteSecurity); } } SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollection; remoteSecurityCollection.CreateInstance(); remoteSecurityCollection->initialize(remoteSecurityCollectionInner); return remoteSecurityCollection; } SmartPtrCPersistenceProtocolCollectionDoc CPersistenceUtils::loadPersistenceProtocolCollection( const std::string& persistenceDir) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "loadPersistenceProtocolCollection"); CAF_CM_VALIDATE_STRING(persistenceDir); const std::string protocolDir = FileSystemUtils::buildPath(persistenceDir, "protocol"); std::deque persistenceProtocolCollectionInner; if (FileSystemUtils::doesDirectoryExist(protocolDir)) { FileSystemUtils::DirectoryItems protocolItems = FileSystemUtils::itemsInDirectory( protocolDir, FileSystemUtils::REGEX_MATCH_ALL); for (TConstIterator protocolIter(protocolItems.directories); protocolIter; protocolIter++) { const std::string protocolId = *protocolIter; const std::string protocolIdDir = FileSystemUtils::buildPath(protocolDir, protocolId); const std::string tlsCipherCollectionDir = FileSystemUtils::buildPath(protocolIdDir, "tlsCipherCollection"); const std::string tlsCertCollectionDir = FileSystemUtils::buildPath(protocolIdDir, "tlsCertCollection"); Cdeqstr tlsCipherCollection; if (FileSystemUtils::doesDirectoryExist(tlsCipherCollectionDir)) { FileSystemUtils::DirectoryItems tlsCipherCollectionItems = FileSystemUtils::itemsInDirectory( tlsCipherCollectionDir, FileSystemUtils::REGEX_MATCH_ALL); for (TConstIterator tlsCipherCollectionIter(tlsCipherCollectionItems.files); tlsCipherCollectionIter; tlsCipherCollectionIter++) { tlsCipherCollection.push_back( loadTextFile(tlsCipherCollectionDir, *tlsCipherCollectionIter)); } } std::deque tlsCertCollectionInner; std::deque tlsCertPathCollectionInner; if (FileSystemUtils::doesDirectoryExist(tlsCertCollectionDir)) { FileSystemUtils::DirectoryItems tlsCertCollectionItems = FileSystemUtils::itemsInDirectory( tlsCertCollectionDir, FileSystemUtils::REGEX_MATCH_ALL); for (TConstIterator tlsCertCollectionIter(tlsCertCollectionItems.files); tlsCertCollectionIter; tlsCertCollectionIter++) { tlsCertCollectionInner.push_back( loadTextFile(tlsCertCollectionDir, *tlsCertCollectionIter)); tlsCertPathCollectionInner.push_back( FileSystemUtils::buildPath(tlsCertCollectionDir, *tlsCertCollectionIter)); } } SmartPtrCCertCollectionDoc tlsCertCollection; tlsCertCollection.CreateInstance(); tlsCertCollection->initialize(tlsCertCollectionInner); SmartPtrCCertPathCollectionDoc tlsCertPathCollection; tlsCertPathCollection.CreateInstance(); tlsCertPathCollection->initialize(tlsCertPathCollectionInner); SmartPtrCPersistenceProtocolDoc persistenceProtocol; persistenceProtocol.CreateInstance(); persistenceProtocol->initialize( loadTextFile(protocolIdDir, "protocolName.txt"), loadTextFile(protocolIdDir, "uri.txt"), loadTextFile(protocolIdDir, "uri_amqp.txt"), loadTextFile(protocolIdDir, "uri_tunnel.txt"), loadTextFile(protocolIdDir, "tlsCert.pem"), loadTextFile(protocolIdDir, "tlsProtocol.txt"), tlsCipherCollection, tlsCertCollection, FileSystemUtils::buildPath(protocolIdDir, "uri_amqp.txt"), FileSystemUtils::buildPath(protocolIdDir, "uri_tunnel.txt"), FileSystemUtils::buildPath(protocolIdDir, "tlsCert.pem"), tlsCertPathCollection); persistenceProtocolCollectionInner.push_back(persistenceProtocol); } } SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollection; persistenceProtocolCollection.CreateInstance(); persistenceProtocolCollection->initialize(persistenceProtocolCollectionInner); return persistenceProtocolCollection; } SmartPtrCPersistenceProtocolDoc CPersistenceUtils::loadPersistenceProtocol( const std::string& persistenceDir) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "loadPersistenceProtocol"); CAF_CM_VALIDATE_STRING(persistenceDir); const SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollection = loadPersistenceProtocolCollection(persistenceDir); return loadPersistenceProtocol(persistenceProtocolCollection); } SmartPtrCPersistenceProtocolDoc CPersistenceUtils::loadPersistenceProtocol( const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollection) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "loadPersistenceProtocol"); CAF_CM_VALIDATE_SMARTPTR(persistenceProtocolCollection); std::deque persistenceProtocolCollectionInner = persistenceProtocolCollection->getPersistenceProtocol(); CAF_CM_VALIDATE_BOOL(persistenceProtocolCollectionInner.size() <= 1); SmartPtrCPersistenceProtocolDoc rc; if (persistenceProtocolCollectionInner.size() == 1) { rc = persistenceProtocolCollectionInner.front(); } return rc; } void CPersistenceUtils::savePersistence( const SmartPtrCPersistenceDoc& persistence, const std::string& persistenceDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPersistenceUtils", "savePersistence"); CAF_CM_VALIDATE_SMARTPTR(persistence); CAF_CM_VALIDATE_STRING(persistenceDir); const std::string protocolDir = FileSystemUtils::buildPath(persistenceDir, "protocol", "amqpBroker_default"); const std::string uriAmqp = loadTextFile(protocolDir, "uri_amqp.txt"); const std::string uriTunnel = loadTextFile(protocolDir, "uri_tunnel.txt"); if (FileSystemUtils::doesDirectoryExist(persistenceDir)) { CAF_CM_LOG_DEBUG_VA1("Removing directory - %s", persistenceDir.c_str()); FileSystemUtils::recursiveRemoveDirectory(persistenceDir); } const SmartPtrCLocalSecurityDoc localSecurity = persistence->getLocalSecurity(); const SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollection = persistence->getRemoteSecurityCollection(); const SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollection = persistence->getPersistenceProtocolCollection(); saveLocalSecurity(localSecurity, persistenceDir); saveRemoteSecurityCollection(remoteSecurityCollection, persistenceDir); savePersistenceProtocolCollection(persistenceProtocolCollection, persistenceDir, uriAmqp, uriTunnel); FileSystemUtils::saveTextFile(persistenceDir, "version.txt", persistence->getVersion()); } void CPersistenceUtils::saveLocalSecurity( const SmartPtrCLocalSecurityDoc& localSecurity, const std::string& persistenceDir) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "saveLocalSecurity"); CAF_CM_VALIDATE_STRING(persistenceDir); if (localSecurity) { const std::string locCertsDir = createDirectory(persistenceDir, "local"); if (! localSecurity->getLocalId().empty()) { FileSystemUtils::saveTextFile( locCertsDir, "localId.txt", localSecurity->getLocalId()); } if (! localSecurity->getCert().empty()) { FileSystemUtils::saveTextFile( locCertsDir, "cert.pem", localSecurity->getCert()); } if (! localSecurity->getPrivateKey().empty()) { FileSystemUtils::saveTextFile( locCertsDir, "privateKey.pem", localSecurity->getPrivateKey()); } } } void CPersistenceUtils::saveRemoteSecurityCollection( const SmartPtrCRemoteSecurityCollectionDoc& remoteSecurityCollection, const std::string& persistenceDir) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "saveRemoteSecurityCollection"); CAF_CM_VALIDATE_STRING(persistenceDir); if (! remoteSecurityCollection.IsNull()) { const std::deque remoteSecurityCollectionInner = remoteSecurityCollection->getRemoteSecurity(); if (! remoteSecurityCollectionInner.empty()) { const std::string rmtCertsDir = createDirectory(persistenceDir, "remote"); for (TConstIterator > remoteSecurityIter(remoteSecurityCollectionInner); remoteSecurityIter; remoteSecurityIter++) { const SmartPtrCRemoteSecurityDoc remoteSecurity = *remoteSecurityIter; CAF_CM_VALIDATE_SMARTPTR(remoteSecurity); const std::string remoteId = remoteSecurity->getRemoteId(); CAF_CM_VALIDATE_STRING(remoteId); const std::string persistenceDir = createDirectory(rmtCertsDir, remoteId); FileSystemUtils::saveTextFile( persistenceDir, "remoteId.txt", remoteSecurity->getRemoteId()); if (! remoteSecurity->getProtocolName().empty()) { FileSystemUtils::saveTextFile( persistenceDir, "protocolName.txt", remoteSecurity->getProtocolName()); } if (! remoteSecurity->getCmsCert().empty()) { FileSystemUtils::saveTextFile( persistenceDir, "cmsCert.pem", remoteSecurity->getCmsCert()); } if (! remoteSecurity->getCmsCipherName().empty()) { FileSystemUtils::saveTextFile( persistenceDir, "cmsCipherName.txt", remoteSecurity->getCmsCipherName()); } if (! remoteSecurity->getCmsCertCollection().IsNull()) { const std::deque cmsCertCollectionInner = remoteSecurity->getCmsCertCollection()->getCert(); if (! cmsCertCollectionInner.empty()) { const std::string certCollectionDir = createDirectory(persistenceDir, "cmsCertCollection"); saveCollection(cmsCertCollectionInner, certCollectionDir, "cmsCert", ".pem"); } } } } } } void CPersistenceUtils::savePersistenceProtocolCollection( const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollection, const std::string& persistenceDir, const std::string& uriAmqp, const std::string& uriTunnel) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "savePersistenceProtocolCollection"); CAF_CM_VALIDATE_STRING(persistenceDir); if (! persistenceProtocolCollection.IsNull()) { const std::deque persistenceProtocolCollectionInner = persistenceProtocolCollection->getPersistenceProtocol(); if (! persistenceProtocolCollectionInner.empty()) { const std::string protocolDir = createDirectory(persistenceDir, "protocol"); for (TConstIterator > persistenceProtocolIter(persistenceProtocolCollectionInner); persistenceProtocolIter; persistenceProtocolIter++) { const SmartPtrCPersistenceProtocolDoc persistenceProtocol = *persistenceProtocolIter; const std::string protocolName = persistenceProtocol->getProtocolName(); CAF_CM_VALIDATE_STRING(protocolName); const std::string amqpQueueDir = createDirectory(protocolDir, protocolName); FileSystemUtils::saveTextFile( amqpQueueDir, "protocolName.txt", persistenceProtocol->getProtocolName()); if (! persistenceProtocol->getUri().empty()) { FileSystemUtils::saveTextFile( amqpQueueDir, "uri.txt", persistenceProtocol->getUri()); } const std::string uriAmqpTmp = persistenceProtocol->getUriAmqp().empty() ? uriAmqp : persistenceProtocol->getUriAmqp(); if (! uriAmqpTmp.empty()) { FileSystemUtils::saveTextFile( amqpQueueDir, "uri_amqp.txt", uriAmqpTmp); } const std::string uriTunnelTmp = persistenceProtocol->getUriTunnel().empty() ? uriTunnel : persistenceProtocol->getUriTunnel(); if (! uriTunnelTmp.empty()) { FileSystemUtils::saveTextFile( amqpQueueDir, "uri_tunnel.txt", uriTunnelTmp); } if (! persistenceProtocol->getTlsCert().empty()) { FileSystemUtils::saveTextFile( amqpQueueDir, "tlsCert.pem", persistenceProtocol->getTlsCert()); } if (! persistenceProtocol->getTlsProtocol().empty()) { FileSystemUtils::saveTextFile( amqpQueueDir, "tlsProtocol.txt", persistenceProtocol->getTlsProtocol()); } const std::deque tlsCipherCollectionInner = persistenceProtocol->getTlsCipherCollection(); if (! tlsCipherCollectionInner.empty()) { const std::string cipherDir = createDirectory(amqpQueueDir, "tlsCipherCollection"); saveCollection(tlsCipherCollectionInner, cipherDir, "tlsCipher", ".txt"); } if (! persistenceProtocol->getTlsCertCollection().IsNull()) { const std::deque tlsCertCollectionInner = persistenceProtocol->getTlsCertCollection()->getCert(); if (! tlsCertCollectionInner.empty()) { const std::string certCollectionDir = createDirectory(amqpQueueDir, "tlsCertCollection"); saveCollection(tlsCertCollectionInner, certCollectionDir, "tlsCert", ".pem"); } } } } } } std::string CPersistenceUtils::loadTextFile( const std::string& dir, const std::string& file, const std::string& defaultVal, const bool isTrimRight) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPersistenceUtils", "loadTextFile"); CAF_CM_VALIDATE_STRING(dir); CAF_CM_VALIDATE_STRING(file); const std::string path = FileSystemUtils::buildPath(dir, file); std::string rc; if (FileSystemUtils::doesFileExist(path)) { rc = FileSystemUtils::loadTextFile(path); if (isTrimRight) { rc = CStringUtils::trimRight(rc); } } else { CAF_CM_LOG_DEBUG_VA1("File not found - %s", path.c_str()); rc = defaultVal; } return rc; } std::string CPersistenceUtils::createDirectory( const std::string& directory, const std::string& subdir) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "createDirectory"); CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(subdir); const std::string dirPath = FileSystemUtils::buildPath(directory, subdir); if (! FileSystemUtils::doesDirectoryExist(dirPath)) { FileSystemUtils::createDirectory(dirPath); } return dirPath; } void CPersistenceUtils::saveCollection( const Cdeqstr& collection, const std::string& directory, const std::string& filePrefix, const std::string& filePostfix) { CAF_CM_STATIC_FUNC_VALIDATE("CPersistenceUtils", "saveCollection"); CAF_CM_VALIDATE_STL(collection); CAF_CM_VALIDATE_STRING(directory); CAF_CM_VALIDATE_STRING(filePrefix); CAF_CM_VALIDATE_STRING(filePostfix); int32 cnt = 0; for (TConstIterator elemIter(collection); elemIter; elemIter++) { const std::string elem = *elemIter; const std::string cntStr = CStringConv::toString(cnt++); std::string elemFilename = filePrefix + cntStr + filePostfix; FileSystemUtils::saveTextFile(directory, elemFilename, elem); } } CPersistenceUtils.h000066400000000000000000000046311321503522500350230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPersistenceUtils_H_ #define CPersistenceUtils_H_ #include #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" namespace Caf { class COMMONAGGREGATOR_LINKAGE CPersistenceUtils { public: static SmartPtrCPersistenceDoc loadPersistence( const std::string& persistenceDir); static SmartPtrCLocalSecurityDoc loadLocalSecurity( const std::string& persistenceDir); static SmartPtrCRemoteSecurityCollectionDoc loadRemoteSecurityCollection( const std::string& persistenceDir); static SmartPtrCPersistenceProtocolCollectionDoc loadPersistenceProtocolCollection( const std::string& persistenceDir); static SmartPtrCPersistenceProtocolDoc loadPersistenceProtocol( const std::string& persistenceDir); static SmartPtrCPersistenceProtocolDoc loadPersistenceProtocol( const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollection); public: static void savePersistence( const SmartPtrCPersistenceDoc& persistence, const std::string& persistenceDir); static void saveLocalSecurity( const SmartPtrCLocalSecurityDoc& localSecurity, const std::string& persistenceDir); static void saveRemoteSecurityCollection( const SmartPtrCRemoteSecurityCollectionDoc& remoteSecurityCollection, const std::string& persistenceDir); static void savePersistenceProtocolCollection( const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollection, const std::string& persistenceDir, const std::string& uriAmqp, const std::string& uriTunnel); private: static std::string loadTextFile( const std::string& dir, const std::string& file, const std::string& defaultVal = std::string(), const bool isTrimRight = true); private: static std::string createDirectory( const std::string& directory, const std::string& subdir); static void saveCollection( const Cdeqstr& collection, const std::string& directory, const std::string& filePrefix, const std::string& filePostfix); private: CAF_CM_DECLARE_NOCREATE(CPersistenceUtils); }; } #endif /* CPersistenceUtils_H_ */ CProcessUtils.cpp000066400000000000000000000300461321503522500345070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CProcessUtils.h" #ifndef WIN32 #include #include #endif using namespace Caf; const std::string ProcessUtils::INHERIT_PARENT_DIRECTORY; void ProcessUtils::runSyncToFiles( const Cdeqstr& argv, const std::string& stdoutPath, const std::string& stderrPath, const ProcessUtils::Priority priority, const std::string workingDirectory) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ProcessUtils", "runSyncToFiles"); CAF_CM_ENTER { CAF_CM_VALIDATE_STL(argv); // stdoutPath is optional // stderrPath is optional std::string stdoutContent; std::string stderrContent; ProcessUtils::runSync( argv, stdoutPath, stderrPath, stdoutContent, stderrContent, priority, workingDirectory); } CAF_CM_EXIT; } void ProcessUtils::runSync( const Cdeqstr& argv, std::string& stdoutContent, std::string& stderrContent, const ProcessUtils::Priority priority, const std::string workingDirectory) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ProcessUtils", "runSync"); CAF_CM_ENTER { CAF_CM_VALIDATE_STL(argv); ProcessUtils::runSync( argv, std::string(), std::string(), stdoutContent, stderrContent, priority, workingDirectory); } CAF_CM_EXIT; } #ifdef WIN32 void ProcessUtils::runSync( const Cdeqstr& argv, const std::string& stdoutPath, const std::string& stderrPath, std::string& stdoutContent, std::string& stderrContent, const ProcessUtils::Priority priority, const std::string& workingDirectory) { CAF_CM_STATIC_FUNC_LOG( "CProcessUtils", "runSync(Win)" ); const uint32 maxCmdLineLen = 1024; PROCESS_INFORMATION processInfo; HANDLE stdoutReadPipe = NULL; HANDLE stdoutWritePipe = NULL; HANDLE stderrReadPipe = NULL; HANDLE stderrWritePipe = NULL; try { CAF_CM_VALIDATE_STL(argv); const std::string cmdLine = convertToString(argv); if (cmdLine.length() > maxCmdLineLen) { CAF_CM_EXCEPTION_VA1(0, "Command-line too long: \"%s\"", cmdLine.c_str()); } CAF_CM_LOG_INFO_VA1("Running command - %s", cmdLine.c_str()); char cmdLineBuf[maxCmdLineLen + 1]; ::strcpy_s(cmdLineBuf, cmdLine.c_str()); SECURITY_ATTRIBUTES securityAttributes; ::ZeroMemory(&securityAttributes, sizeof(securityAttributes)); securityAttributes.nLength = sizeof(securityAttributes); securityAttributes.bInheritHandle = TRUE; //Create pipes to write and read stdout/stderr BOOL apiRc = ::CreatePipe(&stdoutReadPipe, &stdoutWritePipe, &securityAttributes, 0); if (apiRc == FALSE) { const DWORD errorCode = ::GetLastError(); const std::string errorMsg = BasePlatform::PlatformApi::GetApiErrorMessage(errorCode); CAF_CM_EXCEPTION_VA2(errorCode, "Failed to create the stdout pipe - cmdLine: \"%s\", msg: \"%s\"", cmdLine.c_str(), errorMsg.c_str()); } apiRc = ::CreatePipe(&stderrReadPipe, &stderrWritePipe, &securityAttributes, 0); if (apiRc == FALSE) { const DWORD errorCode = ::GetLastError(); const std::string errorMsg = BasePlatform::PlatformApi::GetApiErrorMessage(errorCode); CAF_CM_EXCEPTION_VA2(errorCode, "Failed to create the stderr pipe - cmdLine: \"%s\", msg: \"%s\"", cmdLine.c_str(), errorMsg.c_str()); } STARTUPINFOA startupInfo; ::ZeroMemory(&startupInfo, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); startupInfo.dwFlags |= STARTF_USESTDHANDLES; startupInfo.hStdInput = NULL; startupInfo.hStdOutput = stdoutWritePipe; startupInfo.hStdError = stderrWritePipe; ::ZeroMemory(&processInfo, sizeof(processInfo)); DWORD dwCreationFlags = CREATE_NO_WINDOW; switch (priority) { case LOW: dwCreationFlags |= BELOW_NORMAL_PRIORITY_CLASS; break; case IDLE: dwCreationFlags |= IDLE_PRIORITY_CLASS; break; case NORMAL: default: dwCreationFlags |= NORMAL_PRIORITY_CLASS; break; } // NORMAL_PRIORITY_CLASS BELOW_NORMAL_PRIORITY_CLASS IDLE_PRIORITY_CLASS // Create the process apiRc = ::CreateProcessA( NULL, // Image Name cmdLineBuf, // Command Line NULL, // Security Attributes for the Process NULL, // Security Attributes for the Thread TRUE, // Inherit handles? dwCreationFlags, // Creation flags NULL, // Environment workingDirectory.length() == 0 ? NULL : workingDirectory.c_str(), &startupInfo, // Startup Info &processInfo); // Process Info if (apiRc == FALSE) { const DWORD errorCode = ::GetLastError(); const std::string errorMsg = BasePlatform::PlatformApi::GetApiErrorMessage(errorCode); CAF_CM_EXCEPTION_VA2(errorCode, "Failed to invoke \"%s\", msg: \"%s\"", cmdLine.c_str(), errorMsg.c_str()); } else { // Successfully created the process. Wait for it to finish. ::WaitForSingleObject(processInfo.hProcess, INFINITE); // Get the exit code. DWORD exitCode = 0; apiRc = ::GetExitCodeProcess(processInfo.hProcess, &exitCode); if (apiRc == FALSE) { const DWORD errorCode = ::GetLastError(); const std::string errorMsg = BasePlatform::PlatformApi::GetApiErrorMessage(errorCode); CAF_CM_EXCEPTION_VA2(errorCode, "Executed command but couldn't get exit code - cmdLine: \"%s\", msg: \"%s\"", cmdLine.c_str(), errorMsg.c_str()); } ::CloseHandle(stdoutWritePipe); ::CloseHandle(stderrWritePipe); stdoutWritePipe = NULL; stderrWritePipe = NULL; stdoutContent = readFromPipe(stdoutReadPipe); stderrContent = readFromPipe(stderrReadPipe); if (!stdoutContent.empty() && !stdoutPath.empty()) { FileSystemUtils::saveTextFile(stdoutPath, stdoutContent); } if (!stderrContent.empty() && !stderrPath.empty()) { FileSystemUtils::saveTextFile(stderrPath, stderrContent); } std::ostringstream msgStream; if (exitCode != 0) { msgStream << "Command failed - exitCode: " << exitCode; msgStream << ", cmdLine: \"" << cmdLine << "\""; msgStream << ", stdout: \"" << stdoutContent.c_str() << "\""; msgStream << ", stderr: \"" << stderrContent.c_str() << "\""; std::string msg = msgStream.str(); CAF_CM_LOG_WARN_VA0(msg.c_str()); CAF_CM_EXCEPTIONEX_VA0(ProcessFailedException, exitCode, msg); } msgStream << "Command succeeded - cmdLine: \"" << cmdLine << "\"; output: "; msgStream << ", stdout: \"" << stdoutContent.c_str() << "\""; msgStream << ", stderr: \"" << stderrContent.c_str() << "\""; CAF_CM_LOG_DEBUG_VA0(msgStream.str().c_str()); } } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT try { if (processInfo.hProcess != NULL) { ::CloseHandle(processInfo.hProcess); } if (processInfo.hThread != NULL) { ::CloseHandle(processInfo.hThread); } if (stdoutReadPipe != NULL) { ::CloseHandle(stdoutReadPipe); } if (stdoutWritePipe != NULL) { ::CloseHandle(stdoutWritePipe); } if (stderrReadPipe != NULL) { ::CloseHandle(stderrReadPipe); } if (stderrWritePipe != NULL) { ::CloseHandle(stderrWritePipe); } } CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } std::string ProcessUtils::readFromPipe( const HANDLE readPipe) { CAF_CM_STATIC_FUNC_LOG( "CProcessUtils", "readFromPipe" ); const uint32 maxOutBufSize = 1024; std::string rc = ""; CAF_CM_ENTER { CAF_CM_VALIDATE_PTR(readPipe); char readBuf[maxOutBufSize+1]; DWORD numberOfBytesRead = 0; for (BOOL apiRc = ::ReadFile(readPipe, readBuf, maxOutBufSize, &numberOfBytesRead, NULL); apiRc != FALSE; apiRc = ::ReadFile(readPipe, readBuf, maxOutBufSize, &numberOfBytesRead, NULL)) { readBuf[numberOfBytesRead] = '\0'; rc += std::string(readBuf); } } CAF_CM_EXIT; return rc; } #else void SpawnChildSetup(gpointer data) { int niceLevel = *((int*) data); setpriority(PRIO_PROCESS, 0, niceLevel); } void ProcessUtils::runSync( const Cdeqstr& argv, const std::string& stdoutPath, const std::string& stderrPath, std::string& stdoutContent, std::string& stderrContent, const ProcessUtils::Priority priority, const std::string& workingDirectory) { CAF_CM_STATIC_FUNC_LOG( "CProcessUtils", "runSync(NotWin)" ); GError *gError = NULL; gchar *gStdout = NULL; gchar *gStderr = NULL; const char** argvNative = NULL; try { CAF_CM_VALIDATE_STL(argv); const std::string cmdLine = convertToString(argv); // Each string in argvNative points to the internal memory in // the corresponding string in argv. So int32 as argvNative and // argv have (at least) the same scope, everything should be fine. argvNative = convertToCharArray(argv); int niceLevel; switch (priority) { case LOW: niceLevel = 10; break; case IDLE: niceLevel = 19; break; case NORMAL: default: niceLevel = 0; break; } CAF_CM_LOG_INFO_VA1("Running command - %s", cmdLine.c_str()); gint gStatus = 0; const bool isSuccessful = g_spawn_sync( workingDirectory.length() == 0 ? NULL : workingDirectory.c_str(), const_cast(argvNative), NULL, // child's environment, or NULL to inherit parent's static_cast(0), // GSpawnFlags - the defaults are fine &SpawnChildSetup, // child_setup - function to run in the child just before exec() &niceLevel, // user_data - user data for child_setup &gStdout, &gStderr, &gStatus, &gError); stdoutContent = (gStdout == NULL) ? std::string() : gStdout; stderrContent = (gStderr == NULL) ? std::string() : gStderr; if (!stdoutContent.empty() && !stdoutPath.empty()) { FileSystemUtils::saveTextFile(stdoutPath, stdoutContent); } if (!stderrContent.empty() && !stderrPath.empty()) { FileSystemUtils::saveTextFile(stderrPath, stderrContent); } std::ostringstream msgStream; if(!isSuccessful || (WIFEXITED(gStatus) == FALSE) || (WEXITSTATUS(gStatus) != 0)) { const std::string errorMessage = (gError == NULL) ? std::string() : gError->message; const int32 errorCode = (gError == NULL) ? 0 : gError->code; msgStream << "Failed to invoke command - errorCode: " << errorCode; msgStream << ", errorMessage: \"" << errorMessage.c_str() << "\""; msgStream << ", cmdLine: \"" << cmdLine << "\""; msgStream << ", stdout: \"" << stdoutContent.c_str() << "\""; msgStream << ", stderr: \"" << stderrContent.c_str() << "\""; std::string msg = msgStream.str(); CAF_CM_LOG_WARN_VA0(msg.c_str()); CAF_CM_EXCEPTIONEX_VA0(ProcessFailedException, errorCode, msg); } msgStream << "Command succeeded - cmdLine: \"" << cmdLine << "\"; output: "; msgStream << ", stdout: \"" << stdoutContent.c_str() << "\""; msgStream << ", stderr: \"" << stderrContent.c_str() << "\""; CAF_CM_LOG_DEBUG_VA0(msgStream.str().c_str()); freeMemory(gError, gStdout, gStderr, argvNative); } catch(...) { freeMemory(gError, gStdout, gStderr, argvNative); throw; } } #endif std::string ProcessUtils::getUserName() { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ProcessUtils", "getUserName"); std::string rc; CAF_CM_ENTER { const gchar* gUserName = g_get_user_name(); CAF_CM_VALIDATE_PTR(gUserName); rc = gUserName; } CAF_CM_EXIT; return rc; } std::string ProcessUtils::getRealUserName() { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ProcessUtils", "getRealUserName"); std::string rc; CAF_CM_ENTER { const gchar* gUserName = g_get_real_name(); CAF_CM_VALIDATE_PTR(gUserName); rc = gUserName; } CAF_CM_EXIT; return rc; } const char** ProcessUtils::convertToCharArray( const Cdeqstr& deqstr) { int32 rcIndex = 0; const char** rc = new const char*[deqstr.size() + 1]; for (TConstIterator strIter(deqstr); strIter; strIter++) { rc[rcIndex++] = (*strIter).c_str(); } rc[rcIndex++] = NULL; return rc; } std::string ProcessUtils::convertToString(const Cdeqstr& deqstr) { std::string rc; for (TConstIterator strIter(deqstr); strIter; strIter++) { std::string str = *strIter; #ifdef WIN32 if (rc.empty() && str.find(" ") != std::string::npos) { str = "\"" + *strIter + "\""; } #endif rc += str + std::string(" "); } return rc; } void ProcessUtils::freeMemory( GError *gError, gchar *gStdout, gchar *gStderr, const char** argvNative) { if(gError != NULL) { g_error_free(gError); gError = NULL; } g_free(gStdout); g_free(gStderr); if (argvNative != NULL) { delete[] argvNative; } } CProcessUtils.h000066400000000000000000000033131321503522500341510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProcessUtils_H_ #define CProcessUtils_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE ProcessUtils { public: enum COMMONAGGREGATOR_LINKAGE Priority { NORMAL, LOW, IDLE }; public: // Use for the "workingDirectory" parameter when you want to inherit the parents directory. static const std::string INHERIT_PARENT_DIRECTORY; public: static void runSyncToFiles( const Cdeqstr& argv, const std::string& stdoutPath, const std::string& stderrPath, const ProcessUtils::Priority priority = NORMAL, const std::string workingDirectory = ProcessUtils::INHERIT_PARENT_DIRECTORY); static void runSync( const Cdeqstr& argv, std::string& stdoutContent, std::string& stderrContent, const ProcessUtils::Priority priority = NORMAL, const std::string workingDirectory = ProcessUtils::INHERIT_PARENT_DIRECTORY); public: static std::string getUserName(); static std::string getRealUserName(); private: static void runSync( const Cdeqstr& argv, const std::string& stdoutPath, const std::string& stderrPath, std::string& stdoutContent, std::string& stderrContent, const ProcessUtils::Priority priority, const std::string& workingDirectory); static const char** convertToCharArray( const Cdeqstr& argv); static std::string convertToString( const Cdeqstr& deqstr); static void freeMemory( GError *gError, gchar *gStdout, gchar *gStderr, const char** argvNative); #ifdef WIN32 static std::string readFromPipe( const HANDLE readPipe); #endif private: CAF_CM_DECLARE_NOCREATE(ProcessUtils); }; } #endif /* CProcessUtils_H_ */ CStringUtils.cpp000066400000000000000000000107561321503522500343450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "CStringUtils.h" #include #include #include using namespace Caf; Cdeqstr CStringUtils::split(const std::string &str, const char delim) { Cdeqstr rc; std::string token; std::stringstream stream(str); while(std::getline(stream, token, delim)) { rc.push_back(token); } return rc; } // trim from both ends std::string CStringUtils::trim(const std::string &s) { std::string sTmp = s; return trimLeft(trimRight(sTmp)); } // trim from start std::string CStringUtils::trimLeft(const std::string &s) { std::string sTmp = s; sTmp.erase( sTmp.begin(), std::find_if( sTmp.begin(), sTmp.end(), std::not1(std::ptr_fun(std::isspace)))); return sTmp; } // trim from end std::string CStringUtils::trimRight(const std::string &s) { std::string sTmp = s; sTmp.erase( std::find_if( sTmp.rbegin(), sTmp.rend(), std::not1(std::ptr_fun(std::isspace))).base(), sTmp.end()); return sTmp; } // expand the environment variable in the string. std::string CStringUtils::expandEnv(const std::string &envStr) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CStringUtils", "expandEnv"); CAF_CM_VALIDATE_STRING(envStr); return getAppConfig()->resolveValue(envStr); } UUID CStringUtils::createRandomUuidRaw() { CAF_CM_STATIC_FUNC_LOG("CStringUtils", "createRandomUuidRaw"); UUID randomUuid; if (S_OK != ::UuidCreate(&randomUuid)) { CAF_CM_EXCEPTIONEX_VA0(InvalidHandleException, E_UNEXPECTED, "Failed to create the UUID"); } return randomUuid; } std::string CStringUtils::createRandomUuid() { return BasePlatform::UuidToString(createRandomUuidRaw()); } inline bool caseInsCharCompare(char a, char b) { return(::toupper(a) == ::toupper(b)); } bool CStringUtils::isEqualIgnoreCase( const std::string & src, const std::string & srch) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CStringUtils", "isEqualIgnoreCase"); CAF_CM_VALIDATE_STRING(src); CAF_CM_VALIDATE_STRING(srch); return((src.size() == srch.size()) && std::equal(src.begin(), src.end(), srch.begin(), caseInsCharCompare)); // std::string::iterator it = std::search( // src.begin(), src.end(), // srch.begin(), srch.end(), // [](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); } // ); // // return (it != src.end()); } #ifdef WIN32 std::string CStringUtils::convertWideToNarrow( const std::wstring& src) { CAF_CM_STATIC_FUNC_LOG("CStringUtils", "convertWideToNarrow"); std::string rc; // deal with trivial case of empty string if (! src.empty()) { // determine required length of new string const int32 srcLength = static_cast(src.length()); const int32 reqLength = ::WideCharToMultiByte(CP_UTF8, 0, src.c_str(), srcLength, NULL, 0, NULL, NULL); // construct new string of required length std::string dst(reqLength, '\0'); // convert old string to new string const int32 dstLength = static_cast(dst.length()); ::WideCharToMultiByte(CP_UTF8, 0, src.c_str(), srcLength, &dst[0], dstLength, NULL, NULL); rc = dst; } return rc; } std::wstring CStringUtils::convertNarrowToWide( const std::string& src) { CAF_CM_STATIC_FUNC_LOG("CStringUtils", "convertNarrowToWide"); std::wstring rc; // deal with trivial case of empty string if (! src.empty()) { // determine required length of new string const int32 srcLength = static_cast(src.length()); const int32 reqLength = ::MultiByteToWideChar(CP_UTF8, 0, src.c_str(), srcLength, NULL, 0); // construct new string of required length std::wstring dst(reqLength, L'\0'); // convert old string to new string const int32 dstLength = static_cast(dst.length()); ::MultiByteToWideChar(CP_UTF8, 0, src.c_str(), srcLength, &dst[0], dstLength); rc = dst; } return rc; } #endif std::string CStringUtils::toLower( const std::string& str) { CAF_CM_STATIC_FUNC_VALIDATE("CStringUtils", "toLower"); CAF_CM_VALIDATE_STRING(str); std::string rc(str); std::transform( str.begin(), str.end(), rc.begin(), std::ptr_fun(std::tolower)); return rc; } std::string CStringUtils::toUpper( const std::string& str) { CAF_CM_STATIC_FUNC_VALIDATE("CStringUtils", "toUpper"); CAF_CM_VALIDATE_STRING(str); std::string rc(str); std::transform( str.begin(), str.end(), rc.begin(), std::ptr_fun(std::toupper)); return rc; } CStringUtils.h000066400000000000000000000040451321503522500340040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CSTRINGUTILS_H_ #define CSTRINGUTILS_H_ #include namespace Caf { class COMMONAGGREGATOR_LINKAGE CStringUtils { public: static Cdeqstr split(const std::string &str, const char delim); static std::string trim(const std::string &s); static std::string trimLeft(const std::string &s); static std::string trimRight(const std::string &s); static std::string expandEnv(const std::string &s); static UUID createRandomUuidRaw(); static std::string createRandomUuid(); static bool isEqualIgnoreCase(const std::string & src, const std::string & srch); #ifdef WIN32 static std::string convertWideToNarrow(const std::wstring& src); static std::wstring convertNarrowToWide(const std::string& src); #endif static std::string toLower( const std::string& str); static std::string toUpper( const std::string& str); private: CAF_CM_DECLARE_NOCREATE(CStringUtils); }; namespace CStringConv { // Templates to convert numbers to strings template inline std::basic_string toTString(const T& t) { std::basic_ostringstream o; o << t; if (o.fail()) { throw std::runtime_error("cannot convert number to string"); } return o.str(); } template inline std::string toString(const T& t) { return toTString(t); } template inline std::wstring toWString(const T& t) { return toTString(t); } // Templates to convert strings to numbers template inline T fromTString(const std::basic_string& s) { T t; std::basic_istringstream i(s); i >> t; if (i.fail()) { throw std::runtime_error("cannot convert string '" + s + "' to number"); } return t; } template inline T fromString(const std::string& s) { return fromTString(s); } template inline T fromWString(const std::wstring& s) { return fromTString(s); } }} #endif /* CSTRINGUTILS_H_ */ CThreadPool.cpp000066400000000000000000000037751321503522500341220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * CThreadPool.cpp * * Created on: May 9, 2012 * Author: mdonahue * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CManagedThreadPool.h" #include "Common/CThreadPool.h" #include "Exception/CCafException.h" bool _isInitialized; GThreadPool *_threadPool; gpointer _userData; CThreadPool::CThreadPool() : _isInitialized(false), _threadPool(NULL), _userData(NULL), CAF_CM_INIT("CThreadPool") { CAF_CM_INIT_THREADSAFE; } CThreadPool::~CThreadPool() { if (_threadPool) { g_thread_pool_free(_threadPool, FALSE, TRUE); } } void CThreadPool::init(gpointer userData, gint maxThreads) { CAF_CM_FUNCNAME("init"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); GError *error = NULL; _threadPool = g_thread_pool_new( ThreadFunc, userData, maxThreads, TRUE, &error); if (error) { CAF_CM_THROW_GERROR(error); } _isInitialized = true; } void CThreadPool::term() { CAF_CM_FUNCNAME_VALIDATE("term"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); g_thread_pool_free(_threadPool, FALSE, TRUE); _threadPool = NULL; } void CThreadPool::addTask(const SmartPtrIThreadTask& task) { CAF_CM_FUNCNAME("addTask"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(task); if (_threadPool) { GError *error = NULL; g_thread_pool_push( _threadPool, task.GetAddRefedInterface(), &error); if (error) { task->Release(); CAF_CM_THROW_GERROR(error); } } else { CAF_CM_EXCEPTIONEX_VA0( IllegalStateException, 0, "The thread pool has been shut down"); } } void CThreadPool::ThreadFunc(gpointer data, gpointer userData) { CAF_CM_STATIC_FUNC_LOG("CThreadPool", "ThreadFunc"); CAF_CM_VALIDATE_PTR(data); // userData is optional IThreadTask *task = reinterpret_cast(data); try { task->run(userData); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; task->Release(); } CThreadSignal.cpp000066400000000000000000000041211321503522500344100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CAutoMutex.h" #include "Exception/CCafException.h" #include "Common/CThreadSignal.h" using namespace Caf; CThreadSignal::CThreadSignal(void) : _isInitialized(false), CAF_CM_INIT("CThreadSignal") { CAF_CM_INIT_THREADSAFE ; } CThreadSignal::~CThreadSignal(void) { } void CThreadSignal::initialize(const std::string& conditionName) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(conditionName); _condition.initialize(conditionName); _isInitialized = true; } bool CThreadSignal::isInitialized() const { CAF_CM_LOCK_UNLOCK; return _isInitialized; } void CThreadSignal::signal() { CAF_CM_FUNCNAME_VALIDATE("signal"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _condition.signal(); } void CThreadSignal::wait(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs) { CAF_CM_FUNCNAME("wait"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(mutex); const bool isSignaled = waitOrTimeout(mutex, timeoutMs); if (!isSignaled) { CAF_CM_EXCEPTION_VA1(ERROR_TIMEOUT, "Signal timed-out: %s", _condition.getName().c_str()); } } bool CThreadSignal::waitOrTimeout(SmartPtrCAutoMutex& mutex, const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("waitOrTimeout"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(mutex); bool rc = false; if (0 == timeoutMs) { _condition.wait(mutex); rc = true; } else { gint64 endTime; endTime = ::g_get_monotonic_time() + timeoutMs * G_TIME_SPAN_MILLISECOND; rc = _condition.waitUntil(mutex, endTime); } return rc; } std::string CThreadSignal::getName() const { CAF_CM_FUNCNAME_VALIDATE("getName"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _condition.getName(); } void CThreadSignal::close() { CAF_CM_LOCK_UNLOCK; if (_isInitialized) { _condition.close(); _isInitialized = false; } } CThreadUtils.cpp000066400000000000000000000024141321503522500342760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CThreadUtils.h" using namespace Caf; uint32 CThreadUtils::getThreadStackSizeKb() { CAF_CM_STATIC_FUNC_LOG_ONLY("CThreadUtils", "getThreadStackSizeKb"); uint32 stackSizeKb = AppConfigUtils::getRequiredUint32(_sAppConfigGlobalThreadStackSizeKb); #ifdef __linux__ // The thread stack size is the larger of // PTHREAD_STACK_MIN, 256K and the config file value stackSizeKb = std::max((int32)stackSizeKb, std::max(PTHREAD_STACK_MIN, (256 * 1024)) / 1024); #endif CAF_CM_LOG_DEBUG_VA1("thread_stack_size_kb=%d", stackSizeKb); return stackSizeKb; } GThread* CThreadUtils::startJoinable(threadFunc func, void* data) { CAF_CM_STATIC_FUNC("CThreadUtils", "startJoinable"); GThread *rc = g_thread_new("CThreadUtils::startJoinable", func, data); if(NULL == rc) { CAF_CM_EXCEPTION_VA0(0, "g_thread_new Failed"); } return rc; } void CThreadUtils::join(GThread* thread) { (void) g_thread_join(thread); } void CThreadUtils::sleep( const uint32 milliseconds) { CAF_CM_ENTER { const int32 microseconds = milliseconds * 1000; g_usleep(microseconds); } CAF_CM_EXIT; } CThreadUtils.h000066400000000000000000000011111321503522500337340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CThreadUtils_H_ #define CThreadUtils_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CThreadUtils { public: typedef void* (*threadFunc) (void* data); public: static uint32 getThreadStackSizeKb(); static GThread* startJoinable(threadFunc func, void* data); static void join(GThread* thread); static void sleep(const uint32 milliseconds); private: CAF_CM_DECLARE_NOCREATE(CThreadUtils); }; } #endif /* CThreadUtils_H_ */ CTimeUnit.cpp000066400000000000000000000037041321503522500336070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Nov 17, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CTimeUnit.h" using namespace Caf; int32 CTimeUnit::MILLISECONDS::toDays(const int32 milliseconds) { return milliseconds / (1000*60*60*24); } int32 CTimeUnit::MILLISECONDS::toHours(const int32 milliseconds) { return milliseconds / (1000*60*60); } int32 CTimeUnit::MILLISECONDS::toMinutes(const int32 milliseconds) { return milliseconds / (1000*60); } int32 CTimeUnit::MILLISECONDS::toSeconds(const int32 milliseconds) { return milliseconds / 1000; } int32 CTimeUnit::SECONDS::toDays(const int32 seconds) { return seconds / (60*60*24); } int32 CTimeUnit::SECONDS::toHours(const int32 seconds) { return seconds / (60*60); } int32 CTimeUnit::SECONDS::toMinutes(const int32 seconds) { return seconds / 60; } int32 CTimeUnit::SECONDS::toMilliseconds(const int32 seconds) { return seconds * 1000; } int32 CTimeUnit::MINUTES::toDays(const int32 seconds) { return seconds / (60*24); } int32 CTimeUnit::MINUTES::toHours(const int32 minutes) { return minutes / 60; } int32 CTimeUnit::MINUTES::toSeconds(const int32 minutes) { return minutes * 60; } int32 CTimeUnit::MINUTES::toMilliseconds(const int32 minutes) { return minutes * 1000 * 60; } int32 CTimeUnit::HOURS::toDays(const int32 hours) { return hours / 24; } int32 CTimeUnit::HOURS::toMinutes(const int32 hours) { return hours * 60; } int32 CTimeUnit::HOURS::toSeconds(const int32 hours) { return hours * (60*60); } int32 CTimeUnit::HOURS::toMilliseconds(const int32 hours) { return hours * (60*60*1000); } int32 CTimeUnit::DAYS::toHours(const int32 days) { return days * 24; } int32 CTimeUnit::DAYS::toMinutes(const int32 days) { return days * (24*60); } int32 CTimeUnit::DAYS::toSeconds(const int32 days) { return days * (24*60*60); } int32 CTimeUnit::DAYS::toMilliseconds(const int32 days) { return days * (24*60*60*1000); } CTimeUnit.h000066400000000000000000000030221321503522500332450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: bwilliams * Created: Nov 17, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CTimeUnit_H_ #define CTimeUnit_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CTimeUnit { public: class COMMONAGGREGATOR_LINKAGE MILLISECONDS { public: static int32 toDays(const int32 milliseconds); static int32 toHours(const int32 milliseconds); static int32 toMinutes(const int32 milliseconds); static int32 toSeconds(const int32 milliseconds); }; class COMMONAGGREGATOR_LINKAGE SECONDS { public: static int32 toDays(const int32 seconds); static int32 toHours(const int32 seconds); static int32 toMinutes(const int32 seconds); static int32 toMilliseconds(const int32 seconds); }; class COMMONAGGREGATOR_LINKAGE MINUTES { public: static int32 toDays(const int32 minutes); static int32 toHours(const int32 minutes); static int32 toSeconds(const int32 minutes); static int32 toMilliseconds(const int32 minutes); }; class COMMONAGGREGATOR_LINKAGE HOURS { public: static int32 toDays(const int32 hours); static int32 toMinutes(const int32 hours); static int32 toSeconds(const int32 hours); static int32 toMilliseconds(const int32 hours); }; class COMMONAGGREGATOR_LINKAGE DAYS { public: static int32 toHours(const int32 days); static int32 toMinutes(const int32 days); static int32 toSeconds(const int32 days); static int32 toMilliseconds(const int32 days); }; private: CAF_CM_DECLARE_NOCREATE(CTimeUnit); }; } #endif /* CTimeUnit_H_ */ CVariant.cpp000066400000000000000000000114721321503522500334560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Created on: Jun 7, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "Common/CVariant.h" using namespace Caf; CVariant::CVariant() : _variant(NULL), CAF_CM_INIT("CVariant") { } CVariant::~CVariant() { if (_variant) { g_variant_unref(_variant); } } void CVariant::set(GVariant *variant) { CAF_CM_FUNCNAME_VALIDATE("set"); CAF_CM_VALIDATE_PTR(variant); if (_variant) { g_variant_unref(_variant); _variant = NULL; } _variant = g_variant_ref_sink(variant); } GVariant *CVariant::get() const { CAF_CM_FUNCNAME_VALIDATE("get"); CAF_CM_VALIDATE_PTR(_variant); return _variant; } std::string CVariant::toString() const { CAF_CM_FUNCNAME("toString"); CAF_CM_VALIDATE_PTR(_variant); std::string result; const GVariantType *variantType = g_variant_get_type(_variant); if (g_variant_type_equal(variantType, G_VARIANT_TYPE_BOOLEAN)) { result = g_variant_get_boolean(_variant) ? "true" : "false"; } else if (g_variant_type_equal(variantType, G_VARIANT_TYPE_BYTE)) { result = CStringConv::toString(g_variant_get_byte(_variant)); } else if (g_variant_type_equal(variantType, G_VARIANT_TYPE_INT16)) { result = CStringConv::toString(g_variant_get_int16(_variant)); } else if (g_variant_type_equal(variantType, G_VARIANT_TYPE_UINT16)) { result = CStringConv::toString(g_variant_get_uint16(_variant)); } else if (g_variant_type_equal(variantType, G_VARIANT_TYPE_INT32)) { result = CStringConv::toString(g_variant_get_int32(_variant)); } else if (g_variant_type_equal(variantType, G_VARIANT_TYPE_UINT32)) { result = CStringConv::toString(g_variant_get_uint32(_variant)); } else if (g_variant_type_equal(variantType, G_VARIANT_TYPE_INT64)) { result = CStringConv::toString(g_variant_get_int64(_variant)); } else if (g_variant_type_equal(variantType, G_VARIANT_TYPE_UINT64)) { result = CStringConv::toString(g_variant_get_uint64(_variant)); } else if (g_variant_type_equal(variantType, G_VARIANT_TYPE_STRING)) { result = g_variant_get_string(_variant, NULL); } else { CAF_CM_EXCEPTIONEX_VA1( UnsupportedOperationException, 0, "Unsupported GVariant conversion to string from type '%s'", g_variant_get_type_string(_variant)); } return result; } bool CVariant::isString() const { return isType(G_VARIANT_TYPE_STRING); } bool CVariant::isBool() const { return isType(G_VARIANT_TYPE_BOOLEAN); } bool CVariant::isUint8() const { return isType(G_VARIANT_TYPE_BYTE); } bool CVariant::isInt16() const { return isType(G_VARIANT_TYPE_INT16); } bool CVariant::isUint16() const { return isType(G_VARIANT_TYPE_UINT16); } bool CVariant::isInt32() const { return isType(G_VARIANT_TYPE_INT32); } bool CVariant::isUint32() const { return isType(G_VARIANT_TYPE_UINT32); } bool CVariant::isInt64() const { return isType(G_VARIANT_TYPE_INT64); } bool CVariant::isUint64() const { return isType(G_VARIANT_TYPE_UINT64); } SmartPtrCVariant CVariant::createString(const std::string& value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_string(value.c_str())); return variant; } SmartPtrCVariant CVariant::createBool(const bool value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_boolean(value)); return variant; } SmartPtrCVariant CVariant::createUint8(const uint8 value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_byte(value)); return variant; } SmartPtrCVariant CVariant::createInt16(const int16 value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_int16(value)); return variant; } SmartPtrCVariant CVariant::createUint16(const uint16 value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_uint16(value)); return variant; } SmartPtrCVariant CVariant::createInt32(const int32 value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_int32(value)); return variant; } SmartPtrCVariant CVariant::createUint32(const uint32 value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_uint32(value)); return variant; } SmartPtrCVariant CVariant::createInt64(const int64 value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_int64(value)); return variant; } SmartPtrCVariant CVariant::createUint64(const uint64 value) { SmartPtrCVariant variant; variant.CreateInstance(); variant->set(g_variant_new_uint64(value)); return variant; } bool CVariant::isType(const GVariantType * varType) const { CAF_CM_FUNCNAME_VALIDATE("isType"); CAF_CM_VALIDATE_PTR(_variant); CAF_CM_VALIDATE_PTR(varType); return g_variant_type_equal(g_variant_get_type(_variant), varType); } CafInitialize.cpp000066400000000000000000000030601321503522500344540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 24, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #ifdef WIN32 #include "Common/CWinScm.h" #endif #include "CafInitialize.h" using namespace Caf; HRESULT CafInitialize::init() { return S_OK; } HRESULT CafInitialize::serviceConfig() { #ifdef WIN32 // CWinScm toolsScm("VMTools"); // SmartPtrSServiceConfig toolsConfig = toolsScm.getServiceConfig(false); // if (!toolsConfig.isNull()) { // // Add to path // } CWinScm vgAuthScm("VGAuthService"); Caf::CWinScm::SmartPtrSServiceConfig vgAuthConfig = vgAuthScm.getServiceConfig(false); if (!vgAuthConfig.IsNull() && !vgAuthConfig->_binaryPathName.empty()) { // Add to path std::string dllPath = vgAuthConfig->_binaryPathName; if (dllPath[0] == '\"') { dllPath = dllPath.substr(1, dllPath.length() - 2); } const std::wstring dllPathWide = CStringUtils::convertNarrowToWide(FileSystemUtils::getDirname(dllPath)); // NOTE: Can't use ::AddDllDirectory because it requires a newer base version of windows. Even so, // MSDN documentation specifies search order to be non-deterministic. if (0 == ::SetDllDirectory(dllPathWide.c_str())) { const DWORD lastError = ::GetLastError(); const std::string errorMsg = BasePlatform::PlatformApi::GetApiErrorMessage(lastError); ::fprintf( stderr, "CafInitialize::serviceConfig() ::AddDllDirectory() Failed - : VGAuthService, msg: \"%s\"", errorMsg.c_str()); } } #endif return S_OK; } HRESULT CafInitialize::term() { return S_OK; } CafInitialize.h000066400000000000000000000006521321503522500341250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 24, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAFINITIALIZE_H_ #define CAFINITIALIZE_H_ namespace Caf { class COMMONAGGREGATOR_LINKAGE CafInitialize { public: static HRESULT init(); static HRESULT serviceConfig(); static HRESULT term(); CAF_CM_DECLARE_NOCREATE(CafInitialize); }; } #endif /* CAFINITIALIZE_H_ */ CommonAggregatorLink.h000066400000000000000000000031361321503522500354630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef COMMONAGGREGATORLINK_H_ #define COMMONAGGREGATORLINK_H_ #ifndef COMMONAGGREGATOR_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define COMMONAGGREGATOR_LINKAGE __declspec(dllexport) #else #define COMMONAGGREGATOR_LINKAGE __declspec(dllimport) #endif #else #define COMMONAGGREGATOR_LINKAGE #endif #endif #include #include #include #include #include #include #include #include "../Logging/LoggingLink.h" #include "../Exception/ExceptionLink.h" #include "../Collections/Iterators/IteratorsInc.h" #include "../Collections/Graphs/GraphsInc.h" #include "CTimeUnit.h" #include "CAutoFileUnlock.h" #include "CStringUtils.h" #include "CFileSystemUtils.h" #include "CProcessUtils.h" #include "CDateTimeUtils.h" #include "CThreadUtils.h" #include "AppConfigUtils.h" #include "CAutoMutexLockUnlock.h" #include "CAutoMutexLockUnlockRaw.h" #include "CAutoMutexUnlockLock.h" #include "CafInitialize.h" #include "CHexCodec.h" #include "UriUtils.h" #include "TBlockingCell.h" #include "Common/CVariant.h" #include "CEnvironmentUtils.h" #include "CPersistenceUtils.h" #if defined(__linux__) || defined(__APPLE__) #include "CDaemonUtils.h" #elif WIN32 #endif #include "../SubSystemBase/SubSystemBaseLink.h" #include "../Xml/MarkupParser/MarkupParserLink.h" #include "../Xml/XmlUtils/XmlUtilsLink.h" #endif /* COMMONAGGREGATORLINK_H_ */ TBlockingCell.h000066400000000000000000000044601321503522500340670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Created on: May 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef TBLOCKINGCELL_H_ #define TBLOCKINGCELL_H_ #include "Common/CThreadSignal.h" #include "Exception/CCafException.h" namespace Caf { /** * @brief Simple one-shot IPC mechanism. * Allows a value to be passed from one thread to another in a thread-safe manner. * The value may only be set once and once set may get retrieved as many times as * desired. */ template class TBlockingCell { public: TBlockingCell() : _filled(false) { CAF_CM_INIT_THREADSAFE; CAF_THREADSIGNAL_INIT; //TODO: This has stopped working... why? //_value = NULL; _valueSignal.initialize("valueSignal"); } virtual ~TBlockingCell() { } /** * @brief Wait for a value indefinitely * Waits indefinitely for the value to be set or returns the value if it is * already set. * @return value */ T get() { return get(0); } /** * @brief Wait for a value for a specified amount of time * Waits for a set amout of time (milliseconds) for the value to be set or returns * the value if it is already set. * @retval value if set * @retval TimeoutException thrown if time expires */ T get(uint32 timeoutMs) { CAF_CM_STATIC_FUNC("TBlockingCell", "get"); CAF_CM_LOCK; CAF_THREADSIGNAL_LOCK_UNLOCK; if (!_filled) { CAF_CM_UNLOCK; _valueSignal.waitOrTimeout(CAF_THREADSIGNAL_MUTEX, timeoutMs); CAF_CM_LOCK; if (!_filled) { CAF_CM_UNLOCK; CAF_CM_EXCEPTIONEX_VA0( TimeoutException, 0, "Timed out waiting for value to be set"); } else { CAF_CM_UNLOCK; } } else { CAF_CM_UNLOCK; } return _value; } /** * @brief Sets a new value if the value is not already set * If the value is already set an IllegalStateException will be thrown. */ void set(T newValue) { CAF_CM_STATIC_FUNC("TBlockingCell", "set"); CAF_CM_LOCK_UNLOCK; if (_filled) { CAF_CM_EXCEPTIONEX_VA0( IllegalStateException, 0, "The value can only be set once"); } _value = newValue; _filled = true; _valueSignal.signal(); } private: bool _filled; T _value; CAF_THREADSIGNAL_CREATE; CThreadSignal _valueSignal; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(TBlockingCell); }; } #endif /* TBLOCKINGCELL_H_ */ UriUtils.cpp000066400000000000000000000256061321503522500335330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/* * Author: mdonahue * Created: Feb 4, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "UriUtils.h" using namespace Caf; void UriUtils::parseUriString( const std::string& uri, UriUtils::SUriRecord& data) { CAF_CM_STATIC_FUNC("UriUtils", "parseUriString"); CAF_CM_VALIDATE_STRING(uri); // examples: // // vmcf:service_id@tcp:host=hostname,port=portnum?timeout=timeoutval // tunnel:localhost:6672/amqp_queue_name?vhost=caf;connection_timeout=150000;connection_retries=10;connection_seconds_to_wait=10;channel_cache_size=3 // amqp:guest:guest@10.25.91.81:5672/amqp_queue_name?vhost=caf;connection_timeout=150000;connection_retries=10;connection_seconds_to_wait=10;channel_cache_size=3 static const std::string uriPattern("^(?P[^:]+?):(?P

[^?]+)\\?\?(?P.*)"); static const std::string parmPattern("(?P[^=]+)=(?P[^;]+);?"); static const std::string namePattern("^(?P[^:]+):(?P[^@]+)@(?P.*)"); static const std::string hostPattern("^(?P[^:]+):(?P[^/]+)/"); static const std::string pathPattern("/(?P[^?]+)"); CAF_CM_ENTER { data.protocol = std::string(); data.address = std::string(); data.parameters.clear(); GRegex *regexUri = NULL; GRegex *regexParms = NULL; GRegex *regexName = NULL; GRegex *regexHost = NULL; GRegex *regexPath = NULL; GMatchInfo* matchInfo = NULL; try { CAF_CM_VALIDATE_STRING(uri); GError *error = NULL; regexUri = g_regex_new(uriPattern.c_str(), (GRegexCompileFlags)(G_REGEX_RAW), (GRegexMatchFlags)0, &error); if (error) { throw error; } regexParms = g_regex_new(parmPattern.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_RAW), (GRegexMatchFlags)0, &error); if (error) { throw error; } regexName = g_regex_new(namePattern.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_RAW), (GRegexMatchFlags)0, &error); if (error) { throw error; } regexHost = g_regex_new(hostPattern.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_RAW), (GRegexMatchFlags)0, &error); if (error) { throw error; } regexPath = g_regex_new(pathPattern.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_RAW), (GRegexMatchFlags)0, &error); if (error) { throw error; } if (g_regex_match(regexUri, uri.c_str(), (GRegexMatchFlags)0, &matchInfo)) { gchar *value = g_match_info_fetch_named(matchInfo, "protocol"); data.protocol = value; g_free(value); value = g_match_info_fetch_named(matchInfo, "address"); data.address = value; g_free(value); value = g_match_info_fetch_named(matchInfo, "parameters"); std::string params(value ? value : ""); g_free(value); g_match_info_free(matchInfo); matchInfo = NULL; if (! data.address.empty()) { std::string hostpath = data.address; if (g_regex_match(regexName, data.address.c_str(), (GRegexMatchFlags)0, &matchInfo)) { value = g_match_info_fetch_named(matchInfo, "username"); data.username = value; g_free(value); value = g_match_info_fetch_named(matchInfo, "password"); data.password = value; g_free(value); value = g_match_info_fetch_named(matchInfo, "hostpath"); hostpath = value; g_free(value); } g_match_info_free(matchInfo); matchInfo = NULL; if (g_regex_match(regexHost, hostpath.c_str(), (GRegexMatchFlags)0, &matchInfo)) { value = g_match_info_fetch_named(matchInfo, "host"); data.host = value; g_free(value); value = g_match_info_fetch_named(matchInfo, "port"); data.portStr = value; data.port = CStringConv::fromString(value); g_free(value); } g_match_info_free(matchInfo); matchInfo = NULL; if (g_regex_match(regexPath, hostpath.c_str(), (GRegexMatchFlags)0, &matchInfo)) { value = g_match_info_fetch_named(matchInfo, "path"); data.path = value; g_free(value); } g_match_info_free(matchInfo); matchInfo = NULL; } if (params.length()) { if (g_regex_match(regexParms, params.c_str(), (GRegexMatchFlags)0, &matchInfo)) { while (g_match_info_matches(matchInfo)) { value = g_match_info_fetch_named(matchInfo, "name"); std::string paramName(value); g_free(value); value = g_match_info_fetch_named(matchInfo, "value"); std::string paramValue(value); g_free(value); if (!data.parameters.insert( std::map::value_type(paramName, paramValue)).second) { CAF_CM_EXCEPTION_VA2(ERROR_DUPLICATE_TAG, "Duplicate parameter name %s in %s", paramName.c_str(), uri.c_str()); } g_match_info_next(matchInfo, &error); if (error) { throw error; } } } g_match_info_free(matchInfo); matchInfo = NULL; } } } CAF_CM_CATCH_CAF CAF_CM_CATCH_GERROR if (matchInfo) { g_match_info_free(matchInfo); } if (regexUri) { g_regex_unref(regexUri); } if (regexParms) { g_regex_unref(regexParms); } if (regexName) { g_regex_unref(regexName); } if (regexHost) { g_regex_unref(regexHost); } if (regexPath) { g_regex_unref(regexPath); } CAF_CM_THROWEXCEPTION; } CAF_CM_EXIT; } std::string UriUtils::buildUriString( UriUtils::SUriRecord& data) { CAF_CM_STATIC_FUNC_VALIDATE("UriUtils", "buildUriString"); CAF_CM_VALIDATE_STRING(data.protocol); CAF_CM_VALIDATE_STRING(data.host); CAF_CM_VALIDATE_STRING(data.path); std::string rc = data.protocol + ":"; if (! data.username.empty() || ! data.password.empty()) { rc += data.username + ":" + data.password + "@"; } rc += data.host; if (! data.portStr.empty()) { rc += ":" + data.portStr; } rc += "/" + data.path; rc = appendParameters(rc, data.parameters); return rc; } void UriUtils::parseFileAddress(const std::string& fileUri, UriUtils::SFileUriRecord& data) { CAF_CM_STATIC_FUNC_LOG("UriUtils", "parseFileAddress"); CAF_CM_VALIDATE_STRING(fileUri); // examples: // // ///c:/tmp static const std::string addressPattern("^//(?P[^/]*)/(?P.*)"); static const std::string drivePattern("^[a-zA-Z]:"); CAF_CM_ENTER { data.hostname = std::string(); data.path = std::string(); GRegex *regexAddress = NULL; GRegex *regexDrive = NULL; GMatchInfo* matchInfo = NULL; try { CAF_CM_VALIDATE_STRING(fileUri); GError *error = NULL; regexAddress = g_regex_new(addressPattern.c_str(), (GRegexCompileFlags)(G_REGEX_RAW), (GRegexMatchFlags)0, &error); if (error) { throw error; } if (g_regex_match(regexAddress, fileUri.c_str(), (GRegexMatchFlags)0, &matchInfo)) { gchar *value = g_match_info_fetch_named(matchInfo, "hostname"); data.hostname = value; g_free(value); value = g_match_info_fetch_named(matchInfo, "path"); data.path = value; g_free(value); g_match_info_free(matchInfo); matchInfo = NULL; regexDrive = g_regex_new(drivePattern.c_str(), (GRegexCompileFlags)(G_REGEX_RAW), (GRegexMatchFlags)0, &error); if (error) { throw error; } if (! g_regex_match(regexDrive, data.path.c_str(), (GRegexMatchFlags)0, &matchInfo)) { data.path = "/" + data.path; } g_match_info_free(matchInfo); matchInfo = NULL; } } CAF_CM_CATCH_CAF CAF_CM_CATCH_GERROR if (matchInfo) { g_match_info_free(matchInfo); } if (regexAddress) { g_regex_unref(regexAddress); } if (regexDrive) { g_regex_unref(regexDrive); } CAF_CM_THROWEXCEPTION; } CAF_CM_EXIT; } std::string UriUtils::parseRequiredFilePath( const std::string& uriStr) { CAF_CM_STATIC_FUNC("UriUtils", "parseRequiredFilePath"); CAF_CM_VALIDATE_STRING(uriStr); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(uriStr); SUriRecord uriRecord; parseUriString(uriStr, uriRecord); if(uriRecord.protocol.compare("file") != 0) { CAF_CM_EXCEPTIONEX_VA2(InvalidArgumentException, ERROR_INVALID_DATA, "Unsupported protocol (%s != \"file\") - %s", uriRecord.protocol.c_str(), uriStr.c_str()); } UriUtils::SFileUriRecord fileUriRecord; UriUtils::parseFileAddress(uriRecord.address, fileUriRecord); rc = CStringUtils::expandEnv(fileUriRecord.path); if(! FileSystemUtils::doesFileExist(rc)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "File in URI not found - %s", rc.c_str()); } } CAF_CM_EXIT; return rc; } std::string UriUtils::parseOptionalFilePath( const std::string& uriStr) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("UriUtils", "parseOptionalFilePath"); CAF_CM_VALIDATE_STRING(uriStr); std::string rc = ""; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(uriStr); SUriRecord uriRecord; parseUriString(uriStr, uriRecord); if(uriRecord.protocol.compare("file") != 0) { CAF_CM_LOG_DEBUG_VA2( "Unsupported protocol (%s != \"file\") - %s", uriRecord.protocol.c_str(), uriStr.c_str()); } else { UriUtils::SFileUriRecord fileUriRecord; UriUtils::parseFileAddress(uriRecord.address, fileUriRecord); const std::string filePath = CStringUtils::expandEnv(fileUriRecord.path); if(! FileSystemUtils::doesFileExist(filePath)) { CAF_CM_LOG_DEBUG_VA2( "File in URI not found - uri: %s, path: %s", uriStr.c_str(), filePath.c_str()); } else { rc = filePath; } } } CAF_CM_EXIT; return rc; } std::string UriUtils::appendParameters( const std::string& uriStr, const std::map& parameters) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("UriUtils", "appendParameters"); CAF_CM_VALIDATE_STRING(uriStr); std::string rc = uriStr; if (!parameters.empty()) { rc += "?"; for (TConstMapIterator > parameter(parameters); parameter; parameter++) { rc += parameter.getKey() + "=" + *parameter + ";"; } } CAF_CM_LOG_DEBUG_VA1("Appended parameters - num: %d", parameters.size()); return rc; } std::string UriUtils::findOptParameter( const UriUtils::SUriRecord& uri, const std::string& name, const std::string& defaultValue) { CAF_CM_STATIC_FUNC_VALIDATE("UriUtils", "findOptParameter"); CAF_CM_VALIDATE_STRING(name); std::string rc = defaultValue; const std::map::const_iterator param = uri.parameters.find(name); if(param != uri.parameters.end()) { rc = param->second; } return rc; } std::string UriUtils::findReqParameter( const UriUtils::SUriRecord& uri, const std::string& name) { CAF_CM_STATIC_FUNC("UriUtils", "findReqParameter"); CAF_CM_VALIDATE_STRING(name); const std::map::const_iterator param = uri.parameters.find(name); if(param == uri.parameters.end()) { CAF_CM_EXCEPTION_VA1(E_INVALIDARG, "param not found - %s", name.c_str()); } return param->second; } open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/UriUtils.h000066400000000000000000000026461321503522500332560ustar00rootroot00000000000000/* * Author: mdonahue * Created: Feb 4, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef UriUtils_h_ #define UriUtils_h_ namespace Caf { namespace UriUtils { struct SUriRecord { std::string protocol; std::string address; std::string username; std::string password; std::string host; uint32 port; std::string portStr; std::string path; std::map parameters; }; struct SFileUriRecord { std::string hostname; std::string path; }; void COMMONAGGREGATOR_LINKAGE parseUriString(const std::string& uri, SUriRecord& data); std::string COMMONAGGREGATOR_LINKAGE buildUriString(SUriRecord& data); void COMMONAGGREGATOR_LINKAGE parseFileAddress(const std::string& fileUri, SFileUriRecord& data); std::string COMMONAGGREGATOR_LINKAGE parseRequiredFilePath(const std::string& uriStr); std::string COMMONAGGREGATOR_LINKAGE parseOptionalFilePath(const std::string& uriStr); std::string COMMONAGGREGATOR_LINKAGE appendParameters(const std::string& uriStr, const std::map& parameters); std::string COMMONAGGREGATOR_LINKAGE findOptParameter( const UriUtils::SUriRecord& uri, const std::string& name, const std::string& defaultValue = std::string()); std::string COMMONAGGREGATOR_LINKAGE findReqParameter( const UriUtils::SUriRecord& uri, const std::string& name); }; } #endif /* UriUtils_h_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Common/stdafx.h000066400000000000000000000014011321503522500327530ustar00rootroot00000000000000/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define COMMONAGGREGATOR_LINKAGE __declspec(dllexport) #define EXCEPTION_LINKAGE __declspec(dllexport) #define LOGGING_LINKAGE __declspec(dllexport) #define SUBSYSTEMBASE_LINKAGE __declspec(dllexport) #define MARKUPPARSER_LINKAGE __declspec(dllexport) #define XMLUTILS_LINKAGE __declspec(dllexport) #else #define COMMONAGGREGATOR_LINKAGE #define EXCEPTION_LINKAGE #define LOGGING_LINKAGE #define SUBSYSTEMBASE_LINKAGE #define MARKUPPARSER_LINKAGE #define XMLUTILS_LINKAGE #endif #include #include "CommonAggregatorLink.h" #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/CommonGlobals.cpp000066400000000000000000000042051321503522500333260ustar00rootroot00000000000000/* * Author: bwilliams * Created: 10/19/2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include namespace Caf { const char* _sConfigTmpDir = "tmp_dir"; const char* _sConfigInputDir = "input_dir"; const char* _sConfigOutputDir = "output_dir"; const char* _sConfigSchemaCacheDir = "schema_cache_dir"; const char* _sConfigProviderRegDir = "provider_reg_dir"; const char* _sConfigInstallDir = "install_dir"; const char* _sConfigInvokersDir = "invokers_dir"; const char* _sConfigProvidersDir = "providers_dir"; const char* _sConfigCommonPackagesDir = "common_packages_dir"; const char* _sConfigWorkingDir = "working_dir"; const char* _sConfigPrivateKeyFile = "private_key_file"; const char* _sConfigCertFile = "cert_file"; const char* _sProviderHostArea = "providerHost"; const char* _sManagementAgentArea = "managementAgent"; const char* _sSchemaSummaryFilename = "schemaSummary.xml"; const char* _sProviderResponseFilename = "providerResponse.xml"; const char* _sStdoutFilename = "_provider_stdout_"; const char* _sStderrFilename = "_provider_stderr_"; const char* _sPayloadRequestFilename = "payloadRequest.xml"; const char* _sResponseFilename = "response.xml"; const char* _sErrorResponseFilename = "errorResponse.xml"; const char* _sProviderRequestFilename = "providerRequest.xml"; const char* _sInfraErrFilename = "_infraError_"; const char* _sAppConfigGlobalParamRootDir = "root_dir"; const char* _sAppConfigGlobalParamDataDir = "data_dir"; const char* _sAppConfigGlobalParamLogDir = "log_dir"; const char* _sAppConfigGlobalParamLogConfigFile = "log_config_file"; const char* _sAppConfigGlobalParamInputDir = "input_dir"; const char* _sAppConfigGlobalParamOutputDir = "output_dir"; const char* _sAppConfigGlobalParamDbDir = "db_dir"; const char* _sAppConfigGlobalThreadStackSizeKb = "thread_stack_size_kb"; const GUID CAFCOMMON_GUID_NULL = {0}; #ifdef WIN32 const char* CAFCOMMON_PATH_DELIM = "\\"; const char CAFCOMMON_PATH_DELIM_CHAR = '\\'; #else const char* CAFCOMMON_PATH_DELIM = "/"; const char CAFCOMMON_PATH_DELIM_CHAR = '/'; #endif } open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/000077500000000000000000000000001321503522500305725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/000077500000000000000000000000001321503522500317255ustar00rootroot00000000000000CafCoreTypesDoc/000077500000000000000000000000001321503522500346235ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCAddInCollectionDoc.cpp000066400000000000000000000015771321503522500410650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAddInCollectionDoc.h" using namespace Caf; /// A simple container for objects of type AddInCollection CAddInCollectionDoc::CAddInCollectionDoc() : _isInitialized(false) {} CAddInCollectionDoc::~CAddInCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CAddInCollectionDoc::initialize( const std::deque addInCollection) { if (! _isInitialized) { _addInCollection = addInCollection; _isInitialized = true; } } /// Accessor for the AddIn std::deque CAddInCollectionDoc::getAddInCollection() const { return _addInCollection; } CAddInsDoc.cpp000066400000000000000000000016271321503522500372300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAddInCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAddInsDoc.h" using namespace Caf; /// A simple container for objects of type AddIns CAddInsDoc::CAddInsDoc() : _isInitialized(false) {} CAddInsDoc::~CAddInsDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CAddInsDoc::initialize( const std::deque addInCollection) { if (! _isInitialized) { _addInCollection = addInCollection; _isInitialized = true; } } /// Accessor for the AddInCollection std::deque CAddInsDoc::getAddInCollection() const { return _addInCollection; } CAttachmentCollectionDoc.cpp000066400000000000000000000024371321503522500421720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" using namespace Caf; /// A simple container for objects of type AttachmentCollection CAttachmentCollectionDoc::CAttachmentCollectionDoc() : _isInitialized(false) {} CAttachmentCollectionDoc::~CAttachmentCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CAttachmentCollectionDoc::initialize( const std::deque attachment, const std::deque inlineAttachment) { if (! _isInitialized) { _attachment = attachment; _inlineAttachment = inlineAttachment; _isInitialized = true; } } /// Accessor for the Attachment std::deque CAttachmentCollectionDoc::getAttachment() const { return _attachment; } /// Accessor for the InlineAttachment std::deque CAttachmentCollectionDoc::getInlineAttachment() const { return _inlineAttachment; } CAttachmentDoc.cpp000066400000000000000000000027301321503522500401520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" using namespace Caf; /// A simple container for objects of type Attachment CAttachmentDoc::CAttachmentDoc() : _isInitialized(false), _isReference(false), _cmsPolicy(CMS_POLICY_CAF_ENCRYPTED_AND_SIGNED) {} CAttachmentDoc::~CAttachmentDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CAttachmentDoc::initialize( const std::string name, const std::string type, const std::string uri, const bool isReference, const CMS_POLICY cmsPolicy) { if (! _isInitialized) { _name = name; _type = type; _uri = uri; _isReference = isReference; _cmsPolicy = cmsPolicy; _isInitialized = true; } } /// Accessor for the Name std::string CAttachmentDoc::getName() const { return _name; } /// Accessor for the Type std::string CAttachmentDoc::getType() const { return _type; } /// Accessor for the Uri std::string CAttachmentDoc::getUri() const { return _uri; } /// Accessor for the IsReference bool CAttachmentDoc::getIsReference() const { return _isReference; } /// Accessor for the CMS Policy CMS_POLICY CAttachmentDoc::getCmsPolicy() const { return _cmsPolicy; } CMS_POLICY _cmsPolicy; CAttachmentNameCollectionDoc.cpp000066400000000000000000000016171321503522500427720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" using namespace Caf; /// A simple container for objects of type AttachmentNameCollection CAttachmentNameCollectionDoc::CAttachmentNameCollectionDoc() : _isInitialized(false) {} CAttachmentNameCollectionDoc::~CAttachmentNameCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CAttachmentNameCollectionDoc::initialize( const std::deque name) { if (! _isInitialized) { _name = name; _isInitialized = true; } } /// Accessor for the Name std::deque CAttachmentNameCollectionDoc::getName() const { return _name; } CAuthnAuthzCollectionDoc.cpp000066400000000000000000000017531321503522500421750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzDoc.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzCollectionDoc.h" using namespace Caf; /// Set of logging levels for different components CAuthnAuthzCollectionDoc::CAuthnAuthzCollectionDoc() : _isInitialized(false) {} CAuthnAuthzCollectionDoc::~CAuthnAuthzCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CAuthnAuthzCollectionDoc::initialize( const std::deque authnAuthz) { if (! _isInitialized) { _authnAuthz = authnAuthz; _isInitialized = true; } } /// Used to change the logging level for a specific component std::deque CAuthnAuthzCollectionDoc::getAuthnAuthz() const { return _authnAuthz; } CAuthnAuthzDoc.cpp000066400000000000000000000023271321503522500401570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: May 24, 2015 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzDoc.h" using namespace Caf; /// A simple container for objects of type AuthnAuthz CAuthnAuthzDoc::CAuthnAuthzDoc() : _isInitialized(false), _sequenceNumber(0) {} CAuthnAuthzDoc::~CAuthnAuthzDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CAuthnAuthzDoc::initialize( const std::string type, const std::string value, const std::string name, const int32 sequenceNumber) { if (! _isInitialized) { _type = type; _value = value; _name = name; _sequenceNumber = sequenceNumber; _isInitialized = true; } } /// Accessor for the Type std::string CAuthnAuthzDoc::getType() const { return _type; } /// Accessor for the Value std::string CAuthnAuthzDoc::getValue() const { return _value; } /// Accessor for the Name std::string CAuthnAuthzDoc::getName() const { return _name; } /// Accessor for the SequenceNumber int32 CAuthnAuthzDoc::getSequenceNumber() const { return _sequenceNumber; } CClassFiltersDoc.cpp000066400000000000000000000017601321503522500404620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CClassFiltersDoc.h" using namespace Caf; /// A simple container for objects of type ClassFilters CClassFiltersDoc::CClassFiltersDoc() : _isInitialized(false) {} CClassFiltersDoc::~CClassFiltersDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CClassFiltersDoc::initialize( const std::string dialect, const std::deque classFilter) { if (! _isInitialized) { _dialect = dialect; _classFilter = classFilter; _isInitialized = true; } } /// Accessor for the Dialect std::string CClassFiltersDoc::getDialect() const { return _dialect; } /// Accessor for the ClassFilter std::deque CClassFiltersDoc::getClassFilter() const { return _classFilter; } CClassSpecifierDoc.cpp000066400000000000000000000023651321503522500407650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CClassFiltersDoc.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" using namespace Caf; /// A simple container for objects of type ClassSpecifier CClassSpecifierDoc::CClassSpecifierDoc() : _isInitialized(false) {} CClassSpecifierDoc::~CClassSpecifierDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CClassSpecifierDoc::initialize( const SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClass, const SmartPtrCClassFiltersDoc classFilters) { if (! _isInitialized) { _fullyQualifiedClass = fullyQualifiedClass; _classFilters = classFilters; _isInitialized = true; } } /// Accessor for the FullyQualifiedClass SmartPtrCFullyQualifiedClassGroupDoc CClassSpecifierDoc::getFullyQualifiedClass() const { return _fullyQualifiedClass; } /// Accessor for the ClassFilters SmartPtrCClassFiltersDoc CClassSpecifierDoc::getClassFilters() const { return _classFilters; } CFullyQualifiedClassGroupDoc.cpp000066400000000000000000000024431321503522500430050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" using namespace Caf; /// A simple container for objects of type FullyQualifiedClassGroup CFullyQualifiedClassGroupDoc::CFullyQualifiedClassGroupDoc() : _isInitialized(false) {} CFullyQualifiedClassGroupDoc::~CFullyQualifiedClassGroupDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CFullyQualifiedClassGroupDoc::initialize( const std::string classNamespace, const std::string className, const std::string classVersion) { if (! _isInitialized) { _classNamespace = classNamespace; _className = className; _classVersion = classVersion; _isInitialized = true; } } /// Accessor for the ClassNamespace std::string CFullyQualifiedClassGroupDoc::getClassNamespace() const { return _classNamespace; } /// Accessor for the ClassName std::string CFullyQualifiedClassGroupDoc::getClassName() const { return _className; } /// Accessor for the ClassVersion std::string CFullyQualifiedClassGroupDoc::getClassVersion() const { return _classVersion; } CInlineAttachmentCollectionDoc.cpp000066400000000000000000000020501321503522500433200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentCollectionDoc.h" using namespace Caf; /// A simple container for objects of type InlineAttachmentCollection CInlineAttachmentCollectionDoc::CInlineAttachmentCollectionDoc() : _isInitialized(false) {} CInlineAttachmentCollectionDoc::~CInlineAttachmentCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInlineAttachmentCollectionDoc::initialize( const std::deque attachment) { if (! _isInitialized) { _attachment = attachment; _isInitialized = true; } } /// Accessor for the InlineAttachment std::deque CInlineAttachmentCollectionDoc::getInlineAttachment() const { return _attachment; } CInlineAttachmentDoc.cpp000066400000000000000000000021171321503522500413100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" using namespace Caf; /// A simple container for objects of type InlineAttachment CInlineAttachmentDoc::CInlineAttachmentDoc() : _isInitialized(false) {} CInlineAttachmentDoc::~CInlineAttachmentDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInlineAttachmentDoc::initialize( const std::string name, const std::string type, const std::string value) { if (! _isInitialized) { _name = name; _type = type; _value = value; _isInitialized = true; } } /// Accessor for the Name std::string CInlineAttachmentDoc::getName() const { return _name; } /// Accessor for the Type std::string CInlineAttachmentDoc::getType() const { return _type; } /// Accessor for the Value std::string CInlineAttachmentDoc::getValue() const { return _value; } CLoggingLevelCollectionDoc.cpp000066400000000000000000000020251321503522500424510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelElemDoc.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" using namespace Caf; /// Set of logging levels for different components CLoggingLevelCollectionDoc::CLoggingLevelCollectionDoc() : _isInitialized(false) {} CLoggingLevelCollectionDoc::~CLoggingLevelCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CLoggingLevelCollectionDoc::initialize( const std::deque loggingLevel) { if (! _isInitialized) { _loggingLevel = loggingLevel; _isInitialized = true; } } /// Used to change the logging level for a specific component std::deque CLoggingLevelCollectionDoc::getLoggingLevel() const { return _loggingLevel; } CLoggingLevelElemDoc.cpp000066400000000000000000000022721321503522500412440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelElemDoc.h" using namespace Caf; /// Logging level for a component CLoggingLevelElemDoc::CLoggingLevelElemDoc() : _component(LOGGINGCOMPONENT_NONE), _level(LOGGINGLEVEL_NONE), _isInitialized(false) {} CLoggingLevelElemDoc::~CLoggingLevelElemDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CLoggingLevelElemDoc::initialize( const LOGGINGCOMPONENT_TYPE component, const LOGGINGLEVEL_TYPE level) { if (! _isInitialized) { _component = component; _level = level; _isInitialized = true; } } /// The logging level applies to this component LOGGINGCOMPONENT_TYPE CLoggingLevelElemDoc::getComponent() const { return _component; } /// Set the logging level to this value LOGGINGLEVEL_TYPE CLoggingLevelElemDoc::getLevel() const { return _level; } LOGGINGCOMPONENT_TYPE _component; LOGGINGLEVEL_TYPE _level; COperationDoc.cpp000066400000000000000000000020751321503522500400240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" using namespace Caf; /// A simple container for objects of type Operation COperationDoc::COperationDoc() : _isInitialized(false) {} COperationDoc::~COperationDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void COperationDoc::initialize( const std::string name, const SmartPtrCParameterCollectionDoc parameterCollection) { if (! _isInitialized) { _name = name; _parameterCollection = parameterCollection; _isInitialized = true; } } /// Accessor for the Name std::string COperationDoc::getName() const { return _name; } /// Accessor for the ParameterCollection SmartPtrCParameterCollectionDoc COperationDoc::getParameterCollection() const { return _parameterCollection; } CParameterCollectionDoc.cpp000066400000000000000000000025001321503522500420110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" using namespace Caf; /// A simple container for objects of type ParameterCollection CParameterCollectionDoc::CParameterCollectionDoc() : _isInitialized(false) {} CParameterCollectionDoc::~CParameterCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CParameterCollectionDoc::initialize( const std::deque parameter, const std::deque instanceParameter) { if (! _isInitialized) { _parameter = parameter; _instanceParameter = instanceParameter; _isInitialized = true; } } /// Accessor for the Parameter std::deque CParameterCollectionDoc::getParameter() const { return _parameter; } /// Accessor for the InstanceParameter std::deque CParameterCollectionDoc::getInstanceParameter() const { return _instanceParameter; } CPropertyCollectionDoc.cpp000066400000000000000000000016701321503522500417240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" using namespace Caf; /// A simple container for objects of type PropertyCollection CPropertyCollectionDoc::CPropertyCollectionDoc() : _isInitialized(false) {} CPropertyCollectionDoc::~CPropertyCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPropertyCollectionDoc::initialize( const std::deque property) { if (! _isInitialized) { _property = property; _isInitialized = true; } } /// Accessor for the Property std::deque CPropertyCollectionDoc::getProperty() const { return _property; } CPropertyDoc.cpp000066400000000000000000000021501321503522500377020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" using namespace Caf; /// A simple container for objects of type Property CPropertyDoc::CPropertyDoc() : _type(PROPERTY_NONE), _isInitialized(false) {} CPropertyDoc::~CPropertyDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPropertyDoc::initialize( const std::string name, const PROPERTY_TYPE type, const std::deque value) { if (! _isInitialized) { _name = name; _type = type; _value = value; _isInitialized = true; } } /// Accessor for the Name std::string CPropertyDoc::getName() const { return _name; } /// Accessor for the Type PROPERTY_TYPE CPropertyDoc::getType() const { return _type; } /// Accessor for the Value std::deque CPropertyDoc::getValue() const { return _value; } CProtocolCollectionDoc.cpp000066400000000000000000000016561321503522500417050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CProtocolDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" using namespace Caf; /// Set of protocol CProtocolCollectionDoc::CProtocolCollectionDoc() : _isInitialized(false) {} CProtocolCollectionDoc::~CProtocolCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProtocolCollectionDoc::initialize( const std::deque protocol) { if (! _isInitialized) { _protocol = protocol; _isInitialized = true; } } /// Used to change the logging level for a specific component std::deque CProtocolCollectionDoc::getProtocol() const { return _protocol; } CProtocolDoc.cpp000066400000000000000000000020521321503522500376600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CProtocolDoc.h" using namespace Caf; /// A simple container for objects of Protocol CProtocolDoc::CProtocolDoc() : _sequenceNumber(0), _isInitialized(false) {} CProtocolDoc::~CProtocolDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProtocolDoc::initialize( const std::string uri, const std::string name, const int32 sequenceNumber) { if (! _isInitialized) { _name = name; _uri = uri; _sequenceNumber = sequenceNumber; _isInitialized = true; } } /// Accessor for the Uri std::string CProtocolDoc::getUri() const { return _uri; } /// Accessor for the Name std::string CProtocolDoc::getName() const { return _name; } /// Accessor for the Value int32 CProtocolDoc::getSequenceNumber() const { return _sequenceNumber; } CRequestConfigDoc.cpp000066400000000000000000000034021321503522500406350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAddInsDoc.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestConfigDoc.h" using namespace Caf; /// A simple container for objects of type RequestConfig CRequestConfigDoc::CRequestConfigDoc() : _isInitialized(false) {} CRequestConfigDoc::~CRequestConfigDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CRequestConfigDoc::initialize( const std::string responseFormatType, const SmartPtrCAddInsDoc requestProcessorAddIns, const SmartPtrCAddInsDoc responseProcessorAddIns, const SmartPtrCLoggingLevelCollectionDoc loggingLevelCollection) { if (! _isInitialized) { _responseFormatType = responseFormatType; _requestProcessorAddIns = requestProcessorAddIns; _responseProcessorAddIns = responseProcessorAddIns; _loggingLevelCollection = loggingLevelCollection; _isInitialized = true; } } /// Accessor for the ResponseFormatType std::string CRequestConfigDoc::getResponseFormatType() const { return _responseFormatType; } /// Accessor for the RequestProcessorAddIns SmartPtrCAddInsDoc CRequestConfigDoc::getRequestProcessorAddIns() const { return _requestProcessorAddIns; } /// Accessor for the ResponseProcessorAddIns SmartPtrCAddInsDoc CRequestConfigDoc::getResponseProcessorAddIns() const { return _responseProcessorAddIns; } /// Accessor for the LoggingLevelCollection SmartPtrCLoggingLevelCollectionDoc CRequestConfigDoc::getLoggingLevelCollection() const { return _loggingLevelCollection; } CRequestHeaderDoc.cpp000066400000000000000000000046231321503522500406260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestConfigDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" using namespace Caf; /// A simple container for objects of type RequestHeader CRequestHeaderDoc::CRequestHeaderDoc() : _isInitialized(false), _sessionId(CAFCOMMON_GUID_NULL) {} CRequestHeaderDoc::~CRequestHeaderDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CRequestHeaderDoc::initialize( const SmartPtrCRequestConfigDoc requestConfig, const SmartPtrCAuthnAuthzCollectionDoc authnAuthzCollection, const SmartPtrCProtocolCollectionDoc protocolCollection, const SmartPtrCPropertyCollectionDoc echoPropertyBag, const std::string version, const std::string createdDateTime, const UUID sessionId) { if (! _isInitialized) { _requestConfig = requestConfig; _authnAuthzCollection = authnAuthzCollection; _protocolCollection = protocolCollection; _echoPropertyBag = echoPropertyBag; _version = version; _createdDateTime = createdDateTime; _sessionId = sessionId; _isInitialized = true; } } /// Accessor for the RequestConfig SmartPtrCRequestConfigDoc CRequestHeaderDoc::getRequestConfig() const { return _requestConfig; } /// Accessor for the Authentication / Authorization Collection SmartPtrCAuthnAuthzCollectionDoc CRequestHeaderDoc::getAuthnAuthzCollection() const { return _authnAuthzCollection; } /// Accessor for the Protocol Collection SmartPtrCProtocolCollectionDoc CRequestHeaderDoc::getProtocolCollection() const { return _protocolCollection; } /// Accessor for the EchoPropertyBag SmartPtrCPropertyCollectionDoc CRequestHeaderDoc::getEchoPropertyBag() const { return _echoPropertyBag; } /// Accessor for the version std::string CRequestHeaderDoc::getVersion() const { return _version; } /// Accessor for the date/time when the request was created std::string CRequestHeaderDoc::getCreatedDateTime() const { return _createdDateTime; } /// Accessor for the session ID UUID CRequestHeaderDoc::getSessionId() const { return _sessionId; } CRequestInstanceParameterDoc.cpp000066400000000000000000000031431321503522500430370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" using namespace Caf; /// A simple container for objects of type RequestInstanceParameter CRequestInstanceParameterDoc::CRequestInstanceParameterDoc() : _isInitialized(false) {} CRequestInstanceParameterDoc::~CRequestInstanceParameterDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CRequestInstanceParameterDoc::initialize( const std::string name, const std::string classNamespace, const std::string className, const std::string classVersion, const std::deque value) { if (! _isInitialized) { _name = name; _classNamespace = classNamespace; _className = className; _classVersion = classVersion; _value = value; _isInitialized = true; } } /// Accessor for the Name std::string CRequestInstanceParameterDoc::getName() const { return _name; } /// Accessor for the ClassNamespace std::string CRequestInstanceParameterDoc::getClassNamespace() const { return _classNamespace; } /// Accessor for the ClassName std::string CRequestInstanceParameterDoc::getClassName() const { return _className; } /// Accessor for the ClassVersion std::string CRequestInstanceParameterDoc::getClassVersion() const { return _classVersion; } /// Accessor for the Value std::deque CRequestInstanceParameterDoc::getValue() const { return _value; } CRequestParameterDoc.cpp000066400000000000000000000022731321503522500413550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" using namespace Caf; /// A simple container for objects of type RequestParameter CRequestParameterDoc::CRequestParameterDoc() : _type(PARAMETER_NONE), _isInitialized(false) {} CRequestParameterDoc::~CRequestParameterDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CRequestParameterDoc::initialize( const std::string name, const PARAMETER_TYPE type, const std::deque value) { if (! _isInitialized) { _name = name; _type = type; _value = value; _isInitialized = true; } } /// Accessor for the Name std::string CRequestParameterDoc::getName() const { return _name; } /// Accessor for the Type PARAMETER_TYPE CRequestParameterDoc::getType() const { return _type; } /// Accessor for the Value std::deque CRequestParameterDoc::getValue() const { return _value; } CStatisticsDoc.cpp000066400000000000000000000041331321503522500402130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" using namespace Caf; /// A simple container for objects of type Statistics CStatisticsDoc::CStatisticsDoc() : _providerJobNum(0), _providerJobTotal(0), _providerJobDurationSecs(0), _pmeNum(0), _pmeTotal(0), _pmeDurationSecs(0), _isInitialized(false) {} CStatisticsDoc::~CStatisticsDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CStatisticsDoc::initialize( const SmartPtrCPropertyCollectionDoc propertyCollection, const int32 providerJobNum, const int32 providerJobTotal, const int32 providerJobDurationSecs, const int32 pmeNum, const int32 pmeTotal, const int32 pmeDurationSecs) { if (! _isInitialized) { _propertyCollection = propertyCollection; _providerJobNum = providerJobNum; _providerJobTotal = providerJobTotal; _providerJobDurationSecs = providerJobDurationSecs; _pmeNum = pmeNum; _pmeTotal = pmeTotal; _pmeDurationSecs = pmeDurationSecs; _isInitialized = true; } } /// Accessor for the PropertyCollection SmartPtrCPropertyCollectionDoc CStatisticsDoc::getPropertyCollection() const { return _propertyCollection; } /// Accessor for the ProviderJobNum int32 CStatisticsDoc::getProviderJobNum() const { return _providerJobNum; } /// Accessor for the ProviderJobTotal int32 CStatisticsDoc::getProviderJobTotal() const { return _providerJobTotal; } /// Accessor for the ProviderJobDurationSecs int32 CStatisticsDoc::getProviderJobDurationSecs() const { return _providerJobDurationSecs; } /// Accessor for the PmeNum int32 CStatisticsDoc::getPmeNum() const { return _pmeNum; } /// Accessor for the PmeTotal int32 CStatisticsDoc::getPmeTotal() const { return _pmeTotal; } /// Accessor for the PmeDurationSecs int32 CStatisticsDoc::getPmeDurationSecs() const { return _pmeDurationSecs; } stdafx.h000066400000000000000000000005431321503522500362670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafCoreTypesDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define CAFCORETYPESDOC_LINKAGE __declspec(dllexport) #else #define CAFCORETYPESDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ CafInstallRequestDoc/000077500000000000000000000000001321503522500356655ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCFullPackageElemDoc.cpp000066400000000000000000000035721321503522500421120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CPackageDefnDoc.h" #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" using namespace Caf; /// A simple container for objects of type FullPackageElem CFullPackageElemDoc::CFullPackageElemDoc() : _index(0), _isInitialized(false) {} CFullPackageElemDoc::~CFullPackageElemDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CFullPackageElemDoc::initialize( const int32 index, const std::string packageNamespace, const std::string packageName, const std::string packageVersion, const SmartPtrCPackageDefnDoc installPackage, const SmartPtrCPackageDefnDoc uninstallPackage) { if (! _isInitialized) { _index = index; _packageNamespace = packageNamespace; _packageName = packageName; _packageVersion = packageVersion; _installPackage = installPackage; _uninstallPackage = uninstallPackage; _isInitialized = true; } } /// Accessor for the Index int32 CFullPackageElemDoc::getIndex() const { return _index; } /// Accessor for the PackageNamespace std::string CFullPackageElemDoc::getPackageNamespace() const { return _packageNamespace; } /// Accessor for the PackageName std::string CFullPackageElemDoc::getPackageName() const { return _packageName; } /// Accessor for the PackageVersion std::string CFullPackageElemDoc::getPackageVersion() const { return _packageVersion; } /// Accessor for the InstallPackage SmartPtrCPackageDefnDoc CFullPackageElemDoc::getInstallPackage() const { return _installPackage; } /// Accessor for the UninstallPackage SmartPtrCPackageDefnDoc CFullPackageElemDoc::getUninstallPackage() const { return _uninstallPackage; } CGetInventoryJobDoc.cpp000066400000000000000000000015111321503522500422100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CGetInventoryJobDoc.h" using namespace Caf; /// A simple container for objects of type GetInventoryJob CGetInventoryJobDoc::CGetInventoryJobDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CGetInventoryJobDoc::~CGetInventoryJobDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CGetInventoryJobDoc::initialize( const UUID jobId) { if (! _isInitialized) { _jobId = jobId; _isInitialized = true; } } /// Accessor for the JobId UUID CGetInventoryJobDoc::getJobId() const { return _jobId; } CInstallBatchDoc.cpp000066400000000000000000000030151321503522500414710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CGetInventoryJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallBatchDoc.h" using namespace Caf; /// A simple container for objects of type InstallBatch CInstallBatchDoc::CInstallBatchDoc() : _isInitialized(false) {} CInstallBatchDoc::~CInstallBatchDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInstallBatchDoc::initialize( const SmartPtrCGetInventoryJobDoc getInventory, const SmartPtrCInstallProviderJobDoc installProvider, const SmartPtrCUninstallProviderJobDoc uninstallProvider) { if (! _isInitialized) { _getInventory = getInventory; _installProvider = installProvider; _uninstallProvider = uninstallProvider; _isInitialized = true; } } /// Accessor for the GetInventory SmartPtrCGetInventoryJobDoc CInstallBatchDoc::getGetInventory() const { return _getInventory; } /// Accessor for the InstallProvider SmartPtrCInstallProviderJobDoc CInstallBatchDoc::getInstallProvider() const { return _installProvider; } /// Accessor for the UninstallProvider SmartPtrCUninstallProviderJobDoc CInstallBatchDoc::getUninstallProvider() const { return _uninstallProvider; } CInstallPackageSpecDoc.cpp000066400000000000000000000051501321503522500426200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CInstallPackageSpecDoc.h" using namespace Caf; /// A simple container for objects of type InstallPackageSpec CInstallPackageSpecDoc::CInstallPackageSpecDoc() : _isInitialized(false) {} CInstallPackageSpecDoc::~CInstallPackageSpecDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInstallPackageSpecDoc::initialize( const std::string packageNamespace, const std::string packageName, const std::string packageVersion, const std::string startupAttachmentName, const std::string packageAttachmentName, const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection, const SmartPtrCAttachmentCollectionDoc attachmentCollection, const std::string arguments) { if (! _isInitialized) { _packageNamespace = packageNamespace; _packageName = packageName; _packageVersion = packageVersion; _startupAttachmentName = startupAttachmentName; _packageAttachmentName = packageAttachmentName; _attachmentNameCollection = attachmentNameCollection; _attachmentCollection = attachmentCollection; _arguments = arguments; _isInitialized = true; } } /// Accessor for the PackageNamespace std::string CInstallPackageSpecDoc::getPackageNamespace() const { return _packageNamespace; } /// Accessor for the PackageName std::string CInstallPackageSpecDoc::getPackageName() const { return _packageName; } /// Accessor for the PackageVersion std::string CInstallPackageSpecDoc::getPackageVersion() const { return _packageVersion; } /// Accessor for the StartupAttachmentName std::string CInstallPackageSpecDoc::getStartupAttachmentName() const { return _startupAttachmentName; } /// Accessor for the PackageAttachmentName std::string CInstallPackageSpecDoc::getPackageAttachmentName() const { return _packageAttachmentName; } /// Accessor for the AttachmentNameCollection SmartPtrCAttachmentNameCollectionDoc CInstallPackageSpecDoc::getSupportingAttachmentNameCollection() const { return _attachmentNameCollection; } /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc CInstallPackageSpecDoc::getAttachmentCollection() const { return _attachmentCollection; } /// Accessor for the Arguments std::string CInstallPackageSpecDoc::getArguments() const { return _arguments; } CInstallProviderJobDoc.cpp000066400000000000000000000043501321503522500427000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" using namespace Caf; /// A simple container for objects of type InstallProviderJob CInstallProviderJobDoc::CInstallProviderJobDoc() : _clientId(CAFCOMMON_GUID_NULL), _jobId(CAFCOMMON_GUID_NULL), _packageOSType(PACKAGE_OS_NONE), _isInitialized(false) {} CInstallProviderJobDoc::~CInstallProviderJobDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInstallProviderJobDoc::initialize( const UUID clientId, const UUID jobId, const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const PACKAGE_OS_TYPE packageOSType, const std::deque packageCollection) { if (! _isInitialized) { _clientId = clientId; _jobId = jobId; _providerNamespace = providerNamespace; _providerName = providerName; _providerVersion = providerVersion; _packageOSType = packageOSType; _packageCollection = packageCollection; _isInitialized = true; } } /// Accessor for the ClientId UUID CInstallProviderJobDoc::getClientId() const { return _clientId; } /// Accessor for the JobId UUID CInstallProviderJobDoc::getJobId() const { return _jobId; } /// Accessor for the ProviderNamespace std::string CInstallProviderJobDoc::getProviderNamespace() const { return _providerNamespace; } /// Accessor for the ProviderName std::string CInstallProviderJobDoc::getProviderName() const { return _providerName; } /// Accessor for the ProviderVersion std::string CInstallProviderJobDoc::getProviderVersion() const { return _providerVersion; } /// Accessor for the PackageOSType PACKAGE_OS_TYPE CInstallProviderJobDoc::getPackageOSType() const { return _packageOSType; } /// Accessor for the PackageVal std::deque CInstallProviderJobDoc::getPackageCollection() const { return _packageCollection; } CInstallProviderSpecDoc.cpp000066400000000000000000000034451321503522500430640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" using namespace Caf; /// A simple container for objects of type InstallProviderSpec CInstallProviderSpecDoc::CInstallProviderSpecDoc() : _clientId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CInstallProviderSpecDoc::~CInstallProviderSpecDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInstallProviderSpecDoc::initialize( const UUID clientId, const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const std::deque packageCollection) { if (! _isInitialized) { _clientId = clientId; _providerNamespace = providerNamespace; _providerName = providerName; _providerVersion = providerVersion; _packageCollection = packageCollection; _isInitialized = true; } } /// Accessor for the ClientId UUID CInstallProviderSpecDoc::getClientId() const { return _clientId; } /// Accessor for the ProviderNamespace std::string CInstallProviderSpecDoc::getProviderNamespace() const { return _providerNamespace; } /// Accessor for the ProviderName std::string CInstallProviderSpecDoc::getProviderName() const { return _providerName; } /// Accessor for the ProviderVersion std::string CInstallProviderSpecDoc::getProviderVersion() const { return _providerVersion; } /// Accessor for the PackageVal std::deque CInstallProviderSpecDoc::getPackageCollection() const { return _packageCollection; } CInstallRequestDoc.cpp000066400000000000000000000037221321503522500421050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/CafInstallRequestDoc/CInstallBatchDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" using namespace Caf; /// A simple container for objects of type InstallRequest CInstallRequestDoc::CInstallRequestDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CInstallRequestDoc::~CInstallRequestDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInstallRequestDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCRequestHeaderDoc requestHeader, const SmartPtrCInstallBatchDoc batch, const SmartPtrCAttachmentCollectionDoc attachmentCollection) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _requestHeader = requestHeader; _batch = batch; _attachmentCollection = attachmentCollection; _isInitialized = true; } } /// Accessor for the ClientId UUID CInstallRequestDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CInstallRequestDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CInstallRequestDoc::getPmeId() const { return _pmeId; } /// Accessor for the RequestHeader SmartPtrCRequestHeaderDoc CInstallRequestDoc::getRequestHeader() const { return _requestHeader; } /// Accessor for the Batch SmartPtrCInstallBatchDoc CInstallRequestDoc::getBatch() const { return _batch; } /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc CInstallRequestDoc::getAttachmentCollection() const { return _attachmentCollection; } CMinPackageElemDoc.cpp000066400000000000000000000025641321503522500417330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" using namespace Caf; /// A simple container for objects of type MinPackageElem CMinPackageElemDoc::CMinPackageElemDoc() : _index(0), _isInitialized(false) {} CMinPackageElemDoc::~CMinPackageElemDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMinPackageElemDoc::initialize( const int32 index, const std::string packageNamespace, const std::string packageName, const std::string packageVersion) { if (! _isInitialized) { _index = index; _packageNamespace = packageNamespace; _packageName = packageName; _packageVersion = packageVersion; _isInitialized = true; } } /// Accessor for the Index int32 CMinPackageElemDoc::getIndex() const { return _index; } /// Accessor for the PackageNamespace std::string CMinPackageElemDoc::getPackageNamespace() const { return _packageNamespace; } /// Accessor for the PackageName std::string CMinPackageElemDoc::getPackageName() const { return _packageName; } /// Accessor for the PackageVersion std::string CMinPackageElemDoc::getPackageVersion() const { return _packageVersion; } CPackageDefnDoc.cpp000066400000000000000000000031751321503522500412600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CPackageDefnDoc.h" using namespace Caf; /// A simple container for objects of type PackageDefn CPackageDefnDoc::CPackageDefnDoc() : _isInitialized(false) {} CPackageDefnDoc::~CPackageDefnDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPackageDefnDoc::initialize( const std::string startupAttachmentName, const std::string packageAttachmentName, const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection, const std::string arguments) { if (! _isInitialized) { _startupAttachmentName = startupAttachmentName; _packageAttachmentName = packageAttachmentName; _attachmentNameCollection = attachmentNameCollection; _arguments = arguments; _isInitialized = true; } } /// Accessor for the StartupAttachmentName std::string CPackageDefnDoc::getStartupAttachmentName() const { return _startupAttachmentName; } /// Accessor for the PackageAttachmentName std::string CPackageDefnDoc::getPackageAttachmentName() const { return _packageAttachmentName; } /// Accessor for the AttachmentNameCollection SmartPtrCAttachmentNameCollectionDoc CPackageDefnDoc::getSupportingAttachmentNameCollection() const { return _attachmentNameCollection; } /// Accessor for the Arguments std::string CPackageDefnDoc::getArguments() const { return _arguments; } CUninstallProviderJobDoc.cpp000066400000000000000000000036751321503522500432540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" using namespace Caf; /// A simple container for objects of type UninstallProviderJob CUninstallProviderJobDoc::CUninstallProviderJobDoc() : _clientId(CAFCOMMON_GUID_NULL), _jobId(CAFCOMMON_GUID_NULL), _packageOSType(PACKAGE_OS_NONE), _isInitialized(false) {} CUninstallProviderJobDoc::~CUninstallProviderJobDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CUninstallProviderJobDoc::initialize( const UUID clientId, const UUID jobId, const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const PACKAGE_OS_TYPE packageOSType) { if (! _isInitialized) { _clientId = clientId; _jobId = jobId; _providerNamespace = providerNamespace; _providerName = providerName; _providerVersion = providerVersion; _packageOSType = packageOSType; _isInitialized = true; } } /// Accessor for the ClientId UUID CUninstallProviderJobDoc::getClientId() const { return _clientId; } /// Accessor for the JobId UUID CUninstallProviderJobDoc::getJobId() const { return _jobId; } /// Accessor for the ProviderNamespace std::string CUninstallProviderJobDoc::getProviderNamespace() const { return _providerNamespace; } /// Accessor for the ProviderName std::string CUninstallProviderJobDoc::getProviderName() const { return _providerName; } /// Accessor for the ProviderVersion std::string CUninstallProviderJobDoc::getProviderVersion() const { return _providerVersion; } /// Accessor for the PackageOSType PACKAGE_OS_TYPE CUninstallProviderJobDoc::getPackageOSType() const { return _packageOSType; } stdafx.h000066400000000000000000000005551321503522500373340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/CafInstallRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define CAFINSTALLREQUESTDOC_LINKAGE __declspec(dllexport) #else #define CAFINSTALLREQUESTDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ DiagRequestDoc/000077500000000000000000000000001321503522500345115ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCDiagRequestDoc.cpp000066400000000000000000000031141321503522500401620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/DiagTypesDoc/CDiagBatchDoc.h" #include "Doc/DiagRequestDoc/CDiagRequestDoc.h" using namespace Caf; /// A simple container for objects of type DiagRequest CDiagRequestDoc::CDiagRequestDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CDiagRequestDoc::~CDiagRequestDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDiagRequestDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCRequestHeaderDoc requestHeader, const SmartPtrCDiagBatchDoc batch) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _requestHeader = requestHeader; _batch = batch; _isInitialized = true; } } /// Accessor for the ClientId UUID CDiagRequestDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CDiagRequestDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CDiagRequestDoc::getPmeId() const { return _pmeId; } /// Accessor for the RequestHeader SmartPtrCRequestHeaderDoc CDiagRequestDoc::getRequestHeader() const { return _requestHeader; } /// Accessor for the Batch SmartPtrCDiagBatchDoc CDiagRequestDoc::getBatch() const { return _batch; } stdafx.h000066400000000000000000000005411321503522500361530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define DIAGREQUESTDOC_LINKAGE __declspec(dllexport) #else #define DIAGREQUESTDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ DiagTypesDoc/000077500000000000000000000000001321503522500341655ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCDiagBatchDoc.cpp000066400000000000000000000030731321503522500372330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/DiagTypesDoc/CDiagCollectInstancesDoc.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagBatchDoc.h" using namespace Caf; /// A simple container for objects of type DiagBatch CDiagBatchDoc::CDiagBatchDoc() : _isInitialized(false) {} CDiagBatchDoc::~CDiagBatchDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDiagBatchDoc::initialize( const SmartPtrCDiagCollectInstancesDoc collectInstances, const SmartPtrCDiagSetValueCollectionDoc setValueCollection, const SmartPtrCDiagDeleteValueCollectionDoc deleteValueCollection) { if (! _isInitialized) { _collectInstances = collectInstances; _setValueCollection = setValueCollection; _deleteValueCollection = deleteValueCollection; _isInitialized = true; } } /// Accessor for the CollectInstances SmartPtrCDiagCollectInstancesDoc CDiagBatchDoc::getCollectInstances() const { return _collectInstances; } /// Accessor for the SetValueCollection SmartPtrCDiagSetValueCollectionDoc CDiagBatchDoc::getSetValueCollection() const { return _setValueCollection; } /// Accessor for the DeleteValueCollection SmartPtrCDiagDeleteValueCollectionDoc CDiagBatchDoc::getDeleteValueCollection() const { return _deleteValueCollection; } CDiagCollectInstancesDoc.cpp000066400000000000000000000015511321503522500414460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/DiagTypesDoc/CDiagCollectInstancesDoc.h" using namespace Caf; /// A simple container for objects of type DiagCollectInstances CDiagCollectInstancesDoc::CDiagCollectInstancesDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CDiagCollectInstancesDoc::~CDiagCollectInstancesDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDiagCollectInstancesDoc::initialize( const UUID jobId) { if (! _isInitialized) { _jobId = jobId; _isInitialized = true; } } /// Accessor for the JobId UUID CDiagCollectInstancesDoc::getJobId() const { return _jobId; } CDiagDeleteValueCollectionDoc.cpp000066400000000000000000000021031321503522500424160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueDoc.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.h" using namespace Caf; /// A simple container for objects of type DiagDeleteValueCollection CDiagDeleteValueCollectionDoc::CDiagDeleteValueCollectionDoc() : _isInitialized(false) {} CDiagDeleteValueCollectionDoc::~CDiagDeleteValueCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDiagDeleteValueCollectionDoc::initialize( const std::deque deleteValueCollection) { if (! _isInitialized) { _deleteValueCollection = deleteValueCollection; _isInitialized = true; } } /// Accessor for the DeleteValue std::deque CDiagDeleteValueCollectionDoc::getDeleteValueCollection() const { return _deleteValueCollection; } CDiagDeleteValueDoc.cpp000066400000000000000000000022151321503522500404060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueDoc.h" using namespace Caf; /// A simple container for objects of type DiagDeleteValue CDiagDeleteValueDoc::CDiagDeleteValueDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CDiagDeleteValueDoc::~CDiagDeleteValueDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDiagDeleteValueDoc::initialize( const UUID jobId, const std::string fileAlias, const std::string valueName) { if (! _isInitialized) { _jobId = jobId; _fileAlias = fileAlias; _valueName = valueName; _isInitialized = true; } } /// Accessor for the JobId UUID CDiagDeleteValueDoc::getJobId() const { return _jobId; } /// Accessor for the FileAlias std::string CDiagDeleteValueDoc::getFileAlias() const { return _fileAlias; } /// Accessor for the ValueName std::string CDiagDeleteValueDoc::getValueName() const { return _valueName; } CDiagSetValueCollectionDoc.cpp000066400000000000000000000020201321503522500417450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/DiagTypesDoc/CDiagSetValueDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueCollectionDoc.h" using namespace Caf; /// A simple container for objects of type DiagSetValueCollection CDiagSetValueCollectionDoc::CDiagSetValueCollectionDoc() : _isInitialized(false) {} CDiagSetValueCollectionDoc::~CDiagSetValueCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDiagSetValueCollectionDoc::initialize( const std::deque setValueCollection) { if (! _isInitialized) { _setValueCollection = setValueCollection; _isInitialized = true; } } /// Accessor for the SetValue std::deque CDiagSetValueCollectionDoc::getSetValueCollection() const { return _setValueCollection; } CDiagSetValueDoc.cpp000066400000000000000000000022301321503522500377340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueDoc.h" using namespace Caf; /// A simple container for objects of type DiagSetValue CDiagSetValueDoc::CDiagSetValueDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CDiagSetValueDoc::~CDiagSetValueDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDiagSetValueDoc::initialize( const UUID jobId, const std::string fileAlias, const SmartPtrCPropertyDoc value) { if (! _isInitialized) { _jobId = jobId; _fileAlias = fileAlias; _value = value; _isInitialized = true; } } /// Accessor for the JobId UUID CDiagSetValueDoc::getJobId() const { return _jobId; } /// Accessor for the FileAlias std::string CDiagSetValueDoc::getFileAlias() const { return _fileAlias; } /// Accessor for the Value SmartPtrCPropertyDoc CDiagSetValueDoc::getValue() const { return _value; } stdafx.h000066400000000000000000000005351321503522500356320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/DiagTypesDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define DIAGTYPESDOC_LINKAGE __declspec(dllexport) #else #define DIAGTYPESDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ MgmtRequestDoc/000077500000000000000000000000001321503522500345515ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCMgmtRequestDoc.cpp000066400000000000000000000036241321503522500402700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" using namespace Caf; /// A simple container for objects of type MgmtRequest CMgmtRequestDoc::CMgmtRequestDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CMgmtRequestDoc::~CMgmtRequestDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMgmtRequestDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCRequestHeaderDoc requestHeader, const SmartPtrCMgmtBatchDoc batch, const SmartPtrCAttachmentCollectionDoc attachmentCollection) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _requestHeader = requestHeader; _batch = batch; _attachmentCollection = attachmentCollection; _isInitialized = true; } } /// Accessor for the ClientId UUID CMgmtRequestDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CMgmtRequestDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CMgmtRequestDoc::getPmeId() const { return _pmeId; } /// Accessor for the RequestHeader SmartPtrCRequestHeaderDoc CMgmtRequestDoc::getRequestHeader() const { return _requestHeader; } /// Accessor for the Batch SmartPtrCMgmtBatchDoc CMgmtRequestDoc::getBatch() const { return _batch; } /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc CMgmtRequestDoc::getAttachmentCollection() const { return _attachmentCollection; } stdafx.h000066400000000000000000000005411321503522500362130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define MGMTREQUESTDOC_LINKAGE __declspec(dllexport) #else #define MGMTREQUESTDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ MgmtTypesDoc/000077500000000000000000000000001321503522500342255ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCMgmtBatchDoc.cpp000066400000000000000000000032141321503522500373300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectSchemaDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" using namespace Caf; /// A simple container for objects of type MgmtBatch CMgmtBatchDoc::CMgmtBatchDoc() : _isInitialized(false) {} CMgmtBatchDoc::~CMgmtBatchDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMgmtBatchDoc::initialize( const SmartPtrCMgmtCollectSchemaDoc collectSchema, const SmartPtrCMgmtCollectInstancesCollectionDoc collectInstancesCollection, const SmartPtrCMgmtInvokeOperationCollectionDoc invokeOperationCollection) { if (! _isInitialized) { _collectSchema = collectSchema; _collectInstancesCollection = collectInstancesCollection; _invokeOperationCollection = invokeOperationCollection; _isInitialized = true; } } /// Accessor for the CollectSchema SmartPtrCMgmtCollectSchemaDoc CMgmtBatchDoc::getCollectSchema() const { return _collectSchema; } /// Accessor for the CollectInstancesCollection SmartPtrCMgmtCollectInstancesCollectionDoc CMgmtBatchDoc::getCollectInstancesCollection() const { return _collectInstancesCollection; } /// Accessor for the InvokeOperationCollection SmartPtrCMgmtInvokeOperationCollectionDoc CMgmtBatchDoc::getInvokeOperationCollection() const { return _invokeOperationCollection; } CMgmtCollectInstancesCollectionDoc.cpp000066400000000000000000000022301321503522500435550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" using namespace Caf; /// A simple container for objects of type MgmtCollectInstancesCollection CMgmtCollectInstancesCollectionDoc::CMgmtCollectInstancesCollectionDoc() : _isInitialized(false) {} CMgmtCollectInstancesCollectionDoc::~CMgmtCollectInstancesCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMgmtCollectInstancesCollectionDoc::initialize( const std::deque collectInstancesCollection) { if (! _isInitialized) { _collectInstancesCollection = collectInstancesCollection; _isInitialized = true; } } /// Accessor for the CollectInstances std::deque CMgmtCollectInstancesCollectionDoc::getCollectInstancesCollection() const { return _collectInstancesCollection; } CMgmtCollectInstancesDoc.cpp000066400000000000000000000027151321503522500415510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" using namespace Caf; /// A simple container for objects of type MgmtCollectInstances CMgmtCollectInstancesDoc::CMgmtCollectInstancesDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CMgmtCollectInstancesDoc::~CMgmtCollectInstancesDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMgmtCollectInstancesDoc::initialize( const UUID jobId, const SmartPtrCClassSpecifierDoc classSpecifier, const SmartPtrCParameterCollectionDoc parameterCollection) { if (! _isInitialized) { _jobId = jobId; _classSpecifier = classSpecifier; _parameterCollection = parameterCollection; _isInitialized = true; } } /// Accessor for the JobId UUID CMgmtCollectInstancesDoc::getJobId() const { return _jobId; } /// Accessor for the ClassSpecifier SmartPtrCClassSpecifierDoc CMgmtCollectInstancesDoc::getClassSpecifier() const { return _classSpecifier; } /// Accessor for the ParameterCollection SmartPtrCParameterCollectionDoc CMgmtCollectInstancesDoc::getParameterCollection() const { return _parameterCollection; } CMgmtCollectSchemaDoc.cpp000066400000000000000000000015211321503522500410140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/MgmtTypesDoc/CMgmtCollectSchemaDoc.h" using namespace Caf; /// A simple container for objects of type MgmtCollectSchema CMgmtCollectSchemaDoc::CMgmtCollectSchemaDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CMgmtCollectSchemaDoc::~CMgmtCollectSchemaDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMgmtCollectSchemaDoc::initialize( const UUID jobId) { if (! _isInitialized) { _jobId = jobId; _isInitialized = true; } } /// Accessor for the JobId UUID CMgmtCollectSchemaDoc::getJobId() const { return _jobId; } CMgmtInvokeOperationCollectionDoc.cpp000066400000000000000000000022071321503522500434400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" using namespace Caf; /// A simple container for objects of type MgmtInvokeOperationCollection CMgmtInvokeOperationCollectionDoc::CMgmtInvokeOperationCollectionDoc() : _isInitialized(false) {} CMgmtInvokeOperationCollectionDoc::~CMgmtInvokeOperationCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMgmtInvokeOperationCollectionDoc::initialize( const std::deque invokeOperationCollection) { if (! _isInitialized) { _invokeOperationCollection = invokeOperationCollection; _isInitialized = true; } } /// Accessor for the InvokeOperation std::deque CMgmtInvokeOperationCollectionDoc::getInvokeOperationCollection() const { return _invokeOperationCollection; } CMgmtInvokeOperationDoc.cpp000066400000000000000000000025511321503522500414260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" using namespace Caf; /// A simple container for objects of type MgmtInvokeOperation CMgmtInvokeOperationDoc::CMgmtInvokeOperationDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CMgmtInvokeOperationDoc::~CMgmtInvokeOperationDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMgmtInvokeOperationDoc::initialize( const UUID jobId, const SmartPtrCClassSpecifierDoc classSpecifier, const SmartPtrCOperationDoc operation) { if (! _isInitialized) { _jobId = jobId; _classSpecifier = classSpecifier; _operation = operation; _isInitialized = true; } } /// Accessor for the JobId UUID CMgmtInvokeOperationDoc::getJobId() const { return _jobId; } /// Accessor for the ClassSpecifier SmartPtrCClassSpecifierDoc CMgmtInvokeOperationDoc::getClassSpecifier() const { return _classSpecifier; } /// Accessor for the Operation SmartPtrCOperationDoc CMgmtInvokeOperationDoc::getOperation() const { return _operation; } stdafx.h000066400000000000000000000005351321503522500356720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MgmtTypesDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define MGMTTYPESDOC_LINKAGE __declspec(dllexport) #else #define MGMTTYPESDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ MultiPmeMgmtRequestDoc/000077500000000000000000000000001321503522500362265ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCMultiPmeMgmtBatchCollectionDoc.cpp000066400000000000000000000021071321503522500450220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchCollectionDoc.h" using namespace Caf; /// A simple container for objects of type MultiPmeMgmtBatchCollection CMultiPmeMgmtBatchCollectionDoc::CMultiPmeMgmtBatchCollectionDoc() : _isInitialized(false) {} CMultiPmeMgmtBatchCollectionDoc::~CMultiPmeMgmtBatchCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMultiPmeMgmtBatchCollectionDoc::initialize( const std::deque multiPmeBatch) { if (! _isInitialized) { _multiPmeBatch = multiPmeBatch; _isInitialized = true; } } /// Accessor for the MultiPmeBatch std::deque CMultiPmeMgmtBatchCollectionDoc::getMultiPmeBatch() const { return _multiPmeBatch; } CMultiPmeMgmtBatchDoc.cpp000066400000000000000000000022651321503522500430130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CPmeIdCollectionDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchDoc.h" using namespace Caf; /// A simple container for objects of type MultiPmeMgmtBatch CMultiPmeMgmtBatchDoc::CMultiPmeMgmtBatchDoc() : _isInitialized(false) {} CMultiPmeMgmtBatchDoc::~CMultiPmeMgmtBatchDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMultiPmeMgmtBatchDoc::initialize( const SmartPtrCPmeIdCollectionDoc pmeIdCollection, const SmartPtrCMgmtBatchDoc batch) { if (! _isInitialized) { _pmeIdCollection = pmeIdCollection; _batch = batch; _isInitialized = true; } } /// Accessor for the PmeIdCollection SmartPtrCPmeIdCollectionDoc CMultiPmeMgmtBatchDoc::getPmeIdCollection() const { return _pmeIdCollection; } /// Accessor for the Batch SmartPtrCMgmtBatchDoc CMultiPmeMgmtBatchDoc::getBatch() const { return _batch; } CMultiPmeMgmtRequestDoc.cpp000066400000000000000000000033161321503522500434200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchCollectionDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtRequestDoc.h" using namespace Caf; /// A simple container for objects of type MultiPmeMgmtRequest CMultiPmeMgmtRequestDoc::CMultiPmeMgmtRequestDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CMultiPmeMgmtRequestDoc::~CMultiPmeMgmtRequestDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMultiPmeMgmtRequestDoc::initialize( const UUID clientId, const UUID requestId, const SmartPtrCRequestHeaderDoc requestHeader, const SmartPtrCMultiPmeMgmtBatchCollectionDoc multiPmeBatchCollection) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _requestHeader = requestHeader; _multiPmeBatchCollection = multiPmeBatchCollection; _isInitialized = true; } } /// Accessor for the ClientId UUID CMultiPmeMgmtRequestDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CMultiPmeMgmtRequestDoc::getRequestId() const { return _requestId; } /// Accessor for the RequestHeader SmartPtrCRequestHeaderDoc CMultiPmeMgmtRequestDoc::getRequestHeader() const { return _requestHeader; } /// Accessor for the MultiPmeBatchCollection SmartPtrCMultiPmeMgmtBatchCollectionDoc CMultiPmeMgmtRequestDoc::getMultiPmeBatchCollection() const { return _multiPmeBatchCollection; } CPmeIdCollectionDoc.cpp000066400000000000000000000016061321503522500425000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/MultiPmeMgmtRequestDoc/CPmeIdCollectionDoc.h" using namespace Caf; /// A simple container for objects of type PmeIdCollection CPmeIdCollectionDoc::CPmeIdCollectionDoc() : _isInitialized(false) {} CPmeIdCollectionDoc::~CPmeIdCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPmeIdCollectionDoc::initialize( const std::deque pmeIdCollection) { if (! _isInitialized) { _pmeIdCollection = pmeIdCollection; _isInitialized = true; } } /// Accessor for the PmeId std::deque CPmeIdCollectionDoc::getPmeIdCollection() const { return _pmeIdCollection; } stdafx.h000066400000000000000000000005611321503522500376720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define MULTIPMEMGMTREQUESTDOC_LINKAGE __declspec(dllexport) #else #define MULTIPMEMGMTREQUESTDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ PayloadEnvelopeDoc/000077500000000000000000000000001321503522500353635ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCPayloadEnvelopeDoc.cpp000066400000000000000000000051451321503522500417140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PayloadEnvelopeDoc/* * Author: bwilliams * Created: July 3, 2015 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" using namespace Caf; /// A simple container for objects of type PayloadEnvelope CPayloadEnvelopeDoc::CPayloadEnvelopeDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CPayloadEnvelopeDoc::~CPayloadEnvelopeDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPayloadEnvelopeDoc::initialize( const UUID& clientId, const UUID& requestId, const std::string& pmeId, const std::string& payloadType, const std::string& payloadVersion, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const SmartPtrCProtocolCollectionDoc& protocolCollection, const SmartPtrCPropertyCollectionDoc& headerCollection, const std::string version) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _payloadType = payloadType; _payloadVersion = payloadVersion; _attachmentCollection = attachmentCollection; _protocolCollection = protocolCollection; _headerCollection = headerCollection; _version = version; _isInitialized = true; } } /// Accessor for the ClientId UUID CPayloadEnvelopeDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CPayloadEnvelopeDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CPayloadEnvelopeDoc::getPmeId() const { return _pmeId; } /// Accessor for the PayloadType std::string CPayloadEnvelopeDoc::getPayloadType() const { return _payloadType; } /// Accessor for the PayloadVersion std::string CPayloadEnvelopeDoc::getPayloadVersion() const { return _payloadVersion; } /// Accessor for the Protocol Collection SmartPtrCProtocolCollectionDoc CPayloadEnvelopeDoc::getProtocolCollection() const { return _protocolCollection; } /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc CPayloadEnvelopeDoc::getAttachmentCollection() const { return _attachmentCollection; } /// Accessor for the Headers SmartPtrCPropertyCollectionDoc CPayloadEnvelopeDoc::getHeaderCollection() const { return _headerCollection; } /// Accessor for the version std::string CPayloadEnvelopeDoc::getVersion() const { return _version; } stdafx.h000066400000000000000000000005511321503522500370260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PayloadEnvelopeDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PAYLOADENVELOPEDOC_LINKAGE __declspec(dllexport) #else #define PAYLOADENVELOPEDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ PersistenceDoc/000077500000000000000000000000001321503522500345605ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCCertCollectionDoc.cpp000066400000000000000000000015461321503522500407340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" using namespace Caf; /// A simple container for objects of type CertCollection CCertCollectionDoc::CCertCollectionDoc() : _isInitialized(false) {} CCertCollectionDoc::~CCertCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CCertCollectionDoc::initialize( const std::deque certCollection) { if (! _isInitialized) { _certCollection = certCollection; _isInitialized = true; } } /// Accessor for the Cert std::deque CCertCollectionDoc::getCert() const { return _certCollection; } CCertPathCollectionDoc.cpp000066400000000000000000000016321321503522500415450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" using namespace Caf; /// A simple container for objects of type CertPathCollection CCertPathCollectionDoc::CCertPathCollectionDoc() : _isInitialized(false) {} CCertPathCollectionDoc::~CCertPathCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CCertPathCollectionDoc::initialize( const std::deque certPathCollection) { if (! _isInitialized) { _certPathCollection = certPathCollection; _isInitialized = true; } } /// Accessor for the Cert std::deque CCertPathCollectionDoc::getCertPath() const { return _certPathCollection; } CLocalSecurityDoc.cpp000066400000000000000000000027141321503522500406030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" using namespace Caf; /// A simple container for objects of type CLocalSecurityDoc CLocalSecurityDoc::CLocalSecurityDoc() : _isInitialized(false) {} CLocalSecurityDoc::~CLocalSecurityDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CLocalSecurityDoc::initialize( const std::string& localId, const std::string& privateKey, const std::string& cert, const std::string& privateKeyPath, const std::string& certPath) { if (! _isInitialized) { _localId = localId; _privateKey = privateKey; _cert = cert; _privateKeyPath = privateKeyPath; _certPath = certPath; _isInitialized = true; } } /// Accessor for the LocalId std::string CLocalSecurityDoc::getLocalId() const { return _localId; } /// Accessor for the PrivateKey std::string CLocalSecurityDoc::getPrivateKey() const { return _privateKey; } /// Accessor for the Cert std::string CLocalSecurityDoc::getCert() const { return _cert; } /// Accessor for the PrivateKeyPath std::string CLocalSecurityDoc::getPrivateKeyPath() const { return _privateKeyPath; } /// Accessor for the CertPath std::string CLocalSecurityDoc::getCertPath() const { return _certPath; } CPersistenceDoc.cpp000066400000000000000000000034441321503522500403060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" using namespace Caf; /// A simple container for objects of type PersistenceEnvelope CPersistenceDoc::CPersistenceDoc() : _isInitialized(false) {} CPersistenceDoc::~CPersistenceDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPersistenceDoc::initialize( const SmartPtrCLocalSecurityDoc& localSecurity, const SmartPtrCRemoteSecurityCollectionDoc& remoteSecurityCollection, const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollection, const std::string version) { if (! _isInitialized) { _localSecurity = localSecurity; _remoteSecurityCollection = remoteSecurityCollection; _persistenceProtocolCollection = persistenceProtocolCollection; _version = version; _isInitialized = true; } } /// Accessor for the LocalSecurity SmartPtrCLocalSecurityDoc CPersistenceDoc::getLocalSecurity() const { return _localSecurity; } /// Accessor for the Protocol Collection SmartPtrCRemoteSecurityCollectionDoc CPersistenceDoc::getRemoteSecurityCollection() const { return _remoteSecurityCollection; } /// Accessor for the PersistenceProtocol SmartPtrCPersistenceProtocolCollectionDoc CPersistenceDoc::getPersistenceProtocolCollection() const { return _persistenceProtocolCollection; } /// Accessor for the version std::string CPersistenceDoc::getVersion() const { return _version; } CPersistenceProtocolCollectionDoc.cpp000066400000000000000000000021611321503522500440370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" using namespace Caf; /// A simple container for objects of type PersistenceProtocolCollection CPersistenceProtocolCollectionDoc::CPersistenceProtocolCollectionDoc() : _isInitialized(false) {} CPersistenceProtocolCollectionDoc::~CPersistenceProtocolCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPersistenceProtocolCollectionDoc::initialize( const std::deque persistenceProtocol) { if (! _isInitialized) { _persistenceProtocol = persistenceProtocol; _isInitialized = true; } } /// Accessor for the PersistenceProtocol std::deque CPersistenceProtocolCollectionDoc::getPersistenceProtocol() const { return _persistenceProtocol; } CPersistenceProtocolDoc.cpp000066400000000000000000000061371321503522500420320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" using namespace Caf; /// A simple container for objects of type CPersistenceProtocolDoc CPersistenceProtocolDoc::CPersistenceProtocolDoc() : _isInitialized(false) {} CPersistenceProtocolDoc::~CPersistenceProtocolDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPersistenceProtocolDoc::initialize( const std::string& protocolName, const std::string& uri, const std::string& uriAmqp, const std::string& uriTunnel, const std::string& tlsCert, const std::string& tlsProtocol, const Cdeqstr& tlsCipherCollection, const SmartPtrCCertCollectionDoc& tlsCertCollection, const std::string& uriAmqpPath, const std::string& uriTunnelPath, const std::string& tlsCertPath, const SmartPtrCCertPathCollectionDoc& tlsCertPathCollection) { if (! _isInitialized) { _protocolName = protocolName; _uri = uri; _uriAmqp = uriAmqp; _uriTunnel = uriTunnel; _tlsCert = tlsCert; _tlsProtocol = tlsProtocol; _tlsCipherCollection = tlsCipherCollection; _tlsCertCollection = tlsCertCollection; _uriAmqpPath = uriAmqpPath; _uriTunnelPath = uriTunnelPath; _tlsCertPath = tlsCertPath; _tlsCertPathCollection = tlsCertPathCollection; _isInitialized = true; } } /// Accessor for the ProtocolName std::string CPersistenceProtocolDoc::getProtocolName() const { return _protocolName; } /// Accessor for the Uri std::string CPersistenceProtocolDoc::getUri() const { return _uri; } /// Accessor for the UriAmqp std::string CPersistenceProtocolDoc::getUriAmqp() const { return _uriAmqp; } /// Accessor for the UriTunnel std::string CPersistenceProtocolDoc::getUriTunnel() const { return _uriTunnel; } /// Accessor for the TlsCert std::string CPersistenceProtocolDoc::getTlsCert() const { return _tlsCert; } /// Accessor for the TlsProtocol std::string CPersistenceProtocolDoc::getTlsProtocol() const { return _tlsProtocol; } /// Accessor for the tlsCipherCollection Cdeqstr CPersistenceProtocolDoc::getTlsCipherCollection() const { return _tlsCipherCollection; } /// Accessor for the TlsCertCollection SmartPtrCCertCollectionDoc CPersistenceProtocolDoc::getTlsCertCollection() const { return _tlsCertCollection; } /// Accessor for the UriAmqpPath std::string CPersistenceProtocolDoc::getUriAmqpPath() const { return _uriAmqpPath; } /// Accessor for the UriTunnelPath std::string CPersistenceProtocolDoc::getUriTunnelPath() const { return _uriTunnelPath; } /// Accessor for the TlsCertPath std::string CPersistenceProtocolDoc::getTlsCertPath() const { return _tlsCertPath; } /// Accessor for the TlsCertPathCollection SmartPtrCCertPathCollectionDoc CPersistenceProtocolDoc::getTlsCertPathCollection() const { return _tlsCertPathCollection; } Cdeqstr _tlsCipherCollection; CRemoteSecurityCollectionDoc.cpp000066400000000000000000000020341321503522500430130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" using namespace Caf; /// A simple container for objects of type RemoteSecurityCollection CRemoteSecurityCollectionDoc::CRemoteSecurityCollectionDoc() : _isInitialized(false) {} CRemoteSecurityCollectionDoc::~CRemoteSecurityCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CRemoteSecurityCollectionDoc::initialize( const std::deque remoteSecurity) { if (! _isInitialized) { _remoteSecurity = remoteSecurity; _isInitialized = true; } } /// Accessor for the RemoteSecurity std::deque CRemoteSecurityCollectionDoc::getRemoteSecurity() const { return _remoteSecurity; } CRemoteSecurityDoc.cpp000066400000000000000000000041541321503522500410040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" using namespace Caf; /// A simple container for objects of type CRemoteSecurityDoc CRemoteSecurityDoc::CRemoteSecurityDoc() : _isInitialized(false) {} CRemoteSecurityDoc::~CRemoteSecurityDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CRemoteSecurityDoc::initialize( const std::string& remoteId, const std::string& protocolName, const std::string& cmsCert, const std::string& cmsCipherName, const SmartPtrCCertCollectionDoc& cmsCertCollection, const std::string& cmsCertPath, const SmartPtrCCertPathCollectionDoc& cmsCertPathCollection) { if (! _isInitialized) { _remoteId = remoteId; _protocolName = protocolName; _cmsCert = cmsCert; _cmsCipherName = cmsCipherName; _cmsCertCollection = cmsCertCollection; _cmsCertPath = cmsCertPath; _cmsCertPathCollection = cmsCertPathCollection; _isInitialized = true; } } /// Accessor for the RemoteId std::string CRemoteSecurityDoc::getRemoteId() const { return _remoteId; } /// Accessor for the ProtocolName std::string CRemoteSecurityDoc::getProtocolName() const { return _protocolName; } /// Accessor for the cmsCert std::string CRemoteSecurityDoc::getCmsCert() const { return _cmsCert; } /// Accessor for the CmsCipher std::string CRemoteSecurityDoc::getCmsCipherName() const { return _cmsCipherName; } /// Accessor for the CertCollection SmartPtrCCertCollectionDoc CRemoteSecurityDoc::getCmsCertCollection() const { return _cmsCertCollection; } /// Accessor for the cmsCertPath std::string CRemoteSecurityDoc::getCmsCertPath() const { return _cmsCertPath; } /// Accessor for the CertPathCollection SmartPtrCCertPathCollectionDoc CRemoteSecurityDoc::getCmsCertPathCollection() const { return _cmsCertPathCollection; } stdafx.h000066400000000000000000000005411321503522500362220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/PersistenceDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PERSISTENCEDOC_LINKAGE __declspec(dllexport) #else #define PERSISTENCEDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ ProviderInfraDoc/000077500000000000000000000000001321503522500350465ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCClassCollectionDoc.cpp000066400000000000000000000020231321503522500413610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderInfraDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/ProviderInfraDoc/CClassCollectionDoc.h" using namespace Caf; /// A simple container for objects of type ClassCollection CClassCollectionDoc::CClassCollectionDoc() : _isInitialized(false) {} CClassCollectionDoc::~CClassCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CClassCollectionDoc::initialize( const std::deque fullyQualifiedClass) { if (! _isInitialized) { _fullyQualifiedClass = fullyQualifiedClass; _isInitialized = true; } } /// Accessor for the FullyQualifiedClass std::deque CClassCollectionDoc::getFullyQualifiedClass() const { return _fullyQualifiedClass; } CProviderRegDoc.cpp000066400000000000000000000034101321503522500405310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderInfraDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" using namespace Caf; /// A simple container for objects of type ProviderReg CProviderRegDoc::CProviderRegDoc() : _staleSec(0), _isSchemaVisible(false), _isInitialized(false) {} CProviderRegDoc::~CProviderRegDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderRegDoc::initialize( const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const int32 staleSec, const bool isSchemaVisible, const std::string invokerRelPath) { if (! _isInitialized) { _providerNamespace = providerNamespace; _providerName = providerName; _providerVersion = providerVersion; _staleSec = staleSec; _isSchemaVisible = isSchemaVisible; _invokerRelPath = invokerRelPath; _isInitialized = true; } } /// Accessor for the ProviderNamespace std::string CProviderRegDoc::getProviderNamespace() const { return _providerNamespace; } /// Accessor for the ProviderName std::string CProviderRegDoc::getProviderName() const { return _providerName; } /// Accessor for the ProviderVersion std::string CProviderRegDoc::getProviderVersion() const { return _providerVersion; } /// Accessor for the StaleSec int32 CProviderRegDoc::getStaleSec() const { return _staleSec; } /// Accessor for the IsSchemaVisible bool CProviderRegDoc::getIsSchemaVisible() const { return _isSchemaVisible; } /// Accessor for the InvokerRelPath std::string CProviderRegDoc::getInvokerRelPath() const { return _invokerRelPath; } CSchemaSummaryDoc.cpp000066400000000000000000000032731321503522500410660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderInfraDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ProviderInfraDoc/CClassCollectionDoc.h" #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" using namespace Caf; /// A simple container for objects of type SchemaSummary CSchemaSummaryDoc::CSchemaSummaryDoc() : _isInitialized(false) {} CSchemaSummaryDoc::~CSchemaSummaryDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CSchemaSummaryDoc::initialize( const std::string providerNamespace, const std::string providerName, const std::string providerVersion, const SmartPtrCClassCollectionDoc classCollection, const std::string invokerPath) { if (! _isInitialized) { _providerNamespace = providerNamespace; _providerName = providerName; _providerVersion = providerVersion; _classCollection = classCollection; _invokerPath = invokerPath; _isInitialized = true; } } /// Accessor for the ProviderNamespace std::string CSchemaSummaryDoc::getProviderNamespace() const { return _providerNamespace; } /// Accessor for the ProviderName std::string CSchemaSummaryDoc::getProviderName() const { return _providerName; } /// Accessor for the ProviderVersion std::string CSchemaSummaryDoc::getProviderVersion() const { return _providerVersion; } /// Accessor for the ClassCollection SmartPtrCClassCollectionDoc CSchemaSummaryDoc::getClassCollection() const { return _classCollection; } /// Accessor for the InvokerPath std::string CSchemaSummaryDoc::getInvokerPath() const { return _invokerPath; } stdafx.h000066400000000000000000000005451321503522500365140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderInfraDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PROVIDERINFRADOC_LINKAGE __declspec(dllexport) #else #define PROVIDERINFRADOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ ProviderRequestDoc/000077500000000000000000000000001321503522500354375ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCProviderBatchDoc.cpp000066400000000000000000000031561321503522500414350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderBatchDoc.h" using namespace Caf; /// A simple container for objects of type ProviderBatch CProviderBatchDoc::CProviderBatchDoc() : _isInitialized(false) {} CProviderBatchDoc::~CProviderBatchDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderBatchDoc::initialize( const std::string outputDir, const SmartPtrCProviderCollectInstancesCollectionDoc collectInstancesCollection, const SmartPtrCProviderInvokeOperationCollectionDoc invokeOperationCollection) { if (! _isInitialized) { _outputDir = outputDir; _collectInstancesCollection = collectInstancesCollection; _invokeOperationCollection = invokeOperationCollection; _isInitialized = true; } } /// Accessor for the OutputDir std::string CProviderBatchDoc::getOutputDir() const { return _outputDir; } /// Accessor for the CollectInstancesCollection SmartPtrCProviderCollectInstancesCollectionDoc CProviderBatchDoc::getCollectInstancesCollection() const { return _collectInstancesCollection; } /// Accessor for the InvokeOperationCollection SmartPtrCProviderInvokeOperationCollectionDoc CProviderBatchDoc::getInvokeOperationCollection() const { return _invokeOperationCollection; } CProviderCollectInstancesCollectionDoc.cpp000066400000000000000000000022361321503522500456630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.h" using namespace Caf; /// A simple container for objects of type ProviderCollectInstancesCollection CProviderCollectInstancesCollectionDoc::CProviderCollectInstancesCollectionDoc() : _isInitialized(false) {} CProviderCollectInstancesCollectionDoc::~CProviderCollectInstancesCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderCollectInstancesCollectionDoc::initialize( const std::deque collectInstances) { if (! _isInitialized) { _collectInstances = collectInstances; _isInitialized = true; } } /// Accessor for the CollectInstances std::deque CProviderCollectInstancesCollectionDoc::getCollectInstances() const { return _collectInstances; } CProviderCollectInstancesDoc.cpp000066400000000000000000000037101321503522500436450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" using namespace Caf; /// A simple container for objects of type ProviderCollectInstances CProviderCollectInstancesDoc::CProviderCollectInstancesDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CProviderCollectInstancesDoc::~CProviderCollectInstancesDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderCollectInstancesDoc::initialize( const std::string classNamespace, const std::string className, const std::string classVersion, const UUID jobId, const std::string outputDir, const SmartPtrCParameterCollectionDoc parameterCollection) { if (! _isInitialized) { _classNamespace = classNamespace; _className = className; _classVersion = classVersion; _jobId = jobId; _outputDir = outputDir; _parameterCollection = parameterCollection; _isInitialized = true; } } /// Accessor for the ClassNamespace std::string CProviderCollectInstancesDoc::getClassNamespace() const { return _classNamespace; } /// Accessor for the ClassName std::string CProviderCollectInstancesDoc::getClassName() const { return _className; } /// Accessor for the ClassVersion std::string CProviderCollectInstancesDoc::getClassVersion() const { return _classVersion; } /// Accessor for the JobId UUID CProviderCollectInstancesDoc::getJobId() const { return _jobId; } /// Accessor for the OutputDir std::string CProviderCollectInstancesDoc::getOutputDir() const { return _outputDir; } /// Accessor for the ParameterCollection SmartPtrCParameterCollectionDoc CProviderCollectInstancesDoc::getParameterCollection() const { return _parameterCollection; } CProviderCollectSchemaRequestDoc.cpp000066400000000000000000000036721321503522500444760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" using namespace Caf; /// A simple container for objects of type ProviderCollectSchemaRequest CProviderCollectSchemaRequestDoc::CProviderCollectSchemaRequestDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CProviderCollectSchemaRequestDoc::~CProviderCollectSchemaRequestDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderCollectSchemaRequestDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const UUID jobId, const std::string outputDir, const SmartPtrCProviderRequestHeaderDoc requestHeader) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _jobId = jobId; _outputDir = outputDir; _requestHeader = requestHeader; _isInitialized = true; } } /// Accessor for the ClientId UUID CProviderCollectSchemaRequestDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CProviderCollectSchemaRequestDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CProviderCollectSchemaRequestDoc::getPmeId() const { return _pmeId; } /// Accessor for the JobId UUID CProviderCollectSchemaRequestDoc::getJobId() const { return _jobId; } /// Accessor for the OutputDir std::string CProviderCollectSchemaRequestDoc::getOutputDir() const { return _outputDir; } /// Accessor for the RequestHeader SmartPtrCProviderRequestHeaderDoc CProviderCollectSchemaRequestDoc::getRequestHeader() const { return _requestHeader; } CProviderInvokeOperationCollectionDoc.cpp000066400000000000000000000022151321503522500455370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.h" using namespace Caf; /// A simple container for objects of type ProviderInvokeOperationCollection CProviderInvokeOperationCollectionDoc::CProviderInvokeOperationCollectionDoc() : _isInitialized(false) {} CProviderInvokeOperationCollectionDoc::~CProviderInvokeOperationCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderInvokeOperationCollectionDoc::initialize( const std::deque invokeOperation) { if (! _isInitialized) { _invokeOperation = invokeOperation; _isInitialized = true; } } /// Accessor for the InvokeOperation std::deque CProviderInvokeOperationCollectionDoc::getInvokeOperation() const { return _invokeOperation; } CProviderInvokeOperationDoc.cpp000066400000000000000000000035411321503522500435260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" using namespace Caf; /// A simple container for objects of type ProviderInvokeOperation CProviderInvokeOperationDoc::CProviderInvokeOperationDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CProviderInvokeOperationDoc::~CProviderInvokeOperationDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderInvokeOperationDoc::initialize( const std::string classNamespace, const std::string className, const std::string classVersion, const UUID jobId, const std::string outputDir, const SmartPtrCOperationDoc operation) { if (! _isInitialized) { _classNamespace = classNamespace; _className = className; _classVersion = classVersion; _jobId = jobId; _outputDir = outputDir; _operation = operation; _isInitialized = true; } } /// Accessor for the ClassNamespace std::string CProviderInvokeOperationDoc::getClassNamespace() const { return _classNamespace; } /// Accessor for the ClassName std::string CProviderInvokeOperationDoc::getClassName() const { return _className; } /// Accessor for the ClassVersion std::string CProviderInvokeOperationDoc::getClassVersion() const { return _classVersion; } /// Accessor for the JobId UUID CProviderInvokeOperationDoc::getJobId() const { return _jobId; } /// Accessor for the OutputDir std::string CProviderInvokeOperationDoc::getOutputDir() const { return _outputDir; } /// Accessor for the Operation SmartPtrCOperationDoc CProviderInvokeOperationDoc::getOperation() const { return _operation; } CProviderRequestConfigDoc.cpp000066400000000000000000000024331321503522500431670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestConfigDoc.h" using namespace Caf; /// A simple container for objects of type ProviderRequestConfig CProviderRequestConfigDoc::CProviderRequestConfigDoc() : _isInitialized(false) {} CProviderRequestConfigDoc::~CProviderRequestConfigDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderRequestConfigDoc::initialize( const std::string responseFormatType, const SmartPtrCLoggingLevelCollectionDoc loggingLevelCollection) { if (! _isInitialized) { _responseFormatType = responseFormatType; _loggingLevelCollection = loggingLevelCollection; _isInitialized = true; } } /// Accessor for the ResponseFormatType std::string CProviderRequestConfigDoc::getResponseFormatType() const { return _responseFormatType; } /// Accessor for the LoggingLevelCollection SmartPtrCLoggingLevelCollectionDoc CProviderRequestConfigDoc::getLoggingLevelCollection() const { return _loggingLevelCollection; } CProviderRequestDoc.cpp000066400000000000000000000037711321503522500420470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderBatchDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" using namespace Caf; /// A simple container for objects of type ProviderRequest CProviderRequestDoc::CProviderRequestDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CProviderRequestDoc::~CProviderRequestDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderRequestDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCProviderRequestHeaderDoc requestHeader, const SmartPtrCProviderBatchDoc batch, const SmartPtrCAttachmentCollectionDoc attachmentCollection) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _requestHeader = requestHeader; _batch = batch; _attachmentCollection = attachmentCollection; _isInitialized = true; } } /// Accessor for the ClientId UUID CProviderRequestDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CProviderRequestDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CProviderRequestDoc::getPmeId() const { return _pmeId; } /// Accessor for the RequestHeader SmartPtrCProviderRequestHeaderDoc CProviderRequestDoc::getRequestHeader() const { return _requestHeader; } /// Accessor for the Batch SmartPtrCProviderBatchDoc CProviderRequestDoc::getBatch() const { return _batch; } /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc CProviderRequestDoc::getAttachmentCollection() const { return _attachmentCollection; } CProviderRequestHeaderDoc.cpp000066400000000000000000000024611321503522500431530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestConfigDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" using namespace Caf; /// A simple container for objects of type ProviderRequestHeader CProviderRequestHeaderDoc::CProviderRequestHeaderDoc() : _isInitialized(false) {} CProviderRequestHeaderDoc::~CProviderRequestHeaderDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderRequestHeaderDoc::initialize( const SmartPtrCProviderRequestConfigDoc requestConfig, const SmartPtrCPropertyCollectionDoc echoPropertyBag) { if (! _isInitialized) { _requestConfig = requestConfig; _echoPropertyBag = echoPropertyBag; _isInitialized = true; } } /// Accessor for the RequestConfig SmartPtrCProviderRequestConfigDoc CProviderRequestHeaderDoc::getRequestConfig() const { return _requestConfig; } /// Accessor for the EchoPropertyBag SmartPtrCPropertyCollectionDoc CProviderRequestHeaderDoc::getEchoPropertyBag() const { return _echoPropertyBag; } stdafx.h000066400000000000000000000005511321503522500371020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderRequestDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PROVIDERREQUESTDOC_LINKAGE __declspec(dllexport) #else #define PROVIDERREQUESTDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ ProviderResultsDoc/000077500000000000000000000000001321503522500354505ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCCdifDoc.cpp000066400000000000000000000027071321503522500375600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderResultsDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ProviderResultsDoc/CDefinitionObjectCollectionDoc.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/ProviderResultsDoc/CCdifDoc.h" using namespace Caf; /// A simple container for objects of type Cdif CCdifDoc::CCdifDoc() : _isInitialized(false) {} CCdifDoc::~CCdifDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CCdifDoc::initialize( const SmartPtrCRequestIdentifierDoc requestIdentifier, const SmartPtrCDefinitionObjectCollectionDoc definitionObjectCollection, const SmartPtrCSchemaDoc schema) { if (! _isInitialized) { _requestIdentifier = requestIdentifier; _definitionObjectCollection = definitionObjectCollection; _schema = schema; _isInitialized = true; } } /// Accessor for the RequestIdentifier SmartPtrCRequestIdentifierDoc CCdifDoc::getRequestIdentifier() const { return _requestIdentifier; } /// Accessor for the DefinitionObjectCollection SmartPtrCDefinitionObjectCollectionDoc CCdifDoc::getDefinitionObjectCollection() const { return _definitionObjectCollection; } /// Accessor for the Schema SmartPtrCSchemaDoc CCdifDoc::getSchema() const { return _schema; } CDefinitionObjectCollectionDoc.cpp000066400000000000000000000016761321503522500441520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderResultsDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ProviderResultsDoc/CDefinitionObjectCollectionDoc.h" using namespace Caf; /// Set of elements containing data returned as a result of a provider collection or action CDefinitionObjectCollectionDoc::CDefinitionObjectCollectionDoc() : _isInitialized(false) {} CDefinitionObjectCollectionDoc::~CDefinitionObjectCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDefinitionObjectCollectionDoc::initialize( const std::deque value) { if (! _isInitialized) { _value = value; _isInitialized = true; } } /// Accessor for the Value std::deque CDefinitionObjectCollectionDoc::getValue() const { return _value; } CRequestIdentifierDoc.cpp000066400000000000000000000036061321503522500423450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderResultsDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" using namespace Caf; /// Fields that allow client to determine which request resulted in this response document CRequestIdentifierDoc::CRequestIdentifierDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _jobId(CAFCOMMON_GUID_NULL), _sessionId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CRequestIdentifierDoc::~CRequestIdentifierDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CRequestIdentifierDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const UUID jobId, const SmartPtrCActionClassDoc actionClass, const UUID sessionId) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _jobId = jobId; _actionClass = actionClass; _sessionId = sessionId; _isInitialized = true; } } /// Accessor for the ClientId UUID CRequestIdentifierDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CRequestIdentifierDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CRequestIdentifierDoc::getPmeId() const { return _pmeId; } /// Identifier of the specific job within the request UUID CRequestIdentifierDoc::getJobId() const { return _jobId; } /// Accessor for the ActionClass SmartPtrCActionClassDoc CRequestIdentifierDoc::getActionClass() const { return _actionClass; } /// Client-configurable identifier that is opaque (not used) by the Common Agent Framework UUID CRequestIdentifierDoc::getSessionId() const { return _sessionId; } CSchemaDoc.cpp000066400000000000000000000040461321503522500401110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderResultsDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CLogicalRelationshipDoc.h" #include "Doc/SchemaTypesDoc/CPhysicalRelationshipDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" using namespace Caf; /// Set of elements describing the objects that can be generated by the provider CSchemaDoc::CSchemaDoc() : _isInitialized(false) {} CSchemaDoc::~CSchemaDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CSchemaDoc::initialize( const std::deque dataClassCollection, const std::deque actionClassCollection, const std::deque logicalRelationshipCollection, const std::deque physicalRelationshipCollection) { if (! _isInitialized) { _dataClassCollection = dataClassCollection; _actionClassCollection = actionClassCollection; _logicalRelationshipCollection = logicalRelationshipCollection; _physicalRelationshipCollection = physicalRelationshipCollection; _isInitialized = true; } } /// Accessor for the DataClassCollection std::deque CSchemaDoc::getDataClassCollection() const { return _dataClassCollection; } /// Accessor for the ActionClassCollection std::deque CSchemaDoc::getActionClassCollection() const { return _actionClassCollection; } /// Accessor for the LogicalRelationshipCollection std::deque CSchemaDoc::getLogicalRelationshipCollection() const { return _logicalRelationshipCollection; } /// Accessor for the PhysicalRelationshipCollection std::deque CSchemaDoc::getPhysicalRelationshipCollection() const { return _physicalRelationshipCollection; } stdafx.h000066400000000000000000000005511321503522500371130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ProviderResultsDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PROVIDERRESULTSDOC_LINKAGE __declspec(dllexport) #else #define PROVIDERRESULTSDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ ResponseDoc/000077500000000000000000000000001321503522500340725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCErrorResponseDoc.cpp000066400000000000000000000031211321503522500401340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Doc/ResponseDoc/CErrorResponseDoc.h" using namespace Caf; /// A simple container for objects of type ErrorResponse CErrorResponseDoc::CErrorResponseDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CErrorResponseDoc::~CErrorResponseDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CErrorResponseDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCResponseHeaderDoc responseHeader, const std::string errorMessage) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _responseHeader = responseHeader; _errorMessage = errorMessage; _isInitialized = true; } } /// Accessor for the ClientId UUID CErrorResponseDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CErrorResponseDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CErrorResponseDoc::getPmeId() const { return _pmeId; } /// Accessor for the Response Header SmartPtrCResponseHeaderDoc CErrorResponseDoc::getResponseHeader() const { return _responseHeader; } /// Accessor for the ErrorMessage std::string CErrorResponseDoc::getErrorMessage() const { return _errorMessage; } CEventKeyCollectionDoc.cpp000066400000000000000000000016601321503522500411000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ResponseDoc/CEventKeyDoc.h" #include "Doc/ResponseDoc/CEventKeyCollectionDoc.h" using namespace Caf; /// A simple container for objects of type EventKeyCollection CEventKeyCollectionDoc::CEventKeyCollectionDoc() : _isInitialized(false) {} CEventKeyCollectionDoc::~CEventKeyCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CEventKeyCollectionDoc::initialize( const std::deque eventKey) { if (! _isInitialized) { _eventKey = eventKey; _isInitialized = true; } } /// Accessor for the EventKey std::deque CEventKeyCollectionDoc::getEventKey() const { return _eventKey; } CEventKeyDoc.cpp000066400000000000000000000015721321503522500370660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ResponseDoc/CEventKeyDoc.h" using namespace Caf; /// A simple container for objects of type EventKey CEventKeyDoc::CEventKeyDoc() : _isInitialized(false) {} CEventKeyDoc::~CEventKeyDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CEventKeyDoc::initialize( const std::string name, const std::string value) { if (! _isInitialized) { _name = name; _value = value; _isInitialized = true; } } /// Accessor for the Name std::string CEventKeyDoc::getName() const { return _name; } /// Accessor for the Value std::string CEventKeyDoc::getValue() const { return _value; } CEventManifestDoc.cpp000066400000000000000000000032701321503522500401010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/ResponseDoc/CEventManifestDoc.h" using namespace Caf; /// A simple container for objects of type EventManifest CEventManifestDoc::CEventManifestDoc() : _isInitialized(false) {} CEventManifestDoc::~CEventManifestDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CEventManifestDoc::initialize( const std::string classNamespace, const std::string className, const std::string classVersion, const std::string operationName, const SmartPtrCAttachmentCollectionDoc attachmentCollection) { if (! _isInitialized) { _classNamespace = classNamespace; _className = className; _classVersion = classVersion; _operationName = operationName; _attachmentCollection = attachmentCollection; _isInitialized = true; } } /// Accessor for the ClassNamespace std::string CEventManifestDoc::getClassNamespace() const { return _classNamespace; } /// Accessor for the ClassName std::string CEventManifestDoc::getClassName() const { return _className; } /// Accessor for the ClassVersion std::string CEventManifestDoc::getClassVersion() const { return _classVersion; } /// Accessor for the OperationName std::string CEventManifestDoc::getOperationName() const { return _operationName; } /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc CEventManifestDoc::getAttachmentCollection() const { return _attachmentCollection; } CManifestCollectionDoc.cpp000066400000000000000000000016601321503522500411140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Doc/ResponseDoc/CManifestCollectionDoc.h" using namespace Caf; /// A simple container for objects of type ManifestCollection CManifestCollectionDoc::CManifestCollectionDoc() : _isInitialized(false) {} CManifestCollectionDoc::~CManifestCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CManifestCollectionDoc::initialize( const std::deque manifest) { if (! _isInitialized) { _manifest = manifest; _isInitialized = true; } } /// Accessor for the Manifest std::deque CManifestCollectionDoc::getManifest() const { return _manifest; } CManifestDoc.cpp000066400000000000000000000034661321503522500371060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" using namespace Caf; /// A simple container for objects of type Manifest CManifestDoc::CManifestDoc() : _jobId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CManifestDoc::~CManifestDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CManifestDoc::initialize( const std::string classNamespace, const std::string className, const std::string classVersion, const UUID jobId, const std::string operationName, const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection) { if (! _isInitialized) { _classNamespace = classNamespace; _className = className; _classVersion = classVersion; _jobId = jobId; _operationName = operationName; _attachmentNameCollection = attachmentNameCollection; _isInitialized = true; } } /// Accessor for the ClassNamespace std::string CManifestDoc::getClassNamespace() const { return _classNamespace; } /// Accessor for the ClassName std::string CManifestDoc::getClassName() const { return _className; } /// Accessor for the ClassVersion std::string CManifestDoc::getClassVersion() const { return _classVersion; } /// Accessor for the JobId UUID CManifestDoc::getJobId() const { return _jobId; } /// Accessor for the OperationName std::string CManifestDoc::getOperationName() const { return _operationName; } /// Accessor for the AttachmentNameCollection SmartPtrCAttachmentNameCollectionDoc CManifestDoc::getAttachmentNameCollection() const { return _attachmentNameCollection; } CProviderEventResponseDoc.cpp000066400000000000000000000036371321503522500416530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CEventKeyCollectionDoc.h" #include "Doc/ResponseDoc/CEventManifestDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Doc/ResponseDoc/CProviderEventResponseDoc.h" using namespace Caf; /// A simple container for objects of type ProviderEventResponse CProviderEventResponseDoc::CProviderEventResponseDoc() : _isInitialized(false) {} CProviderEventResponseDoc::~CProviderEventResponseDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderEventResponseDoc::initialize( const std::string pmeId, const SmartPtrCResponseHeaderDoc responseHeader, const SmartPtrCEventManifestDoc manifest, const SmartPtrCEventKeyCollectionDoc eventKeyCollection, const SmartPtrCStatisticsDoc statistics) { if (! _isInitialized) { _pmeId = pmeId; _responseHeader = responseHeader; _manifest = manifest; _eventKeyCollection = eventKeyCollection; _statistics = statistics; _isInitialized = true; } } /// Accessor for the PmeId std::string CProviderEventResponseDoc::getPmeId() const { return _pmeId; } /// Accessor for the ResponseHeader SmartPtrCResponseHeaderDoc CProviderEventResponseDoc::getResponseHeader() const { return _responseHeader; } /// Accessor for the Manifest SmartPtrCEventManifestDoc CProviderEventResponseDoc::getManifest() const { return _manifest; } /// Accessor for the EventKeyCollection SmartPtrCEventKeyCollectionDoc CProviderEventResponseDoc::getEventKeyCollection() const { return _eventKeyCollection; } /// Accessor for the Statistics SmartPtrCStatisticsDoc CProviderEventResponseDoc::getStatistics() const { return _statistics; } CProviderResponseDoc.cpp000066400000000000000000000043301321503522500406400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Doc/ResponseDoc/CProviderResponseDoc.h" using namespace Caf; /// A simple container for objects of type ProviderResponse CProviderResponseDoc::CProviderResponseDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CProviderResponseDoc::~CProviderResponseDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CProviderResponseDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCResponseHeaderDoc responseHeader, const SmartPtrCManifestDoc manifest, const SmartPtrCAttachmentCollectionDoc attachmentCollection, const SmartPtrCStatisticsDoc statistics) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _responseHeader = responseHeader; _manifest = manifest; _attachmentCollection = attachmentCollection; _statistics = statistics; _isInitialized = true; } } /// Accessor for the ClientId UUID CProviderResponseDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CProviderResponseDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CProviderResponseDoc::getPmeId() const { return _pmeId; } /// Accessor for the ResponseHeader SmartPtrCResponseHeaderDoc CProviderResponseDoc::getResponseHeader() const { return _responseHeader; } /// Accessor for the Manifest SmartPtrCManifestDoc CProviderResponseDoc::getManifest() const { return _manifest; } /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc CProviderResponseDoc::getAttachmentCollection() const { return _attachmentCollection; } /// Accessor for the Statistics SmartPtrCStatisticsDoc CProviderResponseDoc::getStatistics() const { return _statistics; } CResponseDoc.cpp000066400000000000000000000043061321503522500371300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CManifestCollectionDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" using namespace Caf; /// A simple container for objects of type Response CResponseDoc::CResponseDoc() : _clientId(CAFCOMMON_GUID_NULL), _requestId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CResponseDoc::~CResponseDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CResponseDoc::initialize( const UUID clientId, const UUID requestId, const std::string pmeId, const SmartPtrCResponseHeaderDoc responseHeader, const SmartPtrCManifestCollectionDoc manifestCollection, const SmartPtrCAttachmentCollectionDoc attachmentCollection, const SmartPtrCStatisticsDoc statistics) { if (! _isInitialized) { _clientId = clientId; _requestId = requestId; _pmeId = pmeId; _responseHeader = responseHeader; _manifestCollection = manifestCollection; _attachmentCollection = attachmentCollection; _statistics = statistics; _isInitialized = true; } } /// Accessor for the ClientId UUID CResponseDoc::getClientId() const { return _clientId; } /// Accessor for the RequestId UUID CResponseDoc::getRequestId() const { return _requestId; } /// Accessor for the PmeId std::string CResponseDoc::getPmeId() const { return _pmeId; } /// Accessor for the ManifestCollection SmartPtrCResponseHeaderDoc CResponseDoc::getResponseHeader() const { return _responseHeader; } /// Accessor for the ManifestCollection SmartPtrCManifestCollectionDoc CResponseDoc::getManifestCollection() const { return _manifestCollection; } /// Accessor for the AttachmentCollection SmartPtrCAttachmentCollectionDoc CResponseDoc::getAttachmentCollection() const { return _attachmentCollection; } /// Accessor for the Statistics SmartPtrCStatisticsDoc CResponseDoc::getStatistics() const { return _statistics; } CResponseHeaderDoc.cpp000066400000000000000000000031501321503522500402350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" using namespace Caf; /// A simple container for objects of type ResponseHeader CResponseHeaderDoc::CResponseHeaderDoc() : _sequenceNumber(0), _isFinalResponse(true), _sessionId(CAFCOMMON_GUID_NULL), _isInitialized(false) {} CResponseHeaderDoc::~CResponseHeaderDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CResponseHeaderDoc::initialize( const std::string version, const std::string createdDateTime, const uint32 sequenceNumber, const bool isFinalResponse, const UUID sessionId) { if (! _isInitialized) { _version = version; _createdDateTime = createdDateTime; _sequenceNumber = sequenceNumber; _isFinalResponse = isFinalResponse; _sessionId = sessionId; _isInitialized = true; } } /// Accessor for the version std::string CResponseHeaderDoc::getVersion() const { return _version; } /// Accessor for the date/time when the request was created std::string CResponseHeaderDoc::getCreatedDateTime() const { return _createdDateTime; } /// Accessor for the sequenceNumber uint32 CResponseHeaderDoc::getSequenceNumber() const { return _sequenceNumber; } /// Accessor for the version bool CResponseHeaderDoc::getIsFinalResponse() const { return _isFinalResponse; } /// Accessor for the session ID UUID CResponseHeaderDoc::getSessionId() const { return _sessionId; } stdafx.h000066400000000000000000000005331321503522500355350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/ResponseDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define RESPONSEDOC_LINKAGE __declspec(dllexport) #else #define RESPONSEDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ SchemaTypesDoc/000077500000000000000000000000001321503522500345215ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDocCActionClassDoc.cpp000066400000000000000000000040531321503522500401630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" using namespace Caf; /// Definition of an action class that may be generated by the provider CActionClassDoc::CActionClassDoc() : _isInitialized(false) {} CActionClassDoc::~CActionClassDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CActionClassDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const SmartPtrCCollectMethodDoc collectMethod, const std::deque methodCollection, const std::string displayName, const std::string description) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _collectMethod = collectMethod; _methodCollection = methodCollection; _displayName = displayName; _description = description; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CActionClassDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CActionClassDoc::getName() const { return _name; } /// Accessor for the Version std::string CActionClassDoc::getVersion() const { return _version; } /// Accessor for the CollectMethod SmartPtrCCollectMethodDoc CActionClassDoc::getCollectMethod() const { return _collectMethod; } /// Accessor for the Method std::deque CActionClassDoc::getMethodCollection() const { return _methodCollection; } /// A hint as to what this class should be called when displaying it to a human std::string CActionClassDoc::getDisplayName() const { return _displayName; } /// A phrase to describe the class for mouse-over text, etc std::string CActionClassDoc::getDescription() const { return _description; } CActionClassInstanceCollectionDoc.cpp000066400000000000000000000022431321503522500436630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CActionClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CActionClassInstanceCollectionDoc.h" using namespace Caf; /// A simple container for objects of type ActionClassInstanceCollection CActionClassInstanceCollectionDoc::CActionClassInstanceCollectionDoc() : _isInitialized(false) {} CActionClassInstanceCollectionDoc::~CActionClassInstanceCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CActionClassInstanceCollectionDoc::initialize( const std::deque actionClassInstanceCollection) { if (! _isInitialized) { _actionClassInstanceCollection = actionClassInstanceCollection; _isInitialized = true; } } /// Accessor for the ActionClassInstance std::deque CActionClassInstanceCollectionDoc::getActionClassInstanceCollection() const { return _actionClassInstanceCollection; } CActionClassInstanceDoc.cpp000066400000000000000000000030671321503522500416540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CInstanceOperationCollectionDoc.h" #include "Doc/SchemaTypesDoc/CActionClassInstanceDoc.h" using namespace Caf; /// A simple container for objects of type ActionClassInstance CActionClassInstanceDoc::CActionClassInstanceDoc() : _isInitialized(false) {} CActionClassInstanceDoc::~CActionClassInstanceDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CActionClassInstanceDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const SmartPtrCInstanceOperationCollectionDoc instanceOperationCollection) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _instanceOperationCollection = instanceOperationCollection; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CActionClassInstanceDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CActionClassInstanceDoc::getName() const { return _name; } /// Accessor for the Version std::string CActionClassInstanceDoc::getVersion() const { return _version; } /// Accessor for the InstanceOperationCollection SmartPtrCInstanceOperationCollectionDoc CActionClassInstanceDoc::getInstanceOperationCollection() const { return _instanceOperationCollection; } CClassCardinalityDoc.cpp000066400000000000000000000025301321503522500412070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" using namespace Caf; /// Class description of one end of a relationship CClassCardinalityDoc::CClassCardinalityDoc() : _isInitialized(false) {} CClassCardinalityDoc::~CClassCardinalityDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CClassCardinalityDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const std::string cardinality) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _cardinality = cardinality; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CClassCardinalityDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CClassCardinalityDoc::getName() const { return _name; } /// Accessor for the Version std::string CClassCardinalityDoc::getVersion() const { return _version; } /// Cardinality of one end relationship, i.e. has one, has many, etc std::string CClassCardinalityDoc::getCardinality() const { return _cardinality; } CClassFieldDoc.cpp000066400000000000000000000024461321503522500377750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassFieldDoc.h" using namespace Caf; /// Description of a class and the field used to identify one end of a relationship CClassFieldDoc::CClassFieldDoc() : _isInitialized(false) {} CClassFieldDoc::~CClassFieldDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CClassFieldDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const std::string field) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _field = field; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CClassFieldDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CClassFieldDoc::getName() const { return _name; } /// Accessor for the Version std::string CClassFieldDoc::getVersion() const { return _version; } /// Description of a class field used to identify one end of a relationship std::string CClassFieldDoc::getField() const { return _field; } CClassIdentifierDoc.cpp000066400000000000000000000021661321503522500410330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" using namespace Caf; /// Tuple of values to uniquely identify a class CClassIdentifierDoc::CClassIdentifierDoc() : _isInitialized(false) {} CClassIdentifierDoc::~CClassIdentifierDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CClassIdentifierDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CClassIdentifierDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CClassIdentifierDoc::getName() const { return _name; } /// Accessor for the Version std::string CClassIdentifierDoc::getVersion() const { return _version; } CClassInstancePropertyDoc.cpp000066400000000000000000000041551321503522500422620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" using namespace Caf; /// Definition of an attribute (field) of a class CClassInstancePropertyDoc::CClassInstancePropertyDoc() : _required(false), _transientVal(false), _list(false), _isInitialized(false) {} CClassInstancePropertyDoc::~CClassInstancePropertyDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CClassInstancePropertyDoc::initialize( const std::string name, const std::deque type, const bool required, const bool transientVal, const bool list, const std::string displayName, const std::string description) { if (! _isInitialized) { _name = name; _type = type; _required = required; _transientVal = transientVal; _list = list; _displayName = displayName; _description = description; _isInitialized = true; } } /// Property name std::string CClassInstancePropertyDoc::getName() const { return _name; } /// Accessor for the Type std::deque CClassInstancePropertyDoc::getType() const { return _type; } /// Whether this is a required property, i.e. this property must always be non-empty bool CClassInstancePropertyDoc::getRequired() const { return _required; } /// Accessor for the TransientVal bool CClassInstancePropertyDoc::getTransientVal() const { return _transientVal; } /// Indicates whether to expect a list of properties in the provider response bool CClassInstancePropertyDoc::getList() const { return _list; } /// A hint as to what this property should be called when displaying it to a human std::string CClassInstancePropertyDoc::getDisplayName() const { return _displayName; } /// A phrase to describe the property for mouse-over text, etc std::string CClassInstancePropertyDoc::getDescription() const { return _description; } CClassPropertyDoc.cpp000066400000000000000000000072421321503522500405750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" using namespace Caf; /// Definition of an attribute (field) of a class CClassPropertyDoc::CClassPropertyDoc() : _type(PROPERTY_NONE), _required(false), _key(false), _list(false), _caseSensitive(false), _transientVal(false), _validator(VALIDATOR_NONE), _isInitialized(false) {} CClassPropertyDoc::~CClassPropertyDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CClassPropertyDoc::initialize( const std::string name, const PROPERTY_TYPE type, const std::deque value, const bool required, const bool key, const bool list, const bool caseSensitive, const bool transientVal, const std::string defaultVal, const VALIDATOR_TYPE validator, const std::string upperRange, const std::string lowerRange, const std::string displayName, const std::string description) { if (! _isInitialized) { _name = name; _type = type; _value = value; _required = required; _key = key; _list = list; _caseSensitive = caseSensitive; _transientVal = transientVal; _defaultVal = defaultVal; _validator = validator; _upperRange = upperRange; _lowerRange = lowerRange; _displayName = displayName; _description = description; _isInitialized = true; } } /// Property name std::string CClassPropertyDoc::getName() const { return _name; } /// Describes the data type of the property PROPERTY_TYPE CClassPropertyDoc::getType() const { return _type; } /// The contents of a validator used on this property std::deque CClassPropertyDoc::getValue() const { return _value; } /// Whether this is a required property, i.e. this property must always be non-empty bool CClassPropertyDoc::getRequired() const { return _required; } /// Indicates this property may be used as a key identifying field bool CClassPropertyDoc::getKey() const { return _key; } /// Indicates whether to expect a list of properties in the provider response bool CClassPropertyDoc::getList() const { return _list; } /// Indicates whether a string field should be treated in a case-sensitive manner bool CClassPropertyDoc::getCaseSensitive() const { return _caseSensitive; } /// Accessor for the TransientVal bool CClassPropertyDoc::getTransientVal() const { return _transientVal; } /// Accessor for the DefaultVal std::string CClassPropertyDoc::getDefaultVal() const { return _defaultVal; } /// The type of validator described in the 'value' sub-elements VALIDATOR_TYPE CClassPropertyDoc::getValidator() const { return _validator; } /// If a 'range' validator is in use, this describes the upper limit of allowable values for the property. QUESTIONABLE: how do we determine inclusive or exclusive range std::string CClassPropertyDoc::getUpperRange() const { return _upperRange; } /// If a 'range' validator is in use, this describes the lower limit of allowable values for the property. QUESTIONABLE: how do we determine inclusive or exclusive range std::string CClassPropertyDoc::getLowerRange() const { return _lowerRange; } /// A hint as to what this property should be called when displaying it to a human std::string CClassPropertyDoc::getDisplayName() const { return _displayName; } /// A phrase to describe the property for mouse-over text, etc std::string CClassPropertyDoc::getDescription() const { return _description; } VALIDATOR_TYPE _validator; CCmdlMetadataDoc.cpp000066400000000000000000000016411321503522500403000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" using namespace Caf; /// A simple container for objects of type CmdlMetadata CCmdlMetadataDoc::CCmdlMetadataDoc() : _isInitialized(false) {} CCmdlMetadataDoc::~CCmdlMetadataDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CCmdlMetadataDoc::initialize( const std::string name, const std::string value) { if (! _isInitialized) { _name = name; _value = value; _isInitialized = true; } } /// Accessor for the Name std::string CCmdlMetadataDoc::getName() const { return _name; } /// Accessor for the Value std::string CCmdlMetadataDoc::getValue() const { return _value; } CCmdlUnionDoc.cpp000066400000000000000000000021041321503522500376430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" using namespace Caf; /// A simple container for objects of type CmdlUnion CCmdlUnionDoc::CCmdlUnionDoc() : _isInitialized(false) {} CCmdlUnionDoc::~CCmdlUnionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CCmdlUnionDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CCmdlUnionDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CCmdlUnionDoc::getName() const { return _name; } /// Accessor for the Version std::string CCmdlUnionDoc::getVersion() const { return _version; } CCollectMethodDoc.cpp000066400000000000000000000047121321503522500405100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" using namespace Caf; /// Definition of a collection method on a class CCollectMethodDoc::CCollectMethodDoc() : _isInitialized(false) {} CCollectMethodDoc::~CCollectMethodDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CCollectMethodDoc::initialize( const std::string name, const std::deque parameterCollection, const std::deque instanceParameterCollection, const std::deque returnValCollection, const std::deque eventValCollection, const std::deque errorCollection) { if (! _isInitialized) { _name = name; _parameterCollection = parameterCollection; _instanceParameterCollection = instanceParameterCollection; _returnValCollection = returnValCollection; _eventValCollection = eventValCollection; _errorCollection = errorCollection; _isInitialized = true; } } /// name of the collection method std::string CCollectMethodDoc::getName() const { return _name; } /// Definition of a parameter that passes simple types to the collection method std::deque CCollectMethodDoc::getParameterCollection() const { return _parameterCollection; } /// Definition of a parameter passing data class instances to the collection method std::deque CCollectMethodDoc::getInstanceParameterCollection() const { return _instanceParameterCollection; } /// Accessor for the ReturnVal std::deque CCollectMethodDoc::getReturnValCollection() const { return _returnValCollection; } /// Accessor for the EventVal std::deque CCollectMethodDoc::getEventValCollection() const { return _eventValCollection; } /// A class that may be returned to indicate an error occurred during the processing of the collection method std::deque CCollectMethodDoc::getErrorCollection() const { return _errorCollection; } CDataClassDoc.cpp000066400000000000000000000051201321503522500376130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" using namespace Caf; /// Definition of a data class that may be generated by the provider CDataClassDoc::CDataClassDoc() : _unique(false), _transientVal(false), _isInitialized(false) {} CDataClassDoc::~CDataClassDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDataClassDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const std::deque propertyCollection, const std::deque instancePropertyCollection, const bool unique, const bool transientVal, const std::string displayName, const std::string description) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _propertyCollection = propertyCollection; _instancePropertyCollection = instancePropertyCollection; _unique = unique; _transientVal = transientVal; _displayName = displayName; _description = description; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CDataClassDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CDataClassDoc::getName() const { return _name; } /// Accessor for the Version std::string CDataClassDoc::getVersion() const { return _version; } /// Accessor for the Property std::deque CDataClassDoc::getPropertyCollection() const { return _propertyCollection; } /// Accessor for the InstanceProperty std::deque CDataClassDoc::getInstancePropertyCollection() const { return _instancePropertyCollection; } /// Indicates whether the key properties of this class are enough to guarantee uniqueness from other classes of the same type bool CDataClassDoc::getUnique() const { return _unique; } /// Accessor for the TransientVal bool CDataClassDoc::getTransientVal() const { return _transientVal; } /// A hint as to what this class should be called when displaying it to a human std::string CDataClassDoc::getDisplayName() const { return _displayName; } /// A phrase to describe the class for mouse-over text, etc std::string CDataClassDoc::getDescription() const { return _description; } CDataClassInstanceCollectionDoc.cpp000066400000000000000000000022011321503522500433110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceCollectionDoc.h" using namespace Caf; /// A simple container for objects of type DataClassInstanceCollection CDataClassInstanceCollectionDoc::CDataClassInstanceCollectionDoc() : _isInitialized(false) {} CDataClassInstanceCollectionDoc::~CDataClassInstanceCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDataClassInstanceCollectionDoc::initialize( const std::deque dataClassInstanceCollection) { if (! _isInitialized) { _dataClassInstanceCollection = dataClassInstanceCollection; _isInitialized = true; } } /// Accessor for the DataClassInstance std::deque CDataClassInstanceCollectionDoc::getDataClassInstanceCollection() const { return _dataClassInstanceCollection; } CDataClassInstanceDoc.cpp000066400000000000000000000046231321503522500413070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" using namespace Caf; /// A simple container for objects of type DataClassInstance CDataClassInstanceDoc::CDataClassInstanceDoc() : _isInitialized(false) {} CDataClassInstanceDoc::~CDataClassInstanceDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDataClassInstanceDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const std::deque cmdlMetadataCollection, const std::deque propertyCollection, const std::deque instancePropertyCollection, const SmartPtrCCmdlUnionDoc cmdlUnion) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _cmdlMetadataCollection = cmdlMetadataCollection; _propertyCollection = propertyCollection; _instancePropertyCollection = instancePropertyCollection; _cmdlUnion = cmdlUnion; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CDataClassInstanceDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CDataClassInstanceDoc::getName() const { return _name; } /// Accessor for the Version std::string CDataClassInstanceDoc::getVersion() const { return _version; } /// Accessor for the CmdlMetadata std::deque CDataClassInstanceDoc::getCmdlMetadataCollection() const { return _cmdlMetadataCollection; } /// Accessor for the Property std::deque CDataClassInstanceDoc::getPropertyCollection() const { return _propertyCollection; } /// Accessor for the InstanceProperty std::deque CDataClassInstanceDoc::getInstancePropertyCollection() const { return _instancePropertyCollection; } /// Accessor for the CmdlUnion SmartPtrCCmdlUnionDoc CDataClassInstanceDoc::getCmdlUnion() const { return _cmdlUnion; } CDataClassPropertyDoc.cpp000066400000000000000000000023541321503522500413660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" using namespace Caf; /// A simple container for objects of type DataClassProperty CDataClassPropertyDoc::CDataClassPropertyDoc() : _isInitialized(false) {} CDataClassPropertyDoc::~CDataClassPropertyDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDataClassPropertyDoc::initialize( const std::string name, const std::deque cmdlMetadata, const std::string value) { if (! _isInitialized) { _name = name; _cmdlMetadata = cmdlMetadata; _value = value; _isInitialized = true; } } /// Accessor for the Name std::string CDataClassPropertyDoc::getName() const { return _name; } /// Accessor for the CmdlMetadata std::deque CDataClassPropertyDoc::getCmdlMetadata() const { return _cmdlMetadata; } /// Accessor for the Value std::string CDataClassPropertyDoc::getValue() const { return _value; } CDataClassSubInstanceDoc.cpp000066400000000000000000000040501321503522500417530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" using namespace Caf; /// A simple container for objects of type DataClassSubInstance CDataClassSubInstanceDoc::CDataClassSubInstanceDoc() : _isInitialized(false) {} CDataClassSubInstanceDoc::~CDataClassSubInstanceDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CDataClassSubInstanceDoc::initialize( const std::string name, const std::deque cmdlMetadataCollection, const std::deque propertyCollection, const std::deque instancePropertyCollection, const SmartPtrCCmdlUnionDoc cmdlUnion) { if (! _isInitialized) { _name = name; _cmdlMetadataCollection = cmdlMetadataCollection; _propertyCollection = propertyCollection; _instancePropertyCollection = instancePropertyCollection; _cmdlUnion = cmdlUnion; _isInitialized = true; } } /// Accessor for the Name std::string CDataClassSubInstanceDoc::getName() const { return _name; } /// Accessor for the CmdlMetadata std::deque CDataClassSubInstanceDoc::getCmdlMetadataCollection() const { return _cmdlMetadataCollection; } /// Accessor for the Property std::deque CDataClassSubInstanceDoc::getPropertyCollection() const { return _propertyCollection; } /// Accessor for the InstanceProperty std::deque CDataClassSubInstanceDoc::getInstancePropertyCollection() const { return _instancePropertyCollection; } /// Accessor for the CmdlUnion SmartPtrCCmdlUnionDoc CDataClassSubInstanceDoc::getCmdlUnion() const { return _cmdlUnion; } CInstanceOperationCollectionDoc.cpp000066400000000000000000000022011321503522500434120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CInstanceOperationDoc.h" #include "Doc/SchemaTypesDoc/CInstanceOperationCollectionDoc.h" using namespace Caf; /// A simple container for objects of type InstanceOperationCollection CInstanceOperationCollectionDoc::CInstanceOperationCollectionDoc() : _isInitialized(false) {} CInstanceOperationCollectionDoc::~CInstanceOperationCollectionDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInstanceOperationCollectionDoc::initialize( const std::deque instanceOperationCollection) { if (! _isInitialized) { _instanceOperationCollection = instanceOperationCollection; _isInitialized = true; } } /// Accessor for the InstanceOperation std::deque CInstanceOperationCollectionDoc::getInstanceOperationCollection() const { return _instanceOperationCollection; } CInstanceOperationDoc.cpp000066400000000000000000000020201321503522500413750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CInstanceOperationDoc.h" using namespace Caf; /// A simple container for objects of type InstanceOperation CInstanceOperationDoc::CInstanceOperationDoc() : _isInitialized(false) {} CInstanceOperationDoc::~CInstanceOperationDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInstanceOperationDoc::initialize( const std::string operationName, const std::string moniker) { if (! _isInitialized) { _operationName = operationName; _moniker = moniker; _isInitialized = true; } } /// Accessor for the OperationName std::string CInstanceOperationDoc::getOperationName() const { return _operationName; } /// Accessor for the Moniker std::string CInstanceOperationDoc::getMoniker() const { return _moniker; } CInstanceParameterDoc.cpp000066400000000000000000000043711321503522500413700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" using namespace Caf; /// A parameter containing a data class instance used by a method to control the outcome CInstanceParameterDoc::CInstanceParameterDoc() : _isOptional(false), _isList(false), _isInitialized(false) {} CInstanceParameterDoc::~CInstanceParameterDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CInstanceParameterDoc::initialize( const std::string name, const std::string instanceNamespace, const std::string instanceName, const std::string instanceVersion, const bool isOptional, const bool isList, const std::string displayName, const std::string description) { if (! _isInitialized) { _name = name; _instanceNamespace = instanceNamespace; _instanceName = instanceName; _instanceVersion = instanceVersion; _isOptional = isOptional; _isList = isList; _displayName = displayName; _description = description; _isInitialized = true; } } /// Name of parameter std::string CInstanceParameterDoc::getName() const { return _name; } /// Namespace of instance object type std::string CInstanceParameterDoc::getInstanceNamespace() const { return _instanceNamespace; } /// Name of instance object type std::string CInstanceParameterDoc::getInstanceName() const { return _instanceName; } /// Version of instance object type std::string CInstanceParameterDoc::getInstanceVersion() const { return _instanceVersion; } /// Indicates this parameter need not be passed bool CInstanceParameterDoc::getIsOptional() const { return _isOptional; } /// Indicates whether to expect a list of values as opposed to a single value (the default if this attribute is not present) bool CInstanceParameterDoc::getIsList() const { return _isList; } /// Human-readable version of the parameter name std::string CInstanceParameterDoc::getDisplayName() const { return _displayName; } /// Short description of what the parameter is for std::string CInstanceParameterDoc::getDescription() const { return _description; } CJoinTypeDoc.cpp000066400000000000000000000031751321503522500375250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassFieldDoc.h" #include "Doc/SchemaTypesDoc/CJoinTypeDoc.h" using namespace Caf; /// A simple container for objects of type JoinType CJoinTypeDoc::CJoinTypeDoc() : _operand(OPERATOR_NONE), _isInitialized(false) {} CJoinTypeDoc::~CJoinTypeDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CJoinTypeDoc::initialize( const OPERATOR_TYPE operand, const SmartPtrCClassFieldDoc dataClassLeft, const SmartPtrCClassFieldDoc dataClassRight, const std::string description) { if (! _isInitialized) { _operand = operand; _dataClassLeft = dataClassLeft; _dataClassRight = dataClassRight; _description = description; _isInitialized = true; } } /// Defines the operand used to join the class fields. Restricted to '=' for now OPERATOR_TYPE CJoinTypeDoc::getOperand() const { return _operand; } /// Identifies the fields on classes that uniquely identify relationship SmartPtrCClassFieldDoc CJoinTypeDoc::getDataClassLeft() const { return _dataClassLeft; } /// Identifies the fields on classes that uniquely identify relationship SmartPtrCClassFieldDoc CJoinTypeDoc::getDataClassRight() const { return _dataClassRight; } /// A short human-readable description of the join std::string CJoinTypeDoc::getDescription() const { return _description; } OPERATOR_TYPE _operand; CLogicalRelationshipDoc.cpp000066400000000000000000000046771321503522500417300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/CJoinTypeDoc.h" #include "Doc/SchemaTypesDoc/CLogicalRelationshipDoc.h" using namespace Caf; /// Definition of a relationship between classes that can be described by identifying the fields on the classes that uniquely identify the relationship CLogicalRelationshipDoc::CLogicalRelationshipDoc() : _arity(ARITY_NONE), _isInitialized(false) {} CLogicalRelationshipDoc::~CLogicalRelationshipDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CLogicalRelationshipDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const ARITY_TYPE arity, const SmartPtrCClassCardinalityDoc dataClassLeft, const SmartPtrCClassCardinalityDoc dataClassRight, const std::deque joinCollection, const std::string description) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _arity = arity; _dataClassLeft = dataClassLeft; _dataClassRight = dataClassRight; _joinCollection = joinCollection; _description = description; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CLogicalRelationshipDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CLogicalRelationshipDoc::getName() const { return _name; } /// Accessor for the Version std::string CLogicalRelationshipDoc::getVersion() const { return _version; } /// Accessor for the Arity ARITY_TYPE CLogicalRelationshipDoc::getArity() const { return _arity; } /// Accessor for the DataClassLeft SmartPtrCClassCardinalityDoc CLogicalRelationshipDoc::getDataClassLeft() const { return _dataClassLeft; } /// Accessor for the DataClassRight SmartPtrCClassCardinalityDoc CLogicalRelationshipDoc::getDataClassRight() const { return _dataClassRight; } /// Defines a join condition of the relationship std::deque CLogicalRelationshipDoc::getJoinCollection() const { return _joinCollection; } /// Accessor for the Description std::string CLogicalRelationshipDoc::getDescription() const { return _description; } CMethodDoc.cpp000066400000000000000000000053041321503522500372000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" using namespace Caf; /// Definition of a method on a class CMethodDoc::CMethodDoc() : _isInitialized(false) {} CMethodDoc::~CMethodDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMethodDoc::initialize( const std::string name, const std::deque parameterCollection, const std::deque instanceParameterCollection, const std::deque returnValCollection, const std::deque eventValCollection, const std::deque errorCollection, const std::string displayName, const std::string description) { if (! _isInitialized) { _name = name; _parameterCollection = parameterCollection; _instanceParameterCollection = instanceParameterCollection; _returnValCollection = returnValCollection; _eventValCollection = eventValCollection; _errorCollection = errorCollection; _displayName = displayName; _description = description; _isInitialized = true; } } /// name of the method std::string CMethodDoc::getName() const { return _name; } /// Definition of a parameter that passes simple types to the method std::deque CMethodDoc::getParameterCollection() const { return _parameterCollection; } /// Definition of a parameter that passes data class instances to the method std::deque CMethodDoc::getInstanceParameterCollection() const { return _instanceParameterCollection; } /// Accessor for the ReturnVal std::deque CMethodDoc::getReturnValCollection() const { return _returnValCollection; } /// Accessor for the EventVal std::deque CMethodDoc::getEventValCollection() const { return _eventValCollection; } /// A class that may be returned to indicate an error occurred during the processing of the collection method std::deque CMethodDoc::getErrorCollection() const { return _errorCollection; } /// Human-readable version of the method name std::string CMethodDoc::getDisplayName() const { return _displayName; } /// A short phrase describing the purpose of the method std::string CMethodDoc::getDescription() const { return _description; } CMethodParameterDoc.cpp000066400000000000000000000040321321503522500410360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" using namespace Caf; /// A parameter containing a simple type used by a method to control the outcome CMethodParameterDoc::CMethodParameterDoc() : _type(PARAMETER_NONE), _isOptional(false), _isList(false), _isInitialized(false) {} CMethodParameterDoc::~CMethodParameterDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CMethodParameterDoc::initialize( const std::string name, const PARAMETER_TYPE type, const bool isOptional, const bool isList, const std::string defaultVal, const std::string displayName, const std::string description) { if (! _isInitialized) { _name = name; _type = type; _isOptional = isOptional; _isList = isList; _defaultVal = defaultVal; _displayName = displayName; _description = description; _isInitialized = true; } } /// Name of parameter std::string CMethodParameterDoc::getName() const { return _name; } /// Describes the data type of the property PARAMETER_TYPE CMethodParameterDoc::getType() const { return _type; } /// Indicates this parameter need not be passed bool CMethodParameterDoc::getIsOptional() const { return _isOptional; } /// Indicates whether to expect a list of values as opposed to a single value (the default if this attribute is not present) bool CMethodParameterDoc::getIsList() const { return _isList; } /// Accessor for the DefaultVal std::string CMethodParameterDoc::getDefaultVal() const { return _defaultVal; } /// Human-readable version of the parameter name std::string CMethodParameterDoc::getDisplayName() const { return _displayName; } /// Short description of what the parameter is for std::string CMethodParameterDoc::getDescription() const { return _description; } CPhysicalRelationshipDoc.cpp000066400000000000000000000042571321503522500421240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/CPhysicalRelationshipDoc.h" using namespace Caf; /// Describes a relationship between dataclass where the key information from data class instances comprising the relationship are listed in an instance of this class CPhysicalRelationshipDoc::CPhysicalRelationshipDoc() : _arity(ARITY_NONE), _isInitialized(false) {} CPhysicalRelationshipDoc::~CPhysicalRelationshipDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CPhysicalRelationshipDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const ARITY_TYPE arity, const SmartPtrCClassCardinalityDoc dataClassLeft, const SmartPtrCClassCardinalityDoc dataClassRight, const std::string description) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _arity = arity; _dataClassLeft = dataClassLeft; _dataClassRight = dataClassRight; _description = description; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CPhysicalRelationshipDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CPhysicalRelationshipDoc::getName() const { return _name; } /// Accessor for the Version std::string CPhysicalRelationshipDoc::getVersion() const { return _version; } /// Accessor for the Arity ARITY_TYPE CPhysicalRelationshipDoc::getArity() const { return _arity; } /// Accessor for the DataClassLeft SmartPtrCClassCardinalityDoc CPhysicalRelationshipDoc::getDataClassLeft() const { return _dataClassLeft; } /// Accessor for the DataClassRight SmartPtrCClassCardinalityDoc CPhysicalRelationshipDoc::getDataClassRight() const { return _dataClassRight; } /// Accessor for the Description std::string CPhysicalRelationshipDoc::getDescription() const { return _description; } CRelationshipDoc.cpp000066400000000000000000000041451321503522500404230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/CRelationshipDoc.h" using namespace Caf; /// Definition of a relationship between data classes CRelationshipDoc::CRelationshipDoc() : _arity(ARITY_NONE), _isInitialized(false) {} CRelationshipDoc::~CRelationshipDoc() {} /// Initializes the object with everything required by this /// container. Once initialized, this object cannot /// be changed (i.e. it is immutable). void CRelationshipDoc::initialize( const std::string namespaceVal, const std::string name, const std::string version, const ARITY_TYPE arity, const SmartPtrCClassCardinalityDoc dataClassLeft, const SmartPtrCClassCardinalityDoc dataClassRight, const std::string description) { if (! _isInitialized) { _namespaceVal = namespaceVal; _name = name; _version = version; _arity = arity; _dataClassLeft = dataClassLeft; _dataClassRight = dataClassRight; _description = description; _isInitialized = true; } } /// Accessor for the NamespaceVal std::string CRelationshipDoc::getNamespaceVal() const { return _namespaceVal; } /// Accessor for the Name std::string CRelationshipDoc::getName() const { return _name; } /// Accessor for the Version std::string CRelationshipDoc::getVersion() const { return _version; } /// Number of parts (sides) to relationship. Restricted to a two-sided relationship for now ARITY_TYPE CRelationshipDoc::getArity() const { return _arity; } /// Identifies the two classes that make up the relationship SmartPtrCClassCardinalityDoc CRelationshipDoc::getDataClassLeft() const { return _dataClassLeft; } /// Identifies the two classes that make up the relationship SmartPtrCClassCardinalityDoc CRelationshipDoc::getDataClassRight() const { return _dataClassRight; } /// A short human-readable description of the relationship std::string CRelationshipDoc::getDescription() const { return _description; } stdafx.h000066400000000000000000000005411321503522500361630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocDoc/SchemaTypesDoc/* * Author: bwilliams * Created: February 25, 2016 * * Copyright (C) 2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define SCHEMATYPESDOC_LINKAGE __declspec(dllexport) #else #define SCHEMATYPESDOC_LINKAGE #endif #include #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/000077500000000000000000000000001321503522500323205ustar00rootroot00000000000000AttachmentUtils.cpp000066400000000000000000000036511321503522500360630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Exception/CCafException.h" #include "AttachmentUtils.h" using namespace Caf; SmartPtrCAttachmentDoc AttachmentUtils::findOptionalAttachment( const std::string& attachmentName, const SmartPtrCAttachmentCollectionDoc& attachmentCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("AttachmentUtils", "findOptionalAttachment"); SmartPtrCAttachmentDoc attachmentRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(attachmentName); CAF_CM_VALIDATE_SMARTPTR(attachmentCollection); const std::deque attachmentCollectionInner = attachmentCollection->getAttachment(); for (TConstIterator > attachmentIter(attachmentCollectionInner); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachmentTmp = *attachmentIter; const std::string attachmentNameTmp = attachmentTmp->getName(); if (attachmentNameTmp.compare(attachmentName) == 0) { attachmentRc = attachmentTmp; } } } CAF_CM_EXIT; return attachmentRc; } SmartPtrCAttachmentDoc AttachmentUtils::findRequiredAttachment( const std::string& attachmentName, const SmartPtrCAttachmentCollectionDoc& attachmentCollection) { CAF_CM_STATIC_FUNC_LOG("AttachmentUtils", "findRequiredAttachment"); SmartPtrCAttachmentDoc attachmentRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(attachmentName); CAF_CM_VALIDATE_SMARTPTR(attachmentCollection); attachmentRc = findOptionalAttachment(attachmentName, attachmentCollection); if (attachmentRc.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Required attachment not found - %s", attachmentName.c_str()); } } CAF_CM_EXIT; return attachmentRc; } AttachmentUtils.h000066400000000000000000000013671321503522500355320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef AttachmentUtils_h_ #define AttachmentUtils_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" namespace Caf { class DOCUTILS_LINKAGE AttachmentUtils { public: static SmartPtrCAttachmentDoc findOptionalAttachment( const std::string& attachmentName, const SmartPtrCAttachmentCollectionDoc& attachmentCollection); static SmartPtrCAttachmentDoc findRequiredAttachment( const std::string& attachmentName, const SmartPtrCAttachmentCollectionDoc& attachmentCollection); private: CAF_CM_DECLARE_NOCREATE(AttachmentUtils); }; } #endif DefnObjectConverter.cpp000066400000000000000000000204431321503522500366430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Integration/IDocument.h" #include "Xml/XmlUtils/CXmlElement.h" #include "DefnObjectConverter.h" using namespace Caf; std::string DefnObjectConverter::toString( const SmartPtrCDataClassInstanceDoc dataClassInstance) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("DefnObjectConverter", "toString"); std::string defnObjXmlStr; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(dataClassInstance); const SmartPtrCXmlElement defnObjXml = CXmlUtils::createRootElement( dataClassInstance->getName(), "http://schemas->vmware->com/caf/schema"); defnObjXml->addAttribute("namespace", dataClassInstance->getNamespaceVal()); defnObjXml->addAttribute("name", dataClassInstance->getName()); defnObjXml->addAttribute("version", dataClassInstance->getVersion()); SmartPtrCDataClassSubInstanceDoc dataClassSubInstance; dataClassSubInstance.CreateInstance(); dataClassSubInstance->initialize( dataClassInstance->getName(), dataClassInstance->getCmdlMetadataCollection(), dataClassInstance->getPropertyCollection(), dataClassInstance->getInstancePropertyCollection(), dataClassInstance->getCmdlUnion()); addDataClassSubInstance(dataClassSubInstance, defnObjXml); defnObjXmlStr = defnObjXml->saveToStringRaw(); } CAF_CM_EXIT; return defnObjXmlStr; } SmartPtrCDataClassInstanceDoc DefnObjectConverter::fromString( const std::string defnObjectXmlStr) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("DefnObjectConverter", "fromString"); SmartPtrCDataClassInstanceDoc dataClassInstanceRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(defnObjectXmlStr); const SmartPtrCXmlElement defnObjectXml = CXmlUtils::parseString(defnObjectXmlStr, std::string()); const SmartPtrCDataClassSubInstanceDoc dataClassSubInstance = parseDataClassSubInstance(defnObjectXml, true); dataClassInstanceRc.CreateInstance(); dataClassInstanceRc->initialize( defnObjectXml->findRequiredAttribute("namespace"), defnObjectXml->findRequiredAttribute("name"), defnObjectXml->findRequiredAttribute("version"), dataClassSubInstance->getCmdlMetadataCollection(), dataClassSubInstance->getPropertyCollection(), dataClassSubInstance->getInstancePropertyCollection(), dataClassSubInstance->getCmdlUnion()); } CAF_CM_EXIT; return dataClassInstanceRc; } void DefnObjectConverter::addDataClassSubInstance( const SmartPtrCDataClassSubInstanceDoc dataClassSubInstance, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("DefnObjectConverter", "addDataClassSubInstance"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(dataClassSubInstance); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque cmdlMetadataCollection = dataClassSubInstance->getCmdlMetadataCollection(); if (! cmdlMetadataCollection.empty()) { addCmdlMetadata(cmdlMetadataCollection, thisXml); } const std::deque dataClassPropertyCollection = dataClassSubInstance->getPropertyCollection(); if (! dataClassPropertyCollection.empty()) { for (TSmartConstIterator > dataClassPropertyIter(dataClassPropertyCollection); dataClassPropertyIter; dataClassPropertyIter++) { const SmartPtrCDataClassPropertyDoc dataClassProperty = *dataClassPropertyIter; const SmartPtrCXmlElement propertyXml = thisXml->createAndAddElement(dataClassProperty->getName()); const std::deque cmdlMetadataCollectionProperty = dataClassProperty->getCmdlMetadata(); if (! cmdlMetadataCollectionProperty.empty()) { addCmdlMetadata(cmdlMetadataCollectionProperty, propertyXml); } propertyXml->setValue(dataClassProperty->getValue()); } } const std::deque instancePropertyCollection = dataClassSubInstance->getInstancePropertyCollection(); if (! instancePropertyCollection.empty()) { for (TSmartConstIterator > dataClassSubInstanceIter(instancePropertyCollection); dataClassSubInstanceIter; dataClassSubInstanceIter++) { const SmartPtrCDataClassSubInstanceDoc instanceProperty = *dataClassSubInstanceIter; const SmartPtrCXmlElement instancePropertyXml = thisXml->createAndAddElement(instanceProperty->getName()); addDataClassSubInstance(instanceProperty, instancePropertyXml); } } } CAF_CM_EXIT; } SmartPtrCDataClassSubInstanceDoc DefnObjectConverter::parseDataClassSubInstance( const SmartPtrCXmlElement dataClassSubInstanceXml, const bool isDataClassInstance) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("DefnObjectConverter", "parseDataClassSubInstance"); SmartPtrCDataClassSubInstanceDoc dataClassSubInstanceRc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(dataClassSubInstanceXml); std::deque cmdlMetadataCollection; if (! isDataClassInstance) { cmdlMetadataCollection = parseCmdlMetadata(dataClassSubInstanceXml); } std::deque dataClassPropertyCollection; std::deque instancePropertyCollection; const CXmlElement::SmartPtrCElementCollection childrenXml = dataClassSubInstanceXml->getAllChildren(); if (! childrenXml.IsNull() && ! childrenXml->empty()) { for (TConstIterator childrenXmlIter(*childrenXml); childrenXmlIter; childrenXmlIter++) { const SmartPtrCXmlElement childXml = childrenXmlIter->second; const CXmlElement::SmartPtrCElementCollection grandChildrenXml = childXml->getAllChildren(); if (! grandChildrenXml.IsNull() && ! grandChildrenXml->empty()) { const SmartPtrCDataClassSubInstanceDoc dataClassSubInstance = parseDataClassSubInstance(childXml, false); instancePropertyCollection.push_back(dataClassSubInstance); } else { const std::deque cmdlMetadataCollectionProperty = parseCmdlMetadata(childXml); SmartPtrCDataClassPropertyDoc dataClassProperty; dataClassProperty.CreateInstance(); dataClassProperty->initialize( childXml->getName(), cmdlMetadataCollectionProperty, childXml->getValue()); dataClassPropertyCollection.push_back(dataClassProperty); } } } dataClassSubInstanceRc.CreateInstance(); dataClassSubInstanceRc->initialize( dataClassSubInstanceXml->getName(), cmdlMetadataCollection, dataClassPropertyCollection, instancePropertyCollection, SmartPtrCCmdlUnionDoc()); } CAF_CM_EXIT; return dataClassSubInstanceRc; } std::deque DefnObjectConverter::parseCmdlMetadata( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("DefnObjectConverter", "parseCmdlMetadata"); std::deque cmdlMetadataCollection; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCAttributeCollection attributeCollection = thisXml->getAllAttributes(); if (! attributeCollection.IsNull() && ! attributeCollection->empty()) { for (TConstIterator childrenXmlIter(*attributeCollection); childrenXmlIter; childrenXmlIter++) { const std::string attributeName = childrenXmlIter->first; const std::string attributeValue = childrenXmlIter->second; SmartPtrCCmdlMetadataDoc cmdlMetadata; cmdlMetadata.CreateInstance(); cmdlMetadata->initialize(attributeName, attributeValue); cmdlMetadataCollection.push_back(cmdlMetadata); } } } CAF_CM_EXIT; return cmdlMetadataCollection; } void DefnObjectConverter::addCmdlMetadata( const std::deque cmdlMetadataCollection, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("DefnObjectConverter", "addCmdlMetadata"); CAF_CM_ENTER { CAF_CM_VALIDATE_STL(cmdlMetadataCollection); CAF_CM_VALIDATE_SMARTPTR(thisXml); for (TSmartConstIterator > cmdlMetadataIter(cmdlMetadataCollection); cmdlMetadataIter; cmdlMetadataIter++) { const SmartPtrCCmdlMetadataDoc cmdlMetadata = *cmdlMetadataIter; thisXml->addAttribute(cmdlMetadata->getName(), cmdlMetadata->getValue()); } } CAF_CM_EXIT; } DefnObjectConverter.h000066400000000000000000000023721321503522500363110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef DefnObjectConverter_h_ #define DefnObjectConverter_h_ #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { class DOCUTILS_LINKAGE DefnObjectConverter { public: static std::string toString( const SmartPtrCDataClassInstanceDoc dataClassInstance); static SmartPtrCDataClassInstanceDoc fromString( const std::string defnObjectXmlStr); private: static void addDataClassSubInstance( const SmartPtrCDataClassSubInstanceDoc dataClassSubInstance, const SmartPtrCXmlElement thisXml); static SmartPtrCDataClassSubInstanceDoc parseDataClassSubInstance( const SmartPtrCXmlElement dataClassInstanceXml, const bool isDataClassInstance); static std::deque parseCmdlMetadata( const SmartPtrCXmlElement thisXml); static void addCmdlMetadata( const std::deque cmdlMetadataCollection, const SmartPtrCXmlElement thisXml); private: CAF_CM_DECLARE_NOCREATE(DefnObjectConverter); }; } #endif DocUtilsInc.h000066400000000000000000000010111321503522500345630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DocUtils_Inc_h_ #define DocUtils_Inc_h_ #include "Doc/DocUtils/EnumConvertersXml.h" #include "DefnObjectConverter.h" #include "ParameterUtils.h" #include "AttachmentUtils.h" #include "DocXmlUtils.h" #endif /* DocUtils_Inc_h_ */ DocUtilsLink.h000066400000000000000000000014461321503522500347630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef DocUtils_Link_h_ #define DocUtils_Link_h_ #ifndef DOCUTILS_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define DOCUTILS_LINKAGE __declspec(dllexport) #else #define DOCUTILS_LINKAGE __declspec(dllimport) #endif #else #define DOCUTILS_LINKAGE #endif #endif #include "Doc/DocUtils/EnumConvertersXml.h" #include "DefnObjectConverter.h" #include "ParameterUtils.h" #include "AttachmentUtils.h" #include "DocXmlUtils.h" #endif /* DocUtils_Link_h_ */ DocXmlUtils.cpp000066400000000000000000000023231321503522500351540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "DocXmlUtils.h" using namespace Caf; std::string DocXmlUtils::getSchemaNamespace( const std::string& relSchemaNamespace) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("DocXmlUtils", "getSchemaNamespace"); std::string schemaNamespace; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(relSchemaNamespace); const std::string schemaNamespaceRoot = AppConfigUtils::getRequiredString("schema_namespace_root"); const std::string pathDelim = "/"; schemaNamespace = schemaNamespaceRoot + pathDelim + relSchemaNamespace; } CAF_CM_EXIT; return schemaNamespace; } std::string DocXmlUtils::getSchemaLocation( const std::string& relSchemaLocation) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("DocXmlUtils", "getSchemaLocation"); std::string schemaLocation; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(relSchemaLocation); const std::string schemaLocationRoot = AppConfigUtils::getRequiredString("schema_location_root"); const std::string pathDelim = "/"; schemaLocation = schemaLocationRoot + pathDelim + relSchemaLocation; } CAF_CM_EXIT; return schemaLocation; } DocXmlUtils.h000066400000000000000000000006661321503522500346310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef DocXmlUtils_h_ #define DocXmlUtils_h_ namespace Caf { namespace DocXmlUtils { std::string DOCUTILS_LINKAGE getSchemaNamespace( const std::string& relSchemaNamespace); std::string DOCUTILS_LINKAGE getSchemaLocation( const std::string& relSchemaLocation); } } #endif EnumConvertersXml.cpp000066400000000000000000000352141321503522500364120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Exception/CCafException.h" using namespace Caf; std::string EnumConvertersXml::convertParameterTypeToString( const PARAMETER_TYPE parameterType) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertParameterTypeToString"); std::string rc; CAF_CM_ENTER { switch(parameterType) { case PARAMETER_NONE: CAF_CM_LOG_DEBUG_VA0("Parameter not set"); break; case PARAMETER_STRING: rc = "String"; break; case PARAMETER_SINT32: rc = "SInt32"; break; case PARAMETER_UINT32: rc = "UInt32"; break; case PARAMETER_SINT64: rc = "SInt64"; break; case PARAMETER_UINT64: rc = "UInt64"; break; case PARAMETER_DECIMAL: rc = "Decimal"; break; case PARAMETER_DOUBLE: rc = "Double"; break; case PARAMETER_BOOLEAN: rc = "Boolean"; break; case PARAMETER_DATETIME: rc = "DateTime"; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown parameter type - %d", static_cast(parameterType)); } } CAF_CM_EXIT; return rc; } PARAMETER_TYPE EnumConvertersXml::convertStringToParameterType( const std::string parameterType) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToParameterType"); PARAMETER_TYPE rc = PARAMETER_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterType); if (parameterType.compare("String") == 0) { rc = PARAMETER_STRING; } else if (parameterType.compare("SInt32") == 0) { rc = PARAMETER_SINT32; } else if (parameterType.compare("UInt32") == 0) { rc = PARAMETER_UINT32; } else if (parameterType.compare("SInt64") == 0) { rc = PARAMETER_SINT64; } else if (parameterType.compare("UInt64") == 0) { rc = PARAMETER_UINT64; } else if (parameterType.compare("Decimal") == 0) { rc = PARAMETER_DECIMAL; } else if (parameterType.compare("Double") == 0) { rc = PARAMETER_DOUBLE; } else if (parameterType.compare("Boolean") == 0) { rc = PARAMETER_BOOLEAN; } else if (parameterType.compare("DateTime") == 0) { rc = PARAMETER_DATETIME; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown parameter type - %s", parameterType.c_str()); } } CAF_CM_EXIT; return rc; } std::string EnumConvertersXml::convertPropertyTypeToString( const PROPERTY_TYPE propertyType) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertPropertyTypeToString"); std::string rc; CAF_CM_ENTER { switch(propertyType) { case PROPERTY_NONE: CAF_CM_LOG_DEBUG_VA0("Property not set"); break; case PROPERTY_STRING: rc = "String"; break; case PROPERTY_SINT32: rc = "SInt32"; break; case PROPERTY_UINT32: rc = "UInt32"; break; case PROPERTY_SINT64: rc = "SInt64"; break; case PROPERTY_UINT64: rc = "UInt64"; break; case PROPERTY_DECIMAL: rc = "Decimal"; break; case PROPERTY_DOUBLE: rc = "Double"; break; case PROPERTY_BOOLEAN: rc = "Boolean"; break; case PROPERTY_DATETIME: rc = "DateTime"; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown property type - %d", static_cast(propertyType)); } } CAF_CM_EXIT; return rc; } PROPERTY_TYPE EnumConvertersXml::convertStringToPropertyType( const std::string propertyType) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToPropertyType"); PROPERTY_TYPE rc = PROPERTY_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(propertyType); if (propertyType.compare("String") == 0) { rc = PROPERTY_STRING; } else if (propertyType.compare("SInt32") == 0) { rc = PROPERTY_SINT32; } else if (propertyType.compare("UInt32") == 0) { rc = PROPERTY_UINT32; } else if (propertyType.compare("SInt64") == 0) { rc = PROPERTY_SINT64; } else if (propertyType.compare("UInt64") == 0) { rc = PROPERTY_UINT64; } else if (propertyType.compare("Decimal") == 0) { rc = PROPERTY_DECIMAL; } else if (propertyType.compare("Double") == 0) { rc = PROPERTY_DOUBLE; } else if (propertyType.compare("Boolean") == 0) { rc = PROPERTY_BOOLEAN; } else if (propertyType.compare("DateTime") == 0) { rc = PROPERTY_DATETIME; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown property type - %s", propertyType.c_str()); } } CAF_CM_EXIT; return rc; } std::string EnumConvertersXml::convertValidatorTypeToString( const VALIDATOR_TYPE validatorType) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertValidatorTypeToString"); std::string rc; CAF_CM_ENTER { switch(validatorType) { case VALIDATOR_NONE: break; case VALIDATOR_ENUM: rc = "enum"; break; case VALIDATOR_RANGE: rc = "range"; break; case VALIDATOR_REGEX: rc = "regex"; break; case VALIDATOR_CUSTOM: rc = "custom"; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown validator type - %d", static_cast(validatorType)); } } CAF_CM_EXIT; return rc; } VALIDATOR_TYPE EnumConvertersXml::convertStringToValidatorType( const std::string validatorType) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToValidatorType"); VALIDATOR_TYPE rc = VALIDATOR_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(validatorType); if (validatorType.compare("enum") == 0) { rc = VALIDATOR_ENUM; } else if (validatorType.compare("range") == 0) { rc = VALIDATOR_RANGE; } else if (validatorType.compare("regex") == 0) { rc = VALIDATOR_REGEX; } else if (validatorType.compare("custom") == 0) { rc = VALIDATOR_CUSTOM; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown validator type - %s", validatorType.c_str()); } } CAF_CM_EXIT; return rc; } std::string EnumConvertersXml::convertOperatorTypeToString( const OPERATOR_TYPE operatorType) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertOperatorTypeToString"); std::string rc; CAF_CM_ENTER { switch(operatorType) { case OPERATOR_NONE: CAF_CM_LOG_DEBUG_VA0("Operator not set"); break; case OPERATOR_EQUAL: rc = "="; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown operator type - %d", static_cast(operatorType)); } } CAF_CM_EXIT; return rc; } OPERATOR_TYPE EnumConvertersXml::convertStringToOperatorType( const std::string operatorType) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToOperatorType"); OPERATOR_TYPE rc = OPERATOR_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(operatorType); if (operatorType.compare("=") == 0) { rc = OPERATOR_EQUAL; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown operator type - %s", operatorType.c_str()); } } CAF_CM_EXIT; return rc; } std::string EnumConvertersXml::convertArityTypeToString( const ARITY_TYPE arityType) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertArityTypeToString"); std::string rc; CAF_CM_ENTER { switch(arityType) { case ARITY_NONE: CAF_CM_LOG_DEBUG_VA0("Arity not set"); break; case ARITY_UNSIGNED_BYTE: rc = "2"; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown arity type - %d", static_cast(arityType)); } } CAF_CM_EXIT; return rc; } ARITY_TYPE EnumConvertersXml::convertStringToArityType( const std::string arityType) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToArityType"); ARITY_TYPE rc = ARITY_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(arityType); if (arityType.compare("2") == 0) { rc = ARITY_UNSIGNED_BYTE; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown arity type - %s", arityType.c_str()); } } CAF_CM_EXIT; return rc; } std::string EnumConvertersXml::convertPackageOSTypeToString( const PACKAGE_OS_TYPE packageOSType) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertPackageOSTypeToString"); std::string rc; CAF_CM_ENTER { switch(packageOSType) { case PACKAGE_OS_NONE: CAF_CM_LOG_DEBUG_VA0("Package OS not set"); break; case PACKAGE_OS_ALL: rc = "All"; break; case PACKAGE_OS_NIX: rc = "Nix"; break; case PACKAGE_OS_WIN: rc = "Win"; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown Package OS type - %d", static_cast(packageOSType)); } } CAF_CM_EXIT; return rc; } PACKAGE_OS_TYPE EnumConvertersXml::convertStringToPackageOSType( const std::string packageOSType) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToPackageOSType"); PACKAGE_OS_TYPE rc = PACKAGE_OS_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(packageOSType); if (packageOSType.compare("All") == 0) { rc = PACKAGE_OS_ALL; } else if (packageOSType.compare("Nix") == 0) { rc = PACKAGE_OS_NIX; } else if (packageOSType.compare("Win") == 0) { rc = PACKAGE_OS_WIN; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown Package OS type - %s", packageOSType.c_str()); } } CAF_CM_EXIT; return rc; } std::string EnumConvertersXml::convertLoggingLevelTypeToString( const LOGGINGLEVEL_TYPE loggingLevelType) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertLoggingLevelTypeToString"); std::string rc; CAF_CM_ENTER { switch(loggingLevelType) { case LOGGINGLEVEL_NONE: CAF_CM_LOG_DEBUG_VA0("Logging level not set"); break; case LOGGINGLEVEL_DEBUG: rc = "DEBUG"; break; case LOGGINGLEVEL_INFO: rc = "INFO"; break; case LOGGINGLEVEL_WARN: rc = "WARN"; break; case LOGGINGLEVEL_ERROR: rc = "ERROR"; break; case LOGGINGLEVEL_CRITICAL: rc = "CRITICAL"; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown logging level type - %d", static_cast(loggingLevelType)); } } CAF_CM_EXIT; return rc; } LOGGINGLEVEL_TYPE EnumConvertersXml::convertStringToLoggingLevelType( const std::string loggingLevelType) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToLoggingLevelType"); LOGGINGLEVEL_TYPE rc = LOGGINGLEVEL_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(loggingLevelType); if (loggingLevelType.compare("DEBUG") == 0) { rc = LOGGINGLEVEL_DEBUG; } else if (loggingLevelType.compare("INFO") == 0) { rc = LOGGINGLEVEL_INFO; } else if (loggingLevelType.compare("WARN") == 0) { rc = LOGGINGLEVEL_WARN; } else if (loggingLevelType.compare("ERROR") == 0) { rc = LOGGINGLEVEL_ERROR; } else if (loggingLevelType.compare("CRITICAL") == 0) { rc = LOGGINGLEVEL_CRITICAL; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown logging level type - %s", loggingLevelType.c_str()); } } CAF_CM_EXIT; return rc; } std::string EnumConvertersXml::convertLoggingComponentTypeToString( const LOGGINGCOMPONENT_TYPE loggingComponentType) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertLoggingComponentTypeToString"); std::string rc; CAF_CM_ENTER { switch(loggingComponentType) { case LOGGINGCOMPONENT_NONE: CAF_CM_LOG_DEBUG_VA0("Logging component not set"); break; case LOGGINGCOMPONENT_COMMUNICATIONS: rc = "Communications"; break; case LOGGINGCOMPONENT_MANAGEMENTAGENT: rc = "ManagementAgent"; break; case LOGGINGCOMPONENT_PROVIDERFRAMEWORK: rc = "ProviderFramework"; break; case LOGGINGCOMPONENT_PROVIDER: rc = "Provider"; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown logging component type - %d", static_cast(loggingComponentType)); } } CAF_CM_EXIT; return rc; } LOGGINGCOMPONENT_TYPE EnumConvertersXml::convertStringToLoggingComponentType( const std::string loggingComponentType) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToLoggingComponentType"); LOGGINGCOMPONENT_TYPE rc = LOGGINGCOMPONENT_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(loggingComponentType); if (loggingComponentType.compare("Communications") == 0) { rc = LOGGINGCOMPONENT_COMMUNICATIONS; } else if (loggingComponentType.compare("ManagementAgent") == 0) { rc = LOGGINGCOMPONENT_MANAGEMENTAGENT; } else if (loggingComponentType.compare("ProviderFramework") == 0) { rc = LOGGINGCOMPONENT_PROVIDERFRAMEWORK; } else if (loggingComponentType.compare("Provider") == 0) { rc = LOGGINGCOMPONENT_PROVIDER; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown logging component type - %s", loggingComponentType.c_str()); } } CAF_CM_EXIT; return rc; } std::string EnumConvertersXml::convertCmsPolicyToString( const CMS_POLICY cmsPolicy) { CAF_CM_STATIC_FUNC_LOG("EnumConvertersXml", "convertCmsPolicyToString"); std::string rc; CAF_CM_ENTER { switch(cmsPolicy) { case CMS_POLICY_NONE: rc = "None"; break; case CMS_POLICY_CAF_ENCRYPTED: rc = "CAF_Encrypted"; break; case CMS_POLICY_CAF_SIGNED: rc = "CAF_Signed"; break; case CMS_POLICY_CAF_ENCRYPTED_AND_SIGNED: rc = "CAF_Encrypted_And_Signed"; break; case CMS_POLICY_APP_ENCRYPTED: rc = "App_Encrypted"; break; case CMS_POLICY_APP_SIGNED: rc = "App_Signed"; break; case CMS_POLICY_APP_ENCRYPTED_AND_SIGNED: rc = "App_Encrypted_And_Signed"; break; default: CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown CMS Policy - %d", static_cast(cmsPolicy)); } } CAF_CM_EXIT; return rc; } CMS_POLICY EnumConvertersXml::convertStringToCmsPolicy( const std::string cmsPolicy) { CAF_CM_STATIC_FUNC("EnumConvertersXml", "convertStringToCmsPolicy"); CMS_POLICY rc = CMS_POLICY_NONE; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(cmsPolicy); if (cmsPolicy.compare("None") == 0) { rc = CMS_POLICY_NONE; } else if (cmsPolicy.compare("CAF_Encrypted") == 0) { rc = CMS_POLICY_CAF_ENCRYPTED; } else if (cmsPolicy.compare("CAF_Signed") == 0) { rc = CMS_POLICY_CAF_SIGNED; } else if (cmsPolicy.compare("CAF_Encrypted_And_Signed") == 0) { rc = CMS_POLICY_CAF_ENCRYPTED_AND_SIGNED; } else if (cmsPolicy.compare("App_Encrypted") == 0) { rc = CMS_POLICY_APP_ENCRYPTED; } else if (cmsPolicy.compare("App_Signed") == 0) { rc = CMS_POLICY_APP_SIGNED; } else if (cmsPolicy.compare("App_Encrypted_And_Signed") == 0) { rc = CMS_POLICY_APP_ENCRYPTED_AND_SIGNED; } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unknown CMS Policy - %s", cmsPolicy.c_str()); } } CAF_CM_EXIT; return rc; } ParameterUtils.cpp000066400000000000000000000244151321503522500357140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" #include "Exception/CCafException.h" #include "ParameterUtils.h" using namespace Caf; SmartPtrCRequestParameterDoc ParameterUtils::findOptionalParameter( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "findOptionalParameter"); SmartPtrCRequestParameterDoc parameterRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const std::deque parameterCollectionInner = parameterCollection->getParameter(); for (TConstIterator > parameterIter(parameterCollectionInner); parameterIter; parameterIter++) { const SmartPtrCRequestParameterDoc parameterTmp = *parameterIter; const std::string parameterNameTmp = parameterTmp->getName(); if (parameterNameTmp.compare(parameterName) == 0) { parameterRc = parameterTmp; } } } CAF_CM_EXIT; return parameterRc; } SmartPtrCRequestParameterDoc ParameterUtils::findRequiredParameter( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG("ParameterUtils", "findRequiredParameter"); SmartPtrCRequestParameterDoc parameterRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); parameterRc = findOptionalParameter(parameterName, parameterCollection); if (parameterRc.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Required parameter not found - %s", parameterName.c_str()); } } CAF_CM_EXIT; return parameterRc; } std::deque ParameterUtils::findOptionalParameterAsStringCollection( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "findOptionalParameterAsStringCollection"); std::deque parameterValueCollectionRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const SmartPtrCRequestParameterDoc parameter = findOptionalParameter(parameterName, parameterCollection); if (! parameter.IsNull()) { parameterValueCollectionRc = parameter->getValue(); } } CAF_CM_EXIT; return parameterValueCollectionRc; } std::deque ParameterUtils::findRequiredParameterAsStringCollection( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "findRequiredParameterAsStringCollection"); std::deque parameterValueCollectionRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const SmartPtrCRequestParameterDoc parameter = findRequiredParameter(parameterName, parameterCollection); parameterValueCollectionRc = parameter->getValue(); } CAF_CM_EXIT; return parameterValueCollectionRc; } std::string ParameterUtils::findOptionalParameterAsString( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "findOptionalParameterAsString"); std::string parameterValueRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const std::deque parameterValueCollection = findOptionalParameterAsStringCollection(parameterName, parameterCollection); if (parameterValueCollection.size() == 1) { parameterValueRc = parameterValueCollection.front(); } } CAF_CM_EXIT; return parameterValueRc; } std::string ParameterUtils::findRequiredParameterAsString( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG("ParameterUtils", "findRequiredParameterAsString"); std::string parameterValueRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const std::deque parameterValueCollection = findOptionalParameterAsStringCollection(parameterName, parameterCollection); if (parameterValueCollection.size() != 1) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Required string parameter not found - %s", parameterName.c_str()); } parameterValueRc = parameterValueCollection.front(); } CAF_CM_EXIT; return parameterValueRc; } SmartPtrCRequestInstanceParameterDoc ParameterUtils::findOptionalInstanceParameter( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "findOptionalInstanceParameter"); SmartPtrCRequestInstanceParameterDoc parameterRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const std::deque parameterCollectionInner = parameterCollection->getInstanceParameter(); for (TConstIterator > parameterIter(parameterCollectionInner); parameterIter; parameterIter++) { const SmartPtrCRequestInstanceParameterDoc parameterTmp = *parameterIter; const std::string parameterNameTmp = parameterTmp->getName(); if (parameterNameTmp.compare(parameterName) == 0) { parameterRc = parameterTmp; } } } CAF_CM_EXIT; return parameterRc; } SmartPtrCRequestInstanceParameterDoc ParameterUtils::findRequiredInstanceParameter( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG("ParameterUtils", "findRequiredInstanceParameter"); SmartPtrCRequestInstanceParameterDoc parameterRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); parameterRc = findOptionalInstanceParameter(parameterName, parameterCollection); if (parameterRc.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Required parameter not found - %s", parameterName.c_str()); } } CAF_CM_EXIT; return parameterRc; } std::deque ParameterUtils::findOptionalInstanceParameterAsStringCollection( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "findOptionalInstanceParameterAsStringCollection"); std::deque parameterValueCollectionRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const SmartPtrCRequestInstanceParameterDoc parameter = findOptionalInstanceParameter(parameterName, parameterCollection); if (! parameter.IsNull()) { parameterValueCollectionRc = parameter->getValue(); } } CAF_CM_EXIT; return parameterValueCollectionRc; } std::deque ParameterUtils::findRequiredInstanceParameterAsStringCollection( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "findRequiredInstanceParameterAsStringCollection"); std::deque parameterValueCollectionRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const SmartPtrCRequestInstanceParameterDoc parameter = findRequiredInstanceParameter(parameterName, parameterCollection); parameterValueCollectionRc = parameter->getValue(); } CAF_CM_EXIT; return parameterValueCollectionRc; } std::string ParameterUtils::findOptionalInstanceParameterAsString( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "findOptionalInstanceParameterAsString"); std::string parameterValueRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const std::deque parameterValueCollection = findOptionalInstanceParameterAsStringCollection(parameterName, parameterCollection); if (parameterValueCollection.size() == 1) { parameterValueRc = parameterValueCollection.front(); } } CAF_CM_EXIT; return parameterValueRc; } std::string ParameterUtils::findRequiredInstanceParameterAsString( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection) { CAF_CM_STATIC_FUNC_LOG("ParameterUtils", "findRequiredInstanceParameterAsString"); std::string parameterValueRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(parameterName); CAF_CM_VALIDATE_SMARTPTR(parameterCollection); const std::deque parameterValueCollection = findOptionalInstanceParameterAsStringCollection(parameterName, parameterCollection); if (parameterValueCollection.size() != 1) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Required string parameter not found - %s", parameterName.c_str()); } parameterValueRc = parameterValueCollection.front(); } CAF_CM_EXIT; return parameterValueRc; } SmartPtrCRequestParameterDoc ParameterUtils::createParameter( const std::string& name, const std::string& value) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "createParameter"); SmartPtrCRequestParameterDoc parameter; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(name); CAF_CM_VALIDATE_STRING(value); std::deque valueCollection; valueCollection.push_back(value); parameter.CreateInstance(); parameter->initialize( name, PARAMETER_STRING, valueCollection); } CAF_CM_EXIT; return parameter; } SmartPtrCRequestParameterDoc ParameterUtils::createParameter( const std::string& name, const std::deque& valueCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("ParameterUtils", "createParameter"); SmartPtrCRequestParameterDoc parameter; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(name); CAF_CM_VALIDATE_STL(valueCollection); parameter.CreateInstance(); parameter->initialize( name, PARAMETER_STRING, valueCollection); } CAF_CM_EXIT; return parameter; } ParameterUtils.h000066400000000000000000000053161321503522500353600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef ParameterUtils_h_ #define ParameterUtils_h_ #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" namespace Caf { class DOCUTILS_LINKAGE ParameterUtils { public: static SmartPtrCRequestParameterDoc findOptionalParameter( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static SmartPtrCRequestParameterDoc findRequiredParameter( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static std::deque findOptionalParameterAsStringCollection( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static std::deque findRequiredParameterAsStringCollection( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static std::string findOptionalParameterAsString( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static std::string findRequiredParameterAsString( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); public: static SmartPtrCRequestInstanceParameterDoc findOptionalInstanceParameter( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static SmartPtrCRequestInstanceParameterDoc findRequiredInstanceParameter( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static std::deque findOptionalInstanceParameterAsStringCollection( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static std::deque findRequiredInstanceParameterAsStringCollection( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static std::string findOptionalInstanceParameterAsString( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); static std::string findRequiredInstanceParameterAsString( const std::string& parameterName, const SmartPtrCParameterCollectionDoc& parameterCollection); public: static SmartPtrCRequestParameterDoc createParameter( const std::string& name, const std::string& value); static SmartPtrCRequestParameterDoc createParameter( const std::string& name, const std::deque& valueCollection); private: CAF_CM_DECLARE_NOCREATE(ParameterUtils); }; } #endif stdafx.h000066400000000000000000000006471321503522500337120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocUtils/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #include #include #include "DocUtilsLink.h" #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/000077500000000000000000000000001321503522500317605ustar00rootroot00000000000000CafCoreTypesXml/000077500000000000000000000000001321503522500347115ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlAddInCollectionXml.cpp000066400000000000000000000040131321503522500410670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAddInCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/AddInCollectionXml.h" using namespace Caf; void AddInCollectionXml::add( const SmartPtrCAddInCollectionDoc addInCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AddInCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(addInCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque addInVal = addInCollectionDoc->getAddInCollection(); CAF_CM_VALIDATE_STL(addInVal); if (! addInVal.empty()) { for (TConstIterator > addInIter(addInVal); addInIter; addInIter++) { const SmartPtrCXmlElement addInXml = thisXml->createAndAddElement("addIn"); addInXml->setValue(*addInIter); } } } CAF_CM_EXIT; } SmartPtrCAddInCollectionDoc AddInCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AddInCollectionXml", "parse"); SmartPtrCAddInCollectionDoc addInCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection addInChildrenXml = thisXml->findRequiredChildren("addIn"); std::deque addInVal; if (! addInChildrenXml.IsNull() && ! addInChildrenXml->empty()) { for (TConstIterator addInXmlIter(*addInChildrenXml); addInXmlIter; addInXmlIter++) { const SmartPtrCXmlElement addInXml = addInXmlIter->second; const std::string addInDoc = addInXml->getValue(); addInVal.push_back(addInDoc); } } addInCollectionDoc.CreateInstance(); addInCollectionDoc->initialize( addInVal); } CAF_CM_EXIT; return addInCollectionDoc; } AddInsXml.cpp000066400000000000000000000045341321503522500372460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAddInCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAddInsDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/AddInsXml.h" #include "Doc/DocXml/CafCoreTypesXml/AddInCollectionXml.h" using namespace Caf; void AddInsXml::add( const SmartPtrCAddInsDoc addInsDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AddInsXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(addInsDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque addInCollectionVal = addInsDoc->getAddInCollection(); CAF_CM_VALIDATE_STL(addInCollectionVal); if (! addInCollectionVal.empty()) { for (TConstIterator > addInCollectionIter(addInCollectionVal); addInCollectionIter; addInCollectionIter++) { const SmartPtrCXmlElement addInCollectionXml = thisXml->createAndAddElement("addInCollection"); AddInCollectionXml::add(*addInCollectionIter, addInCollectionXml); } } } CAF_CM_EXIT; } SmartPtrCAddInsDoc AddInsXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AddInsXml", "parse"); SmartPtrCAddInsDoc addInsDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection addInCollectionChildrenXml = thisXml->findRequiredChildren("addInCollection"); std::deque addInCollectionVal; if (! addInCollectionChildrenXml.IsNull() && ! addInCollectionChildrenXml->empty()) { for (TConstIterator addInCollectionXmlIter(*addInCollectionChildrenXml); addInCollectionXmlIter; addInCollectionXmlIter++) { const SmartPtrCXmlElement addInCollectionXml = addInCollectionXmlIter->second; const SmartPtrCAddInCollectionDoc addInCollectionDoc = AddInCollectionXml::parse(addInCollectionXml); addInCollectionVal.push_back(addInCollectionDoc); } } addInsDoc.CreateInstance(); addInsDoc->initialize( addInCollectionVal); } CAF_CM_EXIT; return addInsDoc; } AttachmentCollectionXml.cpp000066400000000000000000000045411321503522500422060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentXml.h" using namespace Caf; void AttachmentCollectionXml::add( const SmartPtrCAttachmentCollectionDoc attachmentCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AttachmentCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(attachmentCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque attachmentVal = attachmentCollectionDoc->getAttachment(); if (! attachmentVal.empty()) { for (TConstIterator > attachmentIter(attachmentVal); attachmentIter; attachmentIter++) { const SmartPtrCXmlElement attachmentXml = thisXml->createAndAddElement("attachment"); AttachmentXml::add(*attachmentIter, attachmentXml); } } } CAF_CM_EXIT; } SmartPtrCAttachmentCollectionDoc AttachmentCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AttachmentCollectionXml", "parse"); SmartPtrCAttachmentCollectionDoc attachmentCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection attachmentChildrenXml = thisXml->findOptionalChildren("attachment"); std::deque attachmentVal; if (! attachmentChildrenXml.IsNull() && ! attachmentChildrenXml->empty()) { for (TConstIterator attachmentXmlIter(*attachmentChildrenXml); attachmentXmlIter; attachmentXmlIter++) { const SmartPtrCXmlElement attachmentXml = attachmentXmlIter->second; const SmartPtrCAttachmentDoc attachmentDoc = AttachmentXml::parse(attachmentXml); attachmentVal.push_back(attachmentDoc); } } attachmentCollectionDoc.CreateInstance(); attachmentCollectionDoc->initialize( attachmentVal); } CAF_CM_EXIT; return attachmentCollectionDoc; } AttachmentNameCollectionXml.cpp000066400000000000000000000042421321503522500430050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentNameCollectionXml.h" using namespace Caf; void AttachmentNameCollectionXml::add( const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AttachmentNameCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(attachmentNameCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque nameVal = attachmentNameCollectionDoc->getName(); CAF_CM_VALIDATE_STL(nameVal); if (! nameVal.empty()) { for (TConstIterator > nameIter(nameVal); nameIter; nameIter++) { const SmartPtrCXmlElement nameXml = thisXml->createAndAddElement("attachmentName"); nameXml->addAttribute("name", *nameIter); } } } CAF_CM_EXIT; } SmartPtrCAttachmentNameCollectionDoc AttachmentNameCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AttachmentNameCollectionXml", "parse"); SmartPtrCAttachmentNameCollectionDoc attachmentNameCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection nameChildrenXml = thisXml->findRequiredChildren("attachmentName"); std::deque nameVal; if (! nameChildrenXml.IsNull() && ! nameChildrenXml->empty()) { for (TConstIterator nameXmlIter(*nameChildrenXml); nameXmlIter; nameXmlIter++) { const SmartPtrCXmlElement nameXml = nameXmlIter->second; const std::string name = nameXml->findRequiredAttribute("name"); nameVal.push_back(name); } } attachmentNameCollectionDoc.CreateInstance(); attachmentNameCollectionDoc->initialize( nameVal); } CAF_CM_EXIT; return attachmentNameCollectionDoc; } AttachmentXml.cpp000066400000000000000000000054271321503522500401760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentXml.h" using namespace Caf; void AttachmentXml::add( const SmartPtrCAttachmentDoc attachmentDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AttachmentXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(attachmentDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = attachmentDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string typeVal = attachmentDoc->getType(); CAF_CM_VALIDATE_STRING(typeVal); thisXml->addAttribute("type", typeVal); const std::string uriVal = attachmentDoc->getUri(); CAF_CM_VALIDATE_STRING(uriVal); thisXml->addAttribute("uri", uriVal); const std::string isReferenceVal = attachmentDoc->getIsReference() ? "true" : "false"; CAF_CM_VALIDATE_STRING(isReferenceVal); thisXml->addAttribute("isReference", isReferenceVal); const CMS_POLICY cmsPolicyVal = attachmentDoc->getCmsPolicy(); thisXml->addAttribute("cmsPolicy", EnumConvertersXml::convertCmsPolicyToString(cmsPolicyVal)); } CAF_CM_EXIT; } SmartPtrCAttachmentDoc AttachmentXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AttachmentXml", "parse"); SmartPtrCAttachmentDoc attachmentDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string typeStrVal = thisXml->findRequiredAttribute("type"); const std::string typeVal = typeStrVal; const std::string uriStrVal = thisXml->findRequiredAttribute("uri"); const std::string uriVal = uriStrVal; const std::string isReferenceStrVal = thisXml->findRequiredAttribute("isReference"); bool isReferenceVal = false; if (! isReferenceStrVal.empty()) { isReferenceVal = (isReferenceStrVal.compare("true") == 0) ? true : false; } CMS_POLICY cmsPolicyVal = CMS_POLICY_NONE; const std::string cmsPolicyStr = thisXml->findOptionalAttribute("cmsPolicy"); if (! cmsPolicyStr.empty()) { cmsPolicyVal = EnumConvertersXml::convertStringToCmsPolicy(cmsPolicyStr); } attachmentDoc.CreateInstance(); attachmentDoc->initialize( nameVal, typeVal, uriVal, isReferenceVal, cmsPolicyVal); } CAF_CM_EXIT; return attachmentDoc; } AuthnAuthzCollectionXml.cpp000066400000000000000000000046101321503522500422060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/AuthnAuthzCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/AuthnAuthzXml.h" using namespace Caf; void AuthnAuthzCollectionXml::add( const SmartPtrCAuthnAuthzCollectionDoc authnAuthzCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AuthnAuthzCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(authnAuthzCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque authnAuthzVal = authnAuthzCollectionDoc->getAuthnAuthz(); CAF_CM_VALIDATE_STL(authnAuthzVal); if (! authnAuthzVal.empty()) { for (TConstIterator > authnAuthzIter(authnAuthzVal); authnAuthzIter; authnAuthzIter++) { const SmartPtrCXmlElement authnAuthzXml = thisXml->createAndAddElement("authnAuthz"); AuthnAuthzXml::add(*authnAuthzIter, authnAuthzXml); } } } CAF_CM_EXIT; } SmartPtrCAuthnAuthzCollectionDoc AuthnAuthzCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AuthnAuthzCollectionXml", "parse"); SmartPtrCAuthnAuthzCollectionDoc authnAuthzCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection authnAuthzChildrenXml = thisXml->findRequiredChildren("authnAuthz"); std::deque authnAuthzVal; if (! authnAuthzChildrenXml.IsNull() && ! authnAuthzChildrenXml->empty()) { for (TConstIterator authnAuthzXmlIter(*authnAuthzChildrenXml); authnAuthzXmlIter; authnAuthzXmlIter++) { const SmartPtrCXmlElement authnAuthzXml = authnAuthzXmlIter->second; const SmartPtrCAuthnAuthzDoc authnAuthzDoc = AuthnAuthzXml::parse(authnAuthzXml); authnAuthzVal.push_back(authnAuthzDoc); } } authnAuthzCollectionDoc.CreateInstance(); authnAuthzCollectionDoc->initialize( authnAuthzVal); } CAF_CM_EXIT; return authnAuthzCollectionDoc; } AuthnAuthzXml.cpp000066400000000000000000000044141321503522500401740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/AuthnAuthzXml.h" using namespace Caf; void AuthnAuthzXml::add( const SmartPtrCAuthnAuthzDoc authnAuthzDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AuthnAuthzXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(authnAuthzDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string typeVal = authnAuthzDoc->getType(); CAF_CM_VALIDATE_STRING(typeVal); thisXml->addAttribute("type", typeVal); const std::string valueVal = authnAuthzDoc->getValue(); CAF_CM_VALIDATE_STRING(valueVal); const SmartPtrCXmlElement valueXml = thisXml->createAndAddElement("value"); valueXml->setValue(valueVal); const std::string nameVal = authnAuthzDoc->getName(); if (! nameVal.empty()) { thisXml->addAttribute("name", nameVal); } const std::string sequenceNumberVal = CStringConv::toString(authnAuthzDoc->getSequenceNumber()); if (! sequenceNumberVal.empty()) { thisXml->addAttribute("sequenceNumber", sequenceNumberVal); } } CAF_CM_EXIT; } SmartPtrCAuthnAuthzDoc AuthnAuthzXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("AuthnAuthzXml", "parse"); SmartPtrCAuthnAuthzDoc authnAuthzDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string typeVal = thisXml->findRequiredAttribute("type"); const std::string valueVal = thisXml->findRequiredChild("value")->getValue(); const std::string nameVal = thisXml->findOptionalAttribute("name"); const std::string sequenceNumberStrVal = thisXml->findOptionalAttribute("sequenceNumber"); int32 sequenceNumberVal = 0; if (! sequenceNumberStrVal.empty()) { sequenceNumberVal = CStringConv::fromString(sequenceNumberStrVal); } authnAuthzDoc.CreateInstance(); authnAuthzDoc->initialize( typeVal, valueVal, nameVal, sequenceNumberVal); } CAF_CM_EXIT; return authnAuthzDoc; } ClassFiltersXml.cpp000066400000000000000000000046421321503522500405020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CClassFiltersDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/ClassFiltersXml.h" using namespace Caf; void ClassFiltersXml::add( const SmartPtrCClassFiltersDoc classFiltersDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassFiltersXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(classFiltersDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string dialectVal = classFiltersDoc->getDialect(); CAF_CM_VALIDATE_STRING(dialectVal); thisXml->addAttribute("dialect", dialectVal); const std::deque classFilterVal = classFiltersDoc->getClassFilter(); CAF_CM_VALIDATE_STL(classFilterVal); if (! classFilterVal.empty()) { for (TConstIterator > classFilterIter(classFilterVal); classFilterIter; classFilterIter++) { const SmartPtrCXmlElement classFilterXml = thisXml->createAndAddElement("classFilter"); classFilterXml->setValue(*classFilterIter); } } } CAF_CM_EXIT; } SmartPtrCClassFiltersDoc ClassFiltersXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassFiltersXml", "parse"); SmartPtrCClassFiltersDoc classFiltersDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string dialectStrVal = thisXml->findRequiredAttribute("dialect"); const std::string dialectVal = dialectStrVal; const CXmlElement::SmartPtrCElementCollection classFilterChildrenXml = thisXml->findRequiredChildren("classFilter"); std::deque classFilterVal; if (! classFilterChildrenXml.IsNull() && ! classFilterChildrenXml->empty()) { for (TConstIterator classFilterXmlIter(*classFilterChildrenXml); classFilterXmlIter; classFilterXmlIter++) { const SmartPtrCXmlElement classFilterXml = classFilterXmlIter->second; const std::string classFilterDoc = classFilterXml->getValue(); classFilterVal.push_back(classFilterDoc); } } classFiltersDoc.CreateInstance(); classFiltersDoc->initialize( dialectVal, classFilterVal); } CAF_CM_EXIT; return classFiltersDoc; } ClassSpecifierXml.cpp000066400000000000000000000051061321503522500407770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CClassFiltersDoc.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/ClassSpecifierXml.h" #include "Doc/DocXml/CafCoreTypesXml/FullyQualifiedClassGroupXml.h" #include "Doc/DocXml/CafCoreTypesXml/ClassFiltersXml.h" using namespace Caf; void ClassSpecifierXml::add( const SmartPtrCClassSpecifierDoc classSpecifierDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassSpecifierXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(classSpecifierDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClassVal = classSpecifierDoc->getFullyQualifiedClass(); if (! fullyQualifiedClassVal.IsNull()) { const SmartPtrCXmlElement fullyQualifiedClassXml = thisXml->createAndAddElement("fullyQualifiedClass"); FullyQualifiedClassGroupXml::add(fullyQualifiedClassVal, fullyQualifiedClassXml); } const SmartPtrCClassFiltersDoc classFiltersVal = classSpecifierDoc->getClassFilters(); if (! classFiltersVal.IsNull()) { const SmartPtrCXmlElement classFiltersXml = thisXml->createAndAddElement("classFilters"); ClassFiltersXml::add(classFiltersVal, classFiltersXml); } } CAF_CM_EXIT; } SmartPtrCClassSpecifierDoc ClassSpecifierXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassSpecifierXml", "parse"); SmartPtrCClassSpecifierDoc classSpecifierDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement fullyQualifiedClassXml = thisXml->findOptionalChild("fullyQualifiedClass"); SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClassVal; if (! fullyQualifiedClassXml.IsNull()) { fullyQualifiedClassVal = FullyQualifiedClassGroupXml::parse(fullyQualifiedClassXml); } const SmartPtrCXmlElement classFiltersXml = thisXml->findOptionalChild("classFilters"); SmartPtrCClassFiltersDoc classFiltersVal; if (! classFiltersXml.IsNull()) { classFiltersVal = ClassFiltersXml::parse(classFiltersXml); } classSpecifierDoc.CreateInstance(); classSpecifierDoc->initialize( fullyQualifiedClassVal, classFiltersVal); } CAF_CM_EXIT; return classSpecifierDoc; } FullyQualifiedClassGroupXml.cpp000066400000000000000000000044751321503522500430320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/FullyQualifiedClassGroupXml.h" using namespace Caf; void FullyQualifiedClassGroupXml::add( const SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClassGroupDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("FullyQualifiedClassGroupXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(fullyQualifiedClassGroupDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceVal = fullyQualifiedClassGroupDoc->getClassNamespace(); CAF_CM_VALIDATE_STRING(classNamespaceVal); thisXml->addAttribute("classNamespace", classNamespaceVal); const std::string classNameVal = fullyQualifiedClassGroupDoc->getClassName(); CAF_CM_VALIDATE_STRING(classNameVal); thisXml->addAttribute("className", classNameVal); const std::string classVersionVal = fullyQualifiedClassGroupDoc->getClassVersion(); CAF_CM_VALIDATE_STRING(classVersionVal); thisXml->addAttribute("classVersion", classVersionVal); } CAF_CM_EXIT; } SmartPtrCFullyQualifiedClassGroupDoc FullyQualifiedClassGroupXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("FullyQualifiedClassGroupXml", "parse"); SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClassGroupDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceStrVal = thisXml->findRequiredAttribute("classNamespace"); const std::string classNamespaceVal = classNamespaceStrVal; const std::string classNameStrVal = thisXml->findRequiredAttribute("className"); const std::string classNameVal = classNameStrVal; const std::string classVersionStrVal = thisXml->findRequiredAttribute("classVersion"); const std::string classVersionVal = classVersionStrVal; fullyQualifiedClassGroupDoc.CreateInstance(); fullyQualifiedClassGroupDoc->initialize( classNamespaceVal, classNameVal, classVersionVal); } CAF_CM_EXIT; return fullyQualifiedClassGroupDoc; } LoggingLevelCollectionXml.cpp000066400000000000000000000050201321503522500424650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelElemDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/LoggingLevelCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/LoggingLevelElemXml.h" using namespace Caf; void LoggingLevelCollectionXml::add( const SmartPtrCLoggingLevelCollectionDoc loggingLevelCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("LoggingLevelCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(loggingLevelCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque loggingLevelVal = loggingLevelCollectionDoc->getLoggingLevel(); CAF_CM_VALIDATE_STL(loggingLevelVal); if (! loggingLevelVal.empty()) { for (TConstIterator > loggingLevelIter(loggingLevelVal); loggingLevelIter; loggingLevelIter++) { const SmartPtrCXmlElement loggingLevelXml = thisXml->createAndAddElement("loggingLevel"); LoggingLevelElemXml::add(*loggingLevelIter, loggingLevelXml); } } } CAF_CM_EXIT; } SmartPtrCLoggingLevelCollectionDoc LoggingLevelCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("LoggingLevelCollectionXml", "parse"); SmartPtrCLoggingLevelCollectionDoc loggingLevelCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection loggingLevelChildrenXml = thisXml->findRequiredChildren("loggingLevel"); std::deque loggingLevelVal; if (! loggingLevelChildrenXml.IsNull() && ! loggingLevelChildrenXml->empty()) { for (TConstIterator loggingLevelXmlIter(*loggingLevelChildrenXml); loggingLevelXmlIter; loggingLevelXmlIter++) { const SmartPtrCXmlElement loggingLevelXml = loggingLevelXmlIter->second; const SmartPtrCLoggingLevelElemDoc loggingLevelDoc = LoggingLevelElemXml::parse(loggingLevelXml); loggingLevelVal.push_back(loggingLevelDoc); } } loggingLevelCollectionDoc.CreateInstance(); loggingLevelCollectionDoc->initialize( loggingLevelVal); } CAF_CM_EXIT; return loggingLevelCollectionDoc; } LoggingLevelElemXml.cpp000066400000000000000000000043151321503522500412620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelElemDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/LoggingLevelElemXml.h" using namespace Caf; void LoggingLevelElemXml::add( const SmartPtrCLoggingLevelElemDoc loggingLevelElemDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("LoggingLevelElemXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(loggingLevelElemDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string componentVal = EnumConvertersXml::convertLoggingComponentTypeToString(loggingLevelElemDoc->getComponent()); CAF_CM_VALIDATE_STRING(componentVal); thisXml->addAttribute("component", componentVal); const std::string levelVal = EnumConvertersXml::convertLoggingLevelTypeToString(loggingLevelElemDoc->getLevel()); CAF_CM_VALIDATE_STRING(levelVal); thisXml->addAttribute("level", levelVal); } CAF_CM_EXIT; } SmartPtrCLoggingLevelElemDoc LoggingLevelElemXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("LoggingLevelElemXml", "parse"); SmartPtrCLoggingLevelElemDoc loggingLevelElemDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string componentStrVal = thisXml->findRequiredAttribute("component"); LOGGINGCOMPONENT_TYPE componentVal = LOGGINGCOMPONENT_NONE; if (! componentStrVal.empty()) { componentVal = EnumConvertersXml::convertStringToLoggingComponentType(componentStrVal); } const std::string levelStrVal = thisXml->findRequiredAttribute("level"); LOGGINGLEVEL_TYPE levelVal = LOGGINGLEVEL_NONE; if (! levelStrVal.empty()) { levelVal = EnumConvertersXml::convertStringToLoggingLevelType(levelStrVal); } loggingLevelElemDoc.CreateInstance(); loggingLevelElemDoc->initialize( componentVal, levelVal); } CAF_CM_EXIT; return loggingLevelElemDoc; } OperationXml.cpp000066400000000000000000000041201321503522500400330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/OperationXml.h" #include "Doc/DocXml/CafCoreTypesXml/ParameterCollectionXml.h" using namespace Caf; void OperationXml::add( const SmartPtrCOperationDoc operationDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("OperationXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(operationDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = operationDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const SmartPtrCParameterCollectionDoc parameterCollectionVal = operationDoc->getParameterCollection(); if (! parameterCollectionVal.IsNull()) { const SmartPtrCXmlElement parameterCollectionXml = thisXml->createAndAddElement("parameterCollection"); ParameterCollectionXml::add(parameterCollectionVal, parameterCollectionXml); } } CAF_CM_EXIT; } SmartPtrCOperationDoc OperationXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("OperationXml", "parse"); SmartPtrCOperationDoc operationDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const SmartPtrCXmlElement parameterCollectionXml = thisXml->findOptionalChild("parameterCollection"); SmartPtrCParameterCollectionDoc parameterCollectionVal; if (! parameterCollectionXml.IsNull()) { parameterCollectionVal = ParameterCollectionXml::parse(parameterCollectionXml); } operationDoc.CreateInstance(); operationDoc->initialize( nameVal, parameterCollectionVal); } CAF_CM_EXIT; return operationDoc; } ParameterCollectionXml.cpp000066400000000000000000000075311321503522500420400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/ParameterCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/RequestParameterXml.h" #include "Doc/DocXml/CafCoreTypesXml/RequestInstanceParameterXml.h" #include "Doc/DocXml/CafCoreTypesXml/RequestParameterXml.h" using namespace Caf; void ParameterCollectionXml::add( const SmartPtrCParameterCollectionDoc parameterCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ParameterCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(parameterCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque parameterVal = parameterCollectionDoc->getParameter(); if (! parameterVal.empty()) { for (TConstIterator > parameterIter(parameterVal); parameterIter; parameterIter++) { const SmartPtrCXmlElement parameterXml = thisXml->createAndAddElement("parameter"); RequestParameterXml::add(*parameterIter, parameterXml); } } const std::deque instanceParameterVal = parameterCollectionDoc->getInstanceParameter(); if (! instanceParameterVal.empty()) { for (TConstIterator > instanceParameterIter(instanceParameterVal); instanceParameterIter; instanceParameterIter++) { const SmartPtrCXmlElement instanceParameterXml = thisXml->createAndAddElement("instanceParameter"); RequestInstanceParameterXml::add(*instanceParameterIter, instanceParameterXml); } } } CAF_CM_EXIT; } SmartPtrCParameterCollectionDoc ParameterCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ParameterCollectionXml", "parse"); SmartPtrCParameterCollectionDoc parameterCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection parameterChildrenXml = thisXml->findOptionalChildren("parameter"); std::deque parameterVal; if (! parameterChildrenXml.IsNull() && ! parameterChildrenXml->empty()) { for (TConstIterator parameterXmlIter(*parameterChildrenXml); parameterXmlIter; parameterXmlIter++) { const SmartPtrCXmlElement parameterXml = parameterXmlIter->second; const SmartPtrCRequestParameterDoc parameterDoc = RequestParameterXml::parse(parameterXml); parameterVal.push_back(parameterDoc); } } const CXmlElement::SmartPtrCElementCollection instanceParameterChildrenXml = thisXml->findOptionalChildren("instanceParameter"); std::deque instanceParameterVal; if (! instanceParameterChildrenXml.IsNull() && ! instanceParameterChildrenXml->empty()) { for (TConstIterator instanceParameterXmlIter(*instanceParameterChildrenXml); instanceParameterXmlIter; instanceParameterXmlIter++) { const SmartPtrCXmlElement instanceParameterXml = instanceParameterXmlIter->second; const SmartPtrCRequestInstanceParameterDoc instanceParameterDoc = RequestInstanceParameterXml::parse(instanceParameterXml); instanceParameterVal.push_back(instanceParameterDoc); } } parameterCollectionDoc.CreateInstance(); parameterCollectionDoc->initialize( parameterVal, instanceParameterVal); } CAF_CM_EXIT; return parameterCollectionDoc; } PropertyCollectionXml.cpp000066400000000000000000000044401321503522500417400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/PropertyCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/PropertyXml.h" using namespace Caf; void PropertyCollectionXml::add( const SmartPtrCPropertyCollectionDoc propertyCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PropertyCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(propertyCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque propertyVal = propertyCollectionDoc->getProperty(); CAF_CM_VALIDATE_STL(propertyVal); if (! propertyVal.empty()) { for (TConstIterator > propertyIter(propertyVal); propertyIter; propertyIter++) { const SmartPtrCXmlElement propertyXml = thisXml->createAndAddElement("property"); PropertyXml::add(*propertyIter, propertyXml); } } } CAF_CM_EXIT; } SmartPtrCPropertyCollectionDoc PropertyCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PropertyCollectionXml", "parse"); SmartPtrCPropertyCollectionDoc propertyCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection propertyChildrenXml = thisXml->findRequiredChildren("property"); std::deque propertyVal; if (! propertyChildrenXml.IsNull() && ! propertyChildrenXml->empty()) { for (TConstIterator propertyXmlIter(*propertyChildrenXml); propertyXmlIter; propertyXmlIter++) { const SmartPtrCXmlElement propertyXml = propertyXmlIter->second; const SmartPtrCPropertyDoc propertyDoc = PropertyXml::parse(propertyXml); propertyVal.push_back(propertyDoc); } } propertyCollectionDoc.CreateInstance(); propertyCollectionDoc->initialize( propertyVal); } CAF_CM_EXIT; return propertyCollectionDoc; } PropertyXml.cpp000066400000000000000000000052371321503522500377310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/PropertyXml.h" using namespace Caf; void PropertyXml::add( const SmartPtrCPropertyDoc propertyDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PropertyXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(propertyDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = propertyDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string typeVal = EnumConvertersXml::convertPropertyTypeToString(propertyDoc->getType()); CAF_CM_VALIDATE_STRING(typeVal); thisXml->addAttribute("type", typeVal); const std::deque valueVal = propertyDoc->getValue(); CAF_CM_VALIDATE_STL(valueVal); if (! valueVal.empty()) { for (TConstIterator > valueIter(valueVal); valueIter; valueIter++) { const SmartPtrCXmlElement valueXml = thisXml->createAndAddElement("value"); valueXml->setValue(*valueIter); } } } CAF_CM_EXIT; } SmartPtrCPropertyDoc PropertyXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PropertyXml", "parse"); SmartPtrCPropertyDoc propertyDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string typeStrVal = thisXml->findRequiredAttribute("type"); PROPERTY_TYPE typeVal = PROPERTY_NONE; if (! typeStrVal.empty()) { typeVal = EnumConvertersXml::convertStringToPropertyType(typeStrVal); } const CXmlElement::SmartPtrCElementCollection valueChildrenXml = thisXml->findRequiredChildren("value"); std::deque valueVal; if (! valueChildrenXml.IsNull() && ! valueChildrenXml->empty()) { for (TConstIterator valueXmlIter(*valueChildrenXml); valueXmlIter; valueXmlIter++) { const SmartPtrCXmlElement valueXml = valueXmlIter->second; const std::string valueDoc = valueXml->getValue(); valueVal.push_back(valueDoc); } } propertyDoc.CreateInstance(); propertyDoc->initialize( nameVal, typeVal, valueVal); } CAF_CM_EXIT; return propertyDoc; } ProtocolCollectionXml.cpp000066400000000000000000000044401321503522500417150ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/ProtocolCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/ProtocolXml.h" using namespace Caf; void ProtocolCollectionXml::add( const SmartPtrCProtocolCollectionDoc protocolCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProtocolCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(protocolCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque protocolVal = protocolCollectionDoc->getProtocol(); CAF_CM_VALIDATE_STL(protocolVal); if (! protocolVal.empty()) { for (TConstIterator > protocolIter(protocolVal); protocolIter; protocolIter++) { const SmartPtrCXmlElement protocolXml = thisXml->createAndAddElement("protocol"); ProtocolXml::add(*protocolIter, protocolXml); } } } CAF_CM_EXIT; } SmartPtrCProtocolCollectionDoc ProtocolCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProtocolCollectionXml", "parse"); SmartPtrCProtocolCollectionDoc protocolCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection protocolChildrenXml = thisXml->findRequiredChildren("protocol"); std::deque protocolVal; if (! protocolChildrenXml.IsNull() && ! protocolChildrenXml->empty()) { for (TConstIterator protocolXmlIter(*protocolChildrenXml); protocolXmlIter; protocolXmlIter++) { const SmartPtrCXmlElement protocolXml = protocolXmlIter->second; const SmartPtrCProtocolDoc protocolDoc = ProtocolXml::parse(protocolXml); protocolVal.push_back(protocolDoc); } } protocolCollectionDoc.CreateInstance(); protocolCollectionDoc->initialize( protocolVal); } CAF_CM_EXIT; return protocolCollectionDoc; } ProtocolXml.cpp000066400000000000000000000036561321503522500377110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CProtocolDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/ProtocolXml.h" using namespace Caf; void ProtocolXml::add( const SmartPtrCProtocolDoc protocolDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProtocolXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(protocolDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string uriVal = protocolDoc->getUri(); CAF_CM_VALIDATE_STRING(uriVal); thisXml->addAttribute("uri", uriVal); const std::string nameVal = protocolDoc->getName(); if (! nameVal.empty()) { thisXml->addAttribute("name", nameVal); } const std::string sequenceNumberVal = CStringConv::toString(protocolDoc->getSequenceNumber()); if (! sequenceNumberVal.empty()) { thisXml->addAttribute("sequenceNumber", sequenceNumberVal); } } CAF_CM_EXIT; } SmartPtrCProtocolDoc ProtocolXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProtocolXml", "parse"); SmartPtrCProtocolDoc protocolDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string uriVal = thisXml->findRequiredAttribute("uri"); const std::string nameVal = thisXml->findOptionalAttribute("name"); const std::string sequenceNumberStrVal = thisXml->findOptionalAttribute("sequenceNumber"); int32 sequenceNumberVal = 0; if (! sequenceNumberStrVal.empty()) { sequenceNumberVal = CStringConv::fromString(sequenceNumberStrVal); } protocolDoc.CreateInstance(); protocolDoc->initialize( uriVal, nameVal, sequenceNumberVal); } CAF_CM_EXIT; return protocolDoc; } RequestConfigXml.cpp000066400000000000000000000073721321503522500406650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAddInsDoc.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestConfigDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/RequestConfigXml.h" #include "Doc/DocXml/CafCoreTypesXml/AddInsXml.h" #include "Doc/DocXml/CafCoreTypesXml/LoggingLevelCollectionXml.h" using namespace Caf; void RequestConfigXml::add( const SmartPtrCRequestConfigDoc requestConfigDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestConfigXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(requestConfigDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string responseFormatTypeVal = requestConfigDoc->getResponseFormatType(); CAF_CM_VALIDATE_STRING(responseFormatTypeVal); thisXml->addAttribute("responseFormatType", responseFormatTypeVal); const SmartPtrCAddInsDoc requestProcessorAddInsVal = requestConfigDoc->getRequestProcessorAddIns(); if (! requestProcessorAddInsVal.IsNull()) { const SmartPtrCXmlElement requestProcessorAddInsXml = thisXml->createAndAddElement("requestProcessorAddIns"); AddInsXml::add(requestProcessorAddInsVal, requestProcessorAddInsXml); } const SmartPtrCAddInsDoc responseProcessorAddInsVal = requestConfigDoc->getResponseProcessorAddIns(); if (! responseProcessorAddInsVal.IsNull()) { const SmartPtrCXmlElement responseProcessorAddInsXml = thisXml->createAndAddElement("responseProcessorAddIns"); AddInsXml::add(responseProcessorAddInsVal, responseProcessorAddInsXml); } const SmartPtrCLoggingLevelCollectionDoc loggingLevelCollectionVal = requestConfigDoc->getLoggingLevelCollection(); if (! loggingLevelCollectionVal.IsNull()) { const SmartPtrCXmlElement loggingLevelCollectionXml = thisXml->createAndAddElement("loggingLevelCollection"); LoggingLevelCollectionXml::add(loggingLevelCollectionVal, loggingLevelCollectionXml); } } CAF_CM_EXIT; } SmartPtrCRequestConfigDoc RequestConfigXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestConfigXml", "parse"); SmartPtrCRequestConfigDoc requestConfigDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string responseFormatTypeStrVal = thisXml->findRequiredAttribute("responseFormatType"); const std::string responseFormatTypeVal = responseFormatTypeStrVal; const SmartPtrCXmlElement requestProcessorAddInsXml = thisXml->findOptionalChild("requestProcessorAddIns"); SmartPtrCAddInsDoc requestProcessorAddInsVal; if (! requestProcessorAddInsXml.IsNull()) { requestProcessorAddInsVal = AddInsXml::parse(requestProcessorAddInsXml); } const SmartPtrCXmlElement responseProcessorAddInsXml = thisXml->findOptionalChild("responseProcessorAddIns"); SmartPtrCAddInsDoc responseProcessorAddInsVal; if (! responseProcessorAddInsXml.IsNull()) { responseProcessorAddInsVal = AddInsXml::parse(responseProcessorAddInsXml); } const SmartPtrCXmlElement loggingLevelCollectionXml = thisXml->findOptionalChild("loggingLevelCollection"); SmartPtrCLoggingLevelCollectionDoc loggingLevelCollectionVal; if (! loggingLevelCollectionXml.IsNull()) { loggingLevelCollectionVal = LoggingLevelCollectionXml::parse(loggingLevelCollectionXml); } requestConfigDoc.CreateInstance(); requestConfigDoc->initialize( responseFormatTypeVal, requestProcessorAddInsVal, responseProcessorAddInsVal, loggingLevelCollectionVal); } CAF_CM_EXIT; return requestConfigDoc; } RequestHeaderXml.cpp000066400000000000000000000120241321503522500406360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestConfigDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/RequestHeaderXml.h" #include "Doc/DocXml/CafCoreTypesXml/RequestConfigXml.h" #include "Doc/DocXml/CafCoreTypesXml/AuthnAuthzCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/ProtocolCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/PropertyCollectionXml.h" using namespace Caf; void RequestHeaderXml::add( const SmartPtrCRequestHeaderDoc requestHeaderDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestHeaderXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(requestHeaderDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCRequestConfigDoc requestConfigVal = requestHeaderDoc->getRequestConfig(); CAF_CM_VALIDATE_SMARTPTR(requestConfigVal); const SmartPtrCXmlElement requestConfigXml = thisXml->createAndAddElement("requestConfig"); RequestConfigXml::add(requestConfigVal, requestConfigXml); const SmartPtrCAuthnAuthzCollectionDoc authnAuthzCollectionVal = requestHeaderDoc->getAuthnAuthzCollection(); if (! authnAuthzCollectionVal.IsNull()) { const SmartPtrCXmlElement authnAuthzCollectionXml = thisXml->createAndAddElement("authnAuthzCollection"); AuthnAuthzCollectionXml::add(authnAuthzCollectionVal, authnAuthzCollectionXml); } const SmartPtrCProtocolCollectionDoc protocolCollectionVal = requestHeaderDoc->getProtocolCollection(); if (! protocolCollectionVal.IsNull()) { const SmartPtrCXmlElement protocolCollectionXml = thisXml->createAndAddElement("protocolCollection"); ProtocolCollectionXml::add(protocolCollectionVal, protocolCollectionXml); } const SmartPtrCPropertyCollectionDoc echoPropertyBagVal = requestHeaderDoc->getEchoPropertyBag(); if (! echoPropertyBagVal.IsNull()) { const SmartPtrCXmlElement echoPropertyBagXml = thisXml->createAndAddElement("echoPropertyBag"); PropertyCollectionXml::add(echoPropertyBagVal, echoPropertyBagXml); } const std::string versionVal = requestHeaderDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::string createdDateTimeVal = requestHeaderDoc->getCreatedDateTime(); CAF_CM_VALIDATE_STRING(createdDateTimeVal); thisXml->addAttribute("createdDateTime", createdDateTimeVal); const std::string sessionIdVal = BasePlatform::UuidToString(requestHeaderDoc->getSessionId()); if (! sessionIdVal.empty()) { thisXml->addAttribute("sessionId", sessionIdVal); } } CAF_CM_EXIT; } SmartPtrCRequestHeaderDoc RequestHeaderXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestHeaderXml", "parse"); SmartPtrCRequestHeaderDoc requestHeaderDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement requestConfigXml = thisXml->findRequiredChild("requestConfig"); SmartPtrCRequestConfigDoc requestConfigVal; if (! requestConfigXml.IsNull()) { requestConfigVal = RequestConfigXml::parse(requestConfigXml); } const SmartPtrCXmlElement authnAuthzCollectionXml = thisXml->findOptionalChild("authnAuthzCollection"); SmartPtrCAuthnAuthzCollectionDoc authnAuthzCollectionVal; if (! authnAuthzCollectionXml.IsNull()) { authnAuthzCollectionVal = AuthnAuthzCollectionXml::parse(authnAuthzCollectionXml); } const SmartPtrCXmlElement protocolCollectionXml = thisXml->findOptionalChild("protocolCollection"); SmartPtrCProtocolCollectionDoc protocolCollectionVal; if (! protocolCollectionXml.IsNull()) { protocolCollectionVal = ProtocolCollectionXml::parse(protocolCollectionXml); } const SmartPtrCXmlElement echoPropertyBagXml = thisXml->findOptionalChild("echoPropertyBag"); SmartPtrCPropertyCollectionDoc echoPropertyBagVal; if (! echoPropertyBagXml.IsNull()) { echoPropertyBagVal = PropertyCollectionXml::parse(echoPropertyBagXml); } const std::string versionVal = thisXml->findRequiredAttribute("version"); const std::string createdDateTimeVal = thisXml->findRequiredAttribute("createdDateTime"); const std::string sessionIdStrVal = thisXml->findOptionalAttribute("sessionId"); UUID sessionIdVal = CAFCOMMON_GUID_NULL; if (! sessionIdStrVal.empty()) { BasePlatform::UuidFromString(sessionIdStrVal.c_str(), sessionIdVal); } requestHeaderDoc.CreateInstance(); requestHeaderDoc->initialize( requestConfigVal, authnAuthzCollectionVal, protocolCollectionVal, echoPropertyBagVal, versionVal, createdDateTimeVal, sessionIdVal); } CAF_CM_EXIT; return requestHeaderDoc; } RequestInstanceParameterXml.cpp000066400000000000000000000065301321503522500430600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/RequestInstanceParameterXml.h" using namespace Caf; void RequestInstanceParameterXml::add( const SmartPtrCRequestInstanceParameterDoc requestInstanceParameterDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestInstanceParameterXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(requestInstanceParameterDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = requestInstanceParameterDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string classNamespaceVal = requestInstanceParameterDoc->getClassNamespace(); CAF_CM_VALIDATE_STRING(classNamespaceVal); thisXml->addAttribute("classNamespace", classNamespaceVal); const std::string classNameVal = requestInstanceParameterDoc->getClassName(); CAF_CM_VALIDATE_STRING(classNameVal); thisXml->addAttribute("className", classNameVal); const std::string classVersionVal = requestInstanceParameterDoc->getClassVersion(); CAF_CM_VALIDATE_STRING(classVersionVal); thisXml->addAttribute("classVersion", classVersionVal); const std::deque valueVal = requestInstanceParameterDoc->getValue(); if (! valueVal.empty()) { for (TConstIterator > valueIter(valueVal); valueIter; valueIter++) { thisXml->appendValue(*valueIter); } } } CAF_CM_EXIT; } SmartPtrCRequestInstanceParameterDoc RequestInstanceParameterXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestInstanceParameterXml", "parse"); SmartPtrCRequestInstanceParameterDoc requestInstanceParameterDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string classNamespaceStrVal = thisXml->findRequiredAttribute("classNamespace"); const std::string classNamespaceVal = classNamespaceStrVal; const std::string classNameStrVal = thisXml->findRequiredAttribute("className"); const std::string classNameVal = classNameStrVal; const std::string classVersionStrVal = thisXml->findRequiredAttribute("classVersion"); const std::string classVersionVal = classVersionStrVal; const CXmlElement::SmartPtrCElementCollection valueChildrenXml = thisXml->getAllChildren(); std::deque valueVal; if (! valueChildrenXml.IsNull() && ! valueChildrenXml->empty()) { for (TConstIterator valueXmlIter(*valueChildrenXml); valueXmlIter; valueXmlIter++) { const SmartPtrCXmlElement valueXml = valueXmlIter->second; const std::string valueDoc = valueXml->saveToStringRaw(); valueVal.push_back(valueDoc); } } requestInstanceParameterDoc.CreateInstance(); requestInstanceParameterDoc->initialize( nameVal, classNamespaceVal, classNameVal, classVersionVal, valueVal); } CAF_CM_EXIT; return requestInstanceParameterDoc; } RequestParameterXml.cpp000066400000000000000000000054751321503522500414020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/RequestParameterXml.h" using namespace Caf; void RequestParameterXml::add( const SmartPtrCRequestParameterDoc requestParameterDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestParameterXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(requestParameterDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = requestParameterDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string typeVal = EnumConvertersXml::convertParameterTypeToString(requestParameterDoc->getType()); CAF_CM_VALIDATE_STRING(typeVal); thisXml->addAttribute("type", typeVal); const std::deque valueVal = requestParameterDoc->getValue(); CAF_CM_VALIDATE_STL(valueVal); if (! valueVal.empty()) { for (TConstIterator > valueIter(valueVal); valueIter; valueIter++) { const SmartPtrCXmlElement valueXml = thisXml->createAndAddElement("value"); valueXml->setCDataValue(*valueIter); } } } CAF_CM_EXIT; } SmartPtrCRequestParameterDoc RequestParameterXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestParameterXml", "parse"); SmartPtrCRequestParameterDoc requestParameterDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string typeStrVal = thisXml->findRequiredAttribute("type"); PARAMETER_TYPE typeVal = PARAMETER_NONE; if (! typeStrVal.empty()) { typeVal = EnumConvertersXml::convertStringToParameterType(typeStrVal); } const CXmlElement::SmartPtrCElementCollection valueChildrenXml = thisXml->findRequiredChildren("value"); std::deque valueVal; if (! valueChildrenXml.IsNull() && ! valueChildrenXml->empty()) { for (TConstIterator valueXmlIter(*valueChildrenXml); valueXmlIter; valueXmlIter++) { const SmartPtrCXmlElement valueXml = valueXmlIter->second; const std::string valueDoc = valueXml->getCDataValue(); valueVal.push_back(valueDoc); } } requestParameterDoc.CreateInstance(); requestParameterDoc->initialize( nameVal, typeVal, valueVal); } CAF_CM_EXIT; return requestParameterDoc; } RequestXml.cpp000066400000000000000000000020001321503522500375160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: Nov 21, 2014 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/RequestXml.h" using namespace Caf; SmartPtrCXmlElement RequestXml::parseString( const std::string& xml, const std::string& rootName) { CAF_CM_STATIC_FUNC_VALIDATE("RequestXml", "parseString"); CAF_CM_VALIDATE_STRING(xml); // rootName is optional SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, rootName); return rootXml; } SmartPtrCXmlElement RequestXml::parseFile( const std::string& xml, const std::string& rootName) { CAF_CM_STATIC_FUNC_VALIDATE("RequestXml", "parseFile"); CAF_CM_VALIDATE_STRING(xml); // rootName is optional SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(xml, rootName); return rootXml; } StatisticsXml.cpp000066400000000000000000000112151321503522500402300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafCoreTypesXml/StatisticsXml.h" #include "Doc/DocXml/CafCoreTypesXml/PropertyCollectionXml.h" using namespace Caf; void StatisticsXml::add( const SmartPtrCStatisticsDoc statisticsDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("StatisticsXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(statisticsDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCPropertyCollectionDoc propertyCollectionVal = statisticsDoc->getPropertyCollection(); CAF_CM_VALIDATE_SMARTPTR(propertyCollectionVal); const SmartPtrCXmlElement propertyCollectionXml = thisXml->createAndAddElement("propertyCollection"); PropertyCollectionXml::add(propertyCollectionVal, propertyCollectionXml); const std::string providerJobNumVal = CStringConv::toString(statisticsDoc->getProviderJobNum()); if (! providerJobNumVal.empty()) { thisXml->addAttribute("providerJobNum", providerJobNumVal); } const std::string providerJobTotalVal = CStringConv::toString(statisticsDoc->getProviderJobTotal()); if (! providerJobTotalVal.empty()) { thisXml->addAttribute("providerJobTotal", providerJobTotalVal); } const std::string providerJobDurationSecsVal = CStringConv::toString(statisticsDoc->getProviderJobDurationSecs()); if (! providerJobDurationSecsVal.empty()) { thisXml->addAttribute("providerJobDurationSecs", providerJobDurationSecsVal); } const std::string pmeNumVal = CStringConv::toString(statisticsDoc->getPmeNum()); if (! pmeNumVal.empty()) { thisXml->addAttribute("pmeNum", pmeNumVal); } const std::string pmeTotalVal = CStringConv::toString(statisticsDoc->getPmeTotal()); if (! pmeTotalVal.empty()) { thisXml->addAttribute("pmeTotal", pmeTotalVal); } const std::string pmeDurationSecsVal = CStringConv::toString(statisticsDoc->getPmeDurationSecs()); if (! pmeDurationSecsVal.empty()) { thisXml->addAttribute("pmeDurationSecs", pmeDurationSecsVal); } } CAF_CM_EXIT; } SmartPtrCStatisticsDoc StatisticsXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("StatisticsXml", "parse"); SmartPtrCStatisticsDoc statisticsDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement propertyCollectionXml = thisXml->findRequiredChild("propertyCollection"); SmartPtrCPropertyCollectionDoc propertyCollectionVal; if (! propertyCollectionXml.IsNull()) { propertyCollectionVal = PropertyCollectionXml::parse(propertyCollectionXml); } const std::string providerJobNumStrVal = thisXml->findOptionalAttribute("providerJobNum"); int32 providerJobNumVal = 0; if (! providerJobNumStrVal.empty()) { providerJobNumVal = CStringConv::fromString(providerJobNumStrVal); } const std::string providerJobTotalStrVal = thisXml->findOptionalAttribute("providerJobTotal"); int32 providerJobTotalVal = 0; if (! providerJobTotalStrVal.empty()) { providerJobTotalVal = CStringConv::fromString(providerJobTotalStrVal); } const std::string providerJobDurationSecsStrVal = thisXml->findOptionalAttribute("providerJobDurationSecs"); int32 providerJobDurationSecsVal = 0; if (! providerJobDurationSecsStrVal.empty()) { providerJobDurationSecsVal = CStringConv::fromString(providerJobDurationSecsStrVal); } const std::string pmeNumStrVal = thisXml->findOptionalAttribute("pmeNum"); int32 pmeNumVal = 0; if (! pmeNumStrVal.empty()) { pmeNumVal = CStringConv::fromString(pmeNumStrVal); } const std::string pmeTotalStrVal = thisXml->findOptionalAttribute("pmeTotal"); int32 pmeTotalVal = 0; if (! pmeTotalStrVal.empty()) { pmeTotalVal = CStringConv::fromString(pmeTotalStrVal); } const std::string pmeDurationSecsStrVal = thisXml->findOptionalAttribute("pmeDurationSecs"); int32 pmeDurationSecsVal = 0; if (! pmeDurationSecsStrVal.empty()) { pmeDurationSecsVal = CStringConv::fromString(pmeDurationSecsStrVal); } statisticsDoc.CreateInstance(); statisticsDoc->initialize( propertyCollectionVal, providerJobNumVal, providerJobTotalVal, providerJobDurationSecsVal, pmeNumVal, pmeTotalVal, pmeDurationSecsVal); } CAF_CM_EXIT; return statisticsDoc; } stdafx.h000066400000000000000000000010301321503522500363450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafCoreTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define CAFCORETYPESXML_LINKAGE __declspec(dllexport) #else #define CAFCORETYPESXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ CafInstallRequestXml/000077500000000000000000000000001321503522500357535ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlCafInstallRequestXmlRoots.cpp000066400000000000000000000167011321503522500435650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/RequestXml.h" #include "Doc/DocXml/CafInstallRequestXml/InstallPackageSpecXml.h" #include "Doc/DocXml/CafInstallRequestXml/InstallProviderSpecXml.h" #include "Doc/DocXml/CafInstallRequestXml/InstallRequestXml.h" #include "Doc/CafInstallRequestDoc/CInstallPackageSpecDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlRoots.h" using namespace Caf; std::string XmlRoots::saveInstallRequestToString( const SmartPtrCInstallRequestDoc installRequestDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveInstallRequestToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installRequestDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/CafInstallRequest.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "installRequest", schemaNamespace, schemaLocation); InstallRequestXml::add(installRequestDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCInstallRequestDoc XmlRoots::parseInstallRequestFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseInstallRequestFromString"); SmartPtrCInstallRequestDoc installRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = RequestXml::parseString(xml, "caf:installRequest"); installRequestDoc = InstallRequestXml::parse(rootXml); } CAF_CM_EXIT; return installRequestDoc; } void XmlRoots::saveInstallRequestToFile( const SmartPtrCInstallRequestDoc installRequestDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveInstallRequestToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installRequestDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string installRequestStr = saveInstallRequestToString(installRequestDoc); FileSystemUtils::saveTextFile(filePath, installRequestStr); } CAF_CM_EXIT; } SmartPtrCInstallRequestDoc XmlRoots::parseInstallRequestFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseInstallRequestFromFile"); SmartPtrCInstallRequestDoc installRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = RequestXml::parseFile(filePath, "caf:installRequest"); installRequestDoc = InstallRequestXml::parse(rootXml); } CAF_CM_EXIT; return installRequestDoc; } std::string XmlRoots::saveInstallProviderSpecToString( const SmartPtrCInstallProviderSpecDoc installProviderSpecDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveInstallProviderSpecToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderSpecDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/CafInstallRequest.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "installProviderSpec", schemaNamespace, schemaLocation); InstallProviderSpecXml::add(installProviderSpecDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCInstallProviderSpecDoc XmlRoots::parseInstallProviderSpecFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseInstallProviderSpecFromString"); SmartPtrCInstallProviderSpecDoc installProviderSpecDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:installProviderSpec"); installProviderSpecDoc = InstallProviderSpecXml::parse(rootXml); } CAF_CM_EXIT; return installProviderSpecDoc; } void XmlRoots::saveInstallProviderSpecToFile( const SmartPtrCInstallProviderSpecDoc installProviderSpecDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveInstallProviderSpecToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderSpecDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string installProviderSpecStr = saveInstallProviderSpecToString(installProviderSpecDoc); FileSystemUtils::saveTextFile(filePath, installProviderSpecStr); } CAF_CM_EXIT; } SmartPtrCInstallProviderSpecDoc XmlRoots::parseInstallProviderSpecFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseInstallProviderSpecFromFile"); SmartPtrCInstallProviderSpecDoc installProviderSpecDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:installProviderSpec"); installProviderSpecDoc = InstallProviderSpecXml::parse(rootXml); } CAF_CM_EXIT; return installProviderSpecDoc; } std::string XmlRoots::saveInstallPackageSpecToString( const SmartPtrCInstallPackageSpecDoc installPackageSpecDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveInstallPackageSpecToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpecDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/CafInstallRequest.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "installPackageSpec", schemaNamespace, schemaLocation); InstallPackageSpecXml::add(installPackageSpecDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCInstallPackageSpecDoc XmlRoots::parseInstallPackageSpecFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseInstallPackageSpecFromString"); SmartPtrCInstallPackageSpecDoc installPackageSpecDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:installPackageSpec"); installPackageSpecDoc = InstallPackageSpecXml::parse(rootXml); } CAF_CM_EXIT; return installPackageSpecDoc; } void XmlRoots::saveInstallPackageSpecToFile( const SmartPtrCInstallPackageSpecDoc installPackageSpecDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveInstallPackageSpecToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpecDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string installPackageSpecStr = saveInstallPackageSpecToString(installPackageSpecDoc); FileSystemUtils::saveTextFile(filePath, installPackageSpecStr); } CAF_CM_EXIT; } SmartPtrCInstallPackageSpecDoc XmlRoots::parseInstallPackageSpecFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseInstallPackageSpecFromFile"); SmartPtrCInstallPackageSpecDoc installPackageSpecDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:installPackageSpec"); installPackageSpecDoc = InstallPackageSpecXml::parse(rootXml); } CAF_CM_EXIT; return installPackageSpecDoc; } FullPackageElemXml.cpp000066400000000000000000000075651321503522500421360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafInstallRequestXml/PackageDefnXml.h" #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CPackageDefnDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/FullPackageElemXml.h" using namespace Caf; void FullPackageElemXml::add( const SmartPtrCFullPackageElemDoc fullPackageElemDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("FullPackageElemXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(fullPackageElemDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string indexVal = CStringConv::toString(fullPackageElemDoc->getIndex()); CAF_CM_VALIDATE_STRING(indexVal); thisXml->addAttribute("index", indexVal); const std::string packageNamespaceVal = fullPackageElemDoc->getPackageNamespace(); CAF_CM_VALIDATE_STRING(packageNamespaceVal); thisXml->addAttribute("packageNamespace", packageNamespaceVal); const std::string packageNameVal = fullPackageElemDoc->getPackageName(); CAF_CM_VALIDATE_STRING(packageNameVal); thisXml->addAttribute("packageName", packageNameVal); const std::string packageVersionVal = fullPackageElemDoc->getPackageVersion(); CAF_CM_VALIDATE_STRING(packageVersionVal); thisXml->addAttribute("packageVersion", packageVersionVal); const SmartPtrCPackageDefnDoc installPackageVal = fullPackageElemDoc->getInstallPackage(); CAF_CM_VALIDATE_SMARTPTR(installPackageVal); const SmartPtrCXmlElement installPackageXml = thisXml->createAndAddElement("installPackage"); PackageDefnXml::add(installPackageVal, installPackageXml); const SmartPtrCPackageDefnDoc uninstallPackageVal = fullPackageElemDoc->getUninstallPackage(); CAF_CM_VALIDATE_SMARTPTR(uninstallPackageVal); const SmartPtrCXmlElement uninstallPackageXml = thisXml->createAndAddElement("uninstallPackage"); PackageDefnXml::add(uninstallPackageVal, uninstallPackageXml); } CAF_CM_EXIT; } SmartPtrCFullPackageElemDoc FullPackageElemXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("FullPackageElemXml", "parse"); SmartPtrCFullPackageElemDoc fullPackageElemDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string indexStrVal = thisXml->findRequiredAttribute("index"); int32 indexVal = 0; if (! indexStrVal.empty()) { indexVal = CStringConv::fromString(indexStrVal); } const std::string packageNamespaceStrVal = thisXml->findRequiredAttribute("packageNamespace"); const std::string packageNamespaceVal = packageNamespaceStrVal; const std::string packageNameStrVal = thisXml->findRequiredAttribute("packageName"); const std::string packageNameVal = packageNameStrVal; const std::string packageVersionStrVal = thisXml->findRequiredAttribute("packageVersion"); const std::string packageVersionVal = packageVersionStrVal; const SmartPtrCXmlElement installPackageXml = thisXml->findRequiredChild("installPackage"); SmartPtrCPackageDefnDoc installPackageVal; if (! installPackageXml.IsNull()) { installPackageVal = PackageDefnXml::parse(installPackageXml); } const SmartPtrCXmlElement uninstallPackageXml = thisXml->findRequiredChild("uninstallPackage"); SmartPtrCPackageDefnDoc uninstallPackageVal; if (! uninstallPackageXml.IsNull()) { uninstallPackageVal = PackageDefnXml::parse(uninstallPackageXml); } fullPackageElemDoc.CreateInstance(); fullPackageElemDoc->initialize( indexVal, packageNamespaceVal, packageNameVal, packageVersionVal, installPackageVal, uninstallPackageVal); } CAF_CM_EXIT; return fullPackageElemDoc; } GetInventoryJobXml.cpp000066400000000000000000000030521321503522500422300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CGetInventoryJobDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/GetInventoryJobXml.h" using namespace Caf; void GetInventoryJobXml::add( const SmartPtrCGetInventoryJobDoc getInventoryJobDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("GetInventoryJobXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(getInventoryJobDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdVal = BasePlatform::UuidToString(getInventoryJobDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); } CAF_CM_EXIT; } SmartPtrCGetInventoryJobDoc GetInventoryJobXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("GetInventoryJobXml", "parse"); SmartPtrCGetInventoryJobDoc getInventoryJobDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } getInventoryJobDoc.CreateInstance(); getInventoryJobDoc->initialize( jobIdVal); } CAF_CM_EXIT; return getInventoryJobDoc; } InstallBatchXml.cpp000066400000000000000000000064071321503522500415170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafInstallRequestXml/GetInventoryJobXml.h" #include "Doc/DocXml/CafInstallRequestXml/InstallProviderJobXml.h" #include "Doc/DocXml/CafInstallRequestXml/UninstallProviderJobXml.h" #include "Doc/CafInstallRequestDoc/CGetInventoryJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallBatchDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/InstallBatchXml.h" using namespace Caf; void InstallBatchXml::add( const SmartPtrCInstallBatchDoc installBatchDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallBatchXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installBatchDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCGetInventoryJobDoc getInventoryVal = installBatchDoc->getGetInventory(); if (! getInventoryVal.IsNull()) { const SmartPtrCXmlElement getInventoryXml = thisXml->createAndAddElement("getInventory"); GetInventoryJobXml::add(getInventoryVal, getInventoryXml); } const SmartPtrCInstallProviderJobDoc installProviderVal = installBatchDoc->getInstallProvider(); if (! installProviderVal.IsNull()) { const SmartPtrCXmlElement installProviderXml = thisXml->createAndAddElement("installProvider"); InstallProviderJobXml::add(installProviderVal, installProviderXml); } const SmartPtrCUninstallProviderJobDoc uninstallProviderVal = installBatchDoc->getUninstallProvider(); if (! uninstallProviderVal.IsNull()) { const SmartPtrCXmlElement uninstallProviderXml = thisXml->createAndAddElement("uninstallProvider"); UninstallProviderJobXml::add(uninstallProviderVal, uninstallProviderXml); } } CAF_CM_EXIT; } SmartPtrCInstallBatchDoc InstallBatchXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallBatchXml", "parse"); SmartPtrCInstallBatchDoc installBatchDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement getInventoryXml = thisXml->findOptionalChild("getInventory"); SmartPtrCGetInventoryJobDoc getInventoryVal; if (! getInventoryXml.IsNull()) { getInventoryVal = GetInventoryJobXml::parse(getInventoryXml); } const SmartPtrCXmlElement installProviderXml = thisXml->findOptionalChild("installProvider"); SmartPtrCInstallProviderJobDoc installProviderVal; if (! installProviderXml.IsNull()) { installProviderVal = InstallProviderJobXml::parse(installProviderXml); } const SmartPtrCXmlElement uninstallProviderXml = thisXml->findOptionalChild("uninstallProvider"); SmartPtrCUninstallProviderJobDoc uninstallProviderVal; if (! uninstallProviderXml.IsNull()) { uninstallProviderVal = UninstallProviderJobXml::parse(uninstallProviderXml); } installBatchDoc.CreateInstance(); installBatchDoc->initialize( getInventoryVal, installProviderVal, uninstallProviderVal); } CAF_CM_EXIT; return installBatchDoc; } InstallPackageSpecXml.cpp000066400000000000000000000124551321503522500426440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentNameCollectionXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CInstallPackageSpecDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/InstallPackageSpecXml.h" using namespace Caf; void InstallPackageSpecXml::add( const SmartPtrCInstallPackageSpecDoc installPackageSpecDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallPackageSpecXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpecDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string packageNamespaceVal = installPackageSpecDoc->getPackageNamespace(); CAF_CM_VALIDATE_STRING(packageNamespaceVal); thisXml->addAttribute("packageNamespace", packageNamespaceVal); const std::string packageNameVal = installPackageSpecDoc->getPackageName(); CAF_CM_VALIDATE_STRING(packageNameVal); thisXml->addAttribute("packageName", packageNameVal); const std::string packageVersionVal = installPackageSpecDoc->getPackageVersion(); CAF_CM_VALIDATE_STRING(packageVersionVal); thisXml->addAttribute("packageVersion", packageVersionVal); const std::string startupAttachmentNameVal = installPackageSpecDoc->getStartupAttachmentName(); CAF_CM_VALIDATE_STRING(startupAttachmentNameVal); thisXml->addAttribute("startupAttachmentName", startupAttachmentNameVal); const std::string packageAttachmentNameVal = installPackageSpecDoc->getPackageAttachmentName(); CAF_CM_VALIDATE_STRING(packageAttachmentNameVal); thisXml->addAttribute("packageAttachmentName", packageAttachmentNameVal); const SmartPtrCAttachmentNameCollectionDoc supportingAttachmentNameCollectionVal = installPackageSpecDoc->getSupportingAttachmentNameCollection(); if (! supportingAttachmentNameCollectionVal.IsNull()) { const SmartPtrCXmlElement supportingAttachmentNameCollectionXml = thisXml->createAndAddElement("attachmentNameCollection"); AttachmentNameCollectionXml::add(supportingAttachmentNameCollectionVal, supportingAttachmentNameCollectionXml); } const SmartPtrCAttachmentCollectionDoc attachmentCollectionVal = installPackageSpecDoc->getAttachmentCollection(); CAF_CM_VALIDATE_SMARTPTR(attachmentCollectionVal); const SmartPtrCXmlElement attachmentCollectionXml = thisXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionVal, attachmentCollectionXml); const std::string argumentsVal = installPackageSpecDoc->getArguments(); if (! argumentsVal.empty()) { thisXml->addAttribute("arguments", argumentsVal); } thisXml->addAttribute("version", "1.0"); } CAF_CM_EXIT; } SmartPtrCInstallPackageSpecDoc InstallPackageSpecXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallPackageSpecXml", "parse"); SmartPtrCInstallPackageSpecDoc installPackageSpecDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string packageNamespaceStrVal = thisXml->findRequiredAttribute("packageNamespace"); const std::string packageNamespaceVal = packageNamespaceStrVal; const std::string packageNameStrVal = thisXml->findRequiredAttribute("packageName"); const std::string packageNameVal = packageNameStrVal; const std::string packageVersionStrVal = thisXml->findRequiredAttribute("packageVersion"); const std::string packageVersionVal = packageVersionStrVal; const std::string startupAttachmentNameStrVal = thisXml->findRequiredAttribute("startupAttachmentName"); const std::string startupAttachmentNameVal = startupAttachmentNameStrVal; const std::string packageAttachmentNameStrVal = thisXml->findRequiredAttribute("packageAttachmentName"); const std::string packageAttachmentNameVal = packageAttachmentNameStrVal; const SmartPtrCXmlElement supportingAttachmentNameCollectionXml = thisXml->findOptionalChild("attachmentNameCollection"); SmartPtrCAttachmentNameCollectionDoc supportingAttachmentNameCollectionVal; if (! supportingAttachmentNameCollectionXml.IsNull()) { supportingAttachmentNameCollectionVal = AttachmentNameCollectionXml::parse(supportingAttachmentNameCollectionXml); } const SmartPtrCXmlElement attachmentCollectionXml = thisXml->findRequiredChild("attachmentCollection"); SmartPtrCAttachmentCollectionDoc attachmentCollectionVal; if (! attachmentCollectionXml.IsNull()) { attachmentCollectionVal = AttachmentCollectionXml::parse(attachmentCollectionXml); } const std::string argumentsStrVal = thisXml->findOptionalAttribute("arguments"); const std::string argumentsVal = argumentsStrVal; installPackageSpecDoc.CreateInstance(); installPackageSpecDoc->initialize( packageNamespaceVal, packageNameVal, packageVersionVal, startupAttachmentNameVal, packageAttachmentNameVal, supportingAttachmentNameCollectionVal, attachmentCollectionVal, argumentsVal); } CAF_CM_EXIT; return installPackageSpecDoc; } InstallProviderJobXml.cpp000066400000000000000000000122341321503522500427160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/DocXml/CafInstallRequestXml/FullPackageElemXml.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/InstallProviderJobXml.h" using namespace Caf; void InstallProviderJobXml::add( const SmartPtrCInstallProviderJobDoc installProviderJobDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallProviderJobXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderJobDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(installProviderJobDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string jobIdVal = BasePlatform::UuidToString(installProviderJobDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const std::string providerNamespaceVal = installProviderJobDoc->getProviderNamespace(); CAF_CM_VALIDATE_STRING(providerNamespaceVal); thisXml->addAttribute("providerNamespace", providerNamespaceVal); const std::string providerNameVal = installProviderJobDoc->getProviderName(); CAF_CM_VALIDATE_STRING(providerNameVal); thisXml->addAttribute("providerName", providerNameVal); const std::string providerVersionVal = installProviderJobDoc->getProviderVersion(); CAF_CM_VALIDATE_STRING(providerVersionVal); thisXml->addAttribute("providerVersion", providerVersionVal); const std::string packageOSTypeVal = EnumConvertersXml::convertPackageOSTypeToString(installProviderJobDoc->getPackageOSType()); CAF_CM_VALIDATE_STRING(packageOSTypeVal); thisXml->addAttribute("packageOSType", packageOSTypeVal); const std::deque packageValVal = installProviderJobDoc->getPackageCollection(); CAF_CM_VALIDATE_STL(packageValVal); if (! packageValVal.empty()) { const SmartPtrCXmlElement packageCollectionXml = thisXml->createAndAddElement("packageCollection"); for (TConstIterator > packageValIter(packageValVal); packageValIter; packageValIter++) { const SmartPtrCXmlElement packageValXml = packageCollectionXml->createAndAddElement("package"); FullPackageElemXml::add(*packageValIter, packageValXml); } } } CAF_CM_EXIT; } SmartPtrCInstallProviderJobDoc InstallProviderJobXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallProviderJobXml", "parse"); SmartPtrCInstallProviderJobDoc installProviderJobDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); const std::string providerNamespaceStrVal = thisXml->findRequiredAttribute("providerNamespace"); const std::string providerNamespaceVal = providerNamespaceStrVal; const std::string providerNameStrVal = thisXml->findRequiredAttribute("providerName"); const std::string providerNameVal = providerNameStrVal; const std::string providerVersionStrVal = thisXml->findRequiredAttribute("providerVersion"); const std::string providerVersionVal = providerVersionStrVal; const std::string packageOSTypeStrVal = thisXml->findRequiredAttribute("packageOSType"); PACKAGE_OS_TYPE packageOSTypeVal = PACKAGE_OS_NONE; if (! packageOSTypeStrVal.empty()) { packageOSTypeVal = EnumConvertersXml::convertStringToPackageOSType(packageOSTypeStrVal); } const SmartPtrCXmlElement packageCollectionXml = thisXml->findRequiredChild("packageCollection"); const CXmlElement::SmartPtrCElementCollection packageValChildrenXml = packageCollectionXml->findRequiredChildren("package"); std::deque packageValVal; if (! packageValChildrenXml.IsNull() && ! packageValChildrenXml->empty()) { for (TConstIterator packageValXmlIter(*packageValChildrenXml); packageValXmlIter; packageValXmlIter++) { const SmartPtrCXmlElement packageValXml = packageValXmlIter->second; const SmartPtrCFullPackageElemDoc packageValDoc = FullPackageElemXml::parse(packageValXml); packageValVal.push_back(packageValDoc); } } installProviderJobDoc.CreateInstance(); installProviderJobDoc->initialize( clientIdVal, jobIdVal, providerNamespaceVal, providerNameVal, providerVersionVal, packageOSTypeVal, packageValVal); } CAF_CM_EXIT; return installProviderJobDoc; } InstallProviderSpecXml.cpp000066400000000000000000000100151321503522500430710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafInstallRequestXml/MinPackageElemXml.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/InstallProviderSpecXml.h" using namespace Caf; void InstallProviderSpecXml::add( const SmartPtrCInstallProviderSpecDoc installProviderSpecDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallProviderSpecXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderSpecDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(installProviderSpecDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string providerNamespaceVal = installProviderSpecDoc->getProviderNamespace(); CAF_CM_VALIDATE_STRING(providerNamespaceVal); thisXml->addAttribute("providerNamespace", providerNamespaceVal); const std::string providerNameVal = installProviderSpecDoc->getProviderName(); CAF_CM_VALIDATE_STRING(providerNameVal); thisXml->addAttribute("providerName", providerNameVal); const std::string providerVersionVal = installProviderSpecDoc->getProviderVersion(); CAF_CM_VALIDATE_STRING(providerVersionVal); thisXml->addAttribute("providerVersion", providerVersionVal); const std::deque packageValVal = installProviderSpecDoc->getPackageCollection(); CAF_CM_VALIDATE_STL(packageValVal); if (! packageValVal.empty()) { for (TConstIterator > packageValIter(packageValVal); packageValIter; packageValIter++) { const SmartPtrCXmlElement packageValXml = thisXml->createAndAddElement("package"); MinPackageElemXml::add(*packageValIter, packageValXml); } } thisXml->addAttribute("version", "1.0"); } CAF_CM_EXIT; } SmartPtrCInstallProviderSpecDoc InstallProviderSpecXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallProviderSpecXml", "parse"); SmartPtrCInstallProviderSpecDoc installProviderSpecDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string providerNamespaceStrVal = thisXml->findRequiredAttribute("providerNamespace"); const std::string providerNamespaceVal = providerNamespaceStrVal; const std::string providerNameStrVal = thisXml->findRequiredAttribute("providerName"); const std::string providerNameVal = providerNameStrVal; const std::string providerVersionStrVal = thisXml->findRequiredAttribute("providerVersion"); const std::string providerVersionVal = providerVersionStrVal; const CXmlElement::SmartPtrCElementCollection packageValChildrenXml = thisXml->findRequiredChildren("package"); std::deque packageValVal; if (! packageValChildrenXml.IsNull() && ! packageValChildrenXml->empty()) { for (TConstIterator packageValXmlIter(*packageValChildrenXml); packageValXmlIter; packageValXmlIter++) { const SmartPtrCXmlElement packageValXml = packageValXmlIter->second; const SmartPtrCMinPackageElemDoc packageValDoc = MinPackageElemXml::parse(packageValXml); packageValVal.push_back(packageValDoc); } } installProviderSpecDoc.CreateInstance(); installProviderSpecDoc->initialize( clientIdVal, providerNamespaceVal, providerNameVal, providerVersionVal, packageValVal); } CAF_CM_EXIT; return installProviderSpecDoc; } InstallRequestXml.cpp000066400000000000000000000103751321503522500421250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/RequestHeaderXml.h" #include "Doc/DocXml/CafInstallRequestXml/InstallBatchXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/CafInstallRequestDoc/CInstallBatchDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/InstallRequestXml.h" using namespace Caf; void InstallRequestXml::add( const SmartPtrCInstallRequestDoc installRequestDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallRequestXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installRequestDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(installRequestDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string requestIdVal = BasePlatform::UuidToString(installRequestDoc->getRequestId()); CAF_CM_VALIDATE_STRING(requestIdVal); thisXml->addAttribute("requestId", requestIdVal); const std::string pmeIdVal = installRequestDoc->getPmeId(); CAF_CM_VALIDATE_STRING(pmeIdVal); thisXml->addAttribute("pmeId", pmeIdVal); const SmartPtrCRequestHeaderDoc requestHeaderVal = installRequestDoc->getRequestHeader(); CAF_CM_VALIDATE_SMARTPTR(requestHeaderVal); const SmartPtrCXmlElement requestHeaderXml = thisXml->createAndAddElement("requestHeader"); RequestHeaderXml::add(requestHeaderVal, requestHeaderXml); const SmartPtrCInstallBatchDoc batchVal = installRequestDoc->getBatch(); CAF_CM_VALIDATE_SMARTPTR(batchVal); const SmartPtrCXmlElement batchXml = thisXml->createAndAddElement("batch"); InstallBatchXml::add(batchVal, batchXml); const SmartPtrCAttachmentCollectionDoc attachmentCollectionVal = installRequestDoc->getAttachmentCollection(); if (! attachmentCollectionVal.IsNull()) { const SmartPtrCXmlElement attachmentCollectionXml = thisXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionVal, attachmentCollectionXml); } } CAF_CM_EXIT; } SmartPtrCInstallRequestDoc InstallRequestXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstallRequestXml", "parse"); SmartPtrCInstallRequestDoc installRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findRequiredAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findRequiredAttribute("pmeId"); const SmartPtrCXmlElement requestHeaderXml = thisXml->findRequiredChild("requestHeader"); SmartPtrCRequestHeaderDoc requestHeaderVal; if (! requestHeaderXml.IsNull()) { requestHeaderVal = RequestHeaderXml::parse(requestHeaderXml); } const SmartPtrCXmlElement batchXml = thisXml->findRequiredChild("batch"); SmartPtrCInstallBatchDoc batchVal; if (! batchXml.IsNull()) { batchVal = InstallBatchXml::parse(batchXml); } const SmartPtrCXmlElement attachmentCollectionXml = thisXml->findOptionalChild("attachmentCollection"); SmartPtrCAttachmentCollectionDoc attachmentCollectionVal; if (! attachmentCollectionXml.IsNull()) { attachmentCollectionVal = AttachmentCollectionXml::parse(attachmentCollectionXml); } installRequestDoc.CreateInstance(); installRequestDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, requestHeaderVal, batchVal, attachmentCollectionVal); } CAF_CM_EXIT; return installRequestDoc; } MinPackageElemXml.cpp000066400000000000000000000051171321503522500417460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/MinPackageElemXml.h" using namespace Caf; void MinPackageElemXml::add( const SmartPtrCMinPackageElemDoc minPackageElemDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MinPackageElemXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(minPackageElemDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string indexVal = CStringConv::toString(minPackageElemDoc->getIndex()); CAF_CM_VALIDATE_STRING(indexVal); thisXml->addAttribute("index", indexVal); const std::string packageNamespaceVal = minPackageElemDoc->getPackageNamespace(); CAF_CM_VALIDATE_STRING(packageNamespaceVal); thisXml->addAttribute("packageNamespace", packageNamespaceVal); const std::string packageNameVal = minPackageElemDoc->getPackageName(); CAF_CM_VALIDATE_STRING(packageNameVal); thisXml->addAttribute("packageName", packageNameVal); const std::string packageVersionVal = minPackageElemDoc->getPackageVersion(); CAF_CM_VALIDATE_STRING(packageVersionVal); thisXml->addAttribute("packageVersion", packageVersionVal); } CAF_CM_EXIT; } SmartPtrCMinPackageElemDoc MinPackageElemXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MinPackageElemXml", "parse"); SmartPtrCMinPackageElemDoc minPackageElemDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string indexStrVal = thisXml->findRequiredAttribute("index"); int32 indexVal = 0; if (! indexStrVal.empty()) { indexVal = CStringConv::fromString(indexStrVal); } const std::string packageNamespaceStrVal = thisXml->findRequiredAttribute("packageNamespace"); const std::string packageNamespaceVal = packageNamespaceStrVal; const std::string packageNameStrVal = thisXml->findRequiredAttribute("packageName"); const std::string packageNameVal = packageNameStrVal; const std::string packageVersionStrVal = thisXml->findRequiredAttribute("packageVersion"); const std::string packageVersionVal = packageVersionStrVal; minPackageElemDoc.CreateInstance(); minPackageElemDoc->initialize( indexVal, packageNamespaceVal, packageNameVal, packageVersionVal); } CAF_CM_EXIT; return minPackageElemDoc; } PackageDefnXml.cpp000066400000000000000000000063601321503522500412750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentNameCollectionXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CPackageDefnDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/PackageDefnXml.h" using namespace Caf; void PackageDefnXml::add( const SmartPtrCPackageDefnDoc packageDefnDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PackageDefnXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(packageDefnDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string startupAttachmentNameVal = packageDefnDoc->getStartupAttachmentName(); CAF_CM_VALIDATE_STRING(startupAttachmentNameVal); thisXml->addAttribute("startupAttachmentName", startupAttachmentNameVal); const std::string packageAttachmentNameVal = packageDefnDoc->getPackageAttachmentName(); CAF_CM_VALIDATE_STRING(packageAttachmentNameVal); thisXml->addAttribute("packageAttachmentName", packageAttachmentNameVal); const SmartPtrCAttachmentNameCollectionDoc supportingAttachmentNameCollectionVal = packageDefnDoc->getSupportingAttachmentNameCollection(); if (! supportingAttachmentNameCollectionVal.IsNull()) { const SmartPtrCXmlElement supportingAttachmentNameCollectionXml = thisXml->createAndAddElement("attachmentNameCollection"); AttachmentNameCollectionXml::add(supportingAttachmentNameCollectionVal, supportingAttachmentNameCollectionXml); } const std::string argumentsVal = packageDefnDoc->getArguments(); if (! argumentsVal.empty()) { thisXml->addAttribute("arguments", argumentsVal); } } CAF_CM_EXIT; } SmartPtrCPackageDefnDoc PackageDefnXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PackageDefnXml", "parse"); SmartPtrCPackageDefnDoc packageDefnDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string startupAttachmentNameStrVal = thisXml->findRequiredAttribute("startupAttachmentName"); const std::string startupAttachmentNameVal = startupAttachmentNameStrVal; const std::string packageAttachmentNameStrVal = thisXml->findRequiredAttribute("packageAttachmentName"); const std::string packageAttachmentNameVal = packageAttachmentNameStrVal; const SmartPtrCXmlElement supportingAttachmentNameCollectionXml = thisXml->findOptionalChild("attachmentNameCollection"); SmartPtrCAttachmentNameCollectionDoc supportingAttachmentNameCollectionVal; if (! supportingAttachmentNameCollectionXml.IsNull()) { supportingAttachmentNameCollectionVal = AttachmentNameCollectionXml::parse(supportingAttachmentNameCollectionXml); } const std::string argumentsStrVal = thisXml->findOptionalAttribute("arguments"); const std::string argumentsVal = argumentsStrVal; packageDefnDoc.CreateInstance(); packageDefnDoc->initialize( startupAttachmentNameVal, packageAttachmentNameVal, supportingAttachmentNameCollectionVal, argumentsVal); } CAF_CM_EXIT; return packageDefnDoc; } UninstallProviderJobXml.cpp000066400000000000000000000073651321503522500432720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/CafInstallRequestXml/UninstallProviderJobXml.h" using namespace Caf; void UninstallProviderJobXml::add( const SmartPtrCUninstallProviderJobDoc uninstallProviderJobDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("UninstallProviderJobXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(uninstallProviderJobDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(uninstallProviderJobDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string jobIdVal = BasePlatform::UuidToString(uninstallProviderJobDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const std::string providerNamespaceVal = uninstallProviderJobDoc->getProviderNamespace(); CAF_CM_VALIDATE_STRING(providerNamespaceVal); thisXml->addAttribute("providerNamespace", providerNamespaceVal); const std::string providerNameVal = uninstallProviderJobDoc->getProviderName(); CAF_CM_VALIDATE_STRING(providerNameVal); thisXml->addAttribute("providerName", providerNameVal); const std::string providerVersionVal = uninstallProviderJobDoc->getProviderVersion(); CAF_CM_VALIDATE_STRING(providerVersionVal); thisXml->addAttribute("providerVersion", providerVersionVal); const std::string packageOSTypeVal = EnumConvertersXml::convertPackageOSTypeToString(uninstallProviderJobDoc->getPackageOSType()); CAF_CM_VALIDATE_STRING(packageOSTypeVal); thisXml->addAttribute("packageOSType", packageOSTypeVal); } CAF_CM_EXIT; } SmartPtrCUninstallProviderJobDoc UninstallProviderJobXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("UninstallProviderJobXml", "parse"); SmartPtrCUninstallProviderJobDoc uninstallProviderJobDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); const std::string providerNamespaceStrVal = thisXml->findRequiredAttribute("providerNamespace"); const std::string providerNamespaceVal = providerNamespaceStrVal; const std::string providerNameStrVal = thisXml->findRequiredAttribute("providerName"); const std::string providerNameVal = providerNameStrVal; const std::string providerVersionStrVal = thisXml->findRequiredAttribute("providerVersion"); const std::string providerVersionVal = providerVersionStrVal; const std::string packageOSTypeStrVal = thisXml->findRequiredAttribute("packageOSType"); PACKAGE_OS_TYPE packageOSTypeVal = PACKAGE_OS_NONE; if (! packageOSTypeStrVal.empty()) { packageOSTypeVal = EnumConvertersXml::convertStringToPackageOSType(packageOSTypeStrVal); } uninstallProviderJobDoc.CreateInstance(); uninstallProviderJobDoc->initialize( clientIdVal, jobIdVal, providerNamespaceVal, providerNameVal, providerVersionVal, packageOSTypeVal); } CAF_CM_EXIT; return uninstallProviderJobDoc; } stdafx.h000066400000000000000000000010421321503522500374120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/CafInstallRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define CAFINSTALLREQUESTXML_LINKAGE __declspec(dllexport) #else #define CAFINSTALLREQUESTXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ DiagRequestXml/000077500000000000000000000000001321503522500345775ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlDiagRequestXml.cpp000066400000000000000000000065431321503522500402110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/RequestHeaderXml.h" #include "Doc/DocXml/DiagTypesXml/DiagBatchXml.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/DiagRequestDoc/CDiagRequestDoc.h" #include "Doc/DiagTypesDoc/CDiagBatchDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/DiagRequestXml/DiagRequestXml.h" using namespace Caf; void DiagRequestXml::add( const SmartPtrCDiagRequestDoc diagRequestDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagRequestXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagRequestDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(diagRequestDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string requestIdVal = BasePlatform::UuidToString(diagRequestDoc->getRequestId()); CAF_CM_VALIDATE_STRING(requestIdVal); thisXml->addAttribute("requestId", requestIdVal); const std::string pmeIdVal = diagRequestDoc->getPmeId(); CAF_CM_VALIDATE_STRING(pmeIdVal); thisXml->addAttribute("pmeId", pmeIdVal); const SmartPtrCRequestHeaderDoc requestHeaderVal = diagRequestDoc->getRequestHeader(); CAF_CM_VALIDATE_SMARTPTR(requestHeaderVal); const SmartPtrCXmlElement requestHeaderXml = thisXml->createAndAddElement("requestHeader"); RequestHeaderXml::add(requestHeaderVal, requestHeaderXml); const SmartPtrCDiagBatchDoc batchVal = diagRequestDoc->getBatch(); CAF_CM_VALIDATE_SMARTPTR(batchVal); const SmartPtrCXmlElement batchXml = thisXml->createAndAddElement("batch"); DiagBatchXml::add(batchVal, batchXml); } CAF_CM_EXIT; } SmartPtrCDiagRequestDoc DiagRequestXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagRequestXml", "parse"); SmartPtrCDiagRequestDoc diagRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findRequiredAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findRequiredAttribute("pmeId"); const SmartPtrCXmlElement requestHeaderXml = thisXml->findRequiredChild("requestHeader"); SmartPtrCRequestHeaderDoc requestHeaderVal; if (! requestHeaderXml.IsNull()) { requestHeaderVal = RequestHeaderXml::parse(requestHeaderXml); } const SmartPtrCXmlElement batchXml = thisXml->findRequiredChild("batch"); SmartPtrCDiagBatchDoc batchVal; if (! batchXml.IsNull()) { batchVal = DiagBatchXml::parse(batchXml); } diagRequestDoc.CreateInstance(); diagRequestDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, requestHeaderVal, batchVal); } CAF_CM_EXIT; return diagRequestDoc; } DiagRequestXmlRoots.cpp000066400000000000000000000050651321503522500412360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/RequestXml.h" #include "Doc/DocXml/DiagRequestXml/DiagRequestXml.h" #include "Doc/DiagRequestDoc/CDiagRequestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/DiagRequestXml/DiagRequestXmlRoots.h" using namespace Caf; std::string XmlRoots::saveDiagRequestToString( const SmartPtrCDiagRequestDoc diagRequestDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveDiagRequestToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagRequestDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/DiagRequest.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "diagRequest", schemaNamespace, schemaLocation); DiagRequestXml::add(diagRequestDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCDiagRequestDoc XmlRoots::parseDiagRequestFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseDiagRequestFromString"); SmartPtrCDiagRequestDoc diagRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = RequestXml::parseString(xml, "caf:diagRequest"); diagRequestDoc = DiagRequestXml::parse(rootXml); } CAF_CM_EXIT; return diagRequestDoc; } void XmlRoots::saveDiagRequestToFile( const SmartPtrCDiagRequestDoc diagRequestDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveDiagRequestToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagRequestDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string diagRequestStr = saveDiagRequestToString(diagRequestDoc); FileSystemUtils::saveTextFile(filePath, diagRequestStr); } CAF_CM_EXIT; } SmartPtrCDiagRequestDoc XmlRoots::parseDiagRequestFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseDiagRequestFromFile"); SmartPtrCDiagRequestDoc diagRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = RequestXml::parseFile(filePath, "caf:diagRequest"); diagRequestDoc = DiagRequestXml::parse(rootXml); } CAF_CM_EXIT; return diagRequestDoc; } stdafx.h000066400000000000000000000010261321503522500362400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define DIAGREQUESTXML_LINKAGE __declspec(dllexport) #else #define DIAGREQUESTXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ DiagTypesXml/000077500000000000000000000000001321503522500342535ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlDiagBatchXml.cpp000066400000000000000000000065771321503522500372650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/DiagTypesXml/DiagCollectInstancesXml.h" #include "Doc/DocXml/DiagTypesXml/DiagDeleteValueCollectionXml.h" #include "Doc/DocXml/DiagTypesXml/DiagSetValueCollectionXml.h" #include "Doc/DiagTypesDoc/CDiagBatchDoc.h" #include "Doc/DiagTypesDoc/CDiagCollectInstancesDoc.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/DiagTypesXml/DiagBatchXml.h" using namespace Caf; void DiagBatchXml::add( const SmartPtrCDiagBatchDoc diagBatchDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagBatchXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagBatchDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCDiagCollectInstancesDoc collectInstancesVal = diagBatchDoc->getCollectInstances(); if (! collectInstancesVal.IsNull()) { const SmartPtrCXmlElement collectInstancesXml = thisXml->createAndAddElement("collectInstances"); DiagCollectInstancesXml::add(collectInstancesVal, collectInstancesXml); } const SmartPtrCDiagSetValueCollectionDoc setValueCollectionVal = diagBatchDoc->getSetValueCollection(); if (! setValueCollectionVal.IsNull()) { const SmartPtrCXmlElement setValueCollectionXml = thisXml->createAndAddElement("setValueCollection"); DiagSetValueCollectionXml::add(setValueCollectionVal, setValueCollectionXml); } const SmartPtrCDiagDeleteValueCollectionDoc deleteValueCollectionVal = diagBatchDoc->getDeleteValueCollection(); if (! deleteValueCollectionVal.IsNull()) { const SmartPtrCXmlElement deleteValueCollectionXml = thisXml->createAndAddElement("deleteValueCollection"); DiagDeleteValueCollectionXml::add(deleteValueCollectionVal, deleteValueCollectionXml); } } CAF_CM_EXIT; } SmartPtrCDiagBatchDoc DiagBatchXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagBatchXml", "parse"); SmartPtrCDiagBatchDoc diagBatchDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement collectInstancesXml = thisXml->findOptionalChild("collectInstances"); SmartPtrCDiagCollectInstancesDoc collectInstancesVal; if (! collectInstancesXml.IsNull()) { collectInstancesVal = DiagCollectInstancesXml::parse(collectInstancesXml); } const SmartPtrCXmlElement setValueCollectionXml = thisXml->findOptionalChild("setValueCollection"); SmartPtrCDiagSetValueCollectionDoc setValueCollectionVal; if (! setValueCollectionXml.IsNull()) { setValueCollectionVal = DiagSetValueCollectionXml::parse(setValueCollectionXml); } const SmartPtrCXmlElement deleteValueCollectionXml = thisXml->findOptionalChild("deleteValueCollection"); SmartPtrCDiagDeleteValueCollectionDoc deleteValueCollectionVal; if (! deleteValueCollectionXml.IsNull()) { deleteValueCollectionVal = DiagDeleteValueCollectionXml::parse(deleteValueCollectionXml); } diagBatchDoc.CreateInstance(); diagBatchDoc->initialize( collectInstancesVal, setValueCollectionVal, deleteValueCollectionVal); } CAF_CM_EXIT; return diagBatchDoc; } DiagCollectInstancesXml.cpp000066400000000000000000000031521321503522500414630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DiagTypesDoc/CDiagCollectInstancesDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/DiagTypesXml/DiagCollectInstancesXml.h" using namespace Caf; void DiagCollectInstancesXml::add( const SmartPtrCDiagCollectInstancesDoc diagCollectInstancesDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagCollectInstancesXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagCollectInstancesDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdVal = BasePlatform::UuidToString(diagCollectInstancesDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); } CAF_CM_EXIT; } SmartPtrCDiagCollectInstancesDoc DiagCollectInstancesXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagCollectInstancesXml", "parse"); SmartPtrCDiagCollectInstancesDoc diagCollectInstancesDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } diagCollectInstancesDoc.CreateInstance(); diagCollectInstancesDoc->initialize( jobIdVal); } CAF_CM_EXIT; return diagCollectInstancesDoc; } DiagDeleteValueCollectionXml.cpp000066400000000000000000000050331321503522500424410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/DiagTypesXml/DiagDeleteValueXml.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/DiagTypesXml/DiagDeleteValueCollectionXml.h" using namespace Caf; void DiagDeleteValueCollectionXml::add( const SmartPtrCDiagDeleteValueCollectionDoc diagDeleteValueCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagDeleteValueCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagDeleteValueCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque deleteValueVal = diagDeleteValueCollectionDoc->getDeleteValueCollection(); CAF_CM_VALIDATE_STL(deleteValueVal); if (! deleteValueVal.empty()) { for (TConstIterator > deleteValueIter(deleteValueVal); deleteValueIter; deleteValueIter++) { const SmartPtrCXmlElement deleteValueXml = thisXml->createAndAddElement("deleteValue"); DiagDeleteValueXml::add(*deleteValueIter, deleteValueXml); } } } CAF_CM_EXIT; } SmartPtrCDiagDeleteValueCollectionDoc DiagDeleteValueCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagDeleteValueCollectionXml", "parse"); SmartPtrCDiagDeleteValueCollectionDoc diagDeleteValueCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection deleteValueChildrenXml = thisXml->findRequiredChildren("deleteValue"); std::deque deleteValueVal; if (! deleteValueChildrenXml.IsNull() && ! deleteValueChildrenXml->empty()) { for (TConstIterator deleteValueXmlIter(*deleteValueChildrenXml); deleteValueXmlIter; deleteValueXmlIter++) { const SmartPtrCXmlElement deleteValueXml = deleteValueXmlIter->second; const SmartPtrCDiagDeleteValueDoc deleteValueDoc = DiagDeleteValueXml::parse(deleteValueXml); deleteValueVal.push_back(deleteValueDoc); } } diagDeleteValueCollectionDoc.CreateInstance(); diagDeleteValueCollectionDoc->initialize( deleteValueVal); } CAF_CM_EXIT; return diagDeleteValueCollectionDoc; } DiagDeleteValueXml.cpp000066400000000000000000000044461321503522500404340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/DiagTypesXml/DiagDeleteValueXml.h" using namespace Caf; void DiagDeleteValueXml::add( const SmartPtrCDiagDeleteValueDoc diagDeleteValueDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagDeleteValueXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagDeleteValueDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdVal = BasePlatform::UuidToString(diagDeleteValueDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const std::string fileAliasVal = diagDeleteValueDoc->getFileAlias(); CAF_CM_VALIDATE_STRING(fileAliasVal); thisXml->addAttribute("fileAlias", fileAliasVal); const std::string valueNameVal = diagDeleteValueDoc->getValueName(); CAF_CM_VALIDATE_STRING(valueNameVal); const SmartPtrCXmlElement valueNameXml = thisXml->createAndAddElement("valueName"); valueNameXml->setValue(valueNameVal); } CAF_CM_EXIT; } SmartPtrCDiagDeleteValueDoc DiagDeleteValueXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagDeleteValueXml", "parse"); SmartPtrCDiagDeleteValueDoc diagDeleteValueDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const std::string fileAliasStrVal = thisXml->findRequiredAttribute("fileAlias"); const std::string fileAliasVal = fileAliasStrVal; const SmartPtrCXmlElement valueNameXml = thisXml->findRequiredChild("valueName"); std::string valueNameVal; if (! valueNameXml.IsNull()) { valueNameVal = valueNameXml->getValue(); } diagDeleteValueDoc.CreateInstance(); diagDeleteValueDoc->initialize( jobIdVal, fileAliasVal, valueNameVal); } CAF_CM_EXIT; return diagDeleteValueDoc; } DiagSetValueCollectionXml.cpp000066400000000000000000000045771321503522500420060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/DiagTypesXml/DiagSetValueXml.h" #include "Doc/DiagTypesDoc/CDiagSetValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/DiagTypesXml/DiagSetValueCollectionXml.h" using namespace Caf; void DiagSetValueCollectionXml::add( const SmartPtrCDiagSetValueCollectionDoc diagSetValueCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagSetValueCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagSetValueCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque setValueVal = diagSetValueCollectionDoc->getSetValueCollection(); CAF_CM_VALIDATE_STL(setValueVal); if (! setValueVal.empty()) { for (TConstIterator > setValueIter(setValueVal); setValueIter; setValueIter++) { const SmartPtrCXmlElement setValueXml = thisXml->createAndAddElement("setValue"); DiagSetValueXml::add(*setValueIter, setValueXml); } } } CAF_CM_EXIT; } SmartPtrCDiagSetValueCollectionDoc DiagSetValueCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagSetValueCollectionXml", "parse"); SmartPtrCDiagSetValueCollectionDoc diagSetValueCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection setValueChildrenXml = thisXml->findRequiredChildren("setValue"); std::deque setValueVal; if (! setValueChildrenXml.IsNull() && ! setValueChildrenXml->empty()) { for (TConstIterator setValueXmlIter(*setValueChildrenXml); setValueXmlIter; setValueXmlIter++) { const SmartPtrCXmlElement setValueXml = setValueXmlIter->second; const SmartPtrCDiagSetValueDoc setValueDoc = DiagSetValueXml::parse(setValueXml); setValueVal.push_back(setValueDoc); } } diagSetValueCollectionDoc.CreateInstance(); diagSetValueCollectionDoc->initialize( setValueVal); } CAF_CM_EXIT; return diagSetValueCollectionDoc; } DiagSetValueXml.cpp000066400000000000000000000044771321503522500377710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/PropertyXml.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/DiagTypesXml/DiagSetValueXml.h" using namespace Caf; void DiagSetValueXml::add( const SmartPtrCDiagSetValueDoc diagSetValueDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagSetValueXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(diagSetValueDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdVal = BasePlatform::UuidToString(diagSetValueDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const std::string fileAliasVal = diagSetValueDoc->getFileAlias(); CAF_CM_VALIDATE_STRING(fileAliasVal); thisXml->addAttribute("fileAlias", fileAliasVal); const SmartPtrCPropertyDoc valueVal = diagSetValueDoc->getValue(); CAF_CM_VALIDATE_SMARTPTR(valueVal); const SmartPtrCXmlElement valueXml = thisXml->createAndAddElement("value"); PropertyXml::add(valueVal, valueXml); } CAF_CM_EXIT; } SmartPtrCDiagSetValueDoc DiagSetValueXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DiagSetValueXml", "parse"); SmartPtrCDiagSetValueDoc diagSetValueDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const std::string fileAliasStrVal = thisXml->findRequiredAttribute("fileAlias"); const std::string fileAliasVal = fileAliasStrVal; const SmartPtrCXmlElement valueXml = thisXml->findRequiredChild("value"); SmartPtrCPropertyDoc valueVal; if (! valueXml.IsNull()) { valueVal = PropertyXml::parse(valueXml); } diagSetValueDoc.CreateInstance(); diagSetValueDoc->initialize( jobIdVal, fileAliasVal, valueVal); } CAF_CM_EXIT; return diagSetValueDoc; } stdafx.h000066400000000000000000000010221321503522500357100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/DiagTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define DIAGTYPESXML_LINKAGE __declspec(dllexport) #else #define DIAGTYPESXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ MgmtRequestXml/000077500000000000000000000000001321503522500346375ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlMgmtRequestXml.cpp000066400000000000000000000102161321503522500403010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/RequestHeaderXml.h" #include "Doc/DocXml/MgmtTypesXml/MgmtBatchXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXml.h" using namespace Caf; void MgmtRequestXml::add( const SmartPtrCMgmtRequestDoc mgmtRequestDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtRequestXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtRequestDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(mgmtRequestDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string requestIdVal = BasePlatform::UuidToString(mgmtRequestDoc->getRequestId()); CAF_CM_VALIDATE_STRING(requestIdVal); thisXml->addAttribute("requestId", requestIdVal); const std::string pmeIdVal = mgmtRequestDoc->getPmeId(); CAF_CM_VALIDATE_STRING(pmeIdVal); thisXml->addAttribute("pmeId", pmeIdVal); const SmartPtrCRequestHeaderDoc requestHeaderVal = mgmtRequestDoc->getRequestHeader(); CAF_CM_VALIDATE_SMARTPTR(requestHeaderVal); const SmartPtrCXmlElement requestHeaderXml = thisXml->createAndAddElement("requestHeader"); RequestHeaderXml::add(requestHeaderVal, requestHeaderXml); const SmartPtrCMgmtBatchDoc batchVal = mgmtRequestDoc->getBatch(); CAF_CM_VALIDATE_SMARTPTR(batchVal); const SmartPtrCXmlElement batchXml = thisXml->createAndAddElement("batch"); MgmtBatchXml::add(batchVal, batchXml); const SmartPtrCAttachmentCollectionDoc attachmentCollectionVal = mgmtRequestDoc->getAttachmentCollection(); if (! attachmentCollectionVal.IsNull()) { const SmartPtrCXmlElement attachmentCollectionXml = thisXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionVal, attachmentCollectionXml); } } CAF_CM_EXIT; } SmartPtrCMgmtRequestDoc MgmtRequestXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtRequestXml", "parse"); SmartPtrCMgmtRequestDoc mgmtRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findRequiredAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findRequiredAttribute("pmeId"); const SmartPtrCXmlElement requestHeaderXml = thisXml->findRequiredChild("requestHeader"); SmartPtrCRequestHeaderDoc requestHeaderVal; if (! requestHeaderXml.IsNull()) { requestHeaderVal = RequestHeaderXml::parse(requestHeaderXml); } const SmartPtrCXmlElement batchXml = thisXml->findRequiredChild("batch"); SmartPtrCMgmtBatchDoc batchVal; if (! batchXml.IsNull()) { batchVal = MgmtBatchXml::parse(batchXml); } const SmartPtrCXmlElement attachmentCollectionXml = thisXml->findOptionalChild("attachmentCollection"); SmartPtrCAttachmentCollectionDoc attachmentCollectionVal; if (! attachmentCollectionXml.IsNull()) { attachmentCollectionVal = AttachmentCollectionXml::parse(attachmentCollectionXml); } mgmtRequestDoc.CreateInstance(); mgmtRequestDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, requestHeaderVal, batchVal, attachmentCollectionVal); } CAF_CM_EXIT; return mgmtRequestDoc; } MgmtRequestXmlRoots.cpp000066400000000000000000000050651321503522500413360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/RequestXml.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXml.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXmlRoots.h" using namespace Caf; std::string XmlRoots::saveMgmtRequestToString( const SmartPtrCMgmtRequestDoc mgmtRequestDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveMgmtRequestToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtRequestDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/MgmtRequest.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "mgmtRequest", schemaNamespace, schemaLocation); MgmtRequestXml::add(mgmtRequestDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCMgmtRequestDoc XmlRoots::parseMgmtRequestFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseMgmtRequestFromString"); SmartPtrCMgmtRequestDoc mgmtRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = RequestXml::parseString(xml, "caf:mgmtRequest"); mgmtRequestDoc = MgmtRequestXml::parse(rootXml); } CAF_CM_EXIT; return mgmtRequestDoc; } void XmlRoots::saveMgmtRequestToFile( const SmartPtrCMgmtRequestDoc mgmtRequestDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveMgmtRequestToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtRequestDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string mgmtRequestStr = saveMgmtRequestToString(mgmtRequestDoc); FileSystemUtils::saveTextFile(filePath, mgmtRequestStr); } CAF_CM_EXIT; } SmartPtrCMgmtRequestDoc XmlRoots::parseMgmtRequestFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseMgmtRequestFromFile"); SmartPtrCMgmtRequestDoc mgmtRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = RequestXml::parseFile(filePath, "caf:mgmtRequest"); mgmtRequestDoc = MgmtRequestXml::parse(rootXml); } CAF_CM_EXIT; return mgmtRequestDoc; } stdafx.h000066400000000000000000000010261321503522500363000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define MGMTREQUESTXML_LINKAGE __declspec(dllexport) #else #define MGMTREQUESTXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ MgmtTypesXml/000077500000000000000000000000001321503522500343135ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlMgmtBatchXml.cpp000066400000000000000000000070631321503522500373540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/MgmtTypesXml/MgmtCollectInstancesCollectionXml.h" #include "Doc/DocXml/MgmtTypesXml/MgmtCollectSchemaXml.h" #include "Doc/DocXml/MgmtTypesXml/MgmtInvokeOperationCollectionXml.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectSchemaDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MgmtTypesXml/MgmtBatchXml.h" using namespace Caf; void MgmtBatchXml::add( const SmartPtrCMgmtBatchDoc mgmtBatchDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtBatchXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtBatchDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCMgmtCollectSchemaDoc collectSchemaVal = mgmtBatchDoc->getCollectSchema(); if (! collectSchemaVal.IsNull()) { const SmartPtrCXmlElement collectSchemaXml = thisXml->createAndAddElement("collectSchema"); MgmtCollectSchemaXml::add(collectSchemaVal, collectSchemaXml); } const SmartPtrCMgmtCollectInstancesCollectionDoc collectInstancesCollectionVal = mgmtBatchDoc->getCollectInstancesCollection(); if (! collectInstancesCollectionVal.IsNull()) { const SmartPtrCXmlElement collectInstancesCollectionXml = thisXml->createAndAddElement("collectInstancesCollection"); MgmtCollectInstancesCollectionXml::add(collectInstancesCollectionVal, collectInstancesCollectionXml); } const SmartPtrCMgmtInvokeOperationCollectionDoc invokeOperationCollectionVal = mgmtBatchDoc->getInvokeOperationCollection(); if (! invokeOperationCollectionVal.IsNull()) { const SmartPtrCXmlElement invokeOperationCollectionXml = thisXml->createAndAddElement("invokeOperationCollection"); MgmtInvokeOperationCollectionXml::add(invokeOperationCollectionVal, invokeOperationCollectionXml); } } CAF_CM_EXIT; } SmartPtrCMgmtBatchDoc MgmtBatchXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtBatchXml", "parse"); SmartPtrCMgmtBatchDoc mgmtBatchDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement collectSchemaXml = thisXml->findOptionalChild("collectSchema"); SmartPtrCMgmtCollectSchemaDoc collectSchemaVal; if (! collectSchemaXml.IsNull()) { collectSchemaVal = MgmtCollectSchemaXml::parse(collectSchemaXml); } const SmartPtrCXmlElement collectInstancesCollectionXml = thisXml->findOptionalChild("collectInstancesCollection"); SmartPtrCMgmtCollectInstancesCollectionDoc collectInstancesCollectionVal; if (! collectInstancesCollectionXml.IsNull()) { collectInstancesCollectionVal = MgmtCollectInstancesCollectionXml::parse(collectInstancesCollectionXml); } const SmartPtrCXmlElement invokeOperationCollectionXml = thisXml->findOptionalChild("invokeOperationCollection"); SmartPtrCMgmtInvokeOperationCollectionDoc invokeOperationCollectionVal; if (! invokeOperationCollectionXml.IsNull()) { invokeOperationCollectionVal = MgmtInvokeOperationCollectionXml::parse(invokeOperationCollectionXml); } mgmtBatchDoc.CreateInstance(); mgmtBatchDoc->initialize( collectSchemaVal, collectInstancesCollectionVal, invokeOperationCollectionVal); } CAF_CM_EXIT; return mgmtBatchDoc; } MgmtCollectInstancesCollectionXml.cpp000066400000000000000000000054371321503522500436070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/MgmtTypesXml/MgmtCollectInstancesXml.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MgmtTypesXml/MgmtCollectInstancesCollectionXml.h" using namespace Caf; void MgmtCollectInstancesCollectionXml::add( const SmartPtrCMgmtCollectInstancesCollectionDoc mgmtCollectInstancesCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtCollectInstancesCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtCollectInstancesCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque collectInstancesVal = mgmtCollectInstancesCollectionDoc->getCollectInstancesCollection(); CAF_CM_VALIDATE_STL(collectInstancesVal); if (! collectInstancesVal.empty()) { for (TConstIterator > collectInstancesIter(collectInstancesVal); collectInstancesIter; collectInstancesIter++) { const SmartPtrCXmlElement collectInstancesXml = thisXml->createAndAddElement("collectInstances"); MgmtCollectInstancesXml::add(*collectInstancesIter, collectInstancesXml); } } } CAF_CM_EXIT; } SmartPtrCMgmtCollectInstancesCollectionDoc MgmtCollectInstancesCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtCollectInstancesCollectionXml", "parse"); SmartPtrCMgmtCollectInstancesCollectionDoc mgmtCollectInstancesCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection collectInstancesChildrenXml = thisXml->findRequiredChildren("collectInstances"); std::deque collectInstancesVal; if (! collectInstancesChildrenXml.IsNull() && ! collectInstancesChildrenXml->empty()) { for (TConstIterator collectInstancesXmlIter(*collectInstancesChildrenXml); collectInstancesXmlIter; collectInstancesXmlIter++) { const SmartPtrCXmlElement collectInstancesXml = collectInstancesXmlIter->second; const SmartPtrCMgmtCollectInstancesDoc collectInstancesDoc = MgmtCollectInstancesXml::parse(collectInstancesXml); collectInstancesVal.push_back(collectInstancesDoc); } } mgmtCollectInstancesCollectionDoc.CreateInstance(); mgmtCollectInstancesCollectionDoc->initialize( collectInstancesVal); } CAF_CM_EXIT; return mgmtCollectInstancesCollectionDoc; } MgmtCollectInstancesXml.cpp000066400000000000000000000061161321503522500415660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/ClassSpecifierXml.h" #include "Doc/DocXml/CafCoreTypesXml/ParameterCollectionXml.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MgmtTypesXml/MgmtCollectInstancesXml.h" using namespace Caf; void MgmtCollectInstancesXml::add( const SmartPtrCMgmtCollectInstancesDoc mgmtCollectInstancesDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtCollectInstancesXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtCollectInstancesDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdVal = BasePlatform::UuidToString(mgmtCollectInstancesDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const SmartPtrCClassSpecifierDoc classSpecifierVal = mgmtCollectInstancesDoc->getClassSpecifier(); CAF_CM_VALIDATE_SMARTPTR(classSpecifierVal); const SmartPtrCXmlElement classSpecifierXml = thisXml->createAndAddElement("classSpecifier"); ClassSpecifierXml::add(classSpecifierVal, classSpecifierXml); const SmartPtrCParameterCollectionDoc parameterCollectionVal = mgmtCollectInstancesDoc->getParameterCollection(); if (! parameterCollectionVal.IsNull()) { const SmartPtrCXmlElement parameterCollectionXml = thisXml->createAndAddElement("parameterCollection"); ParameterCollectionXml::add(parameterCollectionVal, parameterCollectionXml); } } CAF_CM_EXIT; } SmartPtrCMgmtCollectInstancesDoc MgmtCollectInstancesXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtCollectInstancesXml", "parse"); SmartPtrCMgmtCollectInstancesDoc mgmtCollectInstancesDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const SmartPtrCXmlElement classSpecifierXml = thisXml->findRequiredChild("classSpecifier"); SmartPtrCClassSpecifierDoc classSpecifierVal; if (! classSpecifierXml.IsNull()) { classSpecifierVal = ClassSpecifierXml::parse(classSpecifierXml); } const SmartPtrCXmlElement parameterCollectionXml = thisXml->findOptionalChild("parameterCollection"); SmartPtrCParameterCollectionDoc parameterCollectionVal; if (! parameterCollectionXml.IsNull()) { parameterCollectionVal = ParameterCollectionXml::parse(parameterCollectionXml); } mgmtCollectInstancesDoc.CreateInstance(); mgmtCollectInstancesDoc->initialize( jobIdVal, classSpecifierVal, parameterCollectionVal); } CAF_CM_EXIT; return mgmtCollectInstancesDoc; } MgmtCollectSchemaXml.cpp000066400000000000000000000030721321503522500410350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/MgmtTypesDoc/CMgmtCollectSchemaDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MgmtTypesXml/MgmtCollectSchemaXml.h" using namespace Caf; void MgmtCollectSchemaXml::add( const SmartPtrCMgmtCollectSchemaDoc mgmtCollectSchemaDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtCollectSchemaXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtCollectSchemaDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdVal = BasePlatform::UuidToString(mgmtCollectSchemaDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); } CAF_CM_EXIT; } SmartPtrCMgmtCollectSchemaDoc MgmtCollectSchemaXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtCollectSchemaXml", "parse"); SmartPtrCMgmtCollectSchemaDoc mgmtCollectSchemaDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } mgmtCollectSchemaDoc.CreateInstance(); mgmtCollectSchemaDoc->initialize( jobIdVal); } CAF_CM_EXIT; return mgmtCollectSchemaDoc; } MgmtInvokeOperationCollectionXml.cpp000066400000000000000000000053531321503522500434630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/MgmtTypesXml/MgmtInvokeOperationXml.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MgmtTypesXml/MgmtInvokeOperationCollectionXml.h" using namespace Caf; void MgmtInvokeOperationCollectionXml::add( const SmartPtrCMgmtInvokeOperationCollectionDoc mgmtInvokeOperationCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtInvokeOperationCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtInvokeOperationCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque invokeOperationVal = mgmtInvokeOperationCollectionDoc->getInvokeOperationCollection(); CAF_CM_VALIDATE_STL(invokeOperationVal); if (! invokeOperationVal.empty()) { for (TConstIterator > invokeOperationIter(invokeOperationVal); invokeOperationIter; invokeOperationIter++) { const SmartPtrCXmlElement invokeOperationXml = thisXml->createAndAddElement("invokeOperation"); MgmtInvokeOperationXml::add(*invokeOperationIter, invokeOperationXml); } } } CAF_CM_EXIT; } SmartPtrCMgmtInvokeOperationCollectionDoc MgmtInvokeOperationCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtInvokeOperationCollectionXml", "parse"); SmartPtrCMgmtInvokeOperationCollectionDoc mgmtInvokeOperationCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection invokeOperationChildrenXml = thisXml->findRequiredChildren("invokeOperation"); std::deque invokeOperationVal; if (! invokeOperationChildrenXml.IsNull() && ! invokeOperationChildrenXml->empty()) { for (TConstIterator invokeOperationXmlIter(*invokeOperationChildrenXml); invokeOperationXmlIter; invokeOperationXmlIter++) { const SmartPtrCXmlElement invokeOperationXml = invokeOperationXmlIter->second; const SmartPtrCMgmtInvokeOperationDoc invokeOperationDoc = MgmtInvokeOperationXml::parse(invokeOperationXml); invokeOperationVal.push_back(invokeOperationDoc); } } mgmtInvokeOperationCollectionDoc.CreateInstance(); mgmtInvokeOperationCollectionDoc->initialize( invokeOperationVal); } CAF_CM_EXIT; return mgmtInvokeOperationCollectionDoc; } MgmtInvokeOperationXml.cpp000066400000000000000000000055671321503522500414560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/ClassSpecifierXml.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MgmtTypesXml/MgmtInvokeOperationXml.h" #include "Doc/DocXml/CafCoreTypesXml/OperationXml.h" using namespace Caf; void MgmtInvokeOperationXml::add( const SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperationDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtInvokeOperationXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(mgmtInvokeOperationDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdVal = BasePlatform::UuidToString(mgmtInvokeOperationDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const SmartPtrCClassSpecifierDoc classSpecifierVal = mgmtInvokeOperationDoc->getClassSpecifier(); CAF_CM_VALIDATE_SMARTPTR(classSpecifierVal); const SmartPtrCXmlElement classSpecifierXml = thisXml->createAndAddElement("classSpecifier"); ClassSpecifierXml::add(classSpecifierVal, classSpecifierXml); const SmartPtrCOperationDoc operationVal = mgmtInvokeOperationDoc->getOperation(); CAF_CM_VALIDATE_SMARTPTR(operationVal); const SmartPtrCXmlElement operationXml = thisXml->createAndAddElement("operation"); OperationXml::add(operationVal, operationXml); } CAF_CM_EXIT; } SmartPtrCMgmtInvokeOperationDoc MgmtInvokeOperationXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MgmtInvokeOperationXml", "parse"); SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperationDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const SmartPtrCXmlElement classSpecifierXml = thisXml->findRequiredChild("classSpecifier"); SmartPtrCClassSpecifierDoc classSpecifierVal; if (! classSpecifierXml.IsNull()) { classSpecifierVal = ClassSpecifierXml::parse(classSpecifierXml); } const SmartPtrCXmlElement operationXml = thisXml->findRequiredChild("operation"); SmartPtrCOperationDoc operationVal; if (! operationXml.IsNull()) { operationVal = OperationXml::parse(operationXml); } mgmtInvokeOperationDoc.CreateInstance(); mgmtInvokeOperationDoc->initialize( jobIdVal, classSpecifierVal, operationVal); } CAF_CM_EXIT; return mgmtInvokeOperationDoc; } stdafx.h000066400000000000000000000010221321503522500357500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MgmtTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define MGMTTYPESXML_LINKAGE __declspec(dllexport) #else #define MGMTTYPESXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ MultiPmeMgmtRequestXml/000077500000000000000000000000001321503522500363145ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlMultiPmeMgmtBatchCollectionXml.cpp000066400000000000000000000052411321503522500450420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtBatchXml.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchCollectionDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtBatchCollectionXml.h" using namespace Caf; void MultiPmeMgmtBatchCollectionXml::add( const SmartPtrCMultiPmeMgmtBatchCollectionDoc multiPmeMgmtBatchCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MultiPmeMgmtBatchCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(multiPmeMgmtBatchCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque multiPmeBatchVal = multiPmeMgmtBatchCollectionDoc->getMultiPmeBatch(); CAF_CM_VALIDATE_STL(multiPmeBatchVal); if (! multiPmeBatchVal.empty()) { for (TConstIterator > multiPmeBatchIter(multiPmeBatchVal); multiPmeBatchIter; multiPmeBatchIter++) { const SmartPtrCXmlElement multiPmeBatchXml = thisXml->createAndAddElement("multiPmeBatch"); MultiPmeMgmtBatchXml::add(*multiPmeBatchIter, multiPmeBatchXml); } } } CAF_CM_EXIT; } SmartPtrCMultiPmeMgmtBatchCollectionDoc MultiPmeMgmtBatchCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MultiPmeMgmtBatchCollectionXml", "parse"); SmartPtrCMultiPmeMgmtBatchCollectionDoc multiPmeMgmtBatchCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection multiPmeBatchChildrenXml = thisXml->findRequiredChildren("multiPmeBatch"); std::deque multiPmeBatchVal; if (! multiPmeBatchChildrenXml.IsNull() && ! multiPmeBatchChildrenXml->empty()) { for (TConstIterator multiPmeBatchXmlIter(*multiPmeBatchChildrenXml); multiPmeBatchXmlIter; multiPmeBatchXmlIter++) { const SmartPtrCXmlElement multiPmeBatchXml = multiPmeBatchXmlIter->second; const SmartPtrCMultiPmeMgmtBatchDoc multiPmeBatchDoc = MultiPmeMgmtBatchXml::parse(multiPmeBatchXml); multiPmeBatchVal.push_back(multiPmeBatchDoc); } } multiPmeMgmtBatchCollectionDoc.CreateInstance(); multiPmeMgmtBatchCollectionDoc->initialize( multiPmeBatchVal); } CAF_CM_EXIT; return multiPmeMgmtBatchCollectionDoc; } MultiPmeMgmtBatchXml.cpp000066400000000000000000000046651321503522500430370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/MgmtTypesXml/MgmtBatchXml.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/PmeIdCollectionXml.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CPmeIdCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtBatchXml.h" using namespace Caf; void MultiPmeMgmtBatchXml::add( const SmartPtrCMultiPmeMgmtBatchDoc multiPmeMgmtBatchDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MultiPmeMgmtBatchXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(multiPmeMgmtBatchDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCPmeIdCollectionDoc pmeIdCollectionVal = multiPmeMgmtBatchDoc->getPmeIdCollection(); CAF_CM_VALIDATE_SMARTPTR(pmeIdCollectionVal); const SmartPtrCXmlElement pmeIdCollectionXml = thisXml->createAndAddElement("pmeIdCollection"); PmeIdCollectionXml::add(pmeIdCollectionVal, pmeIdCollectionXml); const SmartPtrCMgmtBatchDoc batchVal = multiPmeMgmtBatchDoc->getBatch(); CAF_CM_VALIDATE_SMARTPTR(batchVal); const SmartPtrCXmlElement batchXml = thisXml->createAndAddElement("batch"); MgmtBatchXml::add(batchVal, batchXml); } CAF_CM_EXIT; } SmartPtrCMultiPmeMgmtBatchDoc MultiPmeMgmtBatchXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MultiPmeMgmtBatchXml", "parse"); SmartPtrCMultiPmeMgmtBatchDoc multiPmeMgmtBatchDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement pmeIdCollectionXml = thisXml->findRequiredChild("pmeIdCollection"); SmartPtrCPmeIdCollectionDoc pmeIdCollectionVal; if (! pmeIdCollectionXml.IsNull()) { pmeIdCollectionVal = PmeIdCollectionXml::parse(pmeIdCollectionXml); } const SmartPtrCXmlElement batchXml = thisXml->findRequiredChild("batch"); SmartPtrCMgmtBatchDoc batchVal; if (! batchXml.IsNull()) { batchVal = MgmtBatchXml::parse(batchXml); } multiPmeMgmtBatchDoc.CreateInstance(); multiPmeMgmtBatchDoc->initialize( pmeIdCollectionVal, batchVal); } CAF_CM_EXIT; return multiPmeMgmtBatchDoc; } MultiPmeMgmtRequestXml.cpp000066400000000000000000000072421321503522500434400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/RequestHeaderXml.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtBatchCollectionXml.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchCollectionDoc.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtRequestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXml.h" using namespace Caf; void MultiPmeMgmtRequestXml::add( const SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MultiPmeMgmtRequestXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(multiPmeMgmtRequestDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(multiPmeMgmtRequestDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string requestIdVal = BasePlatform::UuidToString(multiPmeMgmtRequestDoc->getRequestId()); CAF_CM_VALIDATE_STRING(requestIdVal); thisXml->addAttribute("requestId", requestIdVal); const SmartPtrCRequestHeaderDoc requestHeaderVal = multiPmeMgmtRequestDoc->getRequestHeader(); CAF_CM_VALIDATE_SMARTPTR(requestHeaderVal); const SmartPtrCXmlElement requestHeaderXml = thisXml->createAndAddElement("requestHeader"); RequestHeaderXml::add(requestHeaderVal, requestHeaderXml); const SmartPtrCMultiPmeMgmtBatchCollectionDoc multiPmeBatchCollectionVal = multiPmeMgmtRequestDoc->getMultiPmeBatchCollection(); CAF_CM_VALIDATE_SMARTPTR(multiPmeBatchCollectionVal); const SmartPtrCXmlElement multiPmeBatchCollectionXml = thisXml->createAndAddElement("multiPmeBatchCollection"); MultiPmeMgmtBatchCollectionXml::add(multiPmeBatchCollectionVal, multiPmeBatchCollectionXml); } CAF_CM_EXIT; } SmartPtrCMultiPmeMgmtRequestDoc MultiPmeMgmtRequestXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MultiPmeMgmtRequestXml", "parse"); SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findRequiredAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const SmartPtrCXmlElement requestHeaderXml = thisXml->findRequiredChild("requestHeader"); SmartPtrCRequestHeaderDoc requestHeaderVal; if (! requestHeaderXml.IsNull()) { requestHeaderVal = RequestHeaderXml::parse(requestHeaderXml); } const SmartPtrCXmlElement multiPmeBatchCollectionXml = thisXml->findRequiredChild("multiPmeBatchCollection"); SmartPtrCMultiPmeMgmtBatchCollectionDoc multiPmeBatchCollectionVal; if (! multiPmeBatchCollectionXml.IsNull()) { multiPmeBatchCollectionVal = MultiPmeMgmtBatchCollectionXml::parse(multiPmeBatchCollectionXml); } multiPmeMgmtRequestDoc.CreateInstance(); multiPmeMgmtRequestDoc->initialize( clientIdVal, requestIdVal, requestHeaderVal, multiPmeBatchCollectionVal); } CAF_CM_EXIT; return multiPmeMgmtRequestDoc; } MultiPmeMgmtRequestXmlRoots.cpp000066400000000000000000000056051321503522500444700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/RequestXml.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXml.h" #include "Doc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtRequestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXmlRoots.h" using namespace Caf; std::string XmlRoots::saveMultiPmeMgmtRequestToString( const SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveMultiPmeMgmtRequestToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(multiPmeMgmtRequestDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/MultiPmeMgmtRequest.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "multiPmeMgmtRequest", schemaNamespace, schemaLocation); MultiPmeMgmtRequestXml::add(multiPmeMgmtRequestDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCMultiPmeMgmtRequestDoc XmlRoots::parseMultiPmeMgmtRequestFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseMultiPmeMgmtRequestFromString"); SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = RequestXml::parseString(xml, "caf:multiPmeMgmtRequest"); multiPmeMgmtRequestDoc = MultiPmeMgmtRequestXml::parse(rootXml); } CAF_CM_EXIT; return multiPmeMgmtRequestDoc; } void XmlRoots::saveMultiPmeMgmtRequestToFile( const SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveMultiPmeMgmtRequestToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(multiPmeMgmtRequestDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string multiPmeMgmtRequestStr = saveMultiPmeMgmtRequestToString(multiPmeMgmtRequestDoc); FileSystemUtils::saveTextFile(filePath, multiPmeMgmtRequestStr); } CAF_CM_EXIT; } SmartPtrCMultiPmeMgmtRequestDoc XmlRoots::parseMultiPmeMgmtRequestFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseMultiPmeMgmtRequestFromFile"); SmartPtrCMultiPmeMgmtRequestDoc multiPmeMgmtRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = RequestXml::parseFile(filePath, "caf:multiPmeMgmtRequest"); multiPmeMgmtRequestDoc = MultiPmeMgmtRequestXml::parse(rootXml); } CAF_CM_EXIT; return multiPmeMgmtRequestDoc; } PmeIdCollectionXml.cpp000066400000000000000000000040331321503522500425130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/MultiPmeMgmtRequestDoc/CPmeIdCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/MultiPmeMgmtRequestXml/PmeIdCollectionXml.h" using namespace Caf; void PmeIdCollectionXml::add( const SmartPtrCPmeIdCollectionDoc pmeIdCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PmeIdCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(pmeIdCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque pmeIdVal = pmeIdCollectionDoc->getPmeIdCollection(); CAF_CM_VALIDATE_STL(pmeIdVal); if (! pmeIdVal.empty()) { for (TConstIterator > pmeIdIter(pmeIdVal); pmeIdIter; pmeIdIter++) { const SmartPtrCXmlElement pmeIdXml = thisXml->createAndAddElement("pmeId"); pmeIdXml->setValue(*pmeIdIter); } } } CAF_CM_EXIT; } SmartPtrCPmeIdCollectionDoc PmeIdCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PmeIdCollectionXml", "parse"); SmartPtrCPmeIdCollectionDoc pmeIdCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection pmeIdChildrenXml = thisXml->findRequiredChildren("pmeId"); std::deque pmeIdVal; if (! pmeIdChildrenXml.IsNull() && ! pmeIdChildrenXml->empty()) { for (TConstIterator pmeIdXmlIter(*pmeIdChildrenXml); pmeIdXmlIter; pmeIdXmlIter++) { const SmartPtrCXmlElement pmeIdXml = pmeIdXmlIter->second; const std::string pmeIdDoc = pmeIdXml->getValue(); pmeIdVal.push_back(pmeIdDoc); } } pmeIdCollectionDoc.CreateInstance(); pmeIdCollectionDoc->initialize( pmeIdVal); } CAF_CM_EXIT; return pmeIdCollectionDoc; } stdafx.h000066400000000000000000000010461321503522500377570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define MULTIPMEMGMTREQUESTXML_LINKAGE __declspec(dllexport) #else #define MULTIPMEMGMTREQUESTXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ PayloadEnvelopeXml/000077500000000000000000000000001321503522500354515ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlPayloadEnvelopeXml.cpp000066400000000000000000000120641321503522500417300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PayloadEnvelopeXml/* * Author: bwilliams * Created: July 3, 2015 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/PropertyCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/ProtocolCollectionXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXml.h" using namespace Caf; void PayloadEnvelopeXml::add( const SmartPtrCPayloadEnvelopeDoc payloadEnvelopeDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PayloadEnvelopeXml", "add"); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelopeDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(payloadEnvelopeDoc->getClientId()); if (! clientIdVal.empty()) { thisXml->addAttribute("clientId", clientIdVal); } const std::string requestIdVal = BasePlatform::UuidToString(payloadEnvelopeDoc->getRequestId()); if (! requestIdVal.empty()) { thisXml->addAttribute("requestId", requestIdVal); } const std::string pmeIdVal = payloadEnvelopeDoc->getPmeId(); if (! pmeIdVal.empty()) { thisXml->addAttribute("pmeId", pmeIdVal); } const std::string payloadVersionVal = payloadEnvelopeDoc->getPayloadVersion(); if (! payloadVersionVal.empty()) { thisXml->addAttribute("payloadVersion", payloadVersionVal); } const std::string payloadTypeVal = payloadEnvelopeDoc->getPayloadType(); if (! payloadTypeVal.empty()) { thisXml->addAttribute("payloadType", payloadTypeVal); } const SmartPtrCAttachmentCollectionDoc attachmentCollectionVal = payloadEnvelopeDoc->getAttachmentCollection(); if (! attachmentCollectionVal.IsNull()) { const SmartPtrCXmlElement attachmentCollectionXml = thisXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionVal, attachmentCollectionXml); } const SmartPtrCProtocolCollectionDoc protocolCollectionVal = payloadEnvelopeDoc->getProtocolCollection(); if (! protocolCollectionVal.IsNull()) { const SmartPtrCXmlElement protocolCollectionXml = thisXml->createAndAddElement("protocolCollection"); ProtocolCollectionXml::add(protocolCollectionVal, protocolCollectionXml); } const SmartPtrCPropertyCollectionDoc headerCollectionVal = payloadEnvelopeDoc->getHeaderCollection(); if (! headerCollectionVal.IsNull()) { const SmartPtrCXmlElement headerCollectionXml = thisXml->createAndAddElement("headerCollection"); PropertyCollectionXml::add(headerCollectionVal, headerCollectionXml); } const std::string versionVal = payloadEnvelopeDoc->getVersion().empty() ? "1.0" : payloadEnvelopeDoc->getVersion(); thisXml->addAttribute("version", versionVal); } SmartPtrCPayloadEnvelopeDoc PayloadEnvelopeXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PayloadEnvelopeXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findOptionalAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findOptionalAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findOptionalAttribute("pmeId"); const std::string payloadTypeVal = thisXml->findOptionalAttribute("payloadType"); const std::string payloadVersionVal = thisXml->findOptionalAttribute("payloadVersion"); const SmartPtrCXmlElement attachmentCollectionXml = thisXml->findOptionalChild("attachmentCollection"); SmartPtrCAttachmentCollectionDoc attachmentCollectionVal; if (! attachmentCollectionXml.IsNull()) { attachmentCollectionVal = AttachmentCollectionXml::parse(attachmentCollectionXml); } const SmartPtrCXmlElement protocolCollectionXml = thisXml->findOptionalChild("protocolCollection"); SmartPtrCProtocolCollectionDoc protocolCollectionVal; if (! protocolCollectionXml.IsNull()) { protocolCollectionVal = ProtocolCollectionXml::parse(protocolCollectionXml); } const SmartPtrCXmlElement headerCollectionXml = thisXml->findOptionalChild("headerCollection"); SmartPtrCPropertyCollectionDoc headerCollectionVal; if (! headerCollectionXml.IsNull()) { headerCollectionVal = PropertyCollectionXml::parse(headerCollectionXml); } const std::string versionVal = thisXml->findOptionalAttribute("version"); SmartPtrCPayloadEnvelopeDoc payloadEnvelopeDoc; payloadEnvelopeDoc.CreateInstance(); payloadEnvelopeDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, payloadTypeVal, payloadVersionVal, attachmentCollectionVal, protocolCollectionVal, headerCollectionVal, versionVal); return payloadEnvelopeDoc; } PayloadEnvelopeXmlRoots.cpp000066400000000000000000000044661321503522500427660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PayloadEnvelopeXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXml.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXmlRoots.h" using namespace Caf; std::string XmlRoots::savePayloadEnvelopeToString( const SmartPtrCPayloadEnvelopeDoc payloadEnvelopeDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "savePayloadEnvelopeToString"); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelopeDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/PayloadEnvelope.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "payloadEnvelope", schemaNamespace, schemaLocation); PayloadEnvelopeXml::add(payloadEnvelopeDoc, rootXml); return rootXml->saveToString(); } SmartPtrCPayloadEnvelopeDoc XmlRoots::parsePayloadEnvelopeFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parsePayloadEnvelopeFromString"); CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:payloadEnvelope"); return PayloadEnvelopeXml::parse(rootXml); } void XmlRoots::savePayloadEnvelopeToFile( const SmartPtrCPayloadEnvelopeDoc payloadEnvelopeDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "savePayloadEnvelopeToFile"); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelopeDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string payloadEnvelopeStr = savePayloadEnvelopeToString(payloadEnvelopeDoc); FileSystemUtils::saveTextFile(filePath, payloadEnvelopeStr); } SmartPtrCPayloadEnvelopeDoc XmlRoots::parsePayloadEnvelopeFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parsePayloadEnvelopeFromFile"); CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:payloadEnvelope"); return PayloadEnvelopeXml::parse(rootXml); } stdafx.h000066400000000000000000000010361321503522500371130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PayloadEnvelopeXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PAYLOADENVELOPEXML_LINKAGE __declspec(dllexport) #else #define PAYLOADENVELOPEXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ PersistenceXml/000077500000000000000000000000001321503522500346465ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlAmqpBrokerCollectionXml.cpp000066400000000000000000000000001321503522500421000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXmlAmqpBrokerCollectionXml.h000066400000000000000000000000001321503522500415450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXmlAmqpBrokerXml.cpp000066400000000000000000000000001321503522500400640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXmlAmqpBrokerXml.h000066400000000000000000000000001321503522500375310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXmlCertCollectionXml.cpp000066400000000000000000000033111321503522500407420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/CertCollectionXml.h" using namespace Caf; void CertCollectionXml::add( const SmartPtrCCertCollectionDoc certCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CertCollectionXml", "add"); CAF_CM_VALIDATE_SMARTPTR(certCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque certVal = certCollectionDoc->getCert(); if (! certVal.empty()) { for (TConstIterator > certIter(certVal); certIter; certIter++) { const SmartPtrCXmlElement certXml = thisXml->createAndAddElement("cert"); certXml->setValue(*certIter); } } } SmartPtrCCertCollectionDoc CertCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CertCollectionXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection certChildrenXml = thisXml->findOptionalChildren("cert"); std::deque certVal; if (! certChildrenXml.IsNull() && ! certChildrenXml->empty()) { for (TConstIterator certXmlIter(*certChildrenXml); certXmlIter; certXmlIter++) { const SmartPtrCXmlElement certXml = certXmlIter->second; const std::string certDoc = certXml->getValue(); certVal.push_back(certDoc); } } SmartPtrCCertCollectionDoc certCollectionDoc; certCollectionDoc.CreateInstance(); certCollectionDoc->initialize(certVal); return certCollectionDoc; } CertPathCollectionXml.cpp000066400000000000000000000035651321503522500415720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/CertPathCollectionXml.h" using namespace Caf; void CertPathCollectionXml::add( const SmartPtrCCertPathCollectionDoc certPathCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CertPathCollectionXml", "add"); CAF_CM_VALIDATE_SMARTPTR(certPathCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque certPathVal = certPathCollectionDoc->getCertPath(); if (! certPathVal.empty()) { for (TConstIterator > certPathIter(certPathVal); certPathIter; certPathIter++) { const SmartPtrCXmlElement certPathXml = thisXml->createAndAddElement("certPath"); certPathXml->setValue(*certPathIter); } } } SmartPtrCCertPathCollectionDoc CertPathCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CertPathCollectionXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection certPathChildrenXml = thisXml->findOptionalChildren("certPath"); std::deque certPathVal; if (! certPathChildrenXml.IsNull() && ! certPathChildrenXml->empty()) { for (TConstIterator certPathXmlIter(*certPathChildrenXml); certPathXmlIter; certPathXmlIter++) { const SmartPtrCXmlElement certPathXml = certPathXmlIter->second; const std::string certPathDoc = certPathXml->getValue(); certPathVal.push_back(certPathDoc); } } SmartPtrCCertPathCollectionDoc certPathCollectionDoc; certPathCollectionDoc.CreateInstance(); certPathCollectionDoc->initialize(certPathVal); return certPathCollectionDoc; } LocalSecurityXml.cpp000066400000000000000000000046651321503522500406300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/LocalSecurityXml.h" using namespace Caf; void LocalSecurityXml::add( const SmartPtrCLocalSecurityDoc localSecurityDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("LocalSecurityXml", "add"); CAF_CM_VALIDATE_SMARTPTR(localSecurityDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string localIdVal = localSecurityDoc->getLocalId(); if (! localIdVal.empty()) { thisXml->addAttribute("localId", localIdVal); } const std::string privateKeyVal = localSecurityDoc->getPrivateKey(); if (! privateKeyVal.empty()) { const SmartPtrCXmlElement privateKeyXml = thisXml->createAndAddElement("privateKey"); privateKeyXml->setValue(privateKeyVal); } const std::string certVal = localSecurityDoc->getCert(); if (! certVal.empty()) { const SmartPtrCXmlElement certXml = thisXml->createAndAddElement("cert"); certXml->setValue(certVal); } const std::string privateKeyPathVal = localSecurityDoc->getPrivateKeyPath(); if (! privateKeyPathVal.empty()) { thisXml->addAttribute("privateKeyPath", privateKeyPathVal); } const std::string certPathVal = localSecurityDoc->getCertPath(); if (! certPathVal.empty()) { thisXml->addAttribute("certPath", certPathVal); } } SmartPtrCLocalSecurityDoc LocalSecurityXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("LocalSecurityXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string localIdVal = thisXml->findOptionalAttribute("localId"); std::string privateKeyVal; const SmartPtrCXmlElement privateKeyXml = thisXml->findOptionalChild("privateKey"); if (privateKeyXml) { privateKeyVal = privateKeyXml->getValue(); } std::string certVal; const SmartPtrCXmlElement certXml = thisXml->findOptionalChild("cert"); if (certXml) { certVal = certXml->getValue(); } const std::string privateKeyPathVal = thisXml->findOptionalAttribute("privateKeyPath"); const std::string certPathVal = thisXml->findOptionalAttribute("certPath"); SmartPtrCLocalSecurityDoc localSecurityDoc; localSecurityDoc.CreateInstance(); localSecurityDoc->initialize( localIdVal, privateKeyVal, certVal, privateKeyPathVal, certPathVal); return localSecurityDoc; } PersistenceProtocolCollectionXml.cpp000066400000000000000000000051011321503522500440520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/PersistenceProtocolXml.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/PersistenceProtocolCollectionXml.h" using namespace Caf; void PersistenceProtocolCollectionXml::add( const SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PersistenceProtocolCollectionXml", "add"); CAF_CM_VALIDATE_SMARTPTR(persistenceProtocolCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque persistenceProtocolVal = persistenceProtocolCollectionDoc->getPersistenceProtocol(); if (! persistenceProtocolVal.empty()) { for (TConstIterator > persistenceProtocolIter(persistenceProtocolVal); persistenceProtocolIter; persistenceProtocolIter++) { const SmartPtrCXmlElement persistenceProtocolXml = thisXml->createAndAddElement("persistenceProtocol"); PersistenceProtocolXml::add(*persistenceProtocolIter, persistenceProtocolXml); } } } SmartPtrCPersistenceProtocolCollectionDoc PersistenceProtocolCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PersistenceProtocolCollectionXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection persistenceProtocolChildrenXml = thisXml->findOptionalChildren("persistenceProtocol"); std::deque persistenceProtocolVal; if (! persistenceProtocolChildrenXml.IsNull() && ! persistenceProtocolChildrenXml->empty()) { for (TConstIterator persistenceProtocolXmlIter(*persistenceProtocolChildrenXml); persistenceProtocolXmlIter; persistenceProtocolXmlIter++) { const SmartPtrCXmlElement persistenceProtocolXml = persistenceProtocolXmlIter->second; const SmartPtrCPersistenceProtocolDoc persistenceProtocolDoc = PersistenceProtocolXml::parse(persistenceProtocolXml); persistenceProtocolVal.push_back(persistenceProtocolDoc); } } SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollectionDoc; persistenceProtocolCollectionDoc.CreateInstance(); persistenceProtocolCollectionDoc->initialize( persistenceProtocolVal); return persistenceProtocolCollectionDoc; } PersistenceProtocolXml.cpp000066400000000000000000000142311321503522500420420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/CertCollectionXml.h" #include "Doc/DocXml/PersistenceXml/CertPathCollectionXml.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/PersistenceProtocolXml.h" using namespace Caf; void PersistenceProtocolXml::add( const SmartPtrCPersistenceProtocolDoc persistenceProtocolDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PersistenceProtocolXml", "add"); CAF_CM_VALIDATE_SMARTPTR(persistenceProtocolDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string protocolNameVal = persistenceProtocolDoc->getProtocolName(); if (! protocolNameVal.empty()) { thisXml->addAttribute("protocolName", protocolNameVal); } const std::string uriVal = persistenceProtocolDoc->getUri(); if (! uriVal.empty()) { thisXml->addAttribute("uri", uriVal); } const std::string uriAmqpVal = persistenceProtocolDoc->getUriAmqp(); if (! uriAmqpVal.empty()) { thisXml->addAttribute("uriAmqp", uriAmqpVal); } const std::string uriTunnelVal = persistenceProtocolDoc->getUriTunnel(); if (! uriTunnelVal.empty()) { thisXml->addAttribute("uriTunnel", uriTunnelVal); } const std::string tlsCertVal = persistenceProtocolDoc->getTlsCert(); if (! tlsCertVal.empty()) { const SmartPtrCXmlElement tlsCertXml = thisXml->createAndAddElement("tlsCert"); tlsCertXml->setValue(tlsCertVal); } const std::string tlsProtocolVal = persistenceProtocolDoc->getTlsProtocol(); if (! tlsProtocolVal.empty()) { thisXml->addAttribute("tlsProtocol", tlsProtocolVal); } const Cdeqstr tlsCipherCollectionVal = persistenceProtocolDoc->getTlsCipherCollection(); if (! tlsCipherCollectionVal.empty()) { const SmartPtrCXmlElement tlsCipherCollectionXml = thisXml->createAndAddElement("tlsCipherCollection"); for (TConstIterator > valueIter(tlsCipherCollectionVal); valueIter; valueIter++) { const SmartPtrCXmlElement valueXml = tlsCipherCollectionXml->createAndAddElement("cipher"); valueXml->setValue(*valueIter); } } const SmartPtrCCertCollectionDoc tlsCertCollectionVal = persistenceProtocolDoc->getTlsCertCollection(); if (! tlsCertCollectionVal.IsNull()) { const SmartPtrCXmlElement tlsCertCollectionXml = thisXml->createAndAddElement("tlsCertCollection"); CertCollectionXml::add(tlsCertCollectionVal, tlsCertCollectionXml); } const std::string uriAmqpPathVal = persistenceProtocolDoc->getUriAmqpPath(); if (! uriAmqpPathVal.empty()) { thisXml->addAttribute("uriAmqpPath", uriAmqpPathVal); } const std::string uriTunnelPathVal = persistenceProtocolDoc->getUriTunnelPath(); if (! uriTunnelPathVal.empty()) { thisXml->addAttribute("uriTunnelPath", uriTunnelPathVal); } const std::string tlsCertPathVal = persistenceProtocolDoc->getTlsCertPath(); if (! tlsCertPathVal.empty()) { thisXml->addAttribute("tlsCertPath", tlsCertPathVal); } const SmartPtrCCertPathCollectionDoc tlsCertPathCollectionVal = persistenceProtocolDoc->getTlsCertPathCollection(); if (! tlsCertPathCollectionVal.IsNull()) { const SmartPtrCXmlElement tlsCertPathCollectionXml = thisXml->createAndAddElement("tlsCertPathCollection"); CertPathCollectionXml::add(tlsCertPathCollectionVal, tlsCertPathCollectionXml); } } SmartPtrCPersistenceProtocolDoc PersistenceProtocolXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PersistenceProtocolXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string protocolNameVal = thisXml->findOptionalAttribute("protocolName"); const std::string uriVal = thisXml->findOptionalAttribute("uri"); const std::string uriAmqpVal = thisXml->findOptionalAttribute("uriAmqp"); const std::string uriTunnelVal = thisXml->findOptionalAttribute("uriTunnel"); std::string tlsCertVal; const SmartPtrCXmlElement tlsCertXml = thisXml->findOptionalChild("tlsCert"); if (tlsCertXml) { tlsCertVal = tlsCertXml->getValue(); } const std::string tlsProtocolVal = thisXml->findOptionalAttribute("tlsProtocol"); const SmartPtrCXmlElement tlsCipherCollectionXml = thisXml->findOptionalChild("tlsCipherCollection"); std::deque tlsCipherCollectionVal; if (! tlsCipherCollectionXml.IsNull()) { const CXmlElement::SmartPtrCElementCollection valueCollectionXml = tlsCipherCollectionXml->findOptionalChildren("cipher"); if (! valueCollectionXml.IsNull() && ! valueCollectionXml->empty()) { for (TConstIterator valueXmlIter(*valueCollectionXml); valueXmlIter; valueXmlIter++) { const SmartPtrCXmlElement valueXml = valueXmlIter->second; const std::string valueDoc = valueXml->getValue(); tlsCipherCollectionVal.push_back(valueDoc); } } } const SmartPtrCXmlElement tlsCertCollectionXml = thisXml->findOptionalChild("tlsCertCollection"); SmartPtrCCertCollectionDoc tlsCertCollectionVal; if (! tlsCertCollectionXml.IsNull()) { tlsCertCollectionVal = CertCollectionXml::parse(tlsCertCollectionXml); } const std::string uriAmqpPathVal = thisXml->findOptionalAttribute("uriAmqpPath"); const std::string uriTunnelPathVal = thisXml->findOptionalAttribute("uriTunnelPath"); const std::string tlsCertPathVal = thisXml->findOptionalAttribute("tlsCertPath"); const SmartPtrCXmlElement tlsCertPathCollectionXml = thisXml->findOptionalChild("tlsCertPathCollection"); SmartPtrCCertPathCollectionDoc tlsCertPathCollectionVal; if (! tlsCertPathCollectionXml.IsNull()) { tlsCertPathCollectionVal = CertPathCollectionXml::parse(tlsCertPathCollectionXml); } SmartPtrCPersistenceProtocolDoc persistenceProtocolDoc; persistenceProtocolDoc.CreateInstance(); persistenceProtocolDoc->initialize( protocolNameVal, uriVal, uriAmqpVal, uriTunnelVal, tlsCertVal, tlsProtocolVal, tlsCipherCollectionVal, tlsCertCollectionVal, uriAmqpPathVal, uriTunnelPathVal, tlsCertPathVal, tlsCertPathCollectionVal); return persistenceProtocolDoc; } PersistenceXml.cpp000066400000000000000000000071051321503522500403220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/LocalSecurityXml.h" #include "Doc/DocXml/PersistenceXml/PersistenceProtocolCollectionXml.h" #include "Doc/DocXml/PersistenceXml/RemoteSecurityCollectionXml.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/PersistenceXml.h" using namespace Caf; void PersistenceXml::add( const SmartPtrCPersistenceDoc persistenceDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PersistenceXml", "add"); CAF_CM_VALIDATE_SMARTPTR(persistenceDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCLocalSecurityDoc localSecurityVal = persistenceDoc->getLocalSecurity(); if (! localSecurityVal.IsNull()) { const SmartPtrCXmlElement localSecurityXml = thisXml->createAndAddElement("localSecurity"); LocalSecurityXml::add(localSecurityVal, localSecurityXml); } const SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollectionVal = persistenceDoc->getRemoteSecurityCollection(); if (! remoteSecurityCollectionVal.IsNull()) { const SmartPtrCXmlElement remoteSecurityCollectionXml = thisXml->createAndAddElement("remoteSecurityCollection"); RemoteSecurityCollectionXml::add(remoteSecurityCollectionVal, remoteSecurityCollectionXml); } const SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollectionVal = persistenceDoc->getPersistenceProtocolCollection(); if (! persistenceProtocolCollectionVal.IsNull()) { const SmartPtrCXmlElement persistenceProtocolCollectionXml = thisXml->createAndAddElement("persistenceProtocolCollection"); PersistenceProtocolCollectionXml::add(persistenceProtocolCollectionVal, persistenceProtocolCollectionXml); } const std::string versionVal = persistenceDoc->getVersion().empty() ? "1.0" : persistenceDoc->getVersion(); thisXml->addAttribute("version", versionVal); } SmartPtrCPersistenceDoc PersistenceXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PersistenceXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement localSecurityXml = thisXml->findOptionalChild("localSecurity"); SmartPtrCLocalSecurityDoc localSecurityVal; if (! localSecurityXml.IsNull()) { localSecurityVal = LocalSecurityXml::parse(localSecurityXml); } const SmartPtrCXmlElement remoteSecurityCollectionXml = thisXml->findOptionalChild("remoteSecurityCollection"); SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollectionVal; if (! remoteSecurityCollectionXml.IsNull()) { remoteSecurityCollectionVal = RemoteSecurityCollectionXml::parse(remoteSecurityCollectionXml); } const SmartPtrCXmlElement persistenceProtocolCollectionXml = thisXml->findOptionalChild("persistenceProtocolCollection"); SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollectionVal; if (! persistenceProtocolCollectionXml.IsNull()) { persistenceProtocolCollectionVal = PersistenceProtocolCollectionXml::parse(persistenceProtocolCollectionXml); } const std::string versionVal = thisXml->findOptionalAttribute("version"); SmartPtrCPersistenceDoc persistenceDoc; persistenceDoc.CreateInstance(); persistenceDoc->initialize( localSecurityVal, remoteSecurityCollectionVal, persistenceProtocolCollectionVal, versionVal); return persistenceDoc; } PersistenceXmlRoots.cpp000066400000000000000000000040471321503522500413530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/PersistenceXml.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlRoots.h" using namespace Caf; std::string XmlRoots::savePersistenceToString( const SmartPtrCPersistenceDoc persistenceDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "savePersistenceToString"); CAF_CM_VALIDATE_SMARTPTR(persistenceDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/Persistence.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "persistence", schemaNamespace, schemaLocation); PersistenceXml::add(persistenceDoc, rootXml); return rootXml->saveToString(); } SmartPtrCPersistenceDoc XmlRoots::parsePersistenceFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parsePersistenceFromString"); CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:persistence"); return PersistenceXml::parse(rootXml); } void XmlRoots::savePersistenceToFile( const SmartPtrCPersistenceDoc persistenceDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "savePersistenceToFile"); CAF_CM_VALIDATE_SMARTPTR(persistenceDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string persistenceStr = savePersistenceToString(persistenceDoc); FileSystemUtils::saveTextFile(filePath, persistenceStr); } SmartPtrCPersistenceDoc XmlRoots::parsePersistenceFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parsePersistenceFromFile"); CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:persistence"); return PersistenceXml::parse(rootXml); } RemoteSecurityCollectionXml.cpp000066400000000000000000000045021321503522500430330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/RemoteSecurityXml.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/RemoteSecurityCollectionXml.h" using namespace Caf; void RemoteSecurityCollectionXml::add( const SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RemoteSecurityCollectionXml", "add"); CAF_CM_VALIDATE_SMARTPTR(remoteSecurityCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque remoteSecurityVal = remoteSecurityCollectionDoc->getRemoteSecurity(); if (! remoteSecurityVal.empty()) { for (TConstIterator > remoteSecurityIter(remoteSecurityVal); remoteSecurityIter; remoteSecurityIter++) { const SmartPtrCXmlElement remoteSecurityXml = thisXml->createAndAddElement("remoteSecurity"); RemoteSecurityXml::add(*remoteSecurityIter, remoteSecurityXml); } } } SmartPtrCRemoteSecurityCollectionDoc RemoteSecurityCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RemoteSecurityCollectionXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection remoteSecurityChildrenXml = thisXml->findOptionalChildren("remoteSecurity"); std::deque remoteSecurityVal; if (! remoteSecurityChildrenXml.IsNull() && ! remoteSecurityChildrenXml->empty()) { for (TConstIterator remoteSecurityXmlIter(*remoteSecurityChildrenXml); remoteSecurityXmlIter; remoteSecurityXmlIter++) { const SmartPtrCXmlElement remoteSecurityXml = remoteSecurityXmlIter->second; const SmartPtrCRemoteSecurityDoc remoteSecurityDoc = RemoteSecurityXml::parse(remoteSecurityXml); remoteSecurityVal.push_back(remoteSecurityDoc); } } SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollectionDoc; remoteSecurityCollectionDoc.CreateInstance(); remoteSecurityCollectionDoc->initialize( remoteSecurityVal); return remoteSecurityCollectionDoc; } RemoteSecurityXml.cpp000066400000000000000000000075641321503522500410320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/CertCollectionXml.h" #include "Doc/DocXml/PersistenceXml/CertPathCollectionXml.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CCertPathCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/RemoteSecurityXml.h" using namespace Caf; void RemoteSecurityXml::add( const SmartPtrCRemoteSecurityDoc remoteSecurityDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RemoteSecurityXml", "add"); CAF_CM_VALIDATE_SMARTPTR(remoteSecurityDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string remoteIdVal = remoteSecurityDoc->getRemoteId(); if (! remoteIdVal.empty()) { thisXml->addAttribute("remoteId", remoteIdVal); } const std::string protocolNameVal = remoteSecurityDoc->getProtocolName(); if (! protocolNameVal.empty()) { thisXml->addAttribute("protocolName", protocolNameVal); } const std::string cmsCertVal = remoteSecurityDoc->getCmsCert(); if (! cmsCertVal.empty()) { const SmartPtrCXmlElement cmsCertXml = thisXml->createAndAddElement("cmsCert"); cmsCertXml->setValue(cmsCertVal); } const std::string cmsCipherNameVal = remoteSecurityDoc->getCmsCipherName(); if (! cmsCipherNameVal.empty()) { thisXml->addAttribute("cmsCipherName", cmsCipherNameVal); } const SmartPtrCCertCollectionDoc cmsCertCollectionVal = remoteSecurityDoc->getCmsCertCollection(); if (! cmsCertCollectionVal.IsNull()) { const SmartPtrCXmlElement cmsCertCollectionXml = thisXml->createAndAddElement("cmsCertCollection"); CertCollectionXml::add(cmsCertCollectionVal, cmsCertCollectionXml); } const std::string cmsCertPathVal = remoteSecurityDoc->getCmsCertPath(); if (! cmsCertPathVal.empty()) { thisXml->addAttribute("cmsCertPath", cmsCertPathVal); } const SmartPtrCCertPathCollectionDoc cmsCertPathCollectionVal = remoteSecurityDoc->getCmsCertPathCollection(); if (! cmsCertPathCollectionVal.IsNull()) { const SmartPtrCXmlElement cmsCertPathCollectionXml = thisXml->createAndAddElement("cmsCertPathCollection"); CertPathCollectionXml::add(cmsCertPathCollectionVal, cmsCertPathCollectionXml); } } SmartPtrCRemoteSecurityDoc RemoteSecurityXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("RemoteSecurityXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string remoteIdVal = thisXml->findOptionalAttribute("remoteId"); const std::string protocolNameVal = thisXml->findOptionalAttribute("protocolName"); std::string cmsCertVal; const SmartPtrCXmlElement cmsCertXml = thisXml->findOptionalChild("cmsCert"); if (cmsCertXml) { cmsCertVal = cmsCertXml->getValue(); } const std::string cmsCipherNameVal = thisXml->findOptionalAttribute("cmsCipherName"); const SmartPtrCXmlElement cmsCertCollectionXml = thisXml->findOptionalChild("cmsCertCollection"); SmartPtrCCertCollectionDoc cmsCertCollectionVal; if (! cmsCertCollectionXml.IsNull()) { cmsCertCollectionVal = CertCollectionXml::parse(cmsCertCollectionXml); } const std::string cmsCertPathVal = thisXml->findOptionalAttribute("cmsCertPath"); const SmartPtrCXmlElement cmsCertPathCollectionXml = thisXml->findOptionalChild("cmsCertPathCollection"); SmartPtrCCertPathCollectionDoc cmsCertPathCollectionVal; if (! cmsCertPathCollectionXml.IsNull()) { cmsCertPathCollectionVal = CertPathCollectionXml::parse(cmsCertPathCollectionXml); } SmartPtrCRemoteSecurityDoc remoteSecurityDoc; remoteSecurityDoc.CreateInstance(); remoteSecurityDoc->initialize( remoteIdVal, protocolNameVal, cmsCertVal, cmsCipherNameVal, cmsCertCollectionVal, cmsCertPathVal, cmsCertPathCollectionVal); return remoteSecurityDoc; } stdafx.h000066400000000000000000000006171321503522500363140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PERSISTENCEXML_LINKAGE __declspec(dllexport) #else #define PERSISTENCEXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ ProviderInfraXml/000077500000000000000000000000001321503522500351345ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlClassCollectionXml.cpp000066400000000000000000000052471321503522500414120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/FullyQualifiedClassGroupXml.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/ProviderInfraDoc/CClassCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderInfraXml/ClassCollectionXml.h" using namespace Caf; void ClassCollectionXml::add( const SmartPtrCClassCollectionDoc classCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(classCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque fullyQualifiedClassVal = classCollectionDoc->getFullyQualifiedClass(); CAF_CM_VALIDATE_STL(fullyQualifiedClassVal); if (! fullyQualifiedClassVal.empty()) { for (TConstIterator > fullyQualifiedClassIter(fullyQualifiedClassVal); fullyQualifiedClassIter; fullyQualifiedClassIter++) { const SmartPtrCXmlElement fullyQualifiedClassXml = thisXml->createAndAddElement("fullyQualifiedClass"); FullyQualifiedClassGroupXml::add(*fullyQualifiedClassIter, fullyQualifiedClassXml); } } } CAF_CM_EXIT; } SmartPtrCClassCollectionDoc ClassCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassCollectionXml", "parse"); SmartPtrCClassCollectionDoc classCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection fullyQualifiedClassChildrenXml = thisXml->findRequiredChildren("fullyQualifiedClass"); std::deque fullyQualifiedClassVal; if (! fullyQualifiedClassChildrenXml.IsNull() && ! fullyQualifiedClassChildrenXml->empty()) { for (TConstIterator fullyQualifiedClassXmlIter(*fullyQualifiedClassChildrenXml); fullyQualifiedClassXmlIter; fullyQualifiedClassXmlIter++) { const SmartPtrCXmlElement fullyQualifiedClassXml = fullyQualifiedClassXmlIter->second; const SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClassDoc = FullyQualifiedClassGroupXml::parse(fullyQualifiedClassXml); fullyQualifiedClassVal.push_back(fullyQualifiedClassDoc); } } classCollectionDoc.CreateInstance(); classCollectionDoc->initialize( fullyQualifiedClassVal); } CAF_CM_EXIT; return classCollectionDoc; } ProviderInfraXmlRoots.cpp000066400000000000000000000112621321503522500421240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderInfraXml/ProviderRegXml.h" #include "Doc/DocXml/ProviderInfraXml/SchemaSummaryXml.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlRoots.h" using namespace Caf; std::string XmlRoots::saveProviderRegToString( const SmartPtrCProviderRegDoc providerRegDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveProviderRegToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerRegDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/ProviderInfra.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "providerReg", schemaNamespace, schemaLocation); ProviderRegXml::add(providerRegDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCProviderRegDoc XmlRoots::parseProviderRegFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderRegFromString"); SmartPtrCProviderRegDoc providerRegDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:providerReg"); providerRegDoc = ProviderRegXml::parse(rootXml); } CAF_CM_EXIT; return providerRegDoc; } void XmlRoots::saveProviderRegToFile( const SmartPtrCProviderRegDoc providerRegDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveProviderRegToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerRegDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string providerRegStr = saveProviderRegToString(providerRegDoc); FileSystemUtils::saveTextFile(filePath, providerRegStr); } CAF_CM_EXIT; } SmartPtrCProviderRegDoc XmlRoots::parseProviderRegFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderRegFromFile"); SmartPtrCProviderRegDoc providerRegDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:providerReg"); providerRegDoc = ProviderRegXml::parse(rootXml); } CAF_CM_EXIT; return providerRegDoc; } std::string XmlRoots::saveSchemaSummaryToString( const SmartPtrCSchemaSummaryDoc schemaSummaryDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveSchemaSummaryToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(schemaSummaryDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/ProviderInfra.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "schemaSummary", schemaNamespace, schemaLocation); SchemaSummaryXml::add(schemaSummaryDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCSchemaSummaryDoc XmlRoots::parseSchemaSummaryFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseSchemaSummaryFromString"); SmartPtrCSchemaSummaryDoc schemaSummaryDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:schemaSummary"); schemaSummaryDoc = SchemaSummaryXml::parse(rootXml); } CAF_CM_EXIT; return schemaSummaryDoc; } void XmlRoots::saveSchemaSummaryToFile( const SmartPtrCSchemaSummaryDoc schemaSummaryDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveSchemaSummaryToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(schemaSummaryDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string schemaSummaryStr = saveSchemaSummaryToString(schemaSummaryDoc); FileSystemUtils::saveTextFile(filePath, schemaSummaryStr); } CAF_CM_EXIT; } SmartPtrCSchemaSummaryDoc XmlRoots::parseSchemaSummaryFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseSchemaSummaryFromFile"); SmartPtrCSchemaSummaryDoc schemaSummaryDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:schemaSummary"); schemaSummaryDoc = SchemaSummaryXml::parse(rootXml); } CAF_CM_EXIT; return schemaSummaryDoc; } ProviderRegXml.cpp000066400000000000000000000066541321503522500405640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderInfraXml/ProviderRegXml.h" using namespace Caf; void ProviderRegXml::add( const SmartPtrCProviderRegDoc providerRegDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderRegXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerRegDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string providerNamespaceVal = providerRegDoc->getProviderNamespace(); CAF_CM_VALIDATE_STRING(providerNamespaceVal); thisXml->addAttribute("providerNamespace", providerNamespaceVal); const std::string providerNameVal = providerRegDoc->getProviderName(); CAF_CM_VALIDATE_STRING(providerNameVal); thisXml->addAttribute("providerName", providerNameVal); const std::string providerVersionVal = providerRegDoc->getProviderVersion(); CAF_CM_VALIDATE_STRING(providerVersionVal); thisXml->addAttribute("providerVersion", providerVersionVal); const std::string staleSecVal = CStringConv::toString(providerRegDoc->getStaleSec()); CAF_CM_VALIDATE_STRING(staleSecVal); thisXml->addAttribute("staleSec", staleSecVal); const std::string isSchemaVisibleVal = providerRegDoc->getIsSchemaVisible() ? "true" : "false"; CAF_CM_VALIDATE_STRING(isSchemaVisibleVal); thisXml->addAttribute("isSchemaVisible", isSchemaVisibleVal); const std::string invokerRelPathVal = providerRegDoc->getInvokerRelPath(); if (! invokerRelPathVal.empty()) { thisXml->addAttribute("invokerRelPath", invokerRelPathVal); } } CAF_CM_EXIT; } SmartPtrCProviderRegDoc ProviderRegXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderRegXml", "parse"); SmartPtrCProviderRegDoc providerRegDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string providerNamespaceStrVal = thisXml->findRequiredAttribute("providerNamespace"); const std::string providerNamespaceVal = providerNamespaceStrVal; const std::string providerNameStrVal = thisXml->findRequiredAttribute("providerName"); const std::string providerNameVal = providerNameStrVal; const std::string providerVersionStrVal = thisXml->findRequiredAttribute("providerVersion"); const std::string providerVersionVal = providerVersionStrVal; const std::string staleSecStrVal = thisXml->findRequiredAttribute("staleSec"); int32 staleSecVal = 0; if (! staleSecStrVal.empty()) { staleSecVal = CStringConv::fromString(staleSecStrVal); } const std::string isSchemaVisibleStrVal = thisXml->findRequiredAttribute("isSchemaVisible"); bool isSchemaVisibleVal = false; if (! isSchemaVisibleStrVal.empty()) { isSchemaVisibleVal = (isSchemaVisibleStrVal.compare("true") == 0) ? true : false; } const std::string invokerRelPathStrVal = thisXml->findOptionalAttribute("invokerRelPath"); const std::string invokerRelPathVal = invokerRelPathStrVal; providerRegDoc.CreateInstance(); providerRegDoc->initialize( providerNamespaceVal, providerNameVal, providerVersionVal, staleSecVal, isSchemaVisibleVal, invokerRelPathVal); } CAF_CM_EXIT; return providerRegDoc; } SchemaSummaryXml.cpp000066400000000000000000000063631321503522500411070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderInfraXml/ClassCollectionXml.h" #include "Doc/ProviderInfraDoc/CClassCollectionDoc.h" #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderInfraXml/SchemaSummaryXml.h" using namespace Caf; void SchemaSummaryXml::add( const SmartPtrCSchemaSummaryDoc schemaSummaryDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("SchemaSummaryXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(schemaSummaryDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string providerNamespaceVal = schemaSummaryDoc->getProviderNamespace(); CAF_CM_VALIDATE_STRING(providerNamespaceVal); thisXml->addAttribute("providerNamespace", providerNamespaceVal); const std::string providerNameVal = schemaSummaryDoc->getProviderName(); CAF_CM_VALIDATE_STRING(providerNameVal); thisXml->addAttribute("providerName", providerNameVal); const std::string providerVersionVal = schemaSummaryDoc->getProviderVersion(); CAF_CM_VALIDATE_STRING(providerVersionVal); thisXml->addAttribute("providerVersion", providerVersionVal); const SmartPtrCClassCollectionDoc classCollectionVal = schemaSummaryDoc->getClassCollection(); CAF_CM_VALIDATE_SMARTPTR(classCollectionVal); const SmartPtrCXmlElement classCollectionXml = thisXml->createAndAddElement("classCollection"); ClassCollectionXml::add(classCollectionVal, classCollectionXml); const std::string invokerPathVal = schemaSummaryDoc->getInvokerPath(); if (! invokerPathVal.empty()) { thisXml->addAttribute("invokerPath", invokerPathVal); } } CAF_CM_EXIT; } SmartPtrCSchemaSummaryDoc SchemaSummaryXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("SchemaSummaryXml", "parse"); SmartPtrCSchemaSummaryDoc schemaSummaryDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string providerNamespaceStrVal = thisXml->findRequiredAttribute("providerNamespace"); const std::string providerNamespaceVal = providerNamespaceStrVal; const std::string providerNameStrVal = thisXml->findRequiredAttribute("providerName"); const std::string providerNameVal = providerNameStrVal; const std::string providerVersionStrVal = thisXml->findRequiredAttribute("providerVersion"); const std::string providerVersionVal = providerVersionStrVal; const SmartPtrCXmlElement classCollectionXml = thisXml->findRequiredChild("classCollection"); SmartPtrCClassCollectionDoc classCollectionVal; if (! classCollectionXml.IsNull()) { classCollectionVal = ClassCollectionXml::parse(classCollectionXml); } const std::string invokerPathStrVal = thisXml->findOptionalAttribute("invokerPath"); const std::string invokerPathVal = invokerPathStrVal; schemaSummaryDoc.CreateInstance(); schemaSummaryDoc->initialize( providerNamespaceVal, providerNameVal, providerVersionVal, classCollectionVal, invokerPathVal); } CAF_CM_EXIT; return schemaSummaryDoc; } stdafx.h000066400000000000000000000010321321503522500365720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderInfraXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PROVIDERINFRAXML_LINKAGE __declspec(dllexport) #else #define PROVIDERINFRAXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ ProviderRequestXml/000077500000000000000000000000001321503522500355255ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlProviderBatchXml.cpp000066400000000000000000000065301321503522500414520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderRequestXml/ProviderCollectInstancesCollectionXml.h" #include "Doc/DocXml/ProviderRequestXml/ProviderInvokeOperationCollectionXml.h" #include "Doc/ProviderRequestDoc/CProviderBatchDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderBatchXml.h" using namespace Caf; void ProviderBatchXml::add( const SmartPtrCProviderBatchDoc providerBatchDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderBatchXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerBatchDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string outputDirVal = providerBatchDoc->getOutputDir(); CAF_CM_VALIDATE_STRING(outputDirVal); thisXml->addAttribute("outputDir", outputDirVal); const SmartPtrCProviderCollectInstancesCollectionDoc collectInstancesCollectionVal = providerBatchDoc->getCollectInstancesCollection(); if (! collectInstancesCollectionVal.IsNull()) { const SmartPtrCXmlElement collectInstancesCollectionXml = thisXml->createAndAddElement("collectInstancesCollection"); ProviderCollectInstancesCollectionXml::add(collectInstancesCollectionVal, collectInstancesCollectionXml); } const SmartPtrCProviderInvokeOperationCollectionDoc invokeOperationCollectionVal = providerBatchDoc->getInvokeOperationCollection(); if (! invokeOperationCollectionVal.IsNull()) { const SmartPtrCXmlElement invokeOperationCollectionXml = thisXml->createAndAddElement("invokeOperationCollection"); ProviderInvokeOperationCollectionXml::add(invokeOperationCollectionVal, invokeOperationCollectionXml); } } CAF_CM_EXIT; } SmartPtrCProviderBatchDoc ProviderBatchXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderBatchXml", "parse"); SmartPtrCProviderBatchDoc providerBatchDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string outputDirStrVal = thisXml->findRequiredAttribute("outputDir"); const std::string outputDirVal = outputDirStrVal; const SmartPtrCXmlElement collectInstancesCollectionXml = thisXml->findOptionalChild("collectInstancesCollection"); SmartPtrCProviderCollectInstancesCollectionDoc collectInstancesCollectionVal; if (! collectInstancesCollectionXml.IsNull()) { collectInstancesCollectionVal = ProviderCollectInstancesCollectionXml::parse(collectInstancesCollectionXml); } const SmartPtrCXmlElement invokeOperationCollectionXml = thisXml->findOptionalChild("invokeOperationCollection"); SmartPtrCProviderInvokeOperationCollectionDoc invokeOperationCollectionVal; if (! invokeOperationCollectionXml.IsNull()) { invokeOperationCollectionVal = ProviderInvokeOperationCollectionXml::parse(invokeOperationCollectionXml); } providerBatchDoc.CreateInstance(); providerBatchDoc->initialize( outputDirVal, collectInstancesCollectionVal, invokeOperationCollectionVal); } CAF_CM_EXIT; return providerBatchDoc; } ProviderCollectInstancesCollectionXml.cpp000066400000000000000000000056151321503522500457050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderRequestXml/ProviderCollectInstancesXml.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderCollectInstancesCollectionXml.h" using namespace Caf; void ProviderCollectInstancesCollectionXml::add( const SmartPtrCProviderCollectInstancesCollectionDoc providerCollectInstancesCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderCollectInstancesCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerCollectInstancesCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque collectInstancesVal = providerCollectInstancesCollectionDoc->getCollectInstances(); CAF_CM_VALIDATE_STL(collectInstancesVal); if (! collectInstancesVal.empty()) { for (TConstIterator > collectInstancesIter(collectInstancesVal); collectInstancesIter; collectInstancesIter++) { const SmartPtrCXmlElement collectInstancesXml = thisXml->createAndAddElement("collectInstances"); ProviderCollectInstancesXml::add(*collectInstancesIter, collectInstancesXml); } } } CAF_CM_EXIT; } SmartPtrCProviderCollectInstancesCollectionDoc ProviderCollectInstancesCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderCollectInstancesCollectionXml", "parse"); SmartPtrCProviderCollectInstancesCollectionDoc providerCollectInstancesCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection collectInstancesChildrenXml = thisXml->findRequiredChildren("collectInstances"); std::deque collectInstancesVal; if (! collectInstancesChildrenXml.IsNull() && ! collectInstancesChildrenXml->empty()) { for (TConstIterator collectInstancesXmlIter(*collectInstancesChildrenXml); collectInstancesXmlIter; collectInstancesXmlIter++) { const SmartPtrCXmlElement collectInstancesXml = collectInstancesXmlIter->second; const SmartPtrCProviderCollectInstancesDoc collectInstancesDoc = ProviderCollectInstancesXml::parse(collectInstancesXml); collectInstancesVal.push_back(collectInstancesDoc); } } providerCollectInstancesCollectionDoc.CreateInstance(); providerCollectInstancesCollectionDoc->initialize( collectInstancesVal); } CAF_CM_EXIT; return providerCollectInstancesCollectionDoc; } ProviderCollectInstancesXml.cpp000066400000000000000000000075211321503522500436670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/ParameterCollectionXml.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderCollectInstancesXml.h" using namespace Caf; void ProviderCollectInstancesXml::add( const SmartPtrCProviderCollectInstancesDoc providerCollectInstancesDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderCollectInstancesXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerCollectInstancesDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceVal = providerCollectInstancesDoc->getClassNamespace(); CAF_CM_VALIDATE_STRING(classNamespaceVal); thisXml->addAttribute("classNamespace", classNamespaceVal); const std::string classNameVal = providerCollectInstancesDoc->getClassName(); CAF_CM_VALIDATE_STRING(classNameVal); thisXml->addAttribute("className", classNameVal); const std::string classVersionVal = providerCollectInstancesDoc->getClassVersion(); CAF_CM_VALIDATE_STRING(classVersionVal); thisXml->addAttribute("classVersion", classVersionVal); const std::string jobIdVal = BasePlatform::UuidToString(providerCollectInstancesDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const std::string outputDirVal = providerCollectInstancesDoc->getOutputDir(); CAF_CM_VALIDATE_STRING(outputDirVal); thisXml->addAttribute("outputDir", outputDirVal); const SmartPtrCParameterCollectionDoc parameterCollectionVal = providerCollectInstancesDoc->getParameterCollection(); if (! parameterCollectionVal.IsNull()) { const SmartPtrCXmlElement parameterCollectionXml = thisXml->createAndAddElement("parameterCollection"); ParameterCollectionXml::add(parameterCollectionVal, parameterCollectionXml); } } CAF_CM_EXIT; } SmartPtrCProviderCollectInstancesDoc ProviderCollectInstancesXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderCollectInstancesXml", "parse"); SmartPtrCProviderCollectInstancesDoc providerCollectInstancesDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceStrVal = thisXml->findRequiredAttribute("classNamespace"); const std::string classNamespaceVal = classNamespaceStrVal; const std::string classNameStrVal = thisXml->findRequiredAttribute("className"); const std::string classNameVal = classNameStrVal; const std::string classVersionStrVal = thisXml->findRequiredAttribute("classVersion"); const std::string classVersionVal = classVersionStrVal; const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const std::string outputDirStrVal = thisXml->findRequiredAttribute("outputDir"); const std::string outputDirVal = outputDirStrVal; const SmartPtrCXmlElement parameterCollectionXml = thisXml->findOptionalChild("parameterCollection"); SmartPtrCParameterCollectionDoc parameterCollectionVal; if (! parameterCollectionXml.IsNull()) { parameterCollectionVal = ParameterCollectionXml::parse(parameterCollectionXml); } providerCollectInstancesDoc.CreateInstance(); providerCollectInstancesDoc->initialize( classNamespaceVal, classNameVal, classVersionVal, jobIdVal, outputDirVal, parameterCollectionVal); } CAF_CM_EXIT; return providerCollectInstancesDoc; } ProviderCollectSchemaRequestXml.cpp000066400000000000000000000076751321503522500445230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestHeaderXml.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderCollectSchemaRequestXml.h" using namespace Caf; void ProviderCollectSchemaRequestXml::add( const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderCollectSchemaRequestXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerCollectSchemaRequestDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(providerCollectSchemaRequestDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string requestIdVal = BasePlatform::UuidToString(providerCollectSchemaRequestDoc->getRequestId()); CAF_CM_VALIDATE_STRING(requestIdVal); thisXml->addAttribute("requestId", requestIdVal); const std::string pmeIdVal = providerCollectSchemaRequestDoc->getPmeId(); CAF_CM_VALIDATE_STRING(pmeIdVal); thisXml->addAttribute("pmeId", pmeIdVal); const std::string jobIdVal = BasePlatform::UuidToString(providerCollectSchemaRequestDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const std::string outputDirVal = providerCollectSchemaRequestDoc->getOutputDir(); CAF_CM_VALIDATE_STRING(outputDirVal); thisXml->addAttribute("outputDir", outputDirVal); const SmartPtrCProviderRequestHeaderDoc requestHeaderVal = providerCollectSchemaRequestDoc->getRequestHeader(); CAF_CM_VALIDATE_SMARTPTR(requestHeaderVal); const SmartPtrCXmlElement requestHeaderXml = thisXml->createAndAddElement("requestHeader"); ProviderRequestHeaderXml::add(requestHeaderVal, requestHeaderXml); } CAF_CM_EXIT; } SmartPtrCProviderCollectSchemaRequestDoc ProviderCollectSchemaRequestXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderCollectSchemaRequestXml", "parse"); SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findRequiredAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findRequiredAttribute("pmeId"); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const std::string outputDirStrVal = thisXml->findRequiredAttribute("outputDir"); const std::string outputDirVal = outputDirStrVal; const SmartPtrCXmlElement requestHeaderXml = thisXml->findRequiredChild("requestHeader"); SmartPtrCProviderRequestHeaderDoc requestHeaderVal; if (! requestHeaderXml.IsNull()) { requestHeaderVal = ProviderRequestHeaderXml::parse(requestHeaderXml); } providerCollectSchemaRequestDoc.CreateInstance(); providerCollectSchemaRequestDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, jobIdVal, outputDirVal, requestHeaderVal); } CAF_CM_EXIT; return providerCollectSchemaRequestDoc; } ProviderInvokeOperationCollectionXml.cpp000066400000000000000000000055311321503522500455610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderRequestXml/ProviderInvokeOperationXml.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderInvokeOperationCollectionXml.h" using namespace Caf; void ProviderInvokeOperationCollectionXml::add( const SmartPtrCProviderInvokeOperationCollectionDoc providerInvokeOperationCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderInvokeOperationCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerInvokeOperationCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque invokeOperationVal = providerInvokeOperationCollectionDoc->getInvokeOperation(); CAF_CM_VALIDATE_STL(invokeOperationVal); if (! invokeOperationVal.empty()) { for (TConstIterator > invokeOperationIter(invokeOperationVal); invokeOperationIter; invokeOperationIter++) { const SmartPtrCXmlElement invokeOperationXml = thisXml->createAndAddElement("invokeOperation"); ProviderInvokeOperationXml::add(*invokeOperationIter, invokeOperationXml); } } } CAF_CM_EXIT; } SmartPtrCProviderInvokeOperationCollectionDoc ProviderInvokeOperationCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderInvokeOperationCollectionXml", "parse"); SmartPtrCProviderInvokeOperationCollectionDoc providerInvokeOperationCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection invokeOperationChildrenXml = thisXml->findRequiredChildren("invokeOperation"); std::deque invokeOperationVal; if (! invokeOperationChildrenXml.IsNull() && ! invokeOperationChildrenXml->empty()) { for (TConstIterator invokeOperationXmlIter(*invokeOperationChildrenXml); invokeOperationXmlIter; invokeOperationXmlIter++) { const SmartPtrCXmlElement invokeOperationXml = invokeOperationXmlIter->second; const SmartPtrCProviderInvokeOperationDoc invokeOperationDoc = ProviderInvokeOperationXml::parse(invokeOperationXml); invokeOperationVal.push_back(invokeOperationDoc); } } providerInvokeOperationCollectionDoc.CreateInstance(); providerInvokeOperationCollectionDoc->initialize( invokeOperationVal); } CAF_CM_EXIT; return providerInvokeOperationCollectionDoc; } ProviderInvokeOperationXml.cpp000066400000000000000000000071671321503522500435540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/OperationXml.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderInvokeOperationXml.h" using namespace Caf; void ProviderInvokeOperationXml::add( const SmartPtrCProviderInvokeOperationDoc providerInvokeOperationDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderInvokeOperationXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerInvokeOperationDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceVal = providerInvokeOperationDoc->getClassNamespace(); CAF_CM_VALIDATE_STRING(classNamespaceVal); thisXml->addAttribute("classNamespace", classNamespaceVal); const std::string classNameVal = providerInvokeOperationDoc->getClassName(); CAF_CM_VALIDATE_STRING(classNameVal); thisXml->addAttribute("className", classNameVal); const std::string classVersionVal = providerInvokeOperationDoc->getClassVersion(); CAF_CM_VALIDATE_STRING(classVersionVal); thisXml->addAttribute("classVersion", classVersionVal); const std::string jobIdVal = BasePlatform::UuidToString(providerInvokeOperationDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const std::string outputDirVal = providerInvokeOperationDoc->getOutputDir(); CAF_CM_VALIDATE_STRING(outputDirVal); thisXml->addAttribute("outputDir", outputDirVal); const SmartPtrCOperationDoc operationVal = providerInvokeOperationDoc->getOperation(); CAF_CM_VALIDATE_SMARTPTR(operationVal); const SmartPtrCXmlElement operationXml = thisXml->createAndAddElement("operation"); OperationXml::add(operationVal, operationXml); } CAF_CM_EXIT; } SmartPtrCProviderInvokeOperationDoc ProviderInvokeOperationXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderInvokeOperationXml", "parse"); SmartPtrCProviderInvokeOperationDoc providerInvokeOperationDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceStrVal = thisXml->findRequiredAttribute("classNamespace"); const std::string classNamespaceVal = classNamespaceStrVal; const std::string classNameStrVal = thisXml->findRequiredAttribute("className"); const std::string classNameVal = classNameStrVal; const std::string classVersionStrVal = thisXml->findRequiredAttribute("classVersion"); const std::string classVersionVal = classVersionStrVal; const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const std::string outputDirStrVal = thisXml->findRequiredAttribute("outputDir"); const std::string outputDirVal = outputDirStrVal; const SmartPtrCXmlElement operationXml = thisXml->findRequiredChild("operation"); SmartPtrCOperationDoc operationVal; if (! operationXml.IsNull()) { operationVal = OperationXml::parse(operationXml); } providerInvokeOperationDoc.CreateInstance(); providerInvokeOperationDoc->initialize( classNamespaceVal, classNameVal, classVersionVal, jobIdVal, outputDirVal, operationVal); } CAF_CM_EXIT; return providerInvokeOperationDoc; } ProviderRequestConfigXml.cpp000066400000000000000000000047531321503522500432140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/LoggingLevelCollectionXml.h" #include "Doc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestConfigDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestConfigXml.h" using namespace Caf; void ProviderRequestConfigXml::add( const SmartPtrCProviderRequestConfigDoc providerRequestConfigDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderRequestConfigXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerRequestConfigDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string responseFormatTypeVal = providerRequestConfigDoc->getResponseFormatType(); CAF_CM_VALIDATE_STRING(responseFormatTypeVal); thisXml->addAttribute("responseFormatType", responseFormatTypeVal); const SmartPtrCLoggingLevelCollectionDoc loggingLevelCollectionVal = providerRequestConfigDoc->getLoggingLevelCollection(); if (! loggingLevelCollectionVal.IsNull()) { const SmartPtrCXmlElement loggingLevelCollectionXml = thisXml->createAndAddElement("loggingLevelCollection"); LoggingLevelCollectionXml::add(loggingLevelCollectionVal, loggingLevelCollectionXml); } } CAF_CM_EXIT; } SmartPtrCProviderRequestConfigDoc ProviderRequestConfigXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderRequestConfigXml", "parse"); SmartPtrCProviderRequestConfigDoc providerRequestConfigDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string responseFormatTypeStrVal = thisXml->findRequiredAttribute("responseFormatType"); const std::string responseFormatTypeVal = responseFormatTypeStrVal; const SmartPtrCXmlElement loggingLevelCollectionXml = thisXml->findOptionalChild("loggingLevelCollection"); SmartPtrCLoggingLevelCollectionDoc loggingLevelCollectionVal; if (! loggingLevelCollectionXml.IsNull()) { loggingLevelCollectionVal = LoggingLevelCollectionXml::parse(loggingLevelCollectionXml); } providerRequestConfigDoc.CreateInstance(); providerRequestConfigDoc->initialize( responseFormatTypeVal, loggingLevelCollectionVal); } CAF_CM_EXIT; return providerRequestConfigDoc; } ProviderRequestHeaderXml.cpp000066400000000000000000000052651321503522500431760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/PropertyCollectionXml.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestConfigXml.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestConfigDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestHeaderXml.h" using namespace Caf; void ProviderRequestHeaderXml::add( const SmartPtrCProviderRequestHeaderDoc providerRequestHeaderDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderRequestHeaderXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerRequestHeaderDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCProviderRequestConfigDoc requestConfigVal = providerRequestHeaderDoc->getRequestConfig(); CAF_CM_VALIDATE_SMARTPTR(requestConfigVal); const SmartPtrCXmlElement requestConfigXml = thisXml->createAndAddElement("requestConfig"); ProviderRequestConfigXml::add(requestConfigVal, requestConfigXml); const SmartPtrCPropertyCollectionDoc echoPropertyBagVal = providerRequestHeaderDoc->getEchoPropertyBag(); if (! echoPropertyBagVal.IsNull()) { const SmartPtrCXmlElement echoPropertyBagXml = thisXml->createAndAddElement("echoPropertyBag"); PropertyCollectionXml::add(echoPropertyBagVal, echoPropertyBagXml); } } CAF_CM_EXIT; } SmartPtrCProviderRequestHeaderDoc ProviderRequestHeaderXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderRequestHeaderXml", "parse"); SmartPtrCProviderRequestHeaderDoc providerRequestHeaderDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement requestConfigXml = thisXml->findRequiredChild("requestConfig"); SmartPtrCProviderRequestConfigDoc requestConfigVal; if (! requestConfigXml.IsNull()) { requestConfigVal = ProviderRequestConfigXml::parse(requestConfigXml); } const SmartPtrCXmlElement echoPropertyBagXml = thisXml->findOptionalChild("echoPropertyBag"); SmartPtrCPropertyCollectionDoc echoPropertyBagVal; if (! echoPropertyBagXml.IsNull()) { echoPropertyBagVal = PropertyCollectionXml::parse(echoPropertyBagXml); } providerRequestHeaderDoc.CreateInstance(); providerRequestHeaderDoc->initialize( requestConfigVal, echoPropertyBagVal); } CAF_CM_EXIT; return providerRequestHeaderDoc; } ProviderRequestXml.cpp000066400000000000000000000105061321503522500420570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/DocXml/ProviderRequestXml/ProviderBatchXml.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestHeaderXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderBatchDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXml.h" using namespace Caf; void ProviderRequestXml::add( const SmartPtrCProviderRequestDoc providerRequestDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderRequestXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerRequestDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(providerRequestDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string requestIdVal = BasePlatform::UuidToString(providerRequestDoc->getRequestId()); CAF_CM_VALIDATE_STRING(requestIdVal); thisXml->addAttribute("requestId", requestIdVal); const std::string pmeIdVal = providerRequestDoc->getPmeId(); CAF_CM_VALIDATE_STRING(pmeIdVal); thisXml->addAttribute("pmeId", pmeIdVal); const SmartPtrCProviderRequestHeaderDoc requestHeaderVal = providerRequestDoc->getRequestHeader(); CAF_CM_VALIDATE_SMARTPTR(requestHeaderVal); const SmartPtrCXmlElement requestHeaderXml = thisXml->createAndAddElement("requestHeader"); ProviderRequestHeaderXml::add(requestHeaderVal, requestHeaderXml); const SmartPtrCProviderBatchDoc batchVal = providerRequestDoc->getBatch(); CAF_CM_VALIDATE_SMARTPTR(batchVal); const SmartPtrCXmlElement batchXml = thisXml->createAndAddElement("batch"); ProviderBatchXml::add(batchVal, batchXml); const SmartPtrCAttachmentCollectionDoc attachmentCollectionVal = providerRequestDoc->getAttachmentCollection(); if (! attachmentCollectionVal.IsNull()) { const SmartPtrCXmlElement attachmentCollectionXml = thisXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionVal, attachmentCollectionXml); } } CAF_CM_EXIT; } SmartPtrCProviderRequestDoc ProviderRequestXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderRequestXml", "parse"); SmartPtrCProviderRequestDoc providerRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findRequiredAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findRequiredAttribute("pmeId"); const SmartPtrCXmlElement requestHeaderXml = thisXml->findRequiredChild("requestHeader"); SmartPtrCProviderRequestHeaderDoc requestHeaderVal; if (! requestHeaderXml.IsNull()) { requestHeaderVal = ProviderRequestHeaderXml::parse(requestHeaderXml); } const SmartPtrCXmlElement batchXml = thisXml->findRequiredChild("batch"); SmartPtrCProviderBatchDoc batchVal; if (! batchXml.IsNull()) { batchVal = ProviderBatchXml::parse(batchXml); } const SmartPtrCXmlElement attachmentCollectionXml = thisXml->findOptionalChild("attachmentCollection"); SmartPtrCAttachmentCollectionDoc attachmentCollectionVal; if (! attachmentCollectionXml.IsNull()) { attachmentCollectionVal = AttachmentCollectionXml::parse(attachmentCollectionXml); } providerRequestDoc.CreateInstance(); providerRequestDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, requestHeaderVal, batchVal, attachmentCollectionVal); } CAF_CM_EXIT; return providerRequestDoc; } ProviderRequestXmlRoots.cpp000066400000000000000000000126011321503522500431040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderRequestXml/ProviderCollectSchemaRequestXml.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXml.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlRoots.h" using namespace Caf; std::string XmlRoots::saveProviderCollectSchemaRequestToString( const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveProviderCollectSchemaRequestToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerCollectSchemaRequestDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/ProviderRequest.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "providerCollectSchemaRequest", schemaNamespace, schemaLocation); ProviderCollectSchemaRequestXml::add(providerCollectSchemaRequestDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCProviderCollectSchemaRequestDoc XmlRoots::parseProviderCollectSchemaRequestFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderCollectSchemaRequestFromString"); SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:providerCollectSchemaRequest"); providerCollectSchemaRequestDoc = ProviderCollectSchemaRequestXml::parse(rootXml); } CAF_CM_EXIT; return providerCollectSchemaRequestDoc; } void XmlRoots::saveProviderCollectSchemaRequestToFile( const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveProviderCollectSchemaRequestToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerCollectSchemaRequestDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string providerCollectSchemaRequestStr = saveProviderCollectSchemaRequestToString(providerCollectSchemaRequestDoc); FileSystemUtils::saveTextFile(filePath, providerCollectSchemaRequestStr); } CAF_CM_EXIT; } SmartPtrCProviderCollectSchemaRequestDoc XmlRoots::parseProviderCollectSchemaRequestFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderCollectSchemaRequestFromFile"); SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:providerCollectSchemaRequest"); providerCollectSchemaRequestDoc = ProviderCollectSchemaRequestXml::parse(rootXml); } CAF_CM_EXIT; return providerCollectSchemaRequestDoc; } std::string XmlRoots::saveProviderRequestToString( const SmartPtrCProviderRequestDoc providerRequestDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveProviderRequestToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerRequestDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/ProviderRequest.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "providerRequest", schemaNamespace, schemaLocation); ProviderRequestXml::add(providerRequestDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCProviderRequestDoc XmlRoots::parseProviderRequestFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderRequestFromString"); SmartPtrCProviderRequestDoc providerRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:providerRequest"); providerRequestDoc = ProviderRequestXml::parse(rootXml); } CAF_CM_EXIT; return providerRequestDoc; } void XmlRoots::saveProviderRequestToFile( const SmartPtrCProviderRequestDoc providerRequestDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveProviderRequestToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerRequestDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string providerRequestStr = saveProviderRequestToString(providerRequestDoc); FileSystemUtils::saveTextFile(filePath, providerRequestStr); } CAF_CM_EXIT; } SmartPtrCProviderRequestDoc XmlRoots::parseProviderRequestFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderRequestFromFile"); SmartPtrCProviderRequestDoc providerRequestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:providerRequest"); providerRequestDoc = ProviderRequestXml::parse(rootXml); } CAF_CM_EXIT; return providerRequestDoc; } stdafx.h000066400000000000000000000010361321503522500371670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderRequestXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PROVIDERREQUESTXML_LINKAGE __declspec(dllexport) #else #define PROVIDERREQUESTXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ ProviderResultsXml/000077500000000000000000000000001321503522500355365ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlCdifXml.cpp000066400000000000000000000062331321503522500375740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderResultsXml/DefinitionObjectCollectionXml.h" #include "Doc/DocXml/ProviderResultsXml/RequestIdentifierXml.h" #include "Doc/DocXml/ProviderResultsXml/SchemaXml.h" #include "Doc/ProviderResultsDoc/CCdifDoc.h" #include "Doc/ProviderResultsDoc/CDefinitionObjectCollectionDoc.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderResultsXml/CdifXml.h" using namespace Caf; void CdifXml::add( const SmartPtrCCdifDoc cdifDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CdifXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(cdifDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCRequestIdentifierDoc requestIdentifierVal = cdifDoc->getRequestIdentifier(); CAF_CM_VALIDATE_SMARTPTR(requestIdentifierVal); const SmartPtrCXmlElement requestIdentifierXml = thisXml->createAndAddElement("requestIdentifier"); RequestIdentifierXml::add(requestIdentifierVal, requestIdentifierXml); const SmartPtrCDefinitionObjectCollectionDoc definitionObjectCollectionVal = cdifDoc->getDefinitionObjectCollection(); if (! definitionObjectCollectionVal.IsNull()) { const SmartPtrCXmlElement definitionObjectCollectionXml = thisXml->createAndAddElement("definitionObjectCollection"); DefinitionObjectCollectionXml::add(definitionObjectCollectionVal, definitionObjectCollectionXml); } const SmartPtrCSchemaDoc schemaVal = cdifDoc->getSchema(); CAF_CM_VALIDATE_SMARTPTR(schemaVal); const SmartPtrCXmlElement schemaXml = thisXml->createAndAddElement("schema"); SchemaXml::add(schemaVal, schemaXml); } CAF_CM_EXIT; } SmartPtrCCdifDoc CdifXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CdifXml", "parse"); SmartPtrCCdifDoc cdifDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const SmartPtrCXmlElement requestIdentifierXml = thisXml->findRequiredChild("requestIdentifier"); SmartPtrCRequestIdentifierDoc requestIdentifierVal; if (! requestIdentifierXml.IsNull()) { requestIdentifierVal = RequestIdentifierXml::parse(requestIdentifierXml); } const SmartPtrCXmlElement definitionObjectCollectionXml = thisXml->findOptionalChild("definitionObjectCollection"); SmartPtrCDefinitionObjectCollectionDoc definitionObjectCollectionVal; if (! definitionObjectCollectionXml.IsNull()) { definitionObjectCollectionVal = DefinitionObjectCollectionXml::parse(definitionObjectCollectionXml); } const SmartPtrCXmlElement schemaXml = thisXml->findRequiredChild("schema"); SmartPtrCSchemaDoc schemaVal; if (! schemaXml.IsNull()) { schemaVal = SchemaXml::parse(schemaXml); } cdifDoc.CreateInstance(); cdifDoc->initialize( requestIdentifierVal, definitionObjectCollectionVal, schemaVal); } CAF_CM_EXIT; return cdifDoc; } DefinitionObjectCollectionXml.cpp000066400000000000000000000040741321503522500441630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/ProviderResultsDoc/CDefinitionObjectCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderResultsXml/DefinitionObjectCollectionXml.h" using namespace Caf; void DefinitionObjectCollectionXml::add( const SmartPtrCDefinitionObjectCollectionDoc definitionObjectCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DefinitionObjectCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(definitionObjectCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque valueVal = definitionObjectCollectionDoc->getValue(); if (! valueVal.empty()) { for (TConstIterator > valueIter(valueVal); valueIter; valueIter++) { thisXml->appendValue(*valueIter); } } } CAF_CM_EXIT; } SmartPtrCDefinitionObjectCollectionDoc DefinitionObjectCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DefinitionObjectCollectionXml", "parse"); SmartPtrCDefinitionObjectCollectionDoc definitionObjectCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection valueChildrenXml = thisXml->getAllChildren(); std::deque valueVal; if (! valueChildrenXml.IsNull() && ! valueChildrenXml->empty()) { for (TConstIterator valueXmlIter(*valueChildrenXml); valueXmlIter; valueXmlIter++) { const SmartPtrCXmlElement valueXml = valueXmlIter->second; const std::string valueDoc = valueXml->saveToStringRaw(); valueVal.push_back(valueDoc); } } definitionObjectCollectionDoc.CreateInstance(); definitionObjectCollectionDoc->initialize( valueVal); } CAF_CM_EXIT; return definitionObjectCollectionDoc; } ProviderResultsXmlRoots.cpp000066400000000000000000000103041321503522500431240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ProviderResultsXml/CdifXml.h" #include "Doc/DocXml/ProviderResultsXml/SchemaXml.h" #include "Doc/ProviderResultsDoc/CCdifDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlRoots.h" using namespace Caf; std::string XmlRoots::saveSchemaToString( const SmartPtrCSchemaDoc schemaDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveSchemaToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(schemaDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("cmdl"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("cmdl/ProviderResults.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "schema", schemaNamespace, schemaLocation); SchemaXml::add(schemaDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCSchemaDoc XmlRoots::parseSchemaFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseSchemaFromString"); SmartPtrCSchemaDoc schemaDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:schema"); schemaDoc = SchemaXml::parse(rootXml); } CAF_CM_EXIT; return schemaDoc; } void XmlRoots::saveSchemaToFile( const SmartPtrCSchemaDoc schemaDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveSchemaToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(schemaDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string schemaStr = saveSchemaToString(schemaDoc); FileSystemUtils::saveTextFile(filePath, schemaStr); } CAF_CM_EXIT; } SmartPtrCSchemaDoc XmlRoots::parseSchemaFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseSchemaFromFile"); SmartPtrCSchemaDoc schemaDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:schema"); schemaDoc = SchemaXml::parse(rootXml); } CAF_CM_EXIT; return schemaDoc; } std::string XmlRoots::saveCdifToString( const SmartPtrCCdifDoc cdifDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveCdifToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(cdifDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("cmdl"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("cmdl/ProviderResults.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "cdif", schemaNamespace, schemaLocation); CdifXml::add(cdifDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCCdifDoc XmlRoots::parseCdifFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseCdifFromString"); SmartPtrCCdifDoc cdifDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:cdif"); cdifDoc = CdifXml::parse(rootXml); } CAF_CM_EXIT; return cdifDoc; } void XmlRoots::saveCdifToFile( const SmartPtrCCdifDoc cdifDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveCdifToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(cdifDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string cdifStr = saveCdifToString(cdifDoc); FileSystemUtils::saveTextFile(filePath, cdifStr); } CAF_CM_EXIT; } SmartPtrCCdifDoc XmlRoots::parseCdifFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseCdifFromFile"); SmartPtrCCdifDoc cdifDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:cdif"); cdifDoc = CdifXml::parse(rootXml); } CAF_CM_EXIT; return cdifDoc; } RequestIdentifierXml.cpp000066400000000000000000000074441321503522500423670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/ActionClassXml.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderResultsXml/RequestIdentifierXml.h" using namespace Caf; void RequestIdentifierXml::add( const SmartPtrCRequestIdentifierDoc requestIdentifierDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestIdentifierXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(requestIdentifierDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(requestIdentifierDoc->getClientId()); CAF_CM_VALIDATE_STRING(clientIdVal); thisXml->addAttribute("clientId", clientIdVal); const std::string requestIdVal = BasePlatform::UuidToString(requestIdentifierDoc->getRequestId()); CAF_CM_VALIDATE_STRING(requestIdVal); thisXml->addAttribute("requestId", requestIdVal); const std::string pmeIdVal = requestIdentifierDoc->getPmeId(); CAF_CM_VALIDATE_STRING(pmeIdVal); thisXml->addAttribute("pmeId", pmeIdVal); const std::string jobIdVal = BasePlatform::UuidToString(requestIdentifierDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const SmartPtrCActionClassDoc actionClassVal = requestIdentifierDoc->getActionClass(); CAF_CM_VALIDATE_SMARTPTR(actionClassVal); const SmartPtrCXmlElement actionClassXml = thisXml->createAndAddElement("actionClass"); ActionClassXml::add(actionClassVal, actionClassXml); const std::string sessionIdVal = BasePlatform::UuidToString(requestIdentifierDoc->getSessionId()); if (! sessionIdVal.empty()) { thisXml->addAttribute("sessionId", sessionIdVal); } thisXml->addAttribute("version", "1.0"); } CAF_CM_EXIT; } SmartPtrCRequestIdentifierDoc RequestIdentifierXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RequestIdentifierXml", "parse"); SmartPtrCRequestIdentifierDoc requestIdentifierDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findRequiredAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findRequiredAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findRequiredAttribute("pmeId"); const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const SmartPtrCXmlElement actionClassXml = thisXml->findRequiredChild("actionClass"); SmartPtrCActionClassDoc actionClassVal; if (! actionClassXml.IsNull()) { actionClassVal = ActionClassXml::parse(actionClassXml); } const std::string sessionIdStrVal = thisXml->findOptionalAttribute("sessionId"); UUID sessionIdVal = CAFCOMMON_GUID_NULL; if (! sessionIdStrVal.empty()) { BasePlatform::UuidFromString(sessionIdStrVal.c_str(), sessionIdVal); } requestIdentifierDoc.CreateInstance(); requestIdentifierDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, jobIdVal, actionClassVal, sessionIdVal); } CAF_CM_EXIT; return requestIdentifierDoc; } SchemaXml.cpp000066400000000000000000000142701321503522500401270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/ActionClassXml.h" #include "Doc/DocXml/SchemaTypesXml/DataClassXml.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CLogicalRelationshipDoc.h" #include "Doc/SchemaTypesDoc/CPhysicalRelationshipDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ProviderResultsXml/SchemaXml.h" #include "Doc/DocXml/SchemaTypesXml/LogicalRelationshipXml.h" #include "Doc/DocXml/SchemaTypesXml/PhysicalRelationshipXml.h" using namespace Caf; void SchemaXml::add( const SmartPtrCSchemaDoc schemaDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("SchemaXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(schemaDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque dataClassVal = schemaDoc->getDataClassCollection(); if (! dataClassVal.empty()) { for (TConstIterator > dataClassIter(dataClassVal); dataClassIter; dataClassIter++) { const SmartPtrCXmlElement dataClassXml = thisXml->createAndAddElement("dataClass"); DataClassXml::add(*dataClassIter, dataClassXml); } } const std::deque actionClassVal = schemaDoc->getActionClassCollection(); if (! actionClassVal.empty()) { for (TConstIterator > actionClassIter(actionClassVal); actionClassIter; actionClassIter++) { const SmartPtrCXmlElement actionClassXml = thisXml->createAndAddElement("actionClass"); ActionClassXml::add(*actionClassIter, actionClassXml); } } const std::deque logicalRelationshipVal = schemaDoc->getLogicalRelationshipCollection(); if (! logicalRelationshipVal.empty()) { for (TConstIterator > logicalRelationshipIter(logicalRelationshipVal); logicalRelationshipIter; logicalRelationshipIter++) { const SmartPtrCXmlElement logicalRelationshipXml = thisXml->createAndAddElement("logicalRelationship"); LogicalRelationshipXml::add(*logicalRelationshipIter, logicalRelationshipXml); } } const std::deque physicalRelationshipVal = schemaDoc->getPhysicalRelationshipCollection(); if (! physicalRelationshipVal.empty()) { for (TConstIterator > physicalRelationshipIter(physicalRelationshipVal); physicalRelationshipIter; physicalRelationshipIter++) { const SmartPtrCXmlElement physicalRelationshipXml = thisXml->createAndAddElement("physicalRelationship"); PhysicalRelationshipXml::add(*physicalRelationshipIter, physicalRelationshipXml); } } } CAF_CM_EXIT; } SmartPtrCSchemaDoc SchemaXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("SchemaXml", "parse"); SmartPtrCSchemaDoc schemaDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection dataClassChildrenXml = thisXml->findOptionalChildren("dataClass"); std::deque dataClassVal; if (! dataClassChildrenXml.IsNull() && ! dataClassChildrenXml->empty()) { for (TConstIterator dataClassXmlIter(*dataClassChildrenXml); dataClassXmlIter; dataClassXmlIter++) { const SmartPtrCXmlElement dataClassXml = dataClassXmlIter->second; const SmartPtrCDataClassDoc dataClassDoc = DataClassXml::parse(dataClassXml); dataClassVal.push_back(dataClassDoc); } } const CXmlElement::SmartPtrCElementCollection actionClassChildrenXml = thisXml->findOptionalChildren("actionClass"); std::deque actionClassVal; if (! actionClassChildrenXml.IsNull() && ! actionClassChildrenXml->empty()) { for (TConstIterator actionClassXmlIter(*actionClassChildrenXml); actionClassXmlIter; actionClassXmlIter++) { const SmartPtrCXmlElement actionClassXml = actionClassXmlIter->second; const SmartPtrCActionClassDoc actionClassDoc = ActionClassXml::parse(actionClassXml); actionClassVal.push_back(actionClassDoc); } } const CXmlElement::SmartPtrCElementCollection logicalRelationshipChildrenXml = thisXml->findOptionalChildren("logicalRelationship"); std::deque logicalRelationshipVal; if (! logicalRelationshipChildrenXml.IsNull() && ! logicalRelationshipChildrenXml->empty()) { for (TConstIterator logicalRelationshipXmlIter(*logicalRelationshipChildrenXml); logicalRelationshipXmlIter; logicalRelationshipXmlIter++) { const SmartPtrCXmlElement logicalRelationshipXml = logicalRelationshipXmlIter->second; const SmartPtrCLogicalRelationshipDoc logicalRelationshipDoc = LogicalRelationshipXml::parse(logicalRelationshipXml); logicalRelationshipVal.push_back(logicalRelationshipDoc); } } const CXmlElement::SmartPtrCElementCollection physicalRelationshipChildrenXml = thisXml->findOptionalChildren("physicalRelationship"); std::deque physicalRelationshipVal; if (! physicalRelationshipChildrenXml.IsNull() && ! physicalRelationshipChildrenXml->empty()) { for (TConstIterator physicalRelationshipXmlIter(*physicalRelationshipChildrenXml); physicalRelationshipXmlIter; physicalRelationshipXmlIter++) { const SmartPtrCXmlElement physicalRelationshipXml = physicalRelationshipXmlIter->second; const SmartPtrCPhysicalRelationshipDoc physicalRelationshipDoc = PhysicalRelationshipXml::parse(physicalRelationshipXml); physicalRelationshipVal.push_back(physicalRelationshipDoc); } } schemaDoc.CreateInstance(); schemaDoc->initialize( dataClassVal, actionClassVal, logicalRelationshipVal, physicalRelationshipVal); } CAF_CM_EXIT; return schemaDoc; } stdafx.h000066400000000000000000000010361321503522500372000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ProviderResultsXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define PROVIDERRESULTSXML_LINKAGE __declspec(dllexport) #else #define PROVIDERRESULTSXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ ResponseXml/000077500000000000000000000000001321503522500341605ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlErrorResponseXml.cpp000066400000000000000000000065321321503522500401630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ResponseXml/ResponseHeaderXml.h" #include "Doc/ResponseDoc/CErrorResponseDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/ErrorResponseXml.h" using namespace Caf; void ErrorResponseXml::add( const SmartPtrCErrorResponseDoc errorResponseDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ErrorResponseXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(errorResponseDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(errorResponseDoc->getClientId()); if (! clientIdVal.empty()) { thisXml->addAttribute("clientId", clientIdVal); } const std::string requestIdVal = BasePlatform::UuidToString(errorResponseDoc->getRequestId()); if (! requestIdVal.empty()) { thisXml->addAttribute("requestId", requestIdVal); } const std::string pmeIdVal = errorResponseDoc->getPmeId(); if (! pmeIdVal.empty()) { thisXml->addAttribute("pmeId", pmeIdVal); } const SmartPtrCResponseHeaderDoc responseHeaderVal = errorResponseDoc->getResponseHeader(); if (! responseHeaderVal.IsNull()) { const SmartPtrCXmlElement responseHeaderXml = thisXml->createAndAddElement("responseHeader"); ResponseHeaderXml::add(responseHeaderVal, responseHeaderXml); } const std::string errorMessageVal = errorResponseDoc->getErrorMessage(); if (! errorMessageVal.empty()) { const SmartPtrCXmlElement errorMessageXml = thisXml->createAndAddElement("errorMessage"); errorMessageXml->setValue(errorMessageVal); } } CAF_CM_EXIT; } SmartPtrCErrorResponseDoc ErrorResponseXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ErrorResponseXml", "parse"); SmartPtrCErrorResponseDoc errorResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findOptionalAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findOptionalAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findOptionalAttribute("pmeId"); const SmartPtrCXmlElement responseHeaderXml = thisXml->findOptionalChild("responseHeader"); SmartPtrCResponseHeaderDoc responseHeaderVal; if (! responseHeaderXml.IsNull()) { responseHeaderVal = ResponseHeaderXml::parse(responseHeaderXml); } const SmartPtrCXmlElement errorMessageXml = thisXml->findOptionalChild("errorMessage"); std::string errorMessageVal; if (! errorMessageXml.IsNull()) { errorMessageVal = errorMessageXml->getValue(); } errorResponseDoc.CreateInstance(); errorResponseDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, responseHeaderVal, errorMessageVal); } CAF_CM_EXIT; return errorResponseDoc; } EventKeyCollectionXml.cpp000066400000000000000000000044211321503522500411140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ResponseXml/EventKeyXml.h" #include "Doc/ResponseDoc/CEventKeyCollectionDoc.h" #include "Doc/ResponseDoc/CEventKeyDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/EventKeyCollectionXml.h" using namespace Caf; void EventKeyCollectionXml::add( const SmartPtrCEventKeyCollectionDoc eventKeyCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("EventKeyCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(eventKeyCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque eventKeyVal = eventKeyCollectionDoc->getEventKey(); CAF_CM_VALIDATE_STL(eventKeyVal); if (! eventKeyVal.empty()) { for (TConstIterator > eventKeyIter(eventKeyVal); eventKeyIter; eventKeyIter++) { const SmartPtrCXmlElement eventKeyXml = thisXml->createAndAddElement("eventKey"); EventKeyXml::add(*eventKeyIter, eventKeyXml); } } } CAF_CM_EXIT; } SmartPtrCEventKeyCollectionDoc EventKeyCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("EventKeyCollectionXml", "parse"); SmartPtrCEventKeyCollectionDoc eventKeyCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection eventKeyChildrenXml = thisXml->findRequiredChildren("eventKey"); std::deque eventKeyVal; if (! eventKeyChildrenXml.IsNull() && ! eventKeyChildrenXml->empty()) { for (TConstIterator eventKeyXmlIter(*eventKeyChildrenXml); eventKeyXmlIter; eventKeyXmlIter++) { const SmartPtrCXmlElement eventKeyXml = eventKeyXmlIter->second; const SmartPtrCEventKeyDoc eventKeyDoc = EventKeyXml::parse(eventKeyXml); eventKeyVal.push_back(eventKeyDoc); } } eventKeyCollectionDoc.CreateInstance(); eventKeyCollectionDoc->initialize( eventKeyVal); } CAF_CM_EXIT; return eventKeyCollectionDoc; } EventKeyXml.cpp000066400000000000000000000030621321503522500371000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/ResponseDoc/CEventKeyDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/EventKeyXml.h" using namespace Caf; void EventKeyXml::add( const SmartPtrCEventKeyDoc eventKeyDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("EventKeyXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(eventKeyDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = eventKeyDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string valueVal = eventKeyDoc->getValue(); CAF_CM_VALIDATE_STRING(valueVal); thisXml->addAttribute("value", valueVal); } CAF_CM_EXIT; } SmartPtrCEventKeyDoc EventKeyXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("EventKeyXml", "parse"); SmartPtrCEventKeyDoc eventKeyDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string valueStrVal = thisXml->findRequiredAttribute("value"); const std::string valueVal = valueStrVal; eventKeyDoc.CreateInstance(); eventKeyDoc->initialize( nameVal, valueVal); } CAF_CM_EXIT; return eventKeyDoc; } EventManifestXml.cpp000066400000000000000000000064101321503522500401160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/ResponseDoc/CEventManifestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/EventManifestXml.h" using namespace Caf; void EventManifestXml::add( const SmartPtrCEventManifestDoc eventManifestDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("EventManifestXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(eventManifestDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceVal = eventManifestDoc->getClassNamespace(); CAF_CM_VALIDATE_STRING(classNamespaceVal); thisXml->addAttribute("classNamespace", classNamespaceVal); const std::string classNameVal = eventManifestDoc->getClassName(); CAF_CM_VALIDATE_STRING(classNameVal); thisXml->addAttribute("className", classNameVal); const std::string classVersionVal = eventManifestDoc->getClassVersion(); CAF_CM_VALIDATE_STRING(classVersionVal); thisXml->addAttribute("classVersion", classVersionVal); const std::string operationNameVal = eventManifestDoc->getOperationName(); CAF_CM_VALIDATE_STRING(operationNameVal); thisXml->addAttribute("operationName", operationNameVal); const SmartPtrCAttachmentCollectionDoc attachmentCollectionVal = eventManifestDoc->getAttachmentCollection(); CAF_CM_VALIDATE_SMARTPTR(attachmentCollectionVal); const SmartPtrCXmlElement attachmentCollectionXml = thisXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionVal, attachmentCollectionXml); } CAF_CM_EXIT; } SmartPtrCEventManifestDoc EventManifestXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("EventManifestXml", "parse"); SmartPtrCEventManifestDoc eventManifestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceStrVal = thisXml->findRequiredAttribute("classNamespace"); const std::string classNamespaceVal = classNamespaceStrVal; const std::string classNameStrVal = thisXml->findRequiredAttribute("className"); const std::string classNameVal = classNameStrVal; const std::string classVersionStrVal = thisXml->findRequiredAttribute("classVersion"); const std::string classVersionVal = classVersionStrVal; const std::string operationNameStrVal = thisXml->findRequiredAttribute("operationName"); const std::string operationNameVal = operationNameStrVal; const SmartPtrCXmlElement attachmentCollectionXml = thisXml->findRequiredChild("attachmentCollection"); SmartPtrCAttachmentCollectionDoc attachmentCollectionVal; if (! attachmentCollectionXml.IsNull()) { attachmentCollectionVal = AttachmentCollectionXml::parse(attachmentCollectionXml); } eventManifestDoc.CreateInstance(); eventManifestDoc->initialize( classNamespaceVal, classNameVal, classVersionVal, operationNameVal, attachmentCollectionVal); } CAF_CM_EXIT; return eventManifestDoc; } ManifestCollectionXml.cpp000066400000000000000000000044211321503522500411300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ResponseXml/ManifestXml.h" #include "Doc/ResponseDoc/CManifestCollectionDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/ManifestCollectionXml.h" using namespace Caf; void ManifestCollectionXml::add( const SmartPtrCManifestCollectionDoc manifestCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ManifestCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(manifestCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque manifestVal = manifestCollectionDoc->getManifest(); CAF_CM_VALIDATE_STL(manifestVal); if (! manifestVal.empty()) { for (TConstIterator > manifestIter(manifestVal); manifestIter; manifestIter++) { const SmartPtrCXmlElement manifestXml = thisXml->createAndAddElement("manifest"); ManifestXml::add(*manifestIter, manifestXml); } } } CAF_CM_EXIT; } SmartPtrCManifestCollectionDoc ManifestCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ManifestCollectionXml", "parse"); SmartPtrCManifestCollectionDoc manifestCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection manifestChildrenXml = thisXml->findRequiredChildren("manifest"); std::deque manifestVal; if (! manifestChildrenXml.IsNull() && ! manifestChildrenXml->empty()) { for (TConstIterator manifestXmlIter(*manifestChildrenXml); manifestXmlIter; manifestXmlIter++) { const SmartPtrCXmlElement manifestXml = manifestXmlIter->second; const SmartPtrCManifestDoc manifestDoc = ManifestXml::parse(manifestXml); manifestVal.push_back(manifestDoc); } } manifestCollectionDoc.CreateInstance(); manifestCollectionDoc->initialize( manifestVal); } CAF_CM_EXIT; return manifestCollectionDoc; } ManifestXml.cpp000066400000000000000000000072021321503522500371140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentNameCollectionXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/ManifestXml.h" using namespace Caf; void ManifestXml::add( const SmartPtrCManifestDoc manifestDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ManifestXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(manifestDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceVal = manifestDoc->getClassNamespace(); CAF_CM_VALIDATE_STRING(classNamespaceVal); thisXml->addAttribute("classNamespace", classNamespaceVal); const std::string classNameVal = manifestDoc->getClassName(); CAF_CM_VALIDATE_STRING(classNameVal); thisXml->addAttribute("className", classNameVal); const std::string classVersionVal = manifestDoc->getClassVersion(); CAF_CM_VALIDATE_STRING(classVersionVal); thisXml->addAttribute("classVersion", classVersionVal); const std::string jobIdVal = BasePlatform::UuidToString(manifestDoc->getJobId()); CAF_CM_VALIDATE_STRING(jobIdVal); thisXml->addAttribute("jobId", jobIdVal); const std::string operationNameVal = manifestDoc->getOperationName(); CAF_CM_VALIDATE_STRING(operationNameVal); thisXml->addAttribute("operationName", operationNameVal); const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollectionVal = manifestDoc->getAttachmentNameCollection(); CAF_CM_VALIDATE_SMARTPTR(attachmentNameCollectionVal); const SmartPtrCXmlElement attachmentNameCollectionXml = thisXml->createAndAddElement("attachmentNameCollection"); AttachmentNameCollectionXml::add(attachmentNameCollectionVal, attachmentNameCollectionXml); } CAF_CM_EXIT; } SmartPtrCManifestDoc ManifestXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ManifestXml", "parse"); SmartPtrCManifestDoc manifestDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string classNamespaceStrVal = thisXml->findRequiredAttribute("classNamespace"); const std::string classNamespaceVal = classNamespaceStrVal; const std::string classNameStrVal = thisXml->findRequiredAttribute("className"); const std::string classNameVal = classNameStrVal; const std::string classVersionStrVal = thisXml->findRequiredAttribute("classVersion"); const std::string classVersionVal = classVersionStrVal; const std::string jobIdStrVal = thisXml->findRequiredAttribute("jobId"); UUID jobIdVal = CAFCOMMON_GUID_NULL; if (! jobIdStrVal.empty()) { BasePlatform::UuidFromString(jobIdStrVal.c_str(), jobIdVal); } const std::string operationNameStrVal = thisXml->findRequiredAttribute("operationName"); const std::string operationNameVal = operationNameStrVal; const SmartPtrCXmlElement attachmentNameCollectionXml = thisXml->findRequiredChild("attachmentNameCollection"); SmartPtrCAttachmentNameCollectionDoc attachmentNameCollectionVal; if (! attachmentNameCollectionXml.IsNull()) { attachmentNameCollectionVal = AttachmentNameCollectionXml::parse(attachmentNameCollectionXml); } manifestDoc.CreateInstance(); manifestDoc->initialize( classNamespaceVal, classNameVal, classVersionVal, jobIdVal, operationNameVal, attachmentNameCollectionVal); } CAF_CM_EXIT; return manifestDoc; } ProviderEventResponseXml.cpp000066400000000000000000000101261321503522500416600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/StatisticsXml.h" #include "Doc/DocXml/ResponseXml/EventKeyCollectionXml.h" #include "Doc/DocXml/ResponseXml/ResponseHeaderXml.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CEventKeyCollectionDoc.h" #include "Doc/ResponseDoc/CEventManifestDoc.h" #include "Doc/ResponseDoc/CProviderEventResponseDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/ProviderEventResponseXml.h" #include "Doc/DocXml/ResponseXml/EventManifestXml.h" using namespace Caf; void ProviderEventResponseXml::add( const SmartPtrCProviderEventResponseDoc providerEventResponseDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderEventResponseXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerEventResponseDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string pmeIdVal = providerEventResponseDoc->getPmeId(); CAF_CM_VALIDATE_STRING(pmeIdVal); thisXml->addAttribute("pmeId", pmeIdVal); const SmartPtrCResponseHeaderDoc responseHeaderVal = providerEventResponseDoc->getResponseHeader(); if (! responseHeaderVal.IsNull()) { const SmartPtrCXmlElement responseHeaderXml = thisXml->createAndAddElement("responseHeader"); ResponseHeaderXml::add(responseHeaderVal, responseHeaderXml); } const SmartPtrCEventManifestDoc manifestVal = providerEventResponseDoc->getManifest(); CAF_CM_VALIDATE_SMARTPTR(manifestVal); const SmartPtrCXmlElement manifestXml = thisXml->createAndAddElement("manifest"); EventManifestXml::add(manifestVal, manifestXml); const SmartPtrCEventKeyCollectionDoc eventKeyCollectionVal = providerEventResponseDoc->getEventKeyCollection(); if (! eventKeyCollectionVal.IsNull()) { const SmartPtrCXmlElement eventKeyCollectionXml = thisXml->createAndAddElement("eventKeyCollection"); EventKeyCollectionXml::add(eventKeyCollectionVal, eventKeyCollectionXml); } const SmartPtrCStatisticsDoc statisticsVal = providerEventResponseDoc->getStatistics(); if (! statisticsVal.IsNull()) { const SmartPtrCXmlElement statisticsXml = thisXml->createAndAddElement("statistics"); StatisticsXml::add(statisticsVal, statisticsXml); } } CAF_CM_EXIT; } SmartPtrCProviderEventResponseDoc ProviderEventResponseXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderEventResponseXml", "parse"); SmartPtrCProviderEventResponseDoc providerEventResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string pmeIdVal = thisXml->findRequiredAttribute("pmeId"); const SmartPtrCXmlElement responseHeaderXml = thisXml->findOptionalChild("responseHeader"); SmartPtrCResponseHeaderDoc responseHeaderVal; if (! responseHeaderXml.IsNull()) { responseHeaderVal = ResponseHeaderXml::parse(responseHeaderXml); } const SmartPtrCXmlElement manifestXml = thisXml->findRequiredChild("manifest"); SmartPtrCEventManifestDoc manifestVal; if (! manifestXml.IsNull()) { manifestVal = EventManifestXml::parse(manifestXml); } const SmartPtrCXmlElement eventKeyCollectionXml = thisXml->findOptionalChild("eventKeyCollection"); SmartPtrCEventKeyCollectionDoc eventKeyCollectionVal; if (! eventKeyCollectionXml.IsNull()) { eventKeyCollectionVal = EventKeyCollectionXml::parse(eventKeyCollectionXml); } const SmartPtrCXmlElement statisticsXml = thisXml->findOptionalChild("statistics"); SmartPtrCStatisticsDoc statisticsVal; if (! statisticsXml.IsNull()) { statisticsVal = StatisticsXml::parse(statisticsXml); } providerEventResponseDoc.CreateInstance(); providerEventResponseDoc->initialize( pmeIdVal, responseHeaderVal, manifestVal, eventKeyCollectionVal, statisticsVal); } CAF_CM_EXIT; return providerEventResponseDoc; } ProviderResponseXml.cpp000066400000000000000000000115701321503522500406620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/StatisticsXml.h" #include "Doc/DocXml/ResponseXml/ManifestXml.h" #include "Doc/DocXml/ResponseXml/ResponseHeaderXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Doc/ResponseDoc/CProviderResponseDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/ProviderResponseXml.h" using namespace Caf; void ProviderResponseXml::add( const SmartPtrCProviderResponseDoc providerResponseDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderResponseXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerResponseDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(providerResponseDoc->getClientId()); if (! clientIdVal.empty()) { thisXml->addAttribute("clientId", clientIdVal); } const std::string requestIdVal = BasePlatform::UuidToString(providerResponseDoc->getRequestId()); if (! requestIdVal.empty()) { thisXml->addAttribute("requestId", requestIdVal); } const std::string pmeIdVal = providerResponseDoc->getPmeId(); if (! pmeIdVal.empty()) { thisXml->addAttribute("pmeId", pmeIdVal); } const SmartPtrCResponseHeaderDoc responseHeaderVal = providerResponseDoc->getResponseHeader(); if (! responseHeaderVal.IsNull()) { const SmartPtrCXmlElement responseHeaderXml = thisXml->createAndAddElement("responseHeader"); ResponseHeaderXml::add(responseHeaderVal, responseHeaderXml); } const SmartPtrCManifestDoc manifestVal = providerResponseDoc->getManifest(); if (! manifestVal.IsNull()) { const SmartPtrCXmlElement manifestXml = thisXml->createAndAddElement("manifest"); ManifestXml::add(manifestVal, manifestXml); } const SmartPtrCAttachmentCollectionDoc attachmentCollectionVal = providerResponseDoc->getAttachmentCollection(); if (! attachmentCollectionVal.IsNull()) { const SmartPtrCXmlElement attachmentCollectionXml = thisXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionVal, attachmentCollectionXml); } const SmartPtrCStatisticsDoc statisticsVal = providerResponseDoc->getStatistics(); if (! statisticsVal.IsNull()) { const SmartPtrCXmlElement statisticsXml = thisXml->createAndAddElement("statistics"); StatisticsXml::add(statisticsVal, statisticsXml); } } CAF_CM_EXIT; } SmartPtrCProviderResponseDoc ProviderResponseXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ProviderResponseXml", "parse"); SmartPtrCProviderResponseDoc providerResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findOptionalAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findOptionalAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findOptionalAttribute("pmeId"); const SmartPtrCXmlElement responseHeaderXml = thisXml->findOptionalChild("responseHeader"); SmartPtrCResponseHeaderDoc responseHeaderVal; if (! responseHeaderXml.IsNull()) { responseHeaderVal = ResponseHeaderXml::parse(responseHeaderXml); } const SmartPtrCXmlElement manifestXml = thisXml->findOptionalChild("manifest"); SmartPtrCManifestDoc manifestVal; if (! manifestXml.IsNull()) { manifestVal = ManifestXml::parse(manifestXml); } const SmartPtrCXmlElement attachmentCollectionXml = thisXml->findOptionalChild("attachmentCollection"); SmartPtrCAttachmentCollectionDoc attachmentCollectionVal; if (! attachmentCollectionXml.IsNull()) { attachmentCollectionVal = AttachmentCollectionXml::parse(attachmentCollectionXml); } const SmartPtrCXmlElement statisticsXml = thisXml->findOptionalChild("statistics"); SmartPtrCStatisticsDoc statisticsVal; if (! statisticsXml.IsNull()) { statisticsVal = StatisticsXml::parse(statisticsXml); } providerResponseDoc.CreateInstance(); providerResponseDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, responseHeaderVal, manifestVal, attachmentCollectionVal, statisticsVal); } CAF_CM_EXIT; return providerResponseDoc; } ResponseHeaderXml.cpp000066400000000000000000000061111321503522500402530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/ResponseHeaderXml.h" using namespace Caf; void ResponseHeaderXml::add( const SmartPtrCResponseHeaderDoc responseHeaderDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ResponseHeaderXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(responseHeaderDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string versionVal = responseHeaderDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::string createdDateTimeVal = responseHeaderDoc->getCreatedDateTime(); CAF_CM_VALIDATE_STRING(createdDateTimeVal); thisXml->addAttribute("createdDateTime", createdDateTimeVal); const std::string sequenceNumberVal = CStringConv::toString(responseHeaderDoc->getSequenceNumber()); CAF_CM_VALIDATE_STRING(sequenceNumberVal); thisXml->addAttribute("sequenceNumber", sequenceNumberVal); const std::string isFinalResponseVal = responseHeaderDoc->getIsFinalResponse() ? "true" : "false"; CAF_CM_VALIDATE_STRING(isFinalResponseVal); thisXml->addAttribute("isFinalResponse", isFinalResponseVal); const std::string sessionIdVal = BasePlatform::UuidToString(responseHeaderDoc->getSessionId()); if (! sessionIdVal.empty()) { thisXml->addAttribute("sessionId", sessionIdVal); } } CAF_CM_EXIT; } SmartPtrCResponseHeaderDoc ResponseHeaderXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ResponseHeaderXml", "parse"); SmartPtrCResponseHeaderDoc responseHeaderDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string versionVal = thisXml->findRequiredAttribute("version"); const std::string createdDateTimeVal = thisXml->findRequiredAttribute("createdDateTime"); const std::string sequenceNumberStrVal = thisXml->findRequiredAttribute("sequenceNumber"); uint32 sequenceNumberVal = 0; if (! sequenceNumberStrVal.empty()) { sequenceNumberVal = CStringConv::fromString(sequenceNumberStrVal); } const std::string isFinalResponseStrVal = thisXml->findRequiredAttribute("isFinalResponse"); bool isFinalResponseVal = false; if (! isFinalResponseStrVal.empty()) { isFinalResponseVal = (isFinalResponseStrVal.compare("true") == 0) ? true : false; } const std::string sessionIdStrVal = thisXml->findOptionalAttribute("sessionId"); UUID sessionIdVal = CAFCOMMON_GUID_NULL; if (! sessionIdStrVal.empty()) { BasePlatform::UuidFromString(sessionIdStrVal.c_str(), sessionIdVal); } responseHeaderDoc.CreateInstance(); responseHeaderDoc->initialize( versionVal, createdDateTimeVal, sequenceNumberVal, isFinalResponseVal, sessionIdVal); } CAF_CM_EXIT; return responseHeaderDoc; } ResponseXml.cpp000066400000000000000000000116211321503522500371440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/DocXml/CafCoreTypesXml/StatisticsXml.h" #include "Doc/DocXml/ResponseXml/ManifestCollectionXml.h" #include "Doc/DocXml/ResponseXml/ResponseHeaderXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CStatisticsDoc.h" #include "Doc/ResponseDoc/CManifestCollectionDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/ResponseXml.h" using namespace Caf; void ResponseXml::add( const SmartPtrCResponseDoc responseDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ResponseXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(responseDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdVal = BasePlatform::UuidToString(responseDoc->getClientId()); if (! clientIdVal.empty()) { thisXml->addAttribute("clientId", clientIdVal); } const std::string requestIdVal = BasePlatform::UuidToString(responseDoc->getRequestId()); if (! requestIdVal.empty()) { thisXml->addAttribute("requestId", requestIdVal); } const std::string pmeIdVal = responseDoc->getPmeId(); if (! pmeIdVal.empty()) { thisXml->addAttribute("pmeId", pmeIdVal); } const SmartPtrCResponseHeaderDoc responseHeaderVal = responseDoc->getResponseHeader(); if (! responseHeaderVal.IsNull()) { const SmartPtrCXmlElement responseHeaderXml = thisXml->createAndAddElement("responseHeader"); ResponseHeaderXml::add(responseHeaderVal, responseHeaderXml); } const SmartPtrCManifestCollectionDoc manifestCollectionVal = responseDoc->getManifestCollection(); if (! manifestCollectionVal.IsNull()) { const SmartPtrCXmlElement manifestCollectionXml = thisXml->createAndAddElement("manifestCollection"); ManifestCollectionXml::add(manifestCollectionVal, manifestCollectionXml); } const SmartPtrCAttachmentCollectionDoc attachmentCollectionVal = responseDoc->getAttachmentCollection(); if (! attachmentCollectionVal.IsNull()) { const SmartPtrCXmlElement attachmentCollectionXml = thisXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionVal, attachmentCollectionXml); } const SmartPtrCStatisticsDoc statisticsVal = responseDoc->getStatistics(); if (! statisticsVal.IsNull()) { const SmartPtrCXmlElement statisticsXml = thisXml->createAndAddElement("statistics"); StatisticsXml::add(statisticsVal, statisticsXml); } } CAF_CM_EXIT; } SmartPtrCResponseDoc ResponseXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ResponseXml", "parse"); SmartPtrCResponseDoc responseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string clientIdStrVal = thisXml->findOptionalAttribute("clientId"); UUID clientIdVal = CAFCOMMON_GUID_NULL; if (! clientIdStrVal.empty()) { BasePlatform::UuidFromString(clientIdStrVal.c_str(), clientIdVal); } const std::string requestIdStrVal = thisXml->findOptionalAttribute("requestId"); UUID requestIdVal = CAFCOMMON_GUID_NULL; if (! requestIdStrVal.empty()) { BasePlatform::UuidFromString(requestIdStrVal.c_str(), requestIdVal); } const std::string pmeIdVal = thisXml->findOptionalAttribute("pmeId"); const SmartPtrCXmlElement responseHeaderXml = thisXml->findOptionalChild("responseHeader"); SmartPtrCResponseHeaderDoc responseHeaderVal; if (! responseHeaderXml.IsNull()) { responseHeaderVal = ResponseHeaderXml::parse(responseHeaderXml); } const SmartPtrCXmlElement manifestCollectionXml = thisXml->findOptionalChild("manifestCollection"); SmartPtrCManifestCollectionDoc manifestCollectionVal; if (! manifestCollectionXml.IsNull()) { manifestCollectionVal = ManifestCollectionXml::parse(manifestCollectionXml); } const SmartPtrCXmlElement attachmentCollectionXml = thisXml->findOptionalChild("attachmentCollection"); SmartPtrCAttachmentCollectionDoc attachmentCollectionVal; if (! attachmentCollectionXml.IsNull()) { attachmentCollectionVal = AttachmentCollectionXml::parse(attachmentCollectionXml); } const SmartPtrCXmlElement statisticsXml = thisXml->findOptionalChild("statistics"); SmartPtrCStatisticsDoc statisticsVal; if (! statisticsXml.IsNull()) { statisticsVal = StatisticsXml::parse(statisticsXml); } responseDoc.CreateInstance(); responseDoc->initialize( clientIdVal, requestIdVal, pmeIdVal, responseHeaderVal, manifestCollectionVal, attachmentCollectionVal, statisticsVal); } CAF_CM_EXIT; return responseDoc; } ResponseXmlRoots.cpp000066400000000000000000000223441321503522500401770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/ResponseXml/ResponseXml.h" #include "Doc/ResponseDoc/CErrorResponseDoc.h" #include "Doc/ResponseDoc/CProviderEventResponseDoc.h" #include "Doc/ResponseDoc/CProviderResponseDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/ResponseXml/ResponseXmlRoots.h" #include "Doc/DocXml/ResponseXml/ErrorResponseXml.h" #include "Doc/DocXml/ResponseXml/ProviderResponseXml.h" #include "Doc/DocXml/ResponseXml/ProviderEventResponseXml.h" using namespace Caf; std::string XmlRoots::saveErrorResponseToString( const SmartPtrCErrorResponseDoc errorResponseDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveErrorResponseToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(errorResponseDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/Response.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "errorResponse", schemaNamespace, schemaLocation); ErrorResponseXml::add(errorResponseDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCErrorResponseDoc XmlRoots::parseErrorResponseFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseErrorResponseFromString"); SmartPtrCErrorResponseDoc errorResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:errorResponse"); errorResponseDoc = ErrorResponseXml::parse(rootXml); } CAF_CM_EXIT; return errorResponseDoc; } void XmlRoots::saveErrorResponseToFile( const SmartPtrCErrorResponseDoc errorResponseDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveErrorResponseToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(errorResponseDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string errorResponseStr = saveErrorResponseToString(errorResponseDoc); FileSystemUtils::saveTextFile(filePath, errorResponseStr); } CAF_CM_EXIT; } SmartPtrCErrorResponseDoc XmlRoots::parseErrorResponseFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseErrorResponseFromFile"); SmartPtrCErrorResponseDoc errorResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:errorResponse"); errorResponseDoc = ErrorResponseXml::parse(rootXml); } CAF_CM_EXIT; return errorResponseDoc; } std::string XmlRoots::saveProviderResponseToString( const SmartPtrCProviderResponseDoc providerResponseDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveProviderResponseToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerResponseDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/Response.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "providerResponse", schemaNamespace, schemaLocation); ProviderResponseXml::add(providerResponseDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCProviderResponseDoc XmlRoots::parseProviderResponseFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderResponseFromString"); SmartPtrCProviderResponseDoc providerResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:providerResponse"); providerResponseDoc = ProviderResponseXml::parse(rootXml); } CAF_CM_EXIT; return providerResponseDoc; } void XmlRoots::saveProviderResponseToFile( const SmartPtrCProviderResponseDoc providerResponseDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveProviderResponseToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerResponseDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string providerResponseStr = saveProviderResponseToString(providerResponseDoc); FileSystemUtils::saveTextFile(filePath, providerResponseStr); } CAF_CM_EXIT; } SmartPtrCProviderResponseDoc XmlRoots::parseProviderResponseFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderResponseFromFile"); SmartPtrCProviderResponseDoc providerResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:providerResponse"); providerResponseDoc = ProviderResponseXml::parse(rootXml); } CAF_CM_EXIT; return providerResponseDoc; } std::string XmlRoots::saveResponseToString( const SmartPtrCResponseDoc responseDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveResponseToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(responseDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/Response.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "response", schemaNamespace, schemaLocation); ResponseXml::add(responseDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCResponseDoc XmlRoots::parseResponseFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseResponseFromString"); SmartPtrCResponseDoc responseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:response"); responseDoc = ResponseXml::parse(rootXml); } CAF_CM_EXIT; return responseDoc; } void XmlRoots::saveResponseToFile( const SmartPtrCResponseDoc responseDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveResponseToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(responseDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string responseStr = saveResponseToString(responseDoc); FileSystemUtils::saveTextFile(filePath, responseStr); } CAF_CM_EXIT; } SmartPtrCResponseDoc XmlRoots::parseResponseFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseResponseFromFile"); SmartPtrCResponseDoc responseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:response"); responseDoc = ResponseXml::parse(rootXml); } CAF_CM_EXIT; return responseDoc; } std::string XmlRoots::saveProviderEventResponseToString( const SmartPtrCProviderEventResponseDoc providerEventResponseDoc) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveProviderEventResponseToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerEventResponseDoc); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const std::string schemaLocation = DocXmlUtils::getSchemaLocation("fx/Response.xsd"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "providerEventResponse", schemaNamespace, schemaLocation); ProviderEventResponseXml::add(providerEventResponseDoc, rootXml); rc = rootXml->saveToString(); } CAF_CM_EXIT; return rc; } SmartPtrCProviderEventResponseDoc XmlRoots::parseProviderEventResponseFromString( const std::string xml) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderEventResponseFromString"); SmartPtrCProviderEventResponseDoc providerEventResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(xml); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(xml, "caf:providerEventResponse"); providerEventResponseDoc = ProviderEventResponseXml::parse(rootXml); } CAF_CM_EXIT; return providerEventResponseDoc; } void XmlRoots::saveProviderEventResponseToFile( const SmartPtrCProviderEventResponseDoc providerEventResponseDoc, const std::string filePath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("XmlRoots", "saveProviderEventResponseToFile"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(providerEventResponseDoc); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_LOG_DEBUG_VA1("Saving to file - %s", filePath.c_str()); const std::string providerEventResponseStr = saveProviderEventResponseToString(providerEventResponseDoc); FileSystemUtils::saveTextFile(filePath, providerEventResponseStr); } CAF_CM_EXIT; } SmartPtrCProviderEventResponseDoc XmlRoots::parseProviderEventResponseFromFile( const std::string filePath) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "parseProviderEventResponseFromFile"); SmartPtrCProviderEventResponseDoc providerEventResponseDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, "caf:providerEventResponse"); providerEventResponseDoc = ProviderEventResponseXml::parse(rootXml); } CAF_CM_EXIT; return providerEventResponseDoc; } stdafx.h000066400000000000000000000010201321503522500356130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/ResponseXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define RESPONSEXML_LINKAGE __declspec(dllexport) #else #define RESPONSEXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ SchemaTypesXml/000077500000000000000000000000001321503522500346075ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXmlActionClassInstanceCollectionXml.cpp000066400000000000000000000055431321503522500437070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/ActionClassInstanceXml.h" #include "Doc/SchemaTypesDoc/CActionClassInstanceCollectionDoc.h" #include "Doc/SchemaTypesDoc/CActionClassInstanceDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/ActionClassInstanceCollectionXml.h" using namespace Caf; void ActionClassInstanceCollectionXml::add( const SmartPtrCActionClassInstanceCollectionDoc actionClassInstanceCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ActionClassInstanceCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(actionClassInstanceCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque actionClassInstanceVal = actionClassInstanceCollectionDoc->getActionClassInstanceCollection(); CAF_CM_VALIDATE_STL(actionClassInstanceVal); if (! actionClassInstanceVal.empty()) { for (TConstIterator > actionClassInstanceIter(actionClassInstanceVal); actionClassInstanceIter; actionClassInstanceIter++) { const SmartPtrCXmlElement actionClassInstanceXml = thisXml->createAndAddElement("actionClassInstance"); ActionClassInstanceXml::add(*actionClassInstanceIter, actionClassInstanceXml); } } } CAF_CM_EXIT; } SmartPtrCActionClassInstanceCollectionDoc ActionClassInstanceCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ActionClassInstanceCollectionXml", "parse"); SmartPtrCActionClassInstanceCollectionDoc actionClassInstanceCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection actionClassInstanceChildrenXml = thisXml->findRequiredChildren("actionClassInstance"); std::deque actionClassInstanceVal; if (! actionClassInstanceChildrenXml.IsNull() && ! actionClassInstanceChildrenXml->empty()) { for (TConstIterator actionClassInstanceXmlIter(*actionClassInstanceChildrenXml); actionClassInstanceXmlIter; actionClassInstanceXmlIter++) { const SmartPtrCXmlElement actionClassInstanceXml = actionClassInstanceXmlIter->second; const SmartPtrCActionClassInstanceDoc actionClassInstanceDoc = ActionClassInstanceXml::parse(actionClassInstanceXml); actionClassInstanceVal.push_back(actionClassInstanceDoc); } } actionClassInstanceCollectionDoc.CreateInstance(); actionClassInstanceCollectionDoc->initialize( actionClassInstanceVal); } CAF_CM_EXIT; return actionClassInstanceCollectionDoc; } ActionClassInstanceXml.cpp000066400000000000000000000060461321503522500416720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/InstanceOperationCollectionXml.h" #include "Doc/SchemaTypesDoc/CActionClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CInstanceOperationCollectionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/ActionClassInstanceXml.h" using namespace Caf; void ActionClassInstanceXml::add( const SmartPtrCActionClassInstanceDoc actionClassInstanceDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ActionClassInstanceXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(actionClassInstanceDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = actionClassInstanceDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = actionClassInstanceDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = actionClassInstanceDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const SmartPtrCInstanceOperationCollectionDoc instanceOperationCollectionVal = actionClassInstanceDoc->getInstanceOperationCollection(); CAF_CM_VALIDATE_SMARTPTR(instanceOperationCollectionVal); const SmartPtrCXmlElement instanceOperationCollectionXml = thisXml->createAndAddElement("instanceOperationCollection"); InstanceOperationCollectionXml::add(instanceOperationCollectionVal, instanceOperationCollectionXml); } CAF_CM_EXIT; } SmartPtrCActionClassInstanceDoc ActionClassInstanceXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ActionClassInstanceXml", "parse"); SmartPtrCActionClassInstanceDoc actionClassInstanceDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const SmartPtrCXmlElement instanceOperationCollectionXml = thisXml->findRequiredChild("instanceOperationCollection"); SmartPtrCInstanceOperationCollectionDoc instanceOperationCollectionVal; if (! instanceOperationCollectionXml.IsNull()) { instanceOperationCollectionVal = InstanceOperationCollectionXml::parse(instanceOperationCollectionXml); } actionClassInstanceDoc.CreateInstance(); actionClassInstanceDoc->initialize( namespaceValVal, nameVal, versionVal, instanceOperationCollectionVal); } CAF_CM_EXIT; return actionClassInstanceDoc; } ActionClassXml.cpp000066400000000000000000000104131321503522500401760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/MethodXml.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/ActionClassXml.h" #include "Doc/DocXml/SchemaTypesXml/CollectMethodXml.h" using namespace Caf; void ActionClassXml::add( const SmartPtrCActionClassDoc actionClassDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ActionClassXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(actionClassDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = actionClassDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = actionClassDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = actionClassDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const SmartPtrCCollectMethodDoc collectMethodVal = actionClassDoc->getCollectMethod(); if (! collectMethodVal.IsNull()) { const SmartPtrCXmlElement collectMethodXml = thisXml->createAndAddElement("collectMethod"); CollectMethodXml::add(collectMethodVal, collectMethodXml); } const std::deque methodVal = actionClassDoc->getMethodCollection(); if (! methodVal.empty()) { for (TConstIterator > methodIter(methodVal); methodIter; methodIter++) { const SmartPtrCXmlElement methodXml = thisXml->createAndAddElement("method"); MethodXml::add(*methodIter, methodXml); } } const std::string displayNameVal = actionClassDoc->getDisplayName(); if (! displayNameVal.empty()) { thisXml->addAttribute("displayName", displayNameVal); } const std::string descriptionVal = actionClassDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCActionClassDoc ActionClassXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ActionClassXml", "parse"); SmartPtrCActionClassDoc actionClassDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const SmartPtrCXmlElement collectMethodXml = thisXml->findOptionalChild("collectMethod"); SmartPtrCCollectMethodDoc collectMethodVal; if (! collectMethodXml.IsNull()) { collectMethodVal = CollectMethodXml::parse(collectMethodXml); } const CXmlElement::SmartPtrCElementCollection methodChildrenXml = thisXml->findOptionalChildren("method"); std::deque methodVal; if (! methodChildrenXml.IsNull() && ! methodChildrenXml->empty()) { for (TConstIterator methodXmlIter(*methodChildrenXml); methodXmlIter; methodXmlIter++) { const SmartPtrCXmlElement methodXml = methodXmlIter->second; const SmartPtrCMethodDoc methodDoc = MethodXml::parse(methodXml); methodVal.push_back(methodDoc); } } const std::string displayNameStrVal = thisXml->findOptionalAttribute("displayName"); const std::string displayNameVal = displayNameStrVal; const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; actionClassDoc.CreateInstance(); actionClassDoc->initialize( namespaceValVal, nameVal, versionVal, collectMethodVal, methodVal, displayNameVal, descriptionVal); } CAF_CM_EXIT; return actionClassDoc; } ClassCardinalityXml.cpp000066400000000000000000000046021321503522500412270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/ClassCardinalityXml.h" using namespace Caf; void ClassCardinalityXml::add( const SmartPtrCClassCardinalityDoc classCardinalityDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassCardinalityXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(classCardinalityDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = classCardinalityDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = classCardinalityDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = classCardinalityDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::string cardinalityVal = classCardinalityDoc->getCardinality(); CAF_CM_VALIDATE_STRING(cardinalityVal); thisXml->addAttribute("cardinality", cardinalityVal); } CAF_CM_EXIT; } SmartPtrCClassCardinalityDoc ClassCardinalityXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassCardinalityXml", "parse"); SmartPtrCClassCardinalityDoc classCardinalityDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const std::string cardinalityStrVal = thisXml->findRequiredAttribute("cardinality"); const std::string cardinalityVal = cardinalityStrVal; classCardinalityDoc.CreateInstance(); classCardinalityDoc->initialize( namespaceValVal, nameVal, versionVal, cardinalityVal); } CAF_CM_EXIT; return classCardinalityDoc; } ClassFieldXml.cpp000066400000000000000000000043241321503522500400100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassFieldDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/ClassFieldXml.h" using namespace Caf; void ClassFieldXml::add( const SmartPtrCClassFieldDoc classFieldDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassFieldXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(classFieldDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = classFieldDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = classFieldDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = classFieldDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::string fieldVal = classFieldDoc->getField(); CAF_CM_VALIDATE_STRING(fieldVal); thisXml->addAttribute("field", fieldVal); } CAF_CM_EXIT; } SmartPtrCClassFieldDoc ClassFieldXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassFieldXml", "parse"); SmartPtrCClassFieldDoc classFieldDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const std::string fieldStrVal = thisXml->findRequiredAttribute("field"); const std::string fieldVal = fieldStrVal; classFieldDoc.CreateInstance(); classFieldDoc->initialize( namespaceValVal, nameVal, versionVal, fieldVal); } CAF_CM_EXIT; return classFieldDoc; } ClassIdentifierXml.cpp000066400000000000000000000040331321503522500410440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/ClassIdentifierXml.h" using namespace Caf; void ClassIdentifierXml::add( const SmartPtrCClassIdentifierDoc classIdentifierDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassIdentifierXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(classIdentifierDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = classIdentifierDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = classIdentifierDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = classIdentifierDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); } CAF_CM_EXIT; } SmartPtrCClassIdentifierDoc ClassIdentifierXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassIdentifierXml", "parse"); SmartPtrCClassIdentifierDoc classIdentifierDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; classIdentifierDoc.CreateInstance(); classIdentifierDoc->initialize( namespaceValVal, nameVal, versionVal); } CAF_CM_EXIT; return classIdentifierDoc; } ClassInstancePropertyXml.cpp000066400000000000000000000106751321503522500423040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/ClassIdentifierXml.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/ClassInstancePropertyXml.h" using namespace Caf; void ClassInstancePropertyXml::add( const SmartPtrCClassInstancePropertyDoc classInstancePropertyDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassInstancePropertyXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(classInstancePropertyDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = classInstancePropertyDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::deque typeVal = classInstancePropertyDoc->getType(); CAF_CM_VALIDATE_STL(typeVal); if (! typeVal.empty()) { for (TConstIterator > typeIter(typeVal); typeIter; typeIter++) { const SmartPtrCXmlElement typeXml = thisXml->createAndAddElement("type"); ClassIdentifierXml::add(*typeIter, typeXml); } } const std::string requiredVal = classInstancePropertyDoc->getRequired() ? "true" : "false"; if (! requiredVal.empty()) { thisXml->addAttribute("required", requiredVal); } const std::string transientValVal = classInstancePropertyDoc->getTransientVal() ? "true" : "false"; if (! transientValVal.empty()) { thisXml->addAttribute("transient", transientValVal); } const std::string listVal = classInstancePropertyDoc->getList() ? "true" : "false"; if (! listVal.empty()) { thisXml->addAttribute("list", listVal); } const std::string displayNameVal = classInstancePropertyDoc->getDisplayName(); if (! displayNameVal.empty()) { thisXml->addAttribute("displayName", displayNameVal); } const std::string descriptionVal = classInstancePropertyDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCClassInstancePropertyDoc ClassInstancePropertyXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassInstancePropertyXml", "parse"); SmartPtrCClassInstancePropertyDoc classInstancePropertyDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const CXmlElement::SmartPtrCElementCollection typeChildrenXml = thisXml->findRequiredChildren("type"); std::deque typeVal; if (! typeChildrenXml.IsNull() && ! typeChildrenXml->empty()) { for (TConstIterator typeXmlIter(*typeChildrenXml); typeXmlIter; typeXmlIter++) { const SmartPtrCXmlElement typeXml = typeXmlIter->second; const SmartPtrCClassIdentifierDoc typeDoc = ClassIdentifierXml::parse(typeXml); typeVal.push_back(typeDoc); } } const std::string requiredStrVal = thisXml->findOptionalAttribute("required"); bool requiredVal = false; if (! requiredStrVal.empty()) { requiredVal = (requiredStrVal.compare("true") == 0) ? true : false; } const std::string transientValStrVal = thisXml->findOptionalAttribute("transient"); bool transientValVal = false; if (! transientValStrVal.empty()) { transientValVal = (transientValStrVal.compare("true") == 0) ? true : false; } const std::string listStrVal = thisXml->findOptionalAttribute("list"); bool listVal = false; if (! listStrVal.empty()) { listVal = (listStrVal.compare("true") == 0) ? true : false; } const std::string displayNameStrVal = thisXml->findOptionalAttribute("displayName"); const std::string displayNameVal = displayNameStrVal; const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; classInstancePropertyDoc.CreateInstance(); classInstancePropertyDoc->initialize( nameVal, typeVal, requiredVal, transientValVal, listVal, displayNameVal, descriptionVal); } CAF_CM_EXIT; return classInstancePropertyDoc; } ClassPropertyXml.cpp000066400000000000000000000155341321503522500406160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/ClassPropertyXml.h" using namespace Caf; void ClassPropertyXml::add( const SmartPtrCClassPropertyDoc classPropertyDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassPropertyXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(classPropertyDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = classPropertyDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string typeVal = EnumConvertersXml::convertPropertyTypeToString(classPropertyDoc->getType()); CAF_CM_VALIDATE_STRING(typeVal); thisXml->addAttribute("type", typeVal); const std::deque valueVal = classPropertyDoc->getValue(); if (! valueVal.empty()) { for (TConstIterator > valueIter(valueVal); valueIter; valueIter++) { const SmartPtrCXmlElement valueXml = thisXml->createAndAddElement("value"); valueXml->setValue(*valueIter); } } const std::string requiredVal = classPropertyDoc->getRequired() ? "true" : "false"; if (! requiredVal.empty()) { thisXml->addAttribute("required", requiredVal); } const std::string keyVal = classPropertyDoc->getKey() ? "true" : "false"; if (! keyVal.empty()) { thisXml->addAttribute("key", keyVal); } const std::string listVal = classPropertyDoc->getList() ? "true" : "false"; if (! listVal.empty()) { thisXml->addAttribute("list", listVal); } const std::string caseSensitiveVal = classPropertyDoc->getCaseSensitive() ? "true" : "false"; if (! caseSensitiveVal.empty()) { thisXml->addAttribute("caseSensitive", caseSensitiveVal); } const std::string transientValVal = classPropertyDoc->getTransientVal() ? "true" : "false"; if (! transientValVal.empty()) { thisXml->addAttribute("transient", transientValVal); } const std::string defaultValVal = classPropertyDoc->getDefaultVal(); if (! defaultValVal.empty()) { thisXml->addAttribute("default", defaultValVal); } const std::string validatorVal = EnumConvertersXml::convertValidatorTypeToString(classPropertyDoc->getValidator()); if (! validatorVal.empty()) { thisXml->addAttribute("validator", validatorVal); } const std::string upperRangeVal = classPropertyDoc->getUpperRange(); if (! upperRangeVal.empty()) { thisXml->addAttribute("upperRange", upperRangeVal); } const std::string lowerRangeVal = classPropertyDoc->getLowerRange(); if (! lowerRangeVal.empty()) { thisXml->addAttribute("lowerRange", lowerRangeVal); } const std::string displayNameVal = classPropertyDoc->getDisplayName(); if (! displayNameVal.empty()) { thisXml->addAttribute("displayName", displayNameVal); } const std::string descriptionVal = classPropertyDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCClassPropertyDoc ClassPropertyXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("ClassPropertyXml", "parse"); SmartPtrCClassPropertyDoc classPropertyDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string typeStrVal = thisXml->findRequiredAttribute("type"); PROPERTY_TYPE typeVal = PROPERTY_NONE; if (! typeStrVal.empty()) { typeVal = EnumConvertersXml::convertStringToPropertyType(typeStrVal); } const CXmlElement::SmartPtrCElementCollection valueChildrenXml = thisXml->findOptionalChildren("value"); std::deque valueVal; if (! valueChildrenXml.IsNull() && ! valueChildrenXml->empty()) { for (TConstIterator valueXmlIter(*valueChildrenXml); valueXmlIter; valueXmlIter++) { const SmartPtrCXmlElement valueXml = valueXmlIter->second; const std::string valueDoc = valueXml->getValue(); valueVal.push_back(valueDoc); } } const std::string requiredStrVal = thisXml->findOptionalAttribute("required"); bool requiredVal = false; if (! requiredStrVal.empty()) { requiredVal = (requiredStrVal.compare("true") == 0) ? true : false; } const std::string keyStrVal = thisXml->findOptionalAttribute("key"); bool keyVal = false; if (! keyStrVal.empty()) { keyVal = (keyStrVal.compare("true") == 0) ? true : false; } const std::string listStrVal = thisXml->findOptionalAttribute("list"); bool listVal = false; if (! listStrVal.empty()) { listVal = (listStrVal.compare("true") == 0) ? true : false; } const std::string caseSensitiveStrVal = thisXml->findOptionalAttribute("caseSensitive"); bool caseSensitiveVal = false; if (! caseSensitiveStrVal.empty()) { caseSensitiveVal = (caseSensitiveStrVal.compare("true") == 0) ? true : false; } const std::string transientValStrVal = thisXml->findOptionalAttribute("transient"); bool transientValVal = false; if (! transientValStrVal.empty()) { transientValVal = (transientValStrVal.compare("true") == 0) ? true : false; } const std::string defaultValStrVal = thisXml->findOptionalAttribute("default"); const std::string defaultValVal = defaultValStrVal; const std::string validatorStrVal = thisXml->findOptionalAttribute("validator"); VALIDATOR_TYPE validatorVal = VALIDATOR_NONE; if (! validatorStrVal.empty()) { validatorVal = EnumConvertersXml::convertStringToValidatorType(validatorStrVal); } const std::string upperRangeStrVal = thisXml->findOptionalAttribute("upperRange"); const std::string upperRangeVal = upperRangeStrVal; const std::string lowerRangeStrVal = thisXml->findOptionalAttribute("lowerRange"); const std::string lowerRangeVal = lowerRangeStrVal; const std::string displayNameStrVal = thisXml->findOptionalAttribute("displayName"); const std::string displayNameVal = displayNameStrVal; const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; classPropertyDoc.CreateInstance(); classPropertyDoc->initialize( nameVal, typeVal, valueVal, requiredVal, keyVal, listVal, caseSensitiveVal, transientValVal, defaultValVal, validatorVal, upperRangeVal, lowerRangeVal, displayNameVal, descriptionVal); } CAF_CM_EXIT; return classPropertyDoc; } CmdlMetadataXml.cpp000066400000000000000000000033701321503522500403170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/CmdlMetadataXml.h" using namespace Caf; void CmdlMetadataXml::add( const SmartPtrCCmdlMetadataDoc cmdlMetadataDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CmdlMetadataXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(cmdlMetadataDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = cmdlMetadataDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string valueVal = cmdlMetadataDoc->getValue(); CAF_CM_VALIDATE_STRING(valueVal); const SmartPtrCXmlElement valueXml = thisXml->createAndAddElement("value"); valueXml->setValue(valueVal); } CAF_CM_EXIT; } SmartPtrCCmdlMetadataDoc CmdlMetadataXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CmdlMetadataXml", "parse"); SmartPtrCCmdlMetadataDoc cmdlMetadataDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const SmartPtrCXmlElement valueXml = thisXml->findRequiredChild("value"); std::string valueVal; if (! valueXml.IsNull()) { valueVal = valueXml->getValue(); } cmdlMetadataDoc.CreateInstance(); cmdlMetadataDoc->initialize( nameVal, valueVal); } CAF_CM_EXIT; return cmdlMetadataDoc; } CmdlUnionXml.cpp000066400000000000000000000036571321503522500376770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/CmdlUnionXml.h" using namespace Caf; void CmdlUnionXml::add( const SmartPtrCCmdlUnionDoc cmdlUnionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CmdlUnionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(cmdlUnionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = cmdlUnionDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = cmdlUnionDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = cmdlUnionDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); } CAF_CM_EXIT; } SmartPtrCCmdlUnionDoc CmdlUnionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CmdlUnionXml", "parse"); SmartPtrCCmdlUnionDoc cmdlUnionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; cmdlUnionDoc.CreateInstance(); cmdlUnionDoc->initialize( namespaceValVal, nameVal, versionVal); } CAF_CM_EXIT; return cmdlUnionDoc; } CollectMethodXml.cpp000066400000000000000000000157561321503522500405400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/ClassIdentifierXml.h" #include "Doc/DocXml/SchemaTypesXml/InstanceParameterXml.h" #include "Doc/DocXml/SchemaTypesXml/MethodParameterXml.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/CollectMethodXml.h" using namespace Caf; void CollectMethodXml::add( const SmartPtrCCollectMethodDoc collectMethodDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CollectMethodXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(collectMethodDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = collectMethodDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::deque parameterVal = collectMethodDoc->getParameterCollection(); if (! parameterVal.empty()) { for (TConstIterator > parameterIter(parameterVal); parameterIter; parameterIter++) { const SmartPtrCXmlElement parameterXml = thisXml->createAndAddElement("parameter"); MethodParameterXml::add(*parameterIter, parameterXml); } } const std::deque instanceParameterVal = collectMethodDoc->getInstanceParameterCollection(); if (! instanceParameterVal.empty()) { for (TConstIterator > instanceParameterIter(instanceParameterVal); instanceParameterIter; instanceParameterIter++) { const SmartPtrCXmlElement instanceParameterXml = thisXml->createAndAddElement("instanceParameter"); InstanceParameterXml::add(*instanceParameterIter, instanceParameterXml); } } const std::deque returnValVal = collectMethodDoc->getReturnValCollection(); if (! returnValVal.empty()) { for (TConstIterator > returnValIter(returnValVal); returnValIter; returnValIter++) { const SmartPtrCXmlElement returnValXml = thisXml->createAndAddElement("return"); ClassIdentifierXml::add(*returnValIter, returnValXml); } } const std::deque eventValVal = collectMethodDoc->getEventValCollection(); if (! eventValVal.empty()) { for (TConstIterator > eventValIter(eventValVal); eventValIter; eventValIter++) { const SmartPtrCXmlElement eventValXml = thisXml->createAndAddElement("event"); ClassIdentifierXml::add(*eventValIter, eventValXml); } } const std::deque errorVal = collectMethodDoc->getErrorCollection(); if (! errorVal.empty()) { for (TConstIterator > errorIter(errorVal); errorIter; errorIter++) { const SmartPtrCXmlElement errorXml = thisXml->createAndAddElement("error"); ClassIdentifierXml::add(*errorIter, errorXml); } } } CAF_CM_EXIT; } SmartPtrCCollectMethodDoc CollectMethodXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("CollectMethodXml", "parse"); SmartPtrCCollectMethodDoc collectMethodDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const CXmlElement::SmartPtrCElementCollection parameterChildrenXml = thisXml->findOptionalChildren("parameter"); std::deque parameterVal; if (! parameterChildrenXml.IsNull() && ! parameterChildrenXml->empty()) { for (TConstIterator parameterXmlIter(*parameterChildrenXml); parameterXmlIter; parameterXmlIter++) { const SmartPtrCXmlElement parameterXml = parameterXmlIter->second; const SmartPtrCMethodParameterDoc parameterDoc = MethodParameterXml::parse(parameterXml); parameterVal.push_back(parameterDoc); } } const CXmlElement::SmartPtrCElementCollection instanceParameterChildrenXml = thisXml->findOptionalChildren("instanceParameter"); std::deque instanceParameterVal; if (! instanceParameterChildrenXml.IsNull() && ! instanceParameterChildrenXml->empty()) { for (TConstIterator instanceParameterXmlIter(*instanceParameterChildrenXml); instanceParameterXmlIter; instanceParameterXmlIter++) { const SmartPtrCXmlElement instanceParameterXml = instanceParameterXmlIter->second; const SmartPtrCInstanceParameterDoc instanceParameterDoc = InstanceParameterXml::parse(instanceParameterXml); instanceParameterVal.push_back(instanceParameterDoc); } } const CXmlElement::SmartPtrCElementCollection returnValChildrenXml = thisXml->findOptionalChildren("return"); std::deque returnValVal; if (! returnValChildrenXml.IsNull() && ! returnValChildrenXml->empty()) { for (TConstIterator returnValXmlIter(*returnValChildrenXml); returnValXmlIter; returnValXmlIter++) { const SmartPtrCXmlElement returnValXml = returnValXmlIter->second; const SmartPtrCClassIdentifierDoc returnValDoc = ClassIdentifierXml::parse(returnValXml); returnValVal.push_back(returnValDoc); } } const CXmlElement::SmartPtrCElementCollection eventValChildrenXml = thisXml->findOptionalChildren("event"); std::deque eventValVal; if (! eventValChildrenXml.IsNull() && ! eventValChildrenXml->empty()) { for (TConstIterator eventValXmlIter(*eventValChildrenXml); eventValXmlIter; eventValXmlIter++) { const SmartPtrCXmlElement eventValXml = eventValXmlIter->second; const SmartPtrCClassIdentifierDoc eventValDoc = ClassIdentifierXml::parse(eventValXml); eventValVal.push_back(eventValDoc); } } const CXmlElement::SmartPtrCElementCollection errorChildrenXml = thisXml->findOptionalChildren("error"); std::deque errorVal; if (! errorChildrenXml.IsNull() && ! errorChildrenXml->empty()) { for (TConstIterator errorXmlIter(*errorChildrenXml); errorXmlIter; errorXmlIter++) { const SmartPtrCXmlElement errorXml = errorXmlIter->second; const SmartPtrCClassIdentifierDoc errorDoc = ClassIdentifierXml::parse(errorXml); errorVal.push_back(errorDoc); } } collectMethodDoc.CreateInstance(); collectMethodDoc->initialize( nameVal, parameterVal, instanceParameterVal, returnValVal, eventValVal, errorVal); } CAF_CM_EXIT; return collectMethodDoc; } DataClassInstanceCollectionXml.cpp000066400000000000000000000053731321503522500433440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/DataClassInstanceXml.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceCollectionDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/DataClassInstanceCollectionXml.h" using namespace Caf; void DataClassInstanceCollectionXml::add( const SmartPtrCDataClassInstanceCollectionDoc dataClassInstanceCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassInstanceCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(dataClassInstanceCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque dataClassInstanceVal = dataClassInstanceCollectionDoc->getDataClassInstanceCollection(); CAF_CM_VALIDATE_STL(dataClassInstanceVal); if (! dataClassInstanceVal.empty()) { for (TConstIterator > dataClassInstanceIter(dataClassInstanceVal); dataClassInstanceIter; dataClassInstanceIter++) { const SmartPtrCXmlElement dataClassInstanceXml = thisXml->createAndAddElement("dataClassInstance"); DataClassInstanceXml::add(*dataClassInstanceIter, dataClassInstanceXml); } } } CAF_CM_EXIT; } SmartPtrCDataClassInstanceCollectionDoc DataClassInstanceCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassInstanceCollectionXml", "parse"); SmartPtrCDataClassInstanceCollectionDoc dataClassInstanceCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection dataClassInstanceChildrenXml = thisXml->findRequiredChildren("dataClassInstance"); std::deque dataClassInstanceVal; if (! dataClassInstanceChildrenXml.IsNull() && ! dataClassInstanceChildrenXml->empty()) { for (TConstIterator dataClassInstanceXmlIter(*dataClassInstanceChildrenXml); dataClassInstanceXmlIter; dataClassInstanceXmlIter++) { const SmartPtrCXmlElement dataClassInstanceXml = dataClassInstanceXmlIter->second; const SmartPtrCDataClassInstanceDoc dataClassInstanceDoc = DataClassInstanceXml::parse(dataClassInstanceXml); dataClassInstanceVal.push_back(dataClassInstanceDoc); } } dataClassInstanceCollectionDoc.CreateInstance(); dataClassInstanceCollectionDoc->initialize( dataClassInstanceVal); } CAF_CM_EXIT; return dataClassInstanceCollectionDoc; } DataClassInstanceXml.cpp000066400000000000000000000145771321503522500413360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/CmdlMetadataXml.h" #include "Doc/DocXml/SchemaTypesXml/CmdlUnionXml.h" #include "Doc/DocXml/SchemaTypesXml/DataClassSubInstanceXml.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/DataClassInstanceXml.h" #include "Doc/DocXml/SchemaTypesXml/DataClassPropertyXml.h" using namespace Caf; void DataClassInstanceXml::add( const SmartPtrCDataClassInstanceDoc dataClassInstanceDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassInstanceXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(dataClassInstanceDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = dataClassInstanceDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = dataClassInstanceDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = dataClassInstanceDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::deque cmdlMetadataVal = dataClassInstanceDoc->getCmdlMetadataCollection(); if (! cmdlMetadataVal.empty()) { for (TConstIterator > cmdlMetadataIter(cmdlMetadataVal); cmdlMetadataIter; cmdlMetadataIter++) { const SmartPtrCXmlElement cmdlMetadataXml = thisXml->createAndAddElement("cmdlMetadata"); CmdlMetadataXml::add(*cmdlMetadataIter, cmdlMetadataXml); } } const std::deque propertyVal = dataClassInstanceDoc->getPropertyCollection(); if (! propertyVal.empty()) { for (TConstIterator > propertyIter(propertyVal); propertyIter; propertyIter++) { const SmartPtrCXmlElement propertyXml = thisXml->createAndAddElement("property"); DataClassPropertyXml::add(*propertyIter, propertyXml); } } const std::deque instancePropertyVal = dataClassInstanceDoc->getInstancePropertyCollection(); if (! instancePropertyVal.empty()) { for (TConstIterator > instancePropertyIter(instancePropertyVal); instancePropertyIter; instancePropertyIter++) { const SmartPtrCXmlElement instancePropertyXml = thisXml->createAndAddElement("instanceProperty"); DataClassSubInstanceXml::add(*instancePropertyIter, instancePropertyXml); } } const SmartPtrCCmdlUnionDoc cmdlUnionVal = dataClassInstanceDoc->getCmdlUnion(); if (! cmdlUnionVal.IsNull()) { const SmartPtrCXmlElement cmdlUnionXml = thisXml->createAndAddElement("cmdlUnion"); CmdlUnionXml::add(cmdlUnionVal, cmdlUnionXml); } } CAF_CM_EXIT; } SmartPtrCDataClassInstanceDoc DataClassInstanceXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassInstanceXml", "parse"); SmartPtrCDataClassInstanceDoc dataClassInstanceDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const CXmlElement::SmartPtrCElementCollection cmdlMetadataChildrenXml = thisXml->findOptionalChildren("cmdlMetadata"); std::deque cmdlMetadataVal; if (! cmdlMetadataChildrenXml.IsNull() && ! cmdlMetadataChildrenXml->empty()) { for (TConstIterator cmdlMetadataXmlIter(*cmdlMetadataChildrenXml); cmdlMetadataXmlIter; cmdlMetadataXmlIter++) { const SmartPtrCXmlElement cmdlMetadataXml = cmdlMetadataXmlIter->second; const SmartPtrCCmdlMetadataDoc cmdlMetadataDoc = CmdlMetadataXml::parse(cmdlMetadataXml); cmdlMetadataVal.push_back(cmdlMetadataDoc); } } const CXmlElement::SmartPtrCElementCollection propertyChildrenXml = thisXml->findOptionalChildren("property"); std::deque propertyVal; if (! propertyChildrenXml.IsNull() && ! propertyChildrenXml->empty()) { for (TConstIterator propertyXmlIter(*propertyChildrenXml); propertyXmlIter; propertyXmlIter++) { const SmartPtrCXmlElement propertyXml = propertyXmlIter->second; const SmartPtrCDataClassPropertyDoc propertyDoc = DataClassPropertyXml::parse(propertyXml); propertyVal.push_back(propertyDoc); } } const CXmlElement::SmartPtrCElementCollection instancePropertyChildrenXml = thisXml->findOptionalChildren("instanceProperty"); std::deque instancePropertyVal; if (! instancePropertyChildrenXml.IsNull() && ! instancePropertyChildrenXml->empty()) { for (TConstIterator instancePropertyXmlIter(*instancePropertyChildrenXml); instancePropertyXmlIter; instancePropertyXmlIter++) { const SmartPtrCXmlElement instancePropertyXml = instancePropertyXmlIter->second; const SmartPtrCDataClassSubInstanceDoc instancePropertyDoc = DataClassSubInstanceXml::parse(instancePropertyXml); instancePropertyVal.push_back(instancePropertyDoc); } } const SmartPtrCXmlElement cmdlUnionXml = thisXml->findOptionalChild("cmdlUnion"); SmartPtrCCmdlUnionDoc cmdlUnionVal; if (! cmdlUnionXml.IsNull()) { cmdlUnionVal = CmdlUnionXml::parse(cmdlUnionXml); } dataClassInstanceDoc.CreateInstance(); dataClassInstanceDoc->initialize( namespaceValVal, nameVal, versionVal, cmdlMetadataVal, propertyVal, instancePropertyVal, cmdlUnionVal); } CAF_CM_EXIT; return dataClassInstanceDoc; } DataClassPropertyXml.cpp000066400000000000000000000060741321503522500414070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/CmdlMetadataXml.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/DataClassPropertyXml.h" using namespace Caf; void DataClassPropertyXml::add( const SmartPtrCDataClassPropertyDoc dataClassPropertyDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassPropertyXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(dataClassPropertyDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = dataClassPropertyDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::deque cmdlMetadataVal = dataClassPropertyDoc->getCmdlMetadata(); if (! cmdlMetadataVal.empty()) { for (TConstIterator > cmdlMetadataIter(cmdlMetadataVal); cmdlMetadataIter; cmdlMetadataIter++) { const SmartPtrCXmlElement cmdlMetadataXml = thisXml->createAndAddElement("cmdlMetadata"); CmdlMetadataXml::add(*cmdlMetadataIter, cmdlMetadataXml); } } const std::string valueVal = dataClassPropertyDoc->getValue(); if (! valueVal.empty()) { const SmartPtrCXmlElement valueXml = thisXml->createAndAddElement("value"); valueXml->setValue(valueVal); } } CAF_CM_EXIT; } SmartPtrCDataClassPropertyDoc DataClassPropertyXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassPropertyXml", "parse"); SmartPtrCDataClassPropertyDoc dataClassPropertyDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const CXmlElement::SmartPtrCElementCollection cmdlMetadataChildrenXml = thisXml->findOptionalChildren("cmdlMetadata"); std::deque cmdlMetadataVal; if (! cmdlMetadataChildrenXml.IsNull() && ! cmdlMetadataChildrenXml->empty()) { for (TConstIterator cmdlMetadataXmlIter(*cmdlMetadataChildrenXml); cmdlMetadataXmlIter; cmdlMetadataXmlIter++) { const SmartPtrCXmlElement cmdlMetadataXml = cmdlMetadataXmlIter->second; const SmartPtrCCmdlMetadataDoc cmdlMetadataDoc = CmdlMetadataXml::parse(cmdlMetadataXml); cmdlMetadataVal.push_back(cmdlMetadataDoc); } } const SmartPtrCXmlElement valueXml = thisXml->findOptionalChild("value"); std::string valueVal; if (! valueXml.IsNull()) { if (! valueXml.IsNull()) { valueVal = valueXml->getValue(); } } dataClassPropertyDoc.CreateInstance(); dataClassPropertyDoc->initialize( nameVal, cmdlMetadataVal, valueVal); } CAF_CM_EXIT; return dataClassPropertyDoc; } DataClassSubInstanceXml.cpp000066400000000000000000000132731321503522500420000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/CmdlMetadataXml.h" #include "Doc/DocXml/SchemaTypesXml/CmdlUnionXml.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CCmdlUnionDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/DataClassSubInstanceXml.h" #include "Doc/DocXml/SchemaTypesXml/DataClassPropertyXml.h" using namespace Caf; void DataClassSubInstanceXml::add( const SmartPtrCDataClassSubInstanceDoc dataClassSubInstanceDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassSubInstanceXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(dataClassSubInstanceDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = dataClassSubInstanceDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::deque cmdlMetadataVal = dataClassSubInstanceDoc->getCmdlMetadataCollection(); if (! cmdlMetadataVal.empty()) { for (TConstIterator > cmdlMetadataIter(cmdlMetadataVal); cmdlMetadataIter; cmdlMetadataIter++) { const SmartPtrCXmlElement cmdlMetadataXml = thisXml->createAndAddElement("cmdlMetadata"); CmdlMetadataXml::add(*cmdlMetadataIter, cmdlMetadataXml); } } const std::deque propertyVal = dataClassSubInstanceDoc->getPropertyCollection(); if (! propertyVal.empty()) { for (TConstIterator > propertyIter(propertyVal); propertyIter; propertyIter++) { const SmartPtrCXmlElement propertyXml = thisXml->createAndAddElement("property"); DataClassPropertyXml::add(*propertyIter, propertyXml); } } const std::deque instancePropertyVal = dataClassSubInstanceDoc->getInstancePropertyCollection(); if (! instancePropertyVal.empty()) { for (TConstIterator > instancePropertyIter(instancePropertyVal); instancePropertyIter; instancePropertyIter++) { const SmartPtrCXmlElement instancePropertyXml = thisXml->createAndAddElement("instanceProperty"); DataClassSubInstanceXml::add(*instancePropertyIter, instancePropertyXml); } } const SmartPtrCCmdlUnionDoc cmdlUnionVal = dataClassSubInstanceDoc->getCmdlUnion(); if (! cmdlUnionVal.IsNull()) { const SmartPtrCXmlElement cmdlUnionXml = thisXml->createAndAddElement("cmdlUnion"); CmdlUnionXml::add(cmdlUnionVal, cmdlUnionXml); } } CAF_CM_EXIT; } SmartPtrCDataClassSubInstanceDoc DataClassSubInstanceXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassSubInstanceXml", "parse"); SmartPtrCDataClassSubInstanceDoc dataClassSubInstanceDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const CXmlElement::SmartPtrCElementCollection cmdlMetadataChildrenXml = thisXml->findOptionalChildren("cmdlMetadata"); std::deque cmdlMetadataVal; if (! cmdlMetadataChildrenXml.IsNull() && ! cmdlMetadataChildrenXml->empty()) { for (TConstIterator cmdlMetadataXmlIter(*cmdlMetadataChildrenXml); cmdlMetadataXmlIter; cmdlMetadataXmlIter++) { const SmartPtrCXmlElement cmdlMetadataXml = cmdlMetadataXmlIter->second; const SmartPtrCCmdlMetadataDoc cmdlMetadataDoc = CmdlMetadataXml::parse(cmdlMetadataXml); cmdlMetadataVal.push_back(cmdlMetadataDoc); } } const CXmlElement::SmartPtrCElementCollection propertyChildrenXml = thisXml->findOptionalChildren("property"); std::deque propertyVal; if (! propertyChildrenXml.IsNull() && ! propertyChildrenXml->empty()) { for (TConstIterator propertyXmlIter(*propertyChildrenXml); propertyXmlIter; propertyXmlIter++) { const SmartPtrCXmlElement propertyXml = propertyXmlIter->second; const SmartPtrCDataClassPropertyDoc propertyDoc = DataClassPropertyXml::parse(propertyXml); propertyVal.push_back(propertyDoc); } } const CXmlElement::SmartPtrCElementCollection instancePropertyChildrenXml = thisXml->findOptionalChildren("instanceProperty"); std::deque instancePropertyVal; if (! instancePropertyChildrenXml.IsNull() && ! instancePropertyChildrenXml->empty()) { for (TConstIterator instancePropertyXmlIter(*instancePropertyChildrenXml); instancePropertyXmlIter; instancePropertyXmlIter++) { const SmartPtrCXmlElement instancePropertyXml = instancePropertyXmlIter->second; const SmartPtrCDataClassSubInstanceDoc instancePropertyDoc = DataClassSubInstanceXml::parse(instancePropertyXml); instancePropertyVal.push_back(instancePropertyDoc); } } const SmartPtrCXmlElement cmdlUnionXml = thisXml->findOptionalChild("cmdlUnion"); SmartPtrCCmdlUnionDoc cmdlUnionVal; if (! cmdlUnionXml.IsNull()) { cmdlUnionVal = CmdlUnionXml::parse(cmdlUnionXml); } dataClassSubInstanceDoc.CreateInstance(); dataClassSubInstanceDoc->initialize( nameVal, cmdlMetadataVal, propertyVal, instancePropertyVal, cmdlUnionVal); } CAF_CM_EXIT; return dataClassSubInstanceDoc; } DataClassXml.cpp000066400000000000000000000135641321503522500376440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/ClassInstancePropertyXml.h" #include "Doc/DocXml/SchemaTypesXml/ClassPropertyXml.h" #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/DataClassXml.h" using namespace Caf; void DataClassXml::add( const SmartPtrCDataClassDoc dataClassDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(dataClassDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = dataClassDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = dataClassDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = dataClassDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::deque propertyVal = dataClassDoc->getPropertyCollection(); if (! propertyVal.empty()) { for (TConstIterator > propertyIter(propertyVal); propertyIter; propertyIter++) { const SmartPtrCXmlElement propertyXml = thisXml->createAndAddElement("property"); ClassPropertyXml::add(*propertyIter, propertyXml); } } const std::deque instancePropertyVal = dataClassDoc->getInstancePropertyCollection(); if (! instancePropertyVal.empty()) { for (TConstIterator > instancePropertyIter(instancePropertyVal); instancePropertyIter; instancePropertyIter++) { const SmartPtrCXmlElement instancePropertyXml = thisXml->createAndAddElement("instanceProperty"); ClassInstancePropertyXml::add(*instancePropertyIter, instancePropertyXml); } } const std::string uniqueVal = dataClassDoc->getUnique() ? "true" : "false"; if (! uniqueVal.empty()) { thisXml->addAttribute("unique", uniqueVal); } const std::string transientValVal = dataClassDoc->getTransientVal() ? "true" : "false"; if (! transientValVal.empty()) { thisXml->addAttribute("transient", transientValVal); } const std::string displayNameVal = dataClassDoc->getDisplayName(); if (! displayNameVal.empty()) { thisXml->addAttribute("displayName", displayNameVal); } const std::string descriptionVal = dataClassDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCDataClassDoc DataClassXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("DataClassXml", "parse"); SmartPtrCDataClassDoc dataClassDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const CXmlElement::SmartPtrCElementCollection propertyChildrenXml = thisXml->findOptionalChildren("property"); std::deque propertyVal; if (! propertyChildrenXml.IsNull() && ! propertyChildrenXml->empty()) { for (TConstIterator propertyXmlIter(*propertyChildrenXml); propertyXmlIter; propertyXmlIter++) { const SmartPtrCXmlElement propertyXml = propertyXmlIter->second; const SmartPtrCClassPropertyDoc propertyDoc = ClassPropertyXml::parse(propertyXml); propertyVal.push_back(propertyDoc); } } const CXmlElement::SmartPtrCElementCollection instancePropertyChildrenXml = thisXml->findOptionalChildren("instanceProperty"); std::deque instancePropertyVal; if (! instancePropertyChildrenXml.IsNull() && ! instancePropertyChildrenXml->empty()) { for (TConstIterator instancePropertyXmlIter(*instancePropertyChildrenXml); instancePropertyXmlIter; instancePropertyXmlIter++) { const SmartPtrCXmlElement instancePropertyXml = instancePropertyXmlIter->second; const SmartPtrCClassInstancePropertyDoc instancePropertyDoc = ClassInstancePropertyXml::parse(instancePropertyXml); instancePropertyVal.push_back(instancePropertyDoc); } } const std::string uniqueStrVal = thisXml->findOptionalAttribute("unique"); bool uniqueVal = false; if (! uniqueStrVal.empty()) { uniqueVal = (uniqueStrVal.compare("true") == 0) ? true : false; } const std::string transientValStrVal = thisXml->findOptionalAttribute("transient"); bool transientValVal = false; if (! transientValStrVal.empty()) { transientValVal = (transientValStrVal.compare("true") == 0) ? true : false; } const std::string displayNameStrVal = thisXml->findOptionalAttribute("displayName"); const std::string displayNameVal = displayNameStrVal; const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; dataClassDoc.CreateInstance(); dataClassDoc->initialize( namespaceValVal, nameVal, versionVal, propertyVal, instancePropertyVal, uniqueVal, transientValVal, displayNameVal, descriptionVal); } CAF_CM_EXIT; return dataClassDoc; } InstanceOperationCollectionXml.cpp000066400000000000000000000053731321503522500434450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/InstanceOperationXml.h" #include "Doc/SchemaTypesDoc/CInstanceOperationCollectionDoc.h" #include "Doc/SchemaTypesDoc/CInstanceOperationDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/InstanceOperationCollectionXml.h" using namespace Caf; void InstanceOperationCollectionXml::add( const SmartPtrCInstanceOperationCollectionDoc instanceOperationCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstanceOperationCollectionXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(instanceOperationCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque instanceOperationVal = instanceOperationCollectionDoc->getInstanceOperationCollection(); CAF_CM_VALIDATE_STL(instanceOperationVal); if (! instanceOperationVal.empty()) { for (TConstIterator > instanceOperationIter(instanceOperationVal); instanceOperationIter; instanceOperationIter++) { const SmartPtrCXmlElement instanceOperationXml = thisXml->createAndAddElement("instanceOperation"); InstanceOperationXml::add(*instanceOperationIter, instanceOperationXml); } } } CAF_CM_EXIT; } SmartPtrCInstanceOperationCollectionDoc InstanceOperationCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstanceOperationCollectionXml", "parse"); SmartPtrCInstanceOperationCollectionDoc instanceOperationCollectionDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection instanceOperationChildrenXml = thisXml->findRequiredChildren("instanceOperation"); std::deque instanceOperationVal; if (! instanceOperationChildrenXml.IsNull() && ! instanceOperationChildrenXml->empty()) { for (TConstIterator instanceOperationXmlIter(*instanceOperationChildrenXml); instanceOperationXmlIter; instanceOperationXmlIter++) { const SmartPtrCXmlElement instanceOperationXml = instanceOperationXmlIter->second; const SmartPtrCInstanceOperationDoc instanceOperationDoc = InstanceOperationXml::parse(instanceOperationXml); instanceOperationVal.push_back(instanceOperationDoc); } } instanceOperationCollectionDoc.CreateInstance(); instanceOperationCollectionDoc->initialize( instanceOperationVal); } CAF_CM_EXIT; return instanceOperationCollectionDoc; } InstanceOperationXml.cpp000066400000000000000000000034771321503522500414340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CInstanceOperationDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/InstanceOperationXml.h" using namespace Caf; void InstanceOperationXml::add( const SmartPtrCInstanceOperationDoc instanceOperationDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstanceOperationXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(instanceOperationDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string operationNameVal = instanceOperationDoc->getOperationName(); CAF_CM_VALIDATE_STRING(operationNameVal); thisXml->addAttribute("operationName", operationNameVal); const std::string monikerVal = instanceOperationDoc->getMoniker(); CAF_CM_VALIDATE_STRING(monikerVal); thisXml->addAttribute("moniker", monikerVal); } CAF_CM_EXIT; } SmartPtrCInstanceOperationDoc InstanceOperationXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstanceOperationXml", "parse"); SmartPtrCInstanceOperationDoc instanceOperationDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string operationNameStrVal = thisXml->findRequiredAttribute("operationName"); const std::string operationNameVal = operationNameStrVal; const std::string monikerStrVal = thisXml->findRequiredAttribute("moniker"); const std::string monikerVal = monikerStrVal; instanceOperationDoc.CreateInstance(); instanceOperationDoc->initialize( operationNameVal, monikerVal); } CAF_CM_EXIT; return instanceOperationDoc; } InstanceParameterXml.cpp000066400000000000000000000100201321503522500413720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/InstanceParameterXml.h" using namespace Caf; void InstanceParameterXml::add( const SmartPtrCInstanceParameterDoc instanceParameterDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstanceParameterXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(instanceParameterDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = instanceParameterDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string instanceNamespaceVal = instanceParameterDoc->getInstanceNamespace(); CAF_CM_VALIDATE_STRING(instanceNamespaceVal); thisXml->addAttribute("instanceNamespace", instanceNamespaceVal); const std::string instanceNameVal = instanceParameterDoc->getInstanceName(); CAF_CM_VALIDATE_STRING(instanceNameVal); thisXml->addAttribute("instanceName", instanceNameVal); const std::string instanceVersionVal = instanceParameterDoc->getInstanceVersion(); CAF_CM_VALIDATE_STRING(instanceVersionVal); thisXml->addAttribute("instanceVersion", instanceVersionVal); const std::string isOptionalVal = instanceParameterDoc->getIsOptional() ? "true" : "false"; CAF_CM_VALIDATE_STRING(isOptionalVal); thisXml->addAttribute("isOptional", isOptionalVal); const std::string isListVal = instanceParameterDoc->getIsList() ? "true" : "false"; if (! isListVal.empty()) { thisXml->addAttribute("isList", isListVal); } const std::string displayNameVal = instanceParameterDoc->getDisplayName(); if (! displayNameVal.empty()) { thisXml->addAttribute("displayName", displayNameVal); } const std::string descriptionVal = instanceParameterDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCInstanceParameterDoc InstanceParameterXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("InstanceParameterXml", "parse"); SmartPtrCInstanceParameterDoc instanceParameterDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string instanceNamespaceStrVal = thisXml->findRequiredAttribute("instanceNamespace"); const std::string instanceNamespaceVal = instanceNamespaceStrVal; const std::string instanceNameStrVal = thisXml->findRequiredAttribute("instanceName"); const std::string instanceNameVal = instanceNameStrVal; const std::string instanceVersionStrVal = thisXml->findRequiredAttribute("instanceVersion"); const std::string instanceVersionVal = instanceVersionStrVal; const std::string isOptionalStrVal = thisXml->findRequiredAttribute("isOptional"); bool isOptionalVal = false; if (! isOptionalStrVal.empty()) { isOptionalVal = (isOptionalStrVal.compare("true") == 0) ? true : false; } const std::string isListStrVal = thisXml->findOptionalAttribute("isList"); bool isListVal = false; if (! isListStrVal.empty()) { isListVal = (isListStrVal.compare("true") == 0) ? true : false; } const std::string displayNameStrVal = thisXml->findOptionalAttribute("displayName"); const std::string displayNameVal = displayNameStrVal; const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; instanceParameterDoc.CreateInstance(); instanceParameterDoc->initialize( nameVal, instanceNamespaceVal, instanceNameVal, instanceVersionVal, isOptionalVal, isListVal, displayNameVal, descriptionVal); } CAF_CM_EXIT; return instanceParameterDoc; } JoinTypeXml.cpp000066400000000000000000000061271321503522500375430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/DocXml/SchemaTypesXml/ClassFieldXml.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassFieldDoc.h" #include "Doc/SchemaTypesDoc/CJoinTypeDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/JoinTypeXml.h" using namespace Caf; void JoinTypeXml::add( const SmartPtrCJoinTypeDoc joinTypeDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("JoinTypeXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(joinTypeDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string operandVal = EnumConvertersXml::convertOperatorTypeToString(joinTypeDoc->getOperand()); CAF_CM_VALIDATE_STRING(operandVal); thisXml->addAttribute("operand", operandVal); const SmartPtrCClassFieldDoc dataClassLeftVal = joinTypeDoc->getDataClassLeft(); CAF_CM_VALIDATE_SMARTPTR(dataClassLeftVal); const SmartPtrCXmlElement dataClassLeftXml = thisXml->createAndAddElement("dataClassLeft"); ClassFieldXml::add(dataClassLeftVal, dataClassLeftXml); const SmartPtrCClassFieldDoc dataClassRightVal = joinTypeDoc->getDataClassRight(); CAF_CM_VALIDATE_SMARTPTR(dataClassRightVal); const SmartPtrCXmlElement dataClassRightXml = thisXml->createAndAddElement("dataClassRight"); ClassFieldXml::add(dataClassRightVal, dataClassRightXml); const std::string descriptionVal = joinTypeDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCJoinTypeDoc JoinTypeXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("JoinTypeXml", "parse"); SmartPtrCJoinTypeDoc joinTypeDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string operandStrVal = thisXml->findRequiredAttribute("operand"); OPERATOR_TYPE operandVal = OPERATOR_NONE; if (! operandStrVal.empty()) { operandVal = EnumConvertersXml::convertStringToOperatorType(operandStrVal); } const SmartPtrCXmlElement dataClassLeftXml = thisXml->findRequiredChild("dataClassLeft"); SmartPtrCClassFieldDoc dataClassLeftVal; if (! dataClassLeftXml.IsNull()) { dataClassLeftVal = ClassFieldXml::parse(dataClassLeftXml); } const SmartPtrCXmlElement dataClassRightXml = thisXml->findRequiredChild("dataClassRight"); SmartPtrCClassFieldDoc dataClassRightVal; if (! dataClassRightXml.IsNull()) { dataClassRightVal = ClassFieldXml::parse(dataClassRightXml); } const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; joinTypeDoc.CreateInstance(); joinTypeDoc->initialize( operandVal, dataClassLeftVal, dataClassRightVal, descriptionVal); } CAF_CM_EXIT; return joinTypeDoc; } LogicalRelationshipXml.cpp000066400000000000000000000123371321503522500417360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/DocXml/SchemaTypesXml/ClassCardinalityXml.h" #include "Doc/DocXml/SchemaTypesXml/JoinTypeXml.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/CJoinTypeDoc.h" #include "Doc/SchemaTypesDoc/CLogicalRelationshipDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/LogicalRelationshipXml.h" using namespace Caf; void LogicalRelationshipXml::add( const SmartPtrCLogicalRelationshipDoc logicalRelationshipDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("LogicalRelationshipXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(logicalRelationshipDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = logicalRelationshipDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = logicalRelationshipDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = logicalRelationshipDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::string arityVal = EnumConvertersXml::convertArityTypeToString(logicalRelationshipDoc->getArity()); CAF_CM_VALIDATE_STRING(arityVal); thisXml->addAttribute("arity", arityVal); const SmartPtrCClassCardinalityDoc dataClassLeftVal = logicalRelationshipDoc->getDataClassLeft(); CAF_CM_VALIDATE_SMARTPTR(dataClassLeftVal); const SmartPtrCXmlElement dataClassLeftXml = thisXml->createAndAddElement("dataClassLeft"); ClassCardinalityXml::add(dataClassLeftVal, dataClassLeftXml); const SmartPtrCClassCardinalityDoc dataClassRightVal = logicalRelationshipDoc->getDataClassRight(); CAF_CM_VALIDATE_SMARTPTR(dataClassRightVal); const SmartPtrCXmlElement dataClassRightXml = thisXml->createAndAddElement("dataClassRight"); ClassCardinalityXml::add(dataClassRightVal, dataClassRightXml); const std::deque joinVal = logicalRelationshipDoc->getJoinCollection(); CAF_CM_VALIDATE_STL(joinVal); if (! joinVal.empty()) { for (TConstIterator > joinIter(joinVal); joinIter; joinIter++) { const SmartPtrCXmlElement joinXml = thisXml->createAndAddElement("join"); JoinTypeXml::add(*joinIter, joinXml); } } const std::string descriptionVal = logicalRelationshipDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCLogicalRelationshipDoc LogicalRelationshipXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("LogicalRelationshipXml", "parse"); SmartPtrCLogicalRelationshipDoc logicalRelationshipDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const std::string arityStrVal = thisXml->findRequiredAttribute("arity"); ARITY_TYPE arityVal = ARITY_NONE; if (! arityStrVal.empty()) { arityVal = EnumConvertersXml::convertStringToArityType(arityStrVal); } const SmartPtrCXmlElement dataClassLeftXml = thisXml->findRequiredChild("dataClassLeft"); SmartPtrCClassCardinalityDoc dataClassLeftVal; if (! dataClassLeftXml.IsNull()) { dataClassLeftVal = ClassCardinalityXml::parse(dataClassLeftXml); } const SmartPtrCXmlElement dataClassRightXml = thisXml->findRequiredChild("dataClassRight"); SmartPtrCClassCardinalityDoc dataClassRightVal; if (! dataClassRightXml.IsNull()) { dataClassRightVal = ClassCardinalityXml::parse(dataClassRightXml); } const CXmlElement::SmartPtrCElementCollection joinChildrenXml = thisXml->findRequiredChildren("join"); std::deque joinVal; if (! joinChildrenXml.IsNull() && ! joinChildrenXml->empty()) { for (TConstIterator joinXmlIter(*joinChildrenXml); joinXmlIter; joinXmlIter++) { const SmartPtrCXmlElement joinXml = joinXmlIter->second; const SmartPtrCJoinTypeDoc joinDoc = JoinTypeXml::parse(joinXml); joinVal.push_back(joinDoc); } } const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; logicalRelationshipDoc.CreateInstance(); logicalRelationshipDoc->initialize( namespaceValVal, nameVal, versionVal, arityVal, dataClassLeftVal, dataClassRightVal, joinVal, descriptionVal); } CAF_CM_EXIT; return logicalRelationshipDoc; } MethodParameterXml.cpp000066400000000000000000000073131321503522500410610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/MethodParameterXml.h" using namespace Caf; void MethodParameterXml::add( const SmartPtrCMethodParameterDoc methodParameterDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MethodParameterXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(methodParameterDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = methodParameterDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string typeVal = EnumConvertersXml::convertParameterTypeToString(methodParameterDoc->getType()); CAF_CM_VALIDATE_STRING(typeVal); thisXml->addAttribute("type", typeVal); const std::string isOptionalVal = methodParameterDoc->getIsOptional() ? "true" : "false"; CAF_CM_VALIDATE_STRING(isOptionalVal); thisXml->addAttribute("isOptional", isOptionalVal); const std::string isListVal = methodParameterDoc->getIsList() ? "true" : "false"; if (! isListVal.empty()) { thisXml->addAttribute("isList", isListVal); } const std::string defaultValVal = methodParameterDoc->getDefaultVal(); if (! defaultValVal.empty()) { thisXml->addAttribute("default", defaultValVal); } const std::string displayNameVal = methodParameterDoc->getDisplayName(); if (! displayNameVal.empty()) { thisXml->addAttribute("displayName", displayNameVal); } const std::string descriptionVal = methodParameterDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCMethodParameterDoc MethodParameterXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MethodParameterXml", "parse"); SmartPtrCMethodParameterDoc methodParameterDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string typeStrVal = thisXml->findRequiredAttribute("type"); PARAMETER_TYPE typeVal = PARAMETER_NONE; if (! typeStrVal.empty()) { typeVal = EnumConvertersXml::convertStringToParameterType(typeStrVal); } const std::string isOptionalStrVal = thisXml->findRequiredAttribute("isOptional"); bool isOptionalVal = false; if (! isOptionalStrVal.empty()) { isOptionalVal = (isOptionalStrVal.compare("true") == 0) ? true : false; } const std::string isListStrVal = thisXml->findOptionalAttribute("isList"); bool isListVal = false; if (! isListStrVal.empty()) { isListVal = (isListStrVal.compare("true") == 0) ? true : false; } const std::string defaultValStrVal = thisXml->findOptionalAttribute("default"); const std::string defaultValVal = defaultValStrVal; const std::string displayNameStrVal = thisXml->findOptionalAttribute("displayName"); const std::string displayNameVal = displayNameStrVal; const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; methodParameterDoc.CreateInstance(); methodParameterDoc->initialize( nameVal, typeVal, isOptionalVal, isListVal, defaultValVal, displayNameVal, descriptionVal); } CAF_CM_EXIT; return methodParameterDoc; } MethodXml.cpp000066400000000000000000000167531321503522500372300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocXml/SchemaTypesXml/ClassIdentifierXml.h" #include "Doc/DocXml/SchemaTypesXml/InstanceParameterXml.h" #include "Doc/DocXml/SchemaTypesXml/MethodParameterXml.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/MethodXml.h" using namespace Caf; void MethodXml::add( const SmartPtrCMethodDoc methodDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MethodXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(methodDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameVal = methodDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::deque parameterVal = methodDoc->getParameterCollection(); if (! parameterVal.empty()) { for (TConstIterator > parameterIter(parameterVal); parameterIter; parameterIter++) { const SmartPtrCXmlElement parameterXml = thisXml->createAndAddElement("parameter"); MethodParameterXml::add(*parameterIter, parameterXml); } } const std::deque instanceParameterVal = methodDoc->getInstanceParameterCollection(); if (! instanceParameterVal.empty()) { for (TConstIterator > instanceParameterIter(instanceParameterVal); instanceParameterIter; instanceParameterIter++) { const SmartPtrCXmlElement instanceParameterXml = thisXml->createAndAddElement("instanceParameter"); InstanceParameterXml::add(*instanceParameterIter, instanceParameterXml); } } const std::deque returnValVal = methodDoc->getReturnValCollection(); if (! returnValVal.empty()) { for (TConstIterator > returnValIter(returnValVal); returnValIter; returnValIter++) { const SmartPtrCXmlElement returnValXml = thisXml->createAndAddElement("return"); ClassIdentifierXml::add(*returnValIter, returnValXml); } } const std::deque eventValVal = methodDoc->getEventValCollection(); if (! eventValVal.empty()) { for (TConstIterator > eventValIter(eventValVal); eventValIter; eventValIter++) { const SmartPtrCXmlElement eventValXml = thisXml->createAndAddElement("event"); ClassIdentifierXml::add(*eventValIter, eventValXml); } } const std::deque errorVal = methodDoc->getErrorCollection(); if (! errorVal.empty()) { for (TConstIterator > errorIter(errorVal); errorIter; errorIter++) { const SmartPtrCXmlElement errorXml = thisXml->createAndAddElement("error"); ClassIdentifierXml::add(*errorIter, errorXml); } } const std::string displayNameVal = methodDoc->getDisplayName(); if (! displayNameVal.empty()) { thisXml->addAttribute("displayName", displayNameVal); } const std::string descriptionVal = methodDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCMethodDoc MethodXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("MethodXml", "parse"); SmartPtrCMethodDoc methodDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const CXmlElement::SmartPtrCElementCollection parameterChildrenXml = thisXml->findOptionalChildren("parameter"); std::deque parameterVal; if (! parameterChildrenXml.IsNull() && ! parameterChildrenXml->empty()) { for (TConstIterator parameterXmlIter(*parameterChildrenXml); parameterXmlIter; parameterXmlIter++) { const SmartPtrCXmlElement parameterXml = parameterXmlIter->second; const SmartPtrCMethodParameterDoc parameterDoc = MethodParameterXml::parse(parameterXml); parameterVal.push_back(parameterDoc); } } const CXmlElement::SmartPtrCElementCollection instanceParameterChildrenXml = thisXml->findOptionalChildren("instanceParameter"); std::deque instanceParameterVal; if (! instanceParameterChildrenXml.IsNull() && ! instanceParameterChildrenXml->empty()) { for (TConstIterator instanceParameterXmlIter(*instanceParameterChildrenXml); instanceParameterXmlIter; instanceParameterXmlIter++) { const SmartPtrCXmlElement instanceParameterXml = instanceParameterXmlIter->second; const SmartPtrCInstanceParameterDoc instanceParameterDoc = InstanceParameterXml::parse(instanceParameterXml); instanceParameterVal.push_back(instanceParameterDoc); } } const CXmlElement::SmartPtrCElementCollection returnValChildrenXml = thisXml->findOptionalChildren("return"); std::deque returnValVal; if (! returnValChildrenXml.IsNull() && ! returnValChildrenXml->empty()) { for (TConstIterator returnValXmlIter(*returnValChildrenXml); returnValXmlIter; returnValXmlIter++) { const SmartPtrCXmlElement returnValXml = returnValXmlIter->second; const SmartPtrCClassIdentifierDoc returnValDoc = ClassIdentifierXml::parse(returnValXml); returnValVal.push_back(returnValDoc); } } const CXmlElement::SmartPtrCElementCollection eventValChildrenXml = thisXml->findOptionalChildren("event"); std::deque eventValVal; if (! eventValChildrenXml.IsNull() && ! eventValChildrenXml->empty()) { for (TConstIterator eventValXmlIter(*eventValChildrenXml); eventValXmlIter; eventValXmlIter++) { const SmartPtrCXmlElement eventValXml = eventValXmlIter->second; const SmartPtrCClassIdentifierDoc eventValDoc = ClassIdentifierXml::parse(eventValXml); eventValVal.push_back(eventValDoc); } } const CXmlElement::SmartPtrCElementCollection errorChildrenXml = thisXml->findOptionalChildren("error"); std::deque errorVal; if (! errorChildrenXml.IsNull() && ! errorChildrenXml->empty()) { for (TConstIterator errorXmlIter(*errorChildrenXml); errorXmlIter; errorXmlIter++) { const SmartPtrCXmlElement errorXml = errorXmlIter->second; const SmartPtrCClassIdentifierDoc errorDoc = ClassIdentifierXml::parse(errorXml); errorVal.push_back(errorDoc); } } const std::string displayNameStrVal = thisXml->findOptionalAttribute("displayName"); const std::string displayNameVal = displayNameStrVal; const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; methodDoc.CreateInstance(); methodDoc->initialize( nameVal, parameterVal, instanceParameterVal, returnValVal, eventValVal, errorVal, displayNameVal, descriptionVal); } CAF_CM_EXIT; return methodDoc; } PhysicalRelationshipXml.cpp000066400000000000000000000103641321503522500421360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/DocXml/SchemaTypesXml/ClassCardinalityXml.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/CPhysicalRelationshipDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/PhysicalRelationshipXml.h" using namespace Caf; void PhysicalRelationshipXml::add( const SmartPtrCPhysicalRelationshipDoc physicalRelationshipDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PhysicalRelationshipXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(physicalRelationshipDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = physicalRelationshipDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = physicalRelationshipDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = physicalRelationshipDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::string arityVal = EnumConvertersXml::convertArityTypeToString(physicalRelationshipDoc->getArity()); CAF_CM_VALIDATE_STRING(arityVal); thisXml->addAttribute("arity", arityVal); const SmartPtrCClassCardinalityDoc dataClassLeftVal = physicalRelationshipDoc->getDataClassLeft(); CAF_CM_VALIDATE_SMARTPTR(dataClassLeftVal); const SmartPtrCXmlElement dataClassLeftXml = thisXml->createAndAddElement("dataClassLeft"); ClassCardinalityXml::add(dataClassLeftVal, dataClassLeftXml); const SmartPtrCClassCardinalityDoc dataClassRightVal = physicalRelationshipDoc->getDataClassRight(); CAF_CM_VALIDATE_SMARTPTR(dataClassRightVal); const SmartPtrCXmlElement dataClassRightXml = thisXml->createAndAddElement("dataClassRight"); ClassCardinalityXml::add(dataClassRightVal, dataClassRightXml); const std::string descriptionVal = physicalRelationshipDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCPhysicalRelationshipDoc PhysicalRelationshipXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("PhysicalRelationshipXml", "parse"); SmartPtrCPhysicalRelationshipDoc physicalRelationshipDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const std::string arityStrVal = thisXml->findRequiredAttribute("arity"); ARITY_TYPE arityVal = ARITY_NONE; if (! arityStrVal.empty()) { arityVal = EnumConvertersXml::convertStringToArityType(arityStrVal); } const SmartPtrCXmlElement dataClassLeftXml = thisXml->findRequiredChild("dataClassLeft"); SmartPtrCClassCardinalityDoc dataClassLeftVal; if (! dataClassLeftXml.IsNull()) { dataClassLeftVal = ClassCardinalityXml::parse(dataClassLeftXml); } const SmartPtrCXmlElement dataClassRightXml = thisXml->findRequiredChild("dataClassRight"); SmartPtrCClassCardinalityDoc dataClassRightVal; if (! dataClassRightXml.IsNull()) { dataClassRightVal = ClassCardinalityXml::parse(dataClassRightXml); } const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; physicalRelationshipDoc.CreateInstance(); physicalRelationshipDoc->initialize( namespaceValVal, nameVal, versionVal, arityVal, dataClassLeftVal, dataClassRightVal, descriptionVal); } CAF_CM_EXIT; return physicalRelationshipDoc; } RelationshipXml.cpp000066400000000000000000000101041321503522500404310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #include "stdafx.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/DocXml/SchemaTypesXml/ClassCardinalityXml.h" #include "Doc/SchemaTypesDoc/SchemaTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CClassCardinalityDoc.h" #include "Doc/SchemaTypesDoc/CRelationshipDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/SchemaTypesXml/RelationshipXml.h" using namespace Caf; void RelationshipXml::add( const SmartPtrCRelationshipDoc relationshipDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RelationshipXml", "add"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(relationshipDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValVal = relationshipDoc->getNamespaceVal(); CAF_CM_VALIDATE_STRING(namespaceValVal); thisXml->addAttribute("namespace", namespaceValVal); const std::string nameVal = relationshipDoc->getName(); CAF_CM_VALIDATE_STRING(nameVal); thisXml->addAttribute("name", nameVal); const std::string versionVal = relationshipDoc->getVersion(); CAF_CM_VALIDATE_STRING(versionVal); thisXml->addAttribute("version", versionVal); const std::string arityVal = EnumConvertersXml::convertArityTypeToString(relationshipDoc->getArity()); CAF_CM_VALIDATE_STRING(arityVal); thisXml->addAttribute("arity", arityVal); const SmartPtrCClassCardinalityDoc dataClassLeftVal = relationshipDoc->getDataClassLeft(); CAF_CM_VALIDATE_SMARTPTR(dataClassLeftVal); const SmartPtrCXmlElement dataClassLeftXml = thisXml->createAndAddElement("dataClassLeft"); ClassCardinalityXml::add(dataClassLeftVal, dataClassLeftXml); const SmartPtrCClassCardinalityDoc dataClassRightVal = relationshipDoc->getDataClassRight(); CAF_CM_VALIDATE_SMARTPTR(dataClassRightVal); const SmartPtrCXmlElement dataClassRightXml = thisXml->createAndAddElement("dataClassRight"); ClassCardinalityXml::add(dataClassRightVal, dataClassRightXml); const std::string descriptionVal = relationshipDoc->getDescription(); if (! descriptionVal.empty()) { thisXml->addAttribute("description", descriptionVal); } } CAF_CM_EXIT; } SmartPtrCRelationshipDoc RelationshipXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RelationshipXml", "parse"); SmartPtrCRelationshipDoc relationshipDoc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::string namespaceValStrVal = thisXml->findRequiredAttribute("namespace"); const std::string namespaceValVal = namespaceValStrVal; const std::string nameStrVal = thisXml->findRequiredAttribute("name"); const std::string nameVal = nameStrVal; const std::string versionStrVal = thisXml->findRequiredAttribute("version"); const std::string versionVal = versionStrVal; const std::string arityStrVal = thisXml->findRequiredAttribute("arity"); ARITY_TYPE arityVal = ARITY_NONE; if (! arityStrVal.empty()) { arityVal = EnumConvertersXml::convertStringToArityType(arityStrVal); } const SmartPtrCXmlElement dataClassLeftXml = thisXml->findRequiredChild("dataClassLeft"); SmartPtrCClassCardinalityDoc dataClassLeftVal; if (! dataClassLeftXml.IsNull()) { dataClassLeftVal = ClassCardinalityXml::parse(dataClassLeftXml); } const SmartPtrCXmlElement dataClassRightXml = thisXml->findRequiredChild("dataClassRight"); SmartPtrCClassCardinalityDoc dataClassRightVal; if (! dataClassRightXml.IsNull()) { dataClassRightVal = ClassCardinalityXml::parse(dataClassRightXml); } const std::string descriptionStrVal = thisXml->findOptionalAttribute("description"); const std::string descriptionVal = descriptionStrVal; relationshipDoc.CreateInstance(); relationshipDoc->initialize( namespaceValVal, nameVal, versionVal, arityVal, dataClassLeftVal, dataClassRightVal, descriptionVal); } CAF_CM_EXIT; return relationshipDoc; } stdafx.h000066400000000000000000000010261321503522500362500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/SchemaTypesXml/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * * This code was generated by the script "build/dev/codeGen/genCppXml". Please * speak to Brian W. before modifying it by hand. * */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define SCHEMATYPESXML_LINKAGE __declspec(dllexport) #else #define SCHEMATYPESXML_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/000077500000000000000000000000001321503522500320235ustar00rootroot00000000000000CBacktraceUtils.cpp000066400000000000000000000065041321503522500354600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/*k * Author: bwilliams * Created: Oct 30, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "stdlib.h" #include "CBacktraceUtils.h" #include #ifdef WIN32 #include "StackWalker.h" #else #include #include #endif using namespace Caf; #ifdef WIN32 class StackWalkerToDeque : public StackWalker { public: StackWalkerToDeque() : depth(0) {} std::deque getBacktrace() { return backtrace; } private: static const int STACK_DEPTH_IGNORE = 3; int depth; std::deque backtrace; protected: virtual void OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName) { // Do nothing to suppress default OnSymInit output } virtual void OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion) { // Do nothing to suppress default OnLoadModule output } virtual void OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr){ // Do nothing to suppress default OnDbgHelpErr output } virtual void OnOutput(LPCSTR szText) { try { std::string line = szText; if (STACK_DEPTH_IGNORE < depth++) { backtrace.push_back(CStringUtils::trimRight(line)); } } catch (...) { backtrace.push_back("CBacktraceUtils::getBacktrace() threw an exception"); } } }; std::deque CBacktraceUtils::getBacktrace() { StackWalkerToDeque sw; sw.ShowCallstack(); return sw.getBacktrace(); } #else std::deque CBacktraceUtils::getBacktrace() { char** messages = NULL; std::deque backtrace; try { const int32 maxStackEntries = 50; void *stackEntries[maxStackEntries]; const size_t size = ::backtrace(stackEntries, maxStackEntries); messages = ::backtrace_symbols(stackEntries, size); /* skip first stack frame (points here) */ for (size_t i = 1; i < size && messages != NULL; ++i) { const std::string name = demangleName(messages[i]); backtrace.push_back(name); } } catch (...) { backtrace.push_back("CBacktraceUtils::getBacktrace() threw an exception"); } if (NULL != messages) { ::free(messages); } return backtrace; } std::string CBacktraceUtils::demangleName(char* name) { std::string rc; if (NULL != name) { char* mangled_name = 0; char* offset_begin = 0; char* offset_end = 0; // find parentheses and +address offset surrounding mangled name for (char *p = name; *p; ++p) { if (*p == '(') { mangled_name = p; } else if (*p == '+') { offset_begin = p; } else if (*p == ')') { offset_end = p; break; } } // if the line could be processed, attempt to demangle the symbol if (mangled_name && offset_begin && offset_end && mangled_name < offset_begin) { *mangled_name++ = '\0'; *offset_begin++ = '\0'; *offset_end++ = '\0'; int32 status; char* real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status); // if demangling is successful, output the demangled function name if (status == 0) { rc = real_name; } // otherwise, output the mangled function name else { rc = mangled_name; } ::free(real_name); } // otherwise, print the whole line else { rc = name; } } return rc; } #endif CBacktraceUtils.h000066400000000000000000000012471321503522500351240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: bwilliams * Created: Oct 30, 2014 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CBacktraceUtils_H_ #define CBacktraceUtils_H_ namespace Caf { // See http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes class EXCEPTION_LINKAGE CBacktraceUtils { public: static std::deque getBacktrace(); #ifndef WIN32 private: static std::string demangleName(char* name); #endif private: CBacktraceUtils(); ~CBacktraceUtils(); CBacktraceUtils(const CBacktraceUtils&); CBacktraceUtils& operator=(const CBacktraceUtils&); }; } #endif /* CBacktraceUtils_H_ */ CCafException.cpp000066400000000000000000000057741321503522500351400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include #include #include "CBacktraceUtils.h" using namespace Caf; CCafException::CCafException() : _refCnt(0), _isPopulated(false), _exceptionClassName("CCafException"), _errorCode(S_OK), _backtrace(NULL) { } CCafException::CCafException(const std::string& exceptionClassName) : _refCnt(0), _isPopulated(false), _exceptionClassName(exceptionClassName), _errorCode(S_OK), _backtrace(NULL) { } CCafException::~CCafException() { if (_backtrace != NULL) { delete _backtrace; } } void CCafException::throwSelf() { throw this; } void CCafException::throwAddRefedSelf() { this->AddRef(); throw this; } void CCafException::AddRef() { g_atomic_int_inc(&_refCnt); } void CCafException::Release() { if (g_atomic_int_dec_and_test(&_refCnt)) { delete this; } } void CCafException::QueryInterface(const IID&, void**) { throw std::runtime_error("QueryInterface not supported"); } void CCafException::populate( const std::string& message, const HRESULT errorCode, const std::string& className, const std::string& funcName) { _message = message; _className = className; _funcName = funcName; _errorCode = HRESULT_FROM_WIN32(errorCode); if (_backtrace != NULL) { delete _backtrace; } _backtrace = new std::deque(CBacktraceUtils::getBacktrace()); _isPopulated = true; } void CCafException::populateVA( const HRESULT errorCode, const std::string& className, const std::string& funcName, const char* format, ...) { char buffer[1024]; va_list args; va_start(args, format); #ifdef WIN32 // Returns -1 if the buffer is truncated. const int rc = vsnprintf_s(buffer, 1024, _TRUNCATE, format, args); if ((rc > 0) || (rc == -1)) { #else if (vsnprintf(buffer, 1024, format, args) > 0) { #endif _message = buffer; } else { _message = "*** PopulateVA() INTERNAL ERROR: UNABLE TO FORMAT MESSAGE ***"; } va_end(args); _className = className; _funcName = funcName; _errorCode = HRESULT_FROM_WIN32(errorCode); if (_backtrace != NULL) { delete _backtrace; } _backtrace = new std::deque(CBacktraceUtils::getBacktrace()); _isPopulated = true; } bool CCafException::isPopulated() const { return _isPopulated; } std::string CCafException::getExceptionClassName() const { return _exceptionClassName; } std::string CCafException::getMsg() const { return _message; } std::string CCafException::getClassName() const { return _className; } std::string CCafException::getFuncName() const { return _funcName; } HRESULT CCafException::getError() const { return _errorCode; } std::deque* CCafException::getBacktrace() const { return _backtrace; } std::string CCafException::getFullMsg() const { std::string msg("["); msg += _exceptionClassName; msg += "] "; msg += _className; msg += "::"; msg += _funcName; msg += "() "; msg += _message; return msg; } CCafExceptionEx.cpp000066400000000000000000000031631321503522500354230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Created on: Oct 6, 2011 * Author: mdonahue * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CCafExceptionEx.h" using namespace Caf; // General Runtime Exceptions CAF_CM_DEFINE_EXCEPTION_CLASS(AccessDeniedException); CAF_CM_DEFINE_EXCEPTION_CLASS(NullPointerException); CAF_CM_DEFINE_EXCEPTION_CLASS(BufferOverflowException); CAF_CM_DEFINE_EXCEPTION_CLASS(BufferUnderflowException); CAF_CM_DEFINE_EXCEPTION_CLASS(InvalidArgumentException); CAF_CM_DEFINE_EXCEPTION_CLASS(IllegalStateException); CAF_CM_DEFINE_EXCEPTION_CLASS(IndexOutOfBoundsException); CAF_CM_DEFINE_EXCEPTION_CLASS(NoSuchElementException); CAF_CM_DEFINE_EXCEPTION_CLASS(DuplicateElementException); CAF_CM_DEFINE_EXCEPTION_CLASS(UnsupportedOperationException); CAF_CM_DEFINE_EXCEPTION_CLASS(UnsupportedVersionException); CAF_CM_DEFINE_EXCEPTION_CLASS(InvalidHandleException); CAF_CM_DEFINE_EXCEPTION_CLASS(TimeoutException); CAF_CM_DEFINE_EXCEPTION_CLASS(NoSuchInterfaceException); CAF_CM_DEFINE_EXCEPTION_CLASS(ProcessFailedException); // AppConfig Exceptions CAF_CM_DEFINE_EXCEPTION_CLASS(NoSuchConfigSectionException); CAF_CM_DEFINE_EXCEPTION_CLASS(NoSuchConfigValueException); // Dynamic Library Exception CAF_CM_DEFINE_EXCEPTION_CLASS(LibraryFailedToLoadException); CAF_CM_DEFINE_EXCEPTION_CLASS(NoSuchMethodException); // I/O Exceptions CAF_CM_DEFINE_EXCEPTION_CLASS(IOException); CAF_CM_DEFINE_EXCEPTION_CLASS(EOFException); CAF_CM_DEFINE_EXCEPTION_CLASS(FileNotFoundException); CAF_CM_DEFINE_EXCEPTION_CLASS(PathNotFoundException); CAF_CM_DEFINE_EXCEPTION_CLASS(FileLockedException); CCafExceptionEx.h000066400000000000000000000045041321503522500350700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Created on: Oct 6, 2011 * Author: mdonahue * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCAFEXCEPTIONEX_H_ #define CCAFEXCEPTIONEX_H_ #define CAF_CM_DECLARE_EXCEPTION_CLASS(_exclass_) \ class EXCEPTION_LINKAGE _exclass_ : public Caf::CCafException { \ public: \ _exclass_(); \ virtual ~_exclass_(); \ void throwSelf(); \ void throwAddRefedSelf(); \ private: \ _exclass_(const _exclass_ &); \ _exclass_ & operator=(const _exclass_ &); \ }; \ typedef TCafSmartPtr<_exclass_, TCafObject<_exclass_> > SmartPtr##_exclass_ #define CAF_CM_DEFINE_EXCEPTION_CLASS(_exclass_) \ _exclass_::_exclass_() : CCafException( #_exclass_ ) {} \ _exclass_::~_exclass_() {} \ void _exclass_::throwSelf() { throw this; } \ void _exclass_::throwAddRefedSelf() { this->AddRef(); throw this; } #include "Exception/CCafException.h" namespace Caf { // General Runtime Exceptions CAF_CM_DECLARE_EXCEPTION_CLASS(AccessDeniedException); CAF_CM_DECLARE_EXCEPTION_CLASS(NullPointerException); CAF_CM_DECLARE_EXCEPTION_CLASS(BufferOverflowException); CAF_CM_DECLARE_EXCEPTION_CLASS(BufferUnderflowException); CAF_CM_DECLARE_EXCEPTION_CLASS(InvalidArgumentException); CAF_CM_DECLARE_EXCEPTION_CLASS(IllegalStateException); CAF_CM_DECLARE_EXCEPTION_CLASS(IndexOutOfBoundsException); CAF_CM_DECLARE_EXCEPTION_CLASS(NoSuchElementException); CAF_CM_DECLARE_EXCEPTION_CLASS(DuplicateElementException); CAF_CM_DECLARE_EXCEPTION_CLASS(UnsupportedOperationException); CAF_CM_DECLARE_EXCEPTION_CLASS(UnsupportedVersionException); CAF_CM_DECLARE_EXCEPTION_CLASS(InvalidHandleException); CAF_CM_DECLARE_EXCEPTION_CLASS(TimeoutException); CAF_CM_DECLARE_EXCEPTION_CLASS(NoSuchInterfaceException); CAF_CM_DECLARE_EXCEPTION_CLASS(ProcessFailedException); // AppConfig Exceptions CAF_CM_DECLARE_EXCEPTION_CLASS(NoSuchConfigSectionException); CAF_CM_DECLARE_EXCEPTION_CLASS(NoSuchConfigValueException); // Dynamic Library Exception CAF_CM_DECLARE_EXCEPTION_CLASS(LibraryFailedToLoadException); CAF_CM_DECLARE_EXCEPTION_CLASS(NoSuchMethodException); // I/O Exceptions CAF_CM_DECLARE_EXCEPTION_CLASS(IOException); CAF_CM_DECLARE_EXCEPTION_CLASS(EOFException); CAF_CM_DECLARE_EXCEPTION_CLASS(FileNotFoundException); CAF_CM_DECLARE_EXCEPTION_CLASS(PathNotFoundException); CAF_CM_DECLARE_EXCEPTION_CLASS(FileLockedException); } #endif CValidate.cpp000066400000000000000000000151321321503522500343060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CValidate.h" #include "ValidationMacros.h" using namespace Caf; // Some helper macros that make is easy to validate input arguments. #define CAF_EXCEPTION_VALIDATE(_valmsg_, _variable_text_ ) \ CAF_CM_EXCEPTION_VA2(E_INVALIDARG, "%s %s", _valmsg_, _variable_text_) void CValidate::constructed(const bool value, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (! value ) { CAF_CM_EXCEPTION_VA0(ERROR_INVALID_STATE, _sPRECOND_ISCONSTRUCTED); } } CAF_CM_EXIT; } void CValidate::initialized(const bool value, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (! value ) { CAF_CM_EXCEPTION_VA0(OLE_E_BLANK, _sPRECOND_ISINITIALIZED); } } CAF_CM_EXIT; } void CValidate::notInitialized(const bool value, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value ) { CAF_CM_EXCEPTION_VA0(ERROR_ALREADY_INITIALIZED, _sPRECOND_ISNOTINITIALIZED); } } CAF_CM_EXIT; } void CValidate::notEmptyStr(const std::string& value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value.length() == 0 ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_STRINGEMPTY, name); } } CAF_CM_EXIT; } void CValidate::notEmptyStr(const std::wstring& value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value.length() == 0 ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_STRINGEMPTY, name); } } CAF_CM_EXIT; } void CValidate::notEmptyUuid(const UUID value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (::IsEqualGUID(value, CAFCOMMON_GUID_NULL) ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_GUID, name); } } CAF_CM_EXIT; } void CValidate::notNullOrEmptyStr(const char* value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (NULL == value) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_STRINGPTRNULL, name); } if (value[ 0 ] == '\0' ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_STRINGPTREMPTY, name); } } CAF_CM_EXIT; } void CValidate::notNullOrEmptyStr(const wchar_t* value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (NULL == value) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_STRINGPTRNULL, name); } if (value[ 0 ] == L'\0') { CAF_EXCEPTION_VALIDATE(_sVALIDATE_STRINGPTREMPTY, name); } } CAF_CM_EXIT; } void CValidate::notNullOrEmptyPtrArr(const void** value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (NULL == value) { CAF_EXCEPTION_VALIDATE( _sVALIDATE_PTRARRAYNULL, name); } if (NULL == value[ 0 ]) { CAF_EXCEPTION_VALIDATE( _sVALIDATE_PTRARRAYEMPTY, name); } } CAF_CM_EXIT; } void CValidate::notNullInterface(const ICafObject* value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (NULL == value) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_INTERFACE, name); } } CAF_CM_EXIT; } void CValidate::notNullPtr(const void* value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (NULL == value) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_NOTNULL, name); } } CAF_CM_EXIT; } void CValidate::nullPtr(const void* value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (NULL != value) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_NULL, name); } } CAF_CM_EXIT; } void CValidate::zero(const int32 value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value != 0 ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_ZERO, name); } } CAF_CM_EXIT; } void CValidate::notZero(const int32 value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value == 0 ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_ISNOTZERO, name); } } CAF_CM_EXIT; } void CValidate::positive(const int32 value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value <= 0 ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_POSITIVE, name); } } CAF_CM_EXIT; } void CValidate::negative(const int32 value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value >= 0 ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_NEGATIVE, name); } } CAF_CM_EXIT; } void CValidate::nonNegative(const int32 value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value < 0 ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_NONNEGATIVE, name); } } CAF_CM_EXIT; } void CValidate::nonNegative64(const int64 value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value < 0 ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_NONNEGATIVE, name); } } CAF_CM_EXIT; } void CValidate::isTrue(const bool value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (! value ) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_BOOL, name); } } CAF_CM_EXIT; } void CValidate::notEmptyStl(const size_t value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value < 1) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_STL, name); } } CAF_CM_EXIT; } void CValidate::emptyStl(const size_t value, const char* name, const char* className, const char* funcName) { CAF_CM_STATIC_FUNC(className, funcName); CAF_CM_ENTER { if (value != 0) { CAF_EXCEPTION_VALIDATE(_sVALIDATE_STL_EMPTY, name); } } CAF_CM_EXIT; } CValidate.h000066400000000000000000000050111321503522500337460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVALIDATE_H_ #define CVALIDATE_H_ namespace Caf { class EXCEPTION_LINKAGE CValidate { public: static void constructed(const bool value, const char* className, const char* funcName); static void initialized(const bool value, const char* className, const char* funcName); static void notInitialized(const bool value, const char* className, const char* funcName); static void notEmptyStr(const std::string& value, const char* name, const char* className, const char* funcName); static void notEmptyStr(const std::wstring& value, const char* name, const char* className, const char* funcName); static void notEmptyUuid(const UUID value, const char* name, const char* className, const char* funcName); static void notNullOrEmptyStr(const char* value, const char* name, const char* className, const char* funcName); static void notNullOrEmptyStr(const wchar_t* value, const char* name, const char* className, const char* funcName); static void notNullOrEmptyPtrArr(const void** value, const char* name, const char* className, const char* funcName); static void notNullInterface(const ICafObject* value, const char* name, const char* className, const char* funcName); static void notNullPtr(const void* value, const char* name, const char* className, const char* funcName); static void nullPtr(const void* value, const char* name, const char* className, const char* funcName); static void zero(const int32 value, const char* name, const char* className, const char* funcName); static void notZero(const int32 value, const char* name, const char* className, const char* funcName); static void positive(const int32 value, const char* name, const char* className, const char* funcName); static void negative(const int32 value, const char* name, const char* className, const char* funcName); static void nonNegative(const int32 value, const char* name, const char* className, const char* funcName); static void nonNegative64(const int64 value, const char* name, const char* className, const char* funcName); static void isTrue(const bool value, const char* name, const char* className, const char* funcName); static void notEmptyStl(const size_t value, const char* name, const char* className, const char* funcName); static void emptyStl(const size_t value, const char* name, const char* className, const char* funcName); private: CAF_CM_DECLARE_NOCREATE(CValidate); }; } #endif /* CVALIDATE_H_ */ ClassMacros.h000066400000000000000000000056721321503522500343410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CLASSMACROS_H_ #define CLASSMACROS_H_ // Prevents class creation #define CAF_CM_DECLARE_NOCREATE(_classname_) \ private:\ _classname_();\ ~_classname_();\ _classname_(const _classname_&);\ _classname_& operator=(const _classname_&) // Prevents copying #define CAF_CM_DECLARE_NOCOPY(_classname_) \ private:\ _classname_(const _classname_&);\ _classname_& operator=(const _classname_&) // Initializes the members of the class #define CAF_CM_INIT( _ClassName_ ) _cm_className_( _ClassName_ ) // Sets up a class method for parameter validation only #define CAF_CM_FUNCNAME_VALIDATE( _szFuncNameIn_ ) \ const char * _cm_funcName_ = _szFuncNameIn_ // Sets up a class method for exception handling/parameter validation #define CAF_CM_FUNCNAME( _szFuncNameIn_ ) \ CAF_CM_FUNCNAME_VALIDATE ( _szFuncNameIn_); \ CCafException* _cm_exception_ = NULL #define CAF_CM_CREATE \ private: \ const char * _cm_className_ #define CAF_CM_STATIC_FUNC_VALIDATE( _szScope_, _szFuncName_ ) \ const char * _cm_className_ = _szScope_; \ CAF_CM_FUNCNAME_VALIDATE( _szFuncName_ ) #define CAF_CM_STATIC_FUNC( _szScope_, _szFuncName_ ) \ const char * _cm_className_ = _szScope_; \ CAF_CM_FUNCNAME( _szFuncName_ ) #define CAF_CM_GET_FUNCNAME _cm_funcName_ #define CAF_CM_GET_CLASSNAME _cm_className_ #define CAF_CM_ENTER (void)0; #define CAF_CM_EXIT (void)0 #define CAF_CM_UPTLINE (void)0 // Class-level thread safety macros #define CAF_CM_CREATE_THREADSAFE \ private: \ mutable Caf::SmartPtrCAutoRecMutex _cm_mutex_ #define CAF_CM_INIT_THREADSAFE \ _cm_mutex_.CreateInstance(); \ _cm_mutex_->initialize() #define CAF_CM_ENTER_AND_LOCK \ Caf::CAutoMutexLockUnlock _auto_lock_unlock(_cm_mutex_); \ CAF_CM_ENTER #define CAF_CM_UNLOCK_AND_EXIT CAF_CM_EXIT #define CAF_CM_LOCK _cm_mutex_->lock() #define CAF_CM_UNLOCK _cm_mutex_->unlock() #define CAF_CM_LOCK_UNLOCK Caf::CAutoMutexLockUnlock _auto_lock_unlock(_cm_mutex_) #define CAF_CM_UNLOCK_LOCK Caf::CAutoMutexUnlockLock _auto_unlock_lock(_cm_mutex_) #define CAF_CM_LOCK_UNLOCK_LOG Caf::CAutoMutexLockUnlock _auto_lock_unlock(_cm_mutex_, CAF_CM_GET_CLASSNAME, CAF_CM_GET_FUNCNAME, __LINE__) #define CAF_CM_UNLOCK_LOCK_LOG Caf::CAutoMutexUnlockLock _auto_unlock_lock(_cm_mutex_, CAF_CM_GET_CLASSNAME, CAF_CM_GET_FUNCNAME, __LINE__) #define CAF_CM_LOCK_UNLOCK1(_this_mutex_) Caf::CAutoMutexLockUnlock _auto_lock_unlock1(_this_mutex_) #define CAF_CM_UNLOCK_LOCK1(_this_mutex_) Caf::CAutoMutexUnlockLock _auto_unlock_lock1(_this_mutex_) #define CAF_CM_LOCK_UNLOCK1_LOG(_this_mutex_) Caf::CAutoMutexLockUnlock _auto_lock_unlock1(_this_mutex_, CAF_CM_GET_CLASSNAME, CAF_CM_GET_FUNCNAME, __LINE__) #define CAF_CM_UNLOCK_LOCK1_LOG(_this_mutex_) Caf::CAutoMutexUnlockLock _auto_unlock_lock1(_this_mutex_, CAF_CM_GET_CLASSNAME, CAF_CM_GET_FUNCNAME, __LINE__) #endif /* CLASSMACROS_H_ */ ExceptionExMacros.h000066400000000000000000000046151321503522500355230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Created on: Oct 6, 2011 * Author: mdonahue * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef EXEXCEPTIONEXMACROS_H_ #define EXEXCEPTIONEXMACROS_H_ #define CAF_CM_EXCEPTIONEX_VA0(_exclass_, _code_, _msg_) \ { \ _cm_exception_ = new _exclass_(); \ _cm_exception_->populate(_msg_, _code_, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ throw static_cast<_exclass_*>(_cm_exception_); \ } #define CAF_CM_EXCEPTIONEX_VA1(_exclass_, _code_, _fmt_, _arg1_) \ { \ _cm_exception_ = new _exclass_(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_); \ _cm_exception_->AddRef(); \ throw static_cast<_exclass_*>(_cm_exception_); \ } #define CAF_CM_EXCEPTIONEX_VA2(_exclass_, _code_, _fmt_, _arg1_, _arg2_) \ { \ _cm_exception_ = new _exclass_(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_); \ _cm_exception_->AddRef(); \ throw static_cast<_exclass_*>(_cm_exception_); \ } #define CAF_CM_EXCEPTIONEX_VA3(_exclass_, _code_, _fmt_, _arg1_, _arg2_, _arg3_) \ { \ _cm_exception_ = new _exclass_(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_, _arg3_); \ _cm_exception_->AddRef(); \ throw static_cast<_exclass_*>(_cm_exception_); \ } #define CAF_CM_EXCEPTIONEX_VA4(_exclass_, _code_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_) \ { \ _cm_exception_ = new _exclass_(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_); \ _cm_exception_->AddRef(); \ throw static_cast<_exclass_*>(_cm_exception_); \ } #define CAF_CM_EXCEPTIONEX_VA5(_exclass_, _code_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_) \ { \ _cm_exception_ = new _exclass_(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_); \ _cm_exception_->AddRef(); \ throw static_cast<_exclass_*>(_cm_exception_); \ } #define CAF_CM_EXCEPTIONEX_VA6(_exclass_, _code_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_) \ { \ _cm_exception_ = new _exclass_(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_); \ _cm_exception_->AddRef(); \ throw static_cast<_exclass_*>(_cm_exception_); \ } #endif /* EXEXCEPTIONEXMACROS_H_ */ ExceptionLink.h000066400000000000000000000013761321503522500347000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef EXCEPTIONLINK_H_ #define EXCEPTIONLINK_H_ #ifndef EXCEPTION_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define EXCEPTION_LINKAGE __declspec(dllexport) #else #define EXCEPTION_LINKAGE __declspec(dllimport) #endif #else #define EXCEPTION_LINKAGE #endif #endif #include "CBacktraceUtils.h" #include "ClassMacros.h" #include "ExceptionMacros.h" #include "CCafExceptionEx.h" #include "ExceptionExMacros.h" #include "CValidate.h" #include "ValidationMacros.h" #include "ValidationMacrosRaw.h" #include "StatusMacros.h" #endif /* EXCEPTIONLINK_H_ */ ExceptionMacros.h000066400000000000000000000120321321503522500352160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: mdonahue * Created: Jan 26, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef EXCEPTIONMACROS_H_ #define EXCEPTIONMACROS_H_ #define CAF_CM_EXCEPTION_EFAIL( _msg_ ) \ { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populate(_msg_, E_FAIL, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ throw _cm_exception_; \ } #define CAF_CM_EXCEPTION_VA0(_code_, _msg_) \ { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populate(_msg_, _code_, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ throw _cm_exception_; \ } #define CAF_CM_EXCEPTION_VA1(_code_, _fmt_, _arg1_) \ { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_); \ _cm_exception_->AddRef(); \ throw _cm_exception_; \ } #define CAF_CM_EXCEPTION_VA2(_code_, _fmt_, _arg1_, _arg2_) \ { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_); \ _cm_exception_->AddRef(); \ throw _cm_exception_; \ } #define CAF_CM_EXCEPTION_VA3(_code_, _fmt_, _arg1_, _arg2_, _arg3_) \ { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_, _arg3_); \ _cm_exception_->AddRef(); \ throw _cm_exception_; \ } #define CAF_CM_EXCEPTION_VA4(_code_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_) \ { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_); \ _cm_exception_->AddRef(); \ throw _cm_exception_; \ } #define CAF_CM_EXCEPTION_VA5(_code_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_) \ { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_); \ _cm_exception_->AddRef(); \ throw _cm_exception_; \ } #define CAF_CM_EXCEPTION_VA6(_code_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_) \ { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populateVA(_code_, _cm_className_, _cm_funcName_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_); \ _cm_exception_->AddRef(); \ throw _cm_exception_; \ } #define CAF_CM_CLEAREXCEPTION \ if(NULL != _cm_exception_) { _cm_exception_->Release(); _cm_exception_ = NULL; } #define CAF_CM_ISEXCEPTION \ ((NULL == _cm_exception_) ? false : true) #define CAF_CM_EXCEPTION_GET_FULLMSG \ (NULL == _cm_exception_) ? std::string() : _cm_exception_->getFullMsg() #define CAF_CM_EXCEPTION_GET_MSG \ (NULL == _cm_exception_) ? std::string() : _cm_exception_->getMsg() #define CAF_CM_EXCEPTION_GET_ERROR \ (NULL == _cm_exception_) ? S_OK : _cm_exception_->getError() #define CAF_CM_THROWEXCEPTION \ if(NULL != _cm_exception_) { _cm_exception_->throwSelf(); } #define CAF_CM_GETEXCEPTION \ _cm_exception_ // Catch exceptions and turn them into CafException #define CAF_CM_CATCH_CAF \ catch (CCafException* _catchException_) { \ if(NULL == _cm_exception_) { \ _cm_exception_ = _catchException_; \ } \ } #define CAF_CM_CATCH_HRESULT \ catch (HRESULT& _catchException_) { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populate("HRESULT Exception", _catchException_, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ } #define CAF_CM_CATCH_STL \ catch (exception& _catchException_) { \ const std::string _msg_ = std::string("STL Exception: " ) + std::string( _catchException_.what() ); \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populate(_msg_, E_FAIL, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ } #define CAF_CM_CATCH_STD \ catch (const std::exception& _catchException_) { \ const std::string _msg_ = std::string("STD Exception: " ) + std::string( _catchException_.what() ); \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populate(_msg_, E_FAIL, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ } #define CAF_CM_CATCH_DEFAULT \ catch (...) { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populate("Default Exception", E_FAIL, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ } #define CAF_CM_CATCH_GERROR \ catch (GError* _catchException_) { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populate(_catchException_->message, _catchException_->code, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ g_error_free(_catchException_); \ } #define CAF_CM_THROW_GERROR(_err_) { \ _cm_exception_ = new Caf::CCafException(); \ _cm_exception_->populate(_err_->message, _err_->code, _cm_className_, _cm_funcName_); \ _cm_exception_->AddRef(); \ g_error_free(_err_); \ _cm_exception_->throwSelf(); } #define CAF_CM_CATCH_ALL \ CAF_CM_CATCH_CAF \ CAF_CM_CATCH_HRESULT \ CAF_CM_CATCH_STD \ CAF_CM_CATCH_GERROR \ CAF_CM_CATCH_DEFAULT #endif /* EXCEPTIONMACROS_H_ */ StatusMacros.h000066400000000000000000000015071321503522500345500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STATUSMACROS_H_ #define STATUSMACROS_H_ typedef std::pair CCafStatus; #define CAF_CM_VALIDATE_STATUS(_status_) \ { \ CCafStatus _int_status_ = _status_; \ if (_int_status_.first != S_OK) \ CAF_CM_EXCEPTION_VA0(_int_status_.first, _int_status_.second.c_str()); \ } #define CAF_CM_STATUS _status_ #define CAF_CM_INIT_STATUS CCafStatus CAF_CM_STATUS = std::make_pair(S_OK, ""); #define CAF_CM_SET_STATUS_FROM_EXCEPTION(_arg_) \ { \ if (_arg_->isPopulated()) \ CAF_CM_STATUS = std::make_pair(_arg_->getError(), _arg_->getMsg()); \ else \ CAF_CM_STATUS = std::make_pair(E_FAIL, "Unknown exception"); \ } #endif /* STATUSMACROS_H_ */ ValidationMacros.h000066400000000000000000000161111321503522500353540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef VALIDATIONMACROS_H_ #define VALIDATIONMACROS_H_ // String constants used in validation const char _sPRECOND_ISCONSTRUCTED[] = "Pre-condition failed because object was not constructed successfully"; const char _sPRECOND_ISINITIALIZED[] = "Pre-condition failed because object was not initialized successfully"; const char _sPRECOND_ISNOTINITIALIZED[] = "Pre-condition failed because object has already been initialized"; const char _sPRECOND_ISNOTREADONLY[] = "Pre-condition failed because the object is read-only."; const char _sVALIDATE_STRINGEMPTY[] ="Invalid Argument because a string is empty:"; const char _sVALIDATE_STRINGPTRNULL[] ="Invalid Argument because a string pointer is null:"; const char _sVALIDATE_STRINGPTREMPTY[] ="Invalid Argument because a string pointer is empty:"; const char _sVALIDATE_PTRARRAYNULL[] ="Invalid Argument because a pointer array is null:"; const char _sVALIDATE_PTRARRAYEMPTY[] ="Invalid Argument because a pointer array is empty:"; const char _sVALIDATE_STL[] ="Invalid Argument because an STL container is empty:"; const char _sVALIDATE_STL_EMPTY[] ="Invalid Argument because an STL container is not empty:"; const char _sVALIDATE_STL_ITERATOR[] ="Invalid Argument because an STL iterator is at the end of the containter:"; const char _sVALIDATE_INTERFACE[] ="Invalid Argument because an interface is NULL:"; const char _sVALIDATE_ZERO[] ="Invalid Argument because a number is not equal to zero:"; const char _sVALIDATE_ISNOTZERO[] ="Invalid Argument because a number is equal to zero:"; const char _sVALIDATE_POSITIVE[] ="Invalid Argument because a number is less-than or equal-to zero:"; const char _sVALIDATE_NEGATIVE[] ="Invalid Argument because a number is greater-than or equal-to zero:"; const char _sVALIDATE_NONNEGATIVE[] ="Invalid Argument because a number is less-than zero:"; const char _sVALIDATE_NOTNULL[] ="Invalid Argument is NULL:"; const char _sVALIDATE_NULL[] ="Invalid Argument must be NULL:"; const char _sVALIDATE_BOOL[] ="Invalid Argument because a bool is false:"; const char _sVALIDATE_GUID[] ="Invalid Argument because a GUID is NULL:"; const char _sASSERT_FAILED[] ="Assertion failed:"; // Used internally by some of these macros. #define CAF_CM_EXCEPTION_VALIDATE( _valmsg_, _variable_text_ ) \ CAF_CM_EXCEPTION_VA2(E_INVALIDARG, "%s %s", _valmsg_, _variable_text_) // Some helper macros that make it easy to validate that the object pre-conditions have been met. #define CAF_CM_PRECOND_ISCONSTRUCTED( _bIsConstucted_ ) \ CValidate::constructed(_bIsConstucted_, _cm_className_, _cm_funcName_) #define CAF_CM_PRECOND_ISINITIALIZED( _bIsInitialized_ ) \ CValidate::initialized(_bIsInitialized_, _cm_className_, _cm_funcName_) #define CAF_CM_PRECOND_ISNOTINITIALIZED( _bIsInitialized_ ) \ CValidate::notInitialized(_bIsInitialized_, _cm_className_, _cm_funcName_) // Some helper macros that make is easy to validate input arguments. #define CAF_CM_VALIDATE_STRING( _validate_ ) \ CValidate::notEmptyStr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_STRINGPTRW( _validate_ ) \ CValidate::notNullOrEmptyStr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_STRINGPTRA( _validate_ ) \ CValidate::notNullOrEmptyStr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_ZERO( _validate_) \ CValidate::zero(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_NOTZERO( _validate_) \ CValidate::notZero(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_POSITIVE( _validate_ ) \ CValidate::positive(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_NEGATIVE( _validate_ ) \ CValidate::negative(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_NONNEGATIVE( _validate_ ) \ CValidate::nonNegative(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_NONNEGATIVE_INT64( _validate_ ) \ CValidate::nonNegative64(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_BOOL( _validate_ ) \ CValidate::isTrue(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_GUID( _validate_ ) \ CValidate::notEmptyUuid(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_INTERFACE( _validate_ ) \ CValidate::notNullInterface(_validate_.GetNonAddRefedInterface(), #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_INTERFACEPTR( _validate_ ) \ CValidate::notNullInterface(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_PTR( _validate_ ) \ CValidate::notNullPtr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_NULLPTR( _validate_ ) \ CValidate::nullPtr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_SMARTPTR( _validate_ ) \ CValidate::notNullPtr(_validate_.GetNonAddRefedInterface(), #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_PTRARRAY( _validate_ ) \ CValidate::notNullOrEmptyPtrArr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_STL( _validate_ ) \ CValidate::notEmptyStl(_validate_.size(), #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATE_STL_EMPTY( _validate_ ) \ CValidate::emptyStl(_validate_.size(), #_validate_, _cm_className_, _cm_funcName_) // Not included in CValidate either because these macros are not currently used or because // the types are too varied to include in a class. #define CAF_CM_VALIDATE_STL_ITERATOR( _stlContainer_, _stlIterator ) \ if( _stlIterator == _stlContainer_.end() ) \ CAF_CM_EXCEPTION_VALIDATE( _sVALIDATE_STL_ITERATOR, #_stlContainer_ ) #define CAF_CM_VALIDATE_SMARTSTL_NOTEMPTY( _validate_ ) \ if( _validate_.IsNull() || _validate_->empty() ) \ CAF_CM_EXCEPTION_VALIDATE( _sVALIDATE_STL, #_validate_ ) #define CAF_CM_VALIDATE_COND_VA1( _cond_, _fmt_, _arg1_ ) \ if(! (_cond_) ) { \ const std::string _fullfmt_ = std::string(#_cond_) + " - " + std::string(_fmt_); \ CAF_CM_EXCEPTION_VA1(E_INVALIDARG, _fullfmt_.c_str(), _arg1_); \ } #define CAF_CM_VALIDATE_COND_VA2( _cond_, _fmt_, _arg1_, _arg2_ ) \ if(! (_cond_) ) { \ const std::string _fullfmt_ = std::string(#_cond_) + " - " + std::string(_fmt_); \ CAF_CM_EXCEPTION_VA2(E_INVALIDARG, _fullfmt_.c_str(), _arg1_, _arg2_); \ } #define CAF_CM_VALIDATE_COND_VA3( _cond_, _fmt_, _arg1_, _arg2_, _arg3_ ) \ if(! (_cond_) ) { \ const std::string _fullfmt_ = std::string(#_cond_) + " - " + std::string(_fmt_); \ CAF_CM_EXCEPTION_VA3(E_INVALIDARG, _fullfmt_.c_str(), _arg1_, _arg2_, _arg3_); \ } // Generic assert #define CAF_CM_ASSERT(_exp_) \ if (!(_exp_)) \ CAF_CM_EXCEPTION_VA2(E_FAIL, "%s %s", _sASSERT_FAILED, #_exp_ ) #define CAF_CM_ASSERT_MSG(_exp_, _msg_) \ if (!(_exp_)) \ CAF_CM_EXCEPTION_VA1( E_FAIL, "%s", _msg_ ); #endif /* VALIDATIONMACROS_H_ */ ValidationMacrosRaw.h000066400000000000000000000076171321503522500360410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef VALIDATIONMACROSRAW_H_ #define VALIDATIONMACROSRAW_H_ // Some helper macros that make it easy to validate that the object pre-conditions have been met. #define CAF_CM_PRECONDRAW_ISCONSTRUCTED( _cm_className_, _cm_funcName_, _bIsConstucted_ ) \ CValidate::constructed(_bIsConstucted_, _cm_className_, _cm_funcName_) #define CAF_CM_PRECONDRAW_ISINITIALIZED( _cm_className_, _cm_funcName_, _bIsInitialized_ ) \ CValidate::initialized(_bIsInitialized_, _cm_className_, _cm_funcName_) #define CAF_CM_PRECONDRAW_ISNOTINITIALIZED( _cm_className_, _cm_funcName_, _bIsInitialized_ ) \ CValidate::notInitialized(_bIsInitialized_, _cm_className_, _cm_funcName_) // Some helper macros that make is easy to validate input arguments. #define CAF_CM_VALIDATERAW_STRING( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notEmptyStr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_STRINGPTRW( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notNullOrEmptyStr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_STRINGPTRA( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notNullOrEmptyStr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_ZERO( _cm_className_, _cm_funcName_, _validate_) \ CValidate::zero(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_NOTZERO( _cm_className_, _cm_funcName_, _validate_) \ CValidate::notZero(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_POSITIVE( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::positive(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_NEGATIVE( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::negative(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_NONNEGATIVE( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::nonNegative(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_BOOL( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::isTrue(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_GUID( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notEmptyUuid(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_INTERFACE( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notNullInterface(_validate_.GetNonAddRefedInterface(), #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_INTERFACEPTR( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notNullInterface(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_PTR( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notNullPtr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_NULLPTR( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::nullPtr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_SMARTPTR( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notNullPtr(_validate_.GetNonAddRefedInterface(), #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_PTRARRAY( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notNullOrEmptyPtrArr(_validate_, #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_STL( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::notEmptyStl(_validate_.size(), #_validate_, _cm_className_, _cm_funcName_) #define CAF_CM_VALIDATERAW_STL_EMPTY( _cm_className_, _cm_funcName_, _validate_ ) \ CValidate::emptyStl(_validate_.size(), #_validate_, _cm_className_, _cm_funcName_) #endif /* VALIDATIONMACROSRAW_H_ */ stdafx.h000066400000000000000000000007671321503522500334200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Exception/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define EXCEPTION_LINKAGE __declspec(dllexport) #define COMMONAGGREGATOR_LINKAGE __declspec(dllexport) #else #define EXCEPTION_LINKAGE #define COMMONAGGREGATOR_LINKAGE #endif #include #include #include "ClassMacros.h" #include "ExceptionMacros.h" #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Globals/000077500000000000000000000000001321503522500314505ustar00rootroot00000000000000CafContracts.cpp000066400000000000000000000000001321503522500344350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/GlobalsClassMacroStrings.cpp000066400000000000000000000000001321503522500354640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/GlobalsClassMacroStrings.h000066400000000000000000000000001321503522500351310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/GlobalsCommonDefines.cpp000066400000000000000000000000001321503522500346110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/GlobalsCommonDefines.h000066400000000000000000000000001321503522500342560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/GlobalsCommonGlobalsLink.h000066400000000000000000000000001321503522500351020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/GlobalsIntegration.cpp000066400000000000000000000000001321503522500343460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Globalsopen-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Globals/stdafx.h000066400000000000000000000000001321503522500331000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/000077500000000000000000000000001321503522500323505ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Caf/000077500000000000000000000000001321503522500330415ustar00rootroot00000000000000CBeanPropertiesHelper.cpp000066400000000000000000000045711321503522500376620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "Integration/Caf/CBeanPropertiesHelper.h" using namespace Caf; SmartPtrCBeanPropertiesHelper CBeanPropertiesHelper::create( const IBean::Cprops& properties) { SmartPtrCBeanPropertiesHelper rc; rc.CreateInstance(); rc->initialize(properties); return rc; } CBeanPropertiesHelper::CBeanPropertiesHelper(void) : m_isInitialized(false), CAF_CM_INIT("CBeanPropertiesHelper") { } CBeanPropertiesHelper::~CBeanPropertiesHelper(void) { } void CBeanPropertiesHelper::initialize( const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(m_isInitialized); _properties = properties; m_isInitialized = true; } std::string CBeanPropertiesHelper::getRequiredString( const std::string& key) const { CAF_CM_FUNCNAME("getRequiredString"); CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized); CAF_CM_VALIDATE_STRING(key); const IBean::Cprops::const_iterator iter = _properties.find(key); if (_properties.end() == iter) { CAF_CM_EXCEPTION_VA1(E_FAIL, "Required property not found - %s", key.c_str()); } return iter->second; } std::string CBeanPropertiesHelper::getOptionalString( const std::string& key, const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getOptionalString"); CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized); CAF_CM_VALIDATE_STRING(key); std::string rc = defaultVal; const IBean::Cprops::const_iterator iter = _properties.find(key); if (_properties.end() != iter) { rc = iter->second; } return rc; } bool CBeanPropertiesHelper::getRequiredBool( const std::string& key) const { CAF_CM_FUNCNAME_VALIDATE("getRequiredBool"); CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized); CAF_CM_VALIDATE_STRING(key); const std::string val = getRequiredString(key); return (val.compare("true") == 0); } bool CBeanPropertiesHelper::getOptionalBool( const std::string& key, const bool defaultValue) const { CAF_CM_FUNCNAME_VALIDATE("getOptionalBool"); CAF_CM_PRECOND_ISINITIALIZED(m_isInitialized); CAF_CM_VALIDATE_STRING(key); bool rc = defaultValue; const IBean::Cprops::const_iterator iter = _properties.find(key); if (_properties.end() != iter) { rc = (iter->second.compare("true") == 0); } return rc; } CCafMessageCreator.cpp000066400000000000000000000412321321503522500371110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlRoots.h" #include "Doc/DocXml/DiagRequestXml/DiagRequestXmlRoots.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXmlRoots.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlRoots.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlRoots.h" #include "Doc/DocXml/ResponseXml/ResponseXmlRoots.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Integration/Caf/CCafMessageHeadersWriter.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Doc/CafCoreTypesDoc/CProtocolCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" #include "Doc/DiagRequestDoc/CDiagRequestDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Doc/ResponseDoc/CErrorResponseDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Integration/Caf/CCafMessagePayload.h" #include "Integration/Caf/CCafMessageCreator.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXmlRoots.h" using namespace Caf; SmartPtrIIntMessage CCafMessageCreator::createPayloadEnvelope( const SmartPtrCResponseDoc& response, const std::string& relFilename, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "createPayloadEnvelope"); CAF_CM_VALIDATE_SMARTPTR(response); CAF_CM_VALIDATE_STRING(relFilename); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setRelFilename(relFilename); const SmartPtrIIntMessage rc = createPayloadEnvelope( "response", XmlRoots::saveResponseToString(response), response->getClientId(), response->getRequestId(), response->getPmeId(), response->getResponseHeader()->getVersion(), messageHeadersWriter->getHeaders(), headers, response->getAttachmentCollection()); return rc; } SmartPtrIIntMessage CCafMessageCreator::createPayloadEnvelope( const SmartPtrCErrorResponseDoc& errorResponse, const std::string& relFilename, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "createPayloadEnvelope"); CAF_CM_VALIDATE_SMARTPTR(errorResponse); CAF_CM_VALIDATE_STRING(relFilename); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setRelFilename(relFilename); const SmartPtrIIntMessage rc = createPayloadEnvelope( "errorResponse", XmlRoots::saveErrorResponseToString(errorResponse), errorResponse->getClientId(), errorResponse->getRequestId(), errorResponse->getPmeId(), errorResponse->getResponseHeader()->getVersion(), messageHeadersWriter->getHeaders(), headers); return rc; } SmartPtrIIntMessage CCafMessageCreator::createPayloadEnvelope( const SmartPtrCMgmtRequestDoc& mgmtRequest, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "createPayloadEnvelope"); CAF_CM_VALIDATE_SMARTPTR(mgmtRequest); const SmartPtrIIntMessage rc = createPayloadEnvelope( "mgmtRequest", XmlRoots::saveMgmtRequestToString(mgmtRequest), mgmtRequest->getClientId(), mgmtRequest->getRequestId(), mgmtRequest->getPmeId(), mgmtRequest->getRequestHeader()->getVersion(), IIntMessage::SmartPtrCHeaders(), headers, mgmtRequest->getAttachmentCollection(), mgmtRequest->getRequestHeader()->getProtocolCollection()); return rc; } SmartPtrIIntMessage CCafMessageCreator::createPayloadEnvelope( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const std::deque& attachmentCollection, const IIntMessage::SmartPtrCHeaders& newHeaders, const IIntMessage::SmartPtrCHeaders& origHeaders) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "createPayloadEnvelope"); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelope); SmartPtrCPayloadEnvelopeDoc payloadEnvelopeNew = payloadEnvelope; if (attachmentCollection.size() > 0) { SmartPtrCAttachmentCollectionDoc attachmentCollectionDoc; attachmentCollectionDoc.CreateInstance(); attachmentCollectionDoc->initialize(attachmentCollection); payloadEnvelopeNew.CreateInstance(); payloadEnvelopeNew->initialize( payloadEnvelope->getClientId(), payloadEnvelope->getRequestId(), payloadEnvelope->getPmeId(), payloadEnvelope->getPayloadType(), payloadEnvelope->getPayloadVersion(), attachmentCollectionDoc, payloadEnvelope->getProtocolCollection(), payloadEnvelope->getHeaderCollection(), payloadEnvelope->getVersion()); } const std::string payloadEnvelopeStr = XmlRoots::savePayloadEnvelopeToString(payloadEnvelopeNew); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(payloadEnvelopeStr, newHeaders, origHeaders); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::createFromProviderResponse( const SmartPtrCDynamicByteArray& providerResponse, const std::string& relFilename, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "createFromProviderResponse"); CAF_CM_VALIDATE_SMARTPTR(providerResponse); CAF_CM_VALIDATE_STRING(relFilename); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType("providerResponse"); messageHeadersWriter->setRelFilename(relFilename); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initialize(providerResponse, messageHeadersWriter->getHeaders(), headers); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::create( const SmartPtrCDynamicByteArray payload, const std::deque& attachmentCollection, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "create"); CAF_CM_VALIDATE_SMARTPTR(payload); const std::string payloadStr = reinterpret_cast(payload->getPtr()); const SmartPtrCXmlElement payloadXml = CXmlUtils::parseString(payloadStr, std::string()); payloadXml->removeChild("attachmentCollection"); if (! attachmentCollection.empty()) { SmartPtrCAttachmentCollectionDoc attachmentCollectionDoc; attachmentCollectionDoc.CreateInstance(); attachmentCollectionDoc->initialize(attachmentCollection); const SmartPtrCXmlElement attachmentCollectionXml = payloadXml->createAndAddElement("attachmentCollection"); AttachmentCollectionXml::add(attachmentCollectionDoc, attachmentCollectionXml); } SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr( payloadXml->saveToString(), CIntMessage::SmartPtrCHeaders(), headers); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::create( const SmartPtrCMgmtRequestDoc& mgmtRequest, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "create"); CAF_CM_VALIDATE_SMARTPTR(mgmtRequest); const std::string mgmtRequestStr = XmlRoots::saveMgmtRequestToString(mgmtRequest); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType("mgmtRequest"); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(mgmtRequestStr, messageHeadersWriter->getHeaders(), headers); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::create( const SmartPtrCDiagRequestDoc& diagRequest, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "create"); CAF_CM_VALIDATE_SMARTPTR(diagRequest); const std::string diagRequestStr = XmlRoots::saveDiagRequestToString(diagRequest); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType("diagRequest"); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(diagRequestStr, messageHeadersWriter->getHeaders(), headers); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::create( const SmartPtrCInstallRequestDoc& installRequest, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "create"); CAF_CM_VALIDATE_SMARTPTR(installRequest); const std::string installRequestStr = XmlRoots::saveInstallRequestToString(installRequest); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType("installRequest"); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(installRequestStr, messageHeadersWriter->getHeaders(), headers); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::create( const SmartPtrCProviderRegDoc& providerReg, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "create"); CAF_CM_VALIDATE_SMARTPTR(providerReg); const std::string installRequestStr = XmlRoots::saveProviderRegToString(providerReg); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType("providerReg"); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(installRequestStr, messageHeadersWriter->getHeaders(), headers); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::create( const SmartPtrCProviderCollectSchemaRequestDoc& providerCollectSchemaRequest, const std::string& relFilename, const std::string& relDirectory, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "create"); CAF_CM_VALIDATE_SMARTPTR(providerCollectSchemaRequest); CAF_CM_VALIDATE_STRING(relFilename); CAF_CM_VALIDATE_STRING(relDirectory); const std::string providerCollectSchemaRequestMem = XmlRoots::saveProviderCollectSchemaRequestToString(providerCollectSchemaRequest); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType("providerCollectSchemaRequest"); messageHeadersWriter->setRelFilename(relFilename); messageHeadersWriter->setRelDirectory(relDirectory); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(providerCollectSchemaRequestMem, messageHeadersWriter->getHeaders(), headers); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::create( const SmartPtrCProviderRequestDoc& providerRequest, const std::string& relFilename, const std::string& relDirectory, const std::string& providerUri, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageCreator", "create"); CAF_CM_VALIDATE_SMARTPTR(providerRequest); CAF_CM_VALIDATE_STRING(relFilename); CAF_CM_VALIDATE_STRING(relDirectory); SmartPtrCProviderRequestHeaderDoc requestHeader = providerRequest->getRequestHeader(); SmartPtrCPropertyCollectionDoc propertyBag = requestHeader->getEchoPropertyBag(); std::deque newProperties; if (!propertyBag.IsNull()) { newProperties.assign(propertyBag->getProperty().begin(), propertyBag->getProperty().end()); } std::deque relDirectoryValue(1, relDirectory); SmartPtrCPropertyDoc relDirectoryProp; relDirectoryProp.CreateInstance(); relDirectoryProp->initialize("relDirectory", PROPERTY_STRING, relDirectoryValue); newProperties.push_back(relDirectoryProp); std::deque providerUriValue(1, providerUri); SmartPtrCPropertyDoc providerUriProp; providerUriProp.CreateInstance(); providerUriProp->initialize("providerUri", PROPERTY_STRING, providerUriValue); newProperties.push_back(providerUriProp); SmartPtrCPropertyCollectionDoc newPropertyBag; newPropertyBag.CreateInstance(); newPropertyBag->initialize(newProperties); SmartPtrCProviderRequestHeaderDoc newRequestHeader; newRequestHeader.CreateInstance(); newRequestHeader->initialize(requestHeader->getRequestConfig(), newPropertyBag); SmartPtrCProviderRequestDoc newProviderRequest; newProviderRequest.CreateInstance(); newProviderRequest->initialize(providerRequest->getClientId(), providerRequest->getRequestId(), providerRequest->getPmeId(), newRequestHeader, providerRequest->getBatch(), providerRequest->getAttachmentCollection()); const std::string providerRequestMem = XmlRoots::saveProviderRequestToString(newProviderRequest); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType("providerRequest"); messageHeadersWriter->setRelFilename(relFilename); messageHeadersWriter->setRelDirectory(relDirectory); if (! providerUri.empty()) { messageHeadersWriter->setProviderUri(providerUri); } SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(providerRequestMem, messageHeadersWriter->getHeaders(), headers); return messageImpl; } SmartPtrIIntMessage CCafMessageCreator::createPayloadEnvelope( const std::string& payloadType, const std::string& payloadStr, const UUID& clientId, const UUID& requestId, const std::string& pmeId, const std::string& payloadVersion, const IIntMessage::SmartPtrCHeaders& newHeaders, const IIntMessage::SmartPtrCHeaders& origHeaders, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const SmartPtrCProtocolCollectionDoc& protocolCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CCafMessageCreator", "createPayloadEnvelope"); CAF_CM_VALIDATE_STRING(payloadType); CAF_CM_VALIDATE_STRING(payloadStr); // clientId is optional // requestId is optional // pmeId is optional CAF_CM_VALIDATE_STRING(payloadVersion); SmartPtrCIntMessage messageImpl; if (::IsEqualGUID(requestId, CAFCOMMON_GUID_NULL)) { CAF_CM_LOG_WARN_VA1("Message is not associated with a request - %s", payloadStr.c_str()); } else { const std::string outputDir = AppConfigUtils::getRequiredString(_sAppConfigGlobalParamOutputDir); const std::string destAttachmentFilename = BasePlatform::UuidToString(requestId) + "-EnvelopePayload.xml"; const std::string destAttachmentPath = FileSystemUtils::buildPath( outputDir, "att", destAttachmentFilename); const std::string destAttachmentUri = "file:///" + destAttachmentPath + "?relPath=" + destAttachmentFilename; const SmartPtrCDynamicByteArray payload = CCafMessagePayload::createBufferFromStr(payloadStr); FileSystemUtils::saveByteFile(destAttachmentPath, payload); const std::string cmsPolicyStr = AppConfigUtils::getRequiredString( "security", "cms_policy"); const CMS_POLICY cmsPolicy = EnumConvertersXml::convertStringToCmsPolicy(cmsPolicyStr); SmartPtrCAttachmentDoc envelopePayloadAttachment; envelopePayloadAttachment.CreateInstance(); envelopePayloadAttachment->initialize("_EnvelopePayload_", "EnvelopePayload", destAttachmentUri, false, cmsPolicy); std::deque attachmentCollectionNew; if (! attachmentCollection.IsNull()) { attachmentCollectionNew = attachmentCollection->getAttachment(); } attachmentCollectionNew.push_back(envelopePayloadAttachment); SmartPtrCAttachmentCollectionDoc attachmentCollectionDocNew; attachmentCollectionDocNew.CreateInstance(); attachmentCollectionDocNew->initialize(attachmentCollectionNew); SmartPtrCPayloadEnvelopeDoc payloadEnvelope; payloadEnvelope.CreateInstance(); payloadEnvelope->initialize( clientId, requestId, pmeId, payloadType, payloadVersion, attachmentCollectionDocNew, protocolCollection); const std::string payloadEnvelopeStr = XmlRoots::savePayloadEnvelopeToString(payloadEnvelope); const CIntMessage::SmartPtrCHeaders mergedHeaders = CIntMessage::mergeHeaders(newHeaders, origHeaders); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType(payloadType); messageImpl.CreateInstance(); messageImpl->initializeStr( payloadEnvelopeStr, messageHeadersWriter->getHeaders(), mergedHeaders); } return messageImpl; } CCafMessageHeaders.cpp000066400000000000000000000246131321503522500370710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "IVariant.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "Integration/Caf/CCafMessageHeaders.h" #include "Integration/Core/FileHeaders.h" using namespace Caf; SmartPtrCCafMessageHeaders CCafMessageHeaders::create( const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessageHeaders", "create"); CAF_CM_VALIDATE_SMARTPTR(headers); SmartPtrCCafMessageHeaders rc; rc.CreateInstance(); rc->initialize(headers); return rc; } CCafMessageHeaders::CCafMessageHeaders(void) : _isInitialized(false), CAF_CM_INIT_LOG("CCafMessageHeaders") { } CCafMessageHeaders::~CCafMessageHeaders(void) { } void CCafMessageHeaders::initialize( const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(headers); _headers = headers; _isInitialized = true; } IIntMessage::SmartPtrCHeaders CCafMessageHeaders::getHeaders() const { CAF_CM_FUNCNAME_VALIDATE("getHeaders"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _headers; } std::string CCafMessageHeaders::getPayloadType() const { CAF_CM_FUNCNAME_VALIDATE("getPayloadType"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("payloadType"); } std::string CCafMessageHeaders::getPayloadTypeOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getPayloadTypeOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("payloadType"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } std::string CCafMessageHeaders::getVersion() const { CAF_CM_FUNCNAME_VALIDATE("getVersion"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("version"); } std::string CCafMessageHeaders::getVersionOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getVersionOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("version"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } UUID CCafMessageHeaders::getClientId() const { CAF_CM_FUNCNAME_VALIDATE("getClientId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); UUID rc; const std::string rcStr = getClientIdStr(); BasePlatform::UuidFromString(rcStr.c_str(), rc); return rc; } std::string CCafMessageHeaders::getClientIdStr() const { CAF_CM_FUNCNAME_VALIDATE("getClientIdStr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("clientId"); } UUID CCafMessageHeaders::getClientIdOpt( const UUID defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getClientIdOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); UUID rc = defaultVal; const std::string rcStr = getClientIdStrOpt(); if (! rcStr.empty()) { BasePlatform::UuidFromString(rcStr.c_str(), rc); } return rc; } std::string CCafMessageHeaders::getClientIdStrOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getClientIdStrOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("clientId"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } UUID CCafMessageHeaders::getRequestId() const { CAF_CM_FUNCNAME_VALIDATE("getRequestId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); UUID rc; const std::string rcStr = getRequestIdStr(); BasePlatform::UuidFromString(rcStr.c_str(), rc); return rc; } std::string CCafMessageHeaders::getRequestIdStr() const { CAF_CM_FUNCNAME_VALIDATE("getRequestIdStr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("requestId"); } UUID CCafMessageHeaders::getRequestIdOpt( const UUID defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getRequestIdOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); UUID rc = defaultVal; const std::string rcStr = getRequestIdStrOpt(); if (! rcStr.empty()) { BasePlatform::UuidFromString(rcStr.c_str(), rc); } return rc; } std::string CCafMessageHeaders::getRequestIdStrOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getRequestIdStrOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("requestId"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } std::string CCafMessageHeaders::getPmeId() const { CAF_CM_FUNCNAME_VALIDATE("getPmeId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("pmeId"); } std::string CCafMessageHeaders::getPmeIdOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getPmeIdOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("pmeId"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } UUID CCafMessageHeaders::getSessionId() const { CAF_CM_FUNCNAME_VALIDATE("getSessionId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); UUID rc; const std::string rcStr = getSessionIdStr(); BasePlatform::UuidFromString(rcStr.c_str(), rc); return rc; } std::string CCafMessageHeaders::getSessionIdStr() const { CAF_CM_FUNCNAME_VALIDATE("getSessionIdStr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("sessionId"); } UUID CCafMessageHeaders::getSessionIdOpt( const UUID defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getSessionIdOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); UUID rc = defaultVal; const std::string rcStr = getSessionIdStrOpt(); if (! rcStr.empty()) { BasePlatform::UuidFromString(rcStr.c_str(), rc); } return rc; } std::string CCafMessageHeaders::getSessionIdStrOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getSessionIdStrOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("sessionId"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } std::string CCafMessageHeaders::getRelDirectory() const { CAF_CM_FUNCNAME_VALIDATE("getRelDirectory"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("relDirectory"); } std::string CCafMessageHeaders::getRelDirectoryOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getRelDirectoryOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("relDirectory"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } std::string CCafMessageHeaders::getRelFilename() const { CAF_CM_FUNCNAME_VALIDATE("getRelFilename"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr(FileHeaders::_sFILENAME); } std::string CCafMessageHeaders::getRelFilenameOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getRelFilenameOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr(FileHeaders::_sFILENAME); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } std::string CCafMessageHeaders::getProviderUri() const { CAF_CM_FUNCNAME_VALIDATE("getProviderUri"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("providerUri"); } std::string CCafMessageHeaders::getProviderUriOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getProviderUriOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("providerUri"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } std::string CCafMessageHeaders::getFlowDirection() const { CAF_CM_FUNCNAME_VALIDATE("getFlowDirection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return getRequiredStr("cafcomm.internal.msgflow"); } std::string CCafMessageHeaders::getFlowDirectionOpt( const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getFlowDirectionOpt"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = getOptionalStr("cafcomm.internal.msgflow"); if (rcStr.empty()) { rcStr = defaultVal; } return rcStr; } std::string CCafMessageHeaders::getRequiredStr( const std::string& key) const { CAF_CM_FUNCNAME_VALIDATE("getRequiredStr"); CAF_CM_VALIDATE_STRING(key); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return findRequiredHeader(key)->toString(); } std::string CCafMessageHeaders::getOptionalStr( const std::string& key, const std::string& defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getOptionalStr"); CAF_CM_VALIDATE_STRING(key); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rcStr = defaultVal; const SmartPtrIVariant valueVar = findOptionalHeader(key); if (! valueVar.IsNull()) { rcStr = valueVar->toString(); } return rcStr; } bool CCafMessageHeaders::getRequiredBool( const std::string& key) const { CAF_CM_FUNCNAME_VALIDATE("getRequiredBool"); CAF_CM_VALIDATE_STRING(key); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrIVariant valueVar = findRequiredHeader(key); CAF_CM_VALIDATE_BOOL(valueVar->isBool()); const std::string valueStr = valueVar->toString(); CAF_CM_LOG_DEBUG_VA2("key: %s, value: %s", key.c_str(), valueStr.c_str()); return (valueStr.compare("true") == 0); } bool CCafMessageHeaders::getOptionalBool( const std::string& key, const bool defaultVal) const { CAF_CM_FUNCNAME_VALIDATE("getOptionalBool"); CAF_CM_VALIDATE_STRING(key); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrIVariant valueVar = findOptionalHeader(key); bool rc = defaultVal; if (! valueVar.IsNull()) { CAF_CM_VALIDATE_BOOL(valueVar->isBool()); const std::string valueStr = valueVar->toString(); CAF_CM_LOG_DEBUG_VA2("key: %s, value: %s", key.c_str(), valueStr.c_str()); rc = (valueStr.compare("true") == 0); } return rc; } SmartPtrIVariant CCafMessageHeaders::findOptionalHeader( const std::string& key) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalHeader"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(key); SmartPtrIVariant value; IIntMessage::CHeaders::const_iterator headerIter = _headers->find(key); if (headerIter != _headers->end()) { value = headerIter->second.first; } return value; } SmartPtrIVariant CCafMessageHeaders::findRequiredHeader( const std::string& key) const { CAF_CM_FUNCNAME("findRequiredHeader"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(key); IIntMessage::CHeaders::const_iterator headerIter = _headers->find(key); if (headerIter == _headers->end()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Key not found in headers - %s", key.c_str()); } return headerIter->second.first; } CCafMessageHeadersWriter.cpp000066400000000000000000000143361321503522500402670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IIntMessage.h" #include "Integration/Caf/CCafMessageHeadersWriter.h" #include "Integration/Core/FileHeaders.h" #include "Integration/Core/MessageHeaders.h" using namespace Caf; SmartPtrCCafMessageHeadersWriter CCafMessageHeadersWriter::create() { SmartPtrCCafMessageHeadersWriter rc; rc.CreateInstance(); rc->initialize(); return rc; } CCafMessageHeadersWriter::CCafMessageHeadersWriter(void) : _isInitialized(false), CAF_CM_INIT("CCafMessageHeadersWriter") { } CCafMessageHeadersWriter::~CCafMessageHeadersWriter(void) { } void CCafMessageHeadersWriter::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _headers.CreateInstance(); _isInitialized = true; } IIntMessage::SmartPtrCHeaders CCafMessageHeadersWriter::getHeaders() const { CAF_CM_FUNCNAME_VALIDATE("getHeaders"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _headers; } void CCafMessageHeadersWriter::setPayloadType( const std::string& payloadType) { CAF_CM_FUNCNAME_VALIDATE("setPayloadType"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(payloadType); insertString("payloadType", payloadType); } void CCafMessageHeadersWriter::setVersion( const std::string& version) { CAF_CM_FUNCNAME_VALIDATE("setVersion"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(version); insertString("version", version); } void CCafMessageHeadersWriter::setPayloadVersion( const std::string& payloadVersion) { CAF_CM_FUNCNAME_VALIDATE("setPayloadVersion"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(payloadVersion); insertString("payloadVersion", payloadVersion); } void CCafMessageHeadersWriter::setClientId( const UUID& clientId) { CAF_CM_FUNCNAME_VALIDATE("setClientId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string clientIdStr = BasePlatform::UuidToString(clientId); insertString("clientId", clientIdStr); } void CCafMessageHeadersWriter::setClientId( const std::string& clientIdStr) { CAF_CM_FUNCNAME_VALIDATE("setClientId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(clientIdStr); insertString("clientId", clientIdStr); } void CCafMessageHeadersWriter::setRequestId( const UUID& requestId) { CAF_CM_FUNCNAME_VALIDATE("setRequestId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string requestIdStr = BasePlatform::UuidToString(requestId); insertString("requestId", requestIdStr); } void CCafMessageHeadersWriter::setRequestId( const std::string& requestIdStr) { CAF_CM_FUNCNAME_VALIDATE("setRequestId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(requestIdStr); insertString("requestId", requestIdStr); } void CCafMessageHeadersWriter::setPmeId( const std::string& pmeId) { CAF_CM_FUNCNAME_VALIDATE("setPmeId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(pmeId); insertString("pmeId", pmeId); } void CCafMessageHeadersWriter::setSessionId( const UUID& sessionId) { CAF_CM_FUNCNAME_VALIDATE("setSessionId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string sessionIdStr = BasePlatform::UuidToString(sessionId); insertString("sessionId", sessionIdStr); } void CCafMessageHeadersWriter::setSessionId( const std::string& sessionIdStr) { CAF_CM_FUNCNAME_VALIDATE("setSessionId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(sessionIdStr); insertString("sessionId", sessionIdStr); } void CCafMessageHeadersWriter::setRelDirectory( const std::string& relDirectory) { CAF_CM_FUNCNAME_VALIDATE("setRelDirectory"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(relDirectory); insertString("relDirectory", relDirectory); } void CCafMessageHeadersWriter::setRelFilename( const std::string& relFilename) { CAF_CM_FUNCNAME_VALIDATE("setRelFilename"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(relFilename); insertString(FileHeaders::_sFILENAME, relFilename); } void CCafMessageHeadersWriter::setProviderUri( const std::string& providerUri) { CAF_CM_FUNCNAME_VALIDATE("setProviderUri"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(providerUri); insertString("providerUri", providerUri); } void CCafMessageHeadersWriter::setIsThrowable( const bool& isThrowable) { CAF_CM_FUNCNAME_VALIDATE("setIsThrowable"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); insertBool(MessageHeaders::_sIS_THROWABLE, isThrowable); } void CCafMessageHeadersWriter::setIsMultiPart( const bool& isMultiPart) { CAF_CM_FUNCNAME_VALIDATE("setIsMultiPart"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); insertBool(MessageHeaders::_sMULTIPART, isMultiPart); } void CCafMessageHeadersWriter::setProtocol( const std::string& protocol) { CAF_CM_FUNCNAME_VALIDATE("setProtocol"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(protocol); insertString(MessageHeaders::_sPROTOCOL_TYPE, protocol); } void CCafMessageHeadersWriter::setProtocolAddress( const std::string& protocolAddress) { CAF_CM_FUNCNAME_VALIDATE("setProtocolAddress"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(protocolAddress); insertString(MessageHeaders::_sPROTOCOL_CONNSTR, protocolAddress); } void CCafMessageHeadersWriter::setFlowDirection( const std::string& flowDirection) { CAF_CM_FUNCNAME_VALIDATE("setFlowDirection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(flowDirection); insertString("cafcomm.internal.msgflow", flowDirection); } void CCafMessageHeadersWriter::insertString( const std::string& key, const std::string& value) { CAF_CM_FUNCNAME_VALIDATE("insertString"); CAF_CM_VALIDATE_STRING(key); CAF_CM_VALIDATE_STRING(value); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createString(value), SmartPtrICafObject()))); } void CCafMessageHeadersWriter::insertBool( const std::string& key, const bool& value) { CAF_CM_FUNCNAME_VALIDATE("insertBool"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createBool(value), SmartPtrICafObject()))); } CCafMessagePayload.cpp000066400000000000000000000132351321503522500371050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/ResponseDoc/CEventKeyCollectionDoc.h" #include "Doc/ResponseDoc/CEventKeyDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Integration/Caf/CCafMessagePayload.h" #include "Doc/DocXml/CafCoreTypesXml/RequestHeaderXml.h" #include "Doc/DocXml/ResponseXml/ManifestXml.h" #include "Doc/DocXml/ResponseXml/EventKeyCollectionXml.h" using namespace Caf; SmartPtrCCafMessagePayload CCafMessagePayload::create( const SmartPtrCDynamicByteArray& payload, const std::string& payloadType) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayload", "create"); CAF_CM_VALIDATE_SMARTPTR(payload); SmartPtrCCafMessagePayload rc; rc.CreateInstance(); rc->initialize(payload, payloadType); return rc; } SmartPtrCCafMessagePayload CCafMessagePayload::createFromFile( const std::string& payloadFile, const std::string& payloadType) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayload", "createFromFile"); CAF_CM_VALIDATE_STRING(payloadFile); const SmartPtrCDynamicByteArray payload = FileSystemUtils::loadByteFile(payloadFile); return create(payload, payloadType); } SmartPtrCCafMessagePayload CCafMessagePayload::createFromStr( const std::string& payloadStr, const std::string& payloadType) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayload", "createFromStr"); CAF_CM_VALIDATE_STRING(payloadStr); SmartPtrCDynamicByteArray payload = createBufferFromStr(payloadStr); SmartPtrCCafMessagePayload rc; rc.CreateInstance(); rc->initialize(payload, payloadType); return rc; } SmartPtrCDynamicByteArray CCafMessagePayload::createBufferFromStr( const std::string& payloadStr) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayload", "createBufferFromStr"); CAF_CM_VALIDATE_STRING(payloadStr); SmartPtrCDynamicByteArray rc; rc.CreateInstance(); rc->allocateBytes(static_cast(payloadStr.length())); rc->memCpy(payloadStr.c_str(), static_cast(payloadStr.length())); return rc; } SmartPtrCDynamicByteArray CCafMessagePayload::createBufferFromFile( const std::string& payloadFile) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayload", "createBufferFromFile"); CAF_CM_VALIDATE_STRING(payloadFile); return FileSystemUtils::loadByteFile(payloadFile); } void CCafMessagePayload::saveToFile( const SmartPtrCDynamicByteArray& payload, const std::string& payloadPath) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayload", "saveToFile"); CAF_CM_VALIDATE_SMARTPTR(payload); CAF_CM_VALIDATE_STRING(payloadPath); FileSystemUtils::saveByteFile(payloadPath, payload->getPtr(), payload->getByteCount()); } std::string CCafMessagePayload::saveToStr( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayload", "saveToStr"); CAF_CM_VALIDATE_SMARTPTR(payload); return reinterpret_cast(payload->getPtr()); } CCafMessagePayload::CCafMessagePayload(void) : _isInitialized(false), CAF_CM_INIT("CCafMessagePayload") { } CCafMessagePayload::~CCafMessagePayload(void) { } void CCafMessagePayload::initialize( const SmartPtrCDynamicByteArray& payload, const std::string& payloadType, const std::string& encoding) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(payload); CAF_CM_VALIDATE_STRING(encoding); CAF_CM_VALIDATE_BOOL(encoding.compare("xml") == 0); _payload = payload; _encoding = encoding; _payloadStr = saveToStr(payload); _payloadXml = CXmlUtils::parseString(_payloadStr, payloadType); _isInitialized = true; } std::string CCafMessagePayload::getPayloadStr() const { CAF_CM_FUNCNAME_VALIDATE("getPayloadStr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _payloadStr; } SmartPtrCDynamicByteArray CCafMessagePayload::getPayload() const { CAF_CM_FUNCNAME_VALIDATE("getPayload"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _payload; } std::string CCafMessagePayload::getVersion() const { CAF_CM_FUNCNAME_VALIDATE("getVersion"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrCXmlElement headerXml = _payloadXml->findOptionalChild("requestHeader"); if (headerXml.IsNull()) { headerXml = _payloadXml->findOptionalChild("responseHeader"); } std::string rc; if (headerXml.IsNull()) { rc = _payloadXml->findRequiredAttribute("version"); } else { rc = headerXml->findRequiredAttribute("version"); } return rc; } SmartPtrCRequestHeaderDoc CCafMessagePayload::getRequestHeader() const { CAF_CM_FUNCNAME_VALIDATE("getRequestHeader"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCXmlElement requestHeaderXml = _payloadXml->findRequiredChild("requestHeader"); return RequestHeaderXml::parse(requestHeaderXml); } SmartPtrCManifestDoc CCafMessagePayload::getManifest() const { CAF_CM_FUNCNAME_VALIDATE("getManifest"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCXmlElement manifestXml = _payloadXml->findRequiredChild("manifest"); return ManifestXml::parse(manifestXml); } std::deque CCafMessagePayload::getEventKeyCollection() const { CAF_CM_FUNCNAME_VALIDATE("getEventKeyCollection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::deque rc; SmartPtrCXmlElement eventKeyCollectionXml = _payloadXml->findOptionalChild("eventKeyCollection"); if (eventKeyCollectionXml) { const SmartPtrCEventKeyCollectionDoc eventKeyCollection = EventKeyCollectionXml::parse(eventKeyCollectionXml); rc = eventKeyCollection->getEventKey(); } return rc; } CCafMessagePayloadParser.cpp000066400000000000000000000076141321503522500402660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Caf/* * Author: bwilliams * Created: Jul 2009 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlRoots.h" #include "Doc/DocXml/MgmtRequestXml/MgmtRequestXmlRoots.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlRoots.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlRoots.h" #include "Doc/DocXml/CafInstallRequestXml/InstallProviderJobXml.h" #include "Doc/DocXml/CafInstallRequestXml/UninstallProviderJobXml.h" #include "Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXml.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Integration/Caf/CCafMessagePayloadParser.h" using namespace Caf; SmartPtrCPayloadEnvelopeDoc CCafMessagePayloadParser::getPayloadEnvelope( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "getPayloadEnvelope"); CAF_CM_VALIDATE_SMARTPTR(payload); return PayloadEnvelopeXml::parse(bufferToXml(payload, "caf:payloadEnvelope")); } SmartPtrCInstallProviderJobDoc CCafMessagePayloadParser::getInstallProviderJob( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "getInstallProviderJob"); CAF_CM_VALIDATE_SMARTPTR(payload); return InstallProviderJobXml::parse(bufferToXml(payload, "caf:cafInstallProviderJob")); } SmartPtrCUninstallProviderJobDoc CCafMessagePayloadParser::getUninstallProviderJob( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "getUninstallProviderJob"); CAF_CM_VALIDATE_SMARTPTR(payload); return UninstallProviderJobXml::parse(bufferToXml(payload, "caf:cafUninstallProviderJob")); } SmartPtrCProviderRequestDoc CCafMessagePayloadParser::getProviderRequest( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "getProviderRequest"); CAF_CM_VALIDATE_SMARTPTR(payload); return XmlRoots::parseProviderRequestFromString(bufferToStr(payload)); } SmartPtrCProviderRegDoc CCafMessagePayloadParser::getProviderReg( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "getProviderReg"); CAF_CM_VALIDATE_SMARTPTR(payload); return XmlRoots::parseProviderRegFromString(bufferToStr(payload)); } SmartPtrCInstallRequestDoc CCafMessagePayloadParser::getInstallRequest( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "getInstallRequest"); CAF_CM_VALIDATE_SMARTPTR(payload); return XmlRoots::parseInstallRequestFromString(bufferToStr(payload)); } SmartPtrCMgmtRequestDoc CCafMessagePayloadParser::getMgmtRequest( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "getMgmtRequest"); CAF_CM_VALIDATE_SMARTPTR(payload); return XmlRoots::parseMgmtRequestFromString(bufferToStr(payload)); } SmartPtrCXmlElement CCafMessagePayloadParser::bufferToXml( const SmartPtrCDynamicByteArray& payload, const std::string& payloadType) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "bufferToXml"); CAF_CM_VALIDATE_SMARTPTR(payload); return CXmlUtils::parseString(bufferToStr(payload), payloadType); } std::string CCafMessagePayloadParser::bufferToStr( const SmartPtrCDynamicByteArray& payload) { CAF_CM_STATIC_FUNC_VALIDATE("CCafMessagePayloadParser", "bufferToStr"); CAF_CM_VALIDATE_SMARTPTR(payload); return reinterpret_cast(payload->getPtr()); } stdafx.h000066400000000000000000000006071321503522500344270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Caf/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define INTEGRATIONCAF_LINKAGE __declspec(dllexport) #else #define INTEGRATIONCAF_LINKAGE #endif #include #include #include #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/000077500000000000000000000000001321503522500332405ustar00rootroot00000000000000CAbstractMessageChannel.cpp000066400000000000000000000034411321503522500403330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Created on: Jan 26, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IChannelInterceptor.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/Core/CAbstractMessageChannel.h" CAbstractMessageChannel::CAbstractMessageChannel() : CAF_CM_INIT("CAbstractMessageChannel") { } CAbstractMessageChannel::~CAbstractMessageChannel() { } bool CAbstractMessageChannel::send( const SmartPtrIIntMessage& message) { return send(message, -1); } bool CAbstractMessageChannel::send( const SmartPtrIIntMessage& message, const int32 timeout) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_VALIDATE_INTERFACE(message); // Call all interceptors' preSend() SmartPtrIIntMessage intMessage = message; SmartPtrIMessageChannel channel(this); for (TSmartIterator > interceptor(_interceptors); interceptor; interceptor++) { intMessage = interceptor->preSend(intMessage, channel); if (!intMessage) { break; } } // If an interceptor returned NULL then we're done bool sent = false; if (intMessage) { // Send the message through the subclass doSend() sent = doSend(intMessage, timeout); // Call the interceptors' postSend() for (TSmartIterator > interceptor(_interceptors); interceptor; interceptor++) { interceptor->postSend(intMessage, channel, sent); } } return sent; } void CAbstractMessageChannel::setInterceptors( const IChannelInterceptorSupport::InterceptorCollection& interceptors) { _interceptors = interceptors; } std::list CAbstractMessageChannel::getInterceptors() const { return _interceptors; } CAbstractMessageRouter.cpp000066400000000000000000000045401321503522500402440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Created on: Aug 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/Core/CIntException.h" #include "Exception/CCafException.h" #include "Integration/Core/CAbstractMessageRouter.h" using namespace Caf; CAbstractMessageRouter::CAbstractMessageRouter() : _ignoreSendFailures(false), _sendTimeout(-1), _isInitialized(false), CAF_CM_INIT_LOG("CAbstractMessageRouter") { } CAbstractMessageRouter::~CAbstractMessageRouter() { } void CAbstractMessageRouter::init() { init(SmartPtrIMessageChannel(), false, -1); } void CAbstractMessageRouter::init( const SmartPtrIMessageChannel& defaultOutputChannel, const bool ignoreSendFailures, const int32 sendTimeout) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); // defaultOutputChannel may be NULL _defaultOutputChannel = defaultOutputChannel; _ignoreSendFailures = ignoreSendFailures; _sendTimeout = sendTimeout; _isInitialized = true; } void CAbstractMessageRouter::routeMessage(const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("routeMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); bool isSent = false; ChannelCollection channels; try { channels = getTargetChannels(message); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; for (TSmartConstIterator channelIter(channels); channelIter; channelIter++) { try { SmartPtrIMessageChannel channel(*channelIter); CAF_CM_VALIDATE_INTERFACE(channel); channel->send(message, _sendTimeout); isSent = true; } CAF_CM_CATCH_ALL; if (CAF_CM_ISEXCEPTION && _ignoreSendFailures) { CAF_CM_LOG_DEBUG_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } CAF_CM_THROWEXCEPTION; } if (!isSent) { if (_defaultOutputChannel) { _defaultOutputChannel->send(message, _sendTimeout); } else { if (channels.size()) { CAF_CM_EXCEPTIONEX_VA0( MessageDeliveryException, 0, "failed to send message to resolved channel(s) " "and no default output channel defined"); } else { CAF_CM_EXCEPTIONEX_VA0( MessageDeliveryException, 0, "no channel resolved by router and no default " "output channel defined"); } } } } CAbstractPollableChannel.cpp000066400000000000000000000052401321503522500405000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Created on: Jan 26, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Dependencies/CPollerMetadata.h" #include "Integration/IChannelInterceptor.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/Core/CAbstractPollableChannel.h" CAbstractPollableChannel::CAbstractPollableChannel() : CAF_CM_INIT("CAbstractPollableChannel") { } CAbstractPollableChannel::~CAbstractPollableChannel() { } SmartPtrIIntMessage CAbstractPollableChannel::receive() { return receive(0); } SmartPtrIIntMessage CAbstractPollableChannel::receive(const int32 timeout) { SmartPtrIIntMessage message; CAF_CM_ENTER { std::list interceptors = getInterceptors(); SmartPtrIMessageChannel channel(this); bool preReceiveOk = true; for (TSmartIterator > interceptor(interceptors); interceptor && preReceiveOk; interceptor++) { preReceiveOk = interceptor->preReceive(channel); } if (preReceiveOk) { message = doReceive(timeout); for (TSmartIterator > interceptor(interceptors); interceptor && message; interceptor++) { message = interceptor->postReceive(message, channel); } } } CAF_CM_EXIT; return message; } SmartPtrCPollerMetadata CAbstractPollableChannel::getPollerMetadata() const { CAF_CM_FUNCNAME_VALIDATE("getPollerMetadata"); CAF_CM_VALIDATE_SMARTPTR(_pollerMetadata); return _pollerMetadata; } void CAbstractPollableChannel::setPollerMetadata(const SmartPtrCPollerMetadata& pollerMetadata) { CAF_CM_FUNCNAME_VALIDATE("setPollerMetadata"); CAF_CM_VALIDATE_SMARTPTR(pollerMetadata); _pollerMetadata = pollerMetadata; } void CAbstractPollableChannel::setPollerMetadata(const SmartPtrIDocument& pollerDoc) { // pollerDoc is optional CAF_CM_ENTER { _pollerMetadata.CreateInstance(); _pollerMetadata->putFixedRate(1000); _pollerMetadata->putMaxMessagesPerPoll(1); if (pollerDoc) { const std::string maxMessagesPerPollStr = pollerDoc->findOptionalAttribute("max-messages-per-poll"); if (!maxMessagesPerPollStr.empty()) { const uint32 maxMessagesPerPoll = CStringConv::fromString(maxMessagesPerPollStr); _pollerMetadata->putMaxMessagesPerPoll(maxMessagesPerPoll); } const std::string fixedRateStr = pollerDoc->findOptionalAttribute("fixed-rate"); if (!fixedRateStr.empty()) { const uint32 fixedRate = CStringConv::fromString(fixedRateStr); _pollerMetadata->putFixedRate(fixedRate); } } } CAF_CM_EXIT; } CBroadcastingDispatcher.cpp000066400000000000000000000066151321503522500404070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntException.h" #include "Integration/IErrorHandler.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" #include "Integration/Core/CBroadcastingDispatcher.h" using namespace Caf; CBroadcastingDispatcher::CBroadcastingDispatcher() : _isInitialized(false), CAF_CM_INIT_LOG("CBroadcastingDispatcher") { } CBroadcastingDispatcher::~CBroadcastingDispatcher() { } void CBroadcastingDispatcher::initialize( const SmartPtrIErrorHandler& errorHandler) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(errorHandler); _errorHandler = errorHandler; _messageHandlerCollection.CreateInstance(); _isInitialized = true; } CAF_CM_EXIT; } void CBroadcastingDispatcher::addHandler( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("addHandler"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); const void* handlerPtr = messageHandler.GetNonAddRefedInterface(); _messageHandlerCollection->insert(std::make_pair(handlerPtr, messageHandler)); #ifdef __x86_64__ CAF_CM_LOG_DEBUG_VA1("Added handler - %llX", handlerPtr); #else CAF_CM_LOG_DEBUG_VA1("Added handler - %X", handlerPtr); #endif } CAF_CM_EXIT; } void CBroadcastingDispatcher::removeHandler( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("removeHandler"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); const void* handlerPtr = messageHandler.GetNonAddRefedInterface(); _messageHandlerCollection->erase(handlerPtr); #ifdef __x86_64__ CAF_CM_LOG_DEBUG_VA1("Removed handler - %llX", handlerPtr); #else CAF_CM_LOG_DEBUG_VA1("Removed handler - %X", handlerPtr); #endif } CAF_CM_EXIT; } bool CBroadcastingDispatcher::dispatch( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("dispatch"); bool isMessageHandled = false; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); for (TSmartConstMapIterator messageHandlerIter(*_messageHandlerCollection); messageHandlerIter; messageHandlerIter++) { const SmartPtrIMessageHandler messageHandler = *messageHandlerIter; #ifdef __x86_64__ CAF_CM_LOG_DEBUG_VA1("Dispatching to handler - %llX", messageHandlerIter.getKey()); #else CAF_CM_LOG_DEBUG_VA1("Dispatching to handler - %X", messageHandlerIter.getKey()); #endif try { messageHandler->handleMessage(message); isMessageHandled = true; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; try { if (CAF_CM_ISEXCEPTION) { CAF_CM_VALIDATE_INTERFACE(messageHandler); SmartPtrIIntMessage savedMessage = messageHandler->getSavedMessage(); if (savedMessage.IsNull()) { savedMessage = message; } SmartPtrCIntException intException; intException.CreateInstance(); intException->initialize(CAF_CM_GETEXCEPTION); _errorHandler->handleError(intException, savedMessage); CAF_CM_CLEAREXCEPTION; } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } } CAF_CM_EXIT; return isMessageHandled; } CChannelInterceptorAdapter.cpp000066400000000000000000000016241321503522500410630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Created on: Jan 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/Core/CChannelInterceptorAdapter.h" CChannelInterceptorAdapter::CChannelInterceptorAdapter() { } CChannelInterceptorAdapter::~CChannelInterceptorAdapter() { } SmartPtrIIntMessage& CChannelInterceptorAdapter::preSend( SmartPtrIIntMessage& message, SmartPtrIMessageChannel&) { return message; } void CChannelInterceptorAdapter::postSend( SmartPtrIIntMessage&, SmartPtrIMessageChannel&, bool) { } bool CChannelInterceptorAdapter::preReceive( SmartPtrIMessageChannel&) { return true; } SmartPtrIIntMessage& CChannelInterceptorAdapter::postReceive( SmartPtrIIntMessage& message, SmartPtrIMessageChannel&) { return message; } CChannelResolver.cpp000066400000000000000000000044451321503522500370710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" #include "Integration/Core/CChannelResolver.h" #include "Exception/CCafException.h" using namespace Caf; CChannelResolver::CChannelResolver() : _isInitialized(false), CAF_CM_INIT("CChannelResolver") { } CChannelResolver::~CChannelResolver() { } void CChannelResolver::initialize( const SmartPtrCIntegrationObjectCollection& integrationObjectCollection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTSTL_NOTEMPTY(integrationObjectCollection); _integrationObjectCollection = integrationObjectCollection; _isInitialized = true; } CAF_CM_EXIT; } SmartPtrIMessageChannel CChannelResolver::resolveChannelName( const std::string& channelName) const { CAF_CM_FUNCNAME("resolveChannelName"); SmartPtrIMessageChannel messageChannel; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(channelName); const SmartPtrIIntegrationObject integrationObject = resolveChannelNameToObject(channelName); messageChannel.QueryInterface(integrationObject, false); if (messageChannel.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Integration object is not a message channel - %s", channelName.c_str()); } } CAF_CM_EXIT; return messageChannel; } SmartPtrIIntegrationObject CChannelResolver::resolveChannelNameToObject( const std::string& channelName) const { CAF_CM_FUNCNAME("resolveChannelNameToObject"); SmartPtrIIntegrationObject integrationObject; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(channelName); const CIntegrationObjectCollection::const_iterator integrationObjectCollectionIter = _integrationObjectCollection->find(channelName); if (integrationObjectCollectionIter == _integrationObjectCollection->end()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Bean with given ID not found - %s", channelName.c_str()); } integrationObject = integrationObjectCollectionIter->second; } CAF_CM_EXIT; return integrationObject; } CDocument.cpp000066400000000000000000000151451321503522500355540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Integration/Core/CDocument.h" #include "Common/IAppConfig.h" using namespace Caf; CDocument::CDocument() : _isInitialized(false), CAF_CM_INIT("CDocument") { } CDocument::~CDocument() { } void CDocument::initialize( const SmartPtrCXmlElement& xmlElement) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(xmlElement); _xmlElement = xmlElement; // iterate over all attributes and resolve the attribute values // for environment and appConfig value references SmartPtrIAppConfig appConfig = getAppConfig(); std::deque stack; stack.push_back(_xmlElement); while (stack.size()) { SmartPtrCXmlElement element = stack.front(); stack.pop_front(); CXmlElement::SmartPtrCAttributeCollection attributes = element->getAllAttributes(); for (TConstMapIterator attribute(*attributes); attribute; attribute++) { element->setAttribute( attribute.getKey(), appConfig->resolveValue(*attribute)); } CXmlElement::SmartPtrCElementCollection children = element->getAllChildren(); std::transform( children->begin(), children->end(), std::insert_iterator >(stack, stack.end()), select2nd()); } _isInitialized = true; } CAF_CM_EXIT; } SmartPtrCXmlElement CDocument::getXmlElement() const { CAF_CM_FUNCNAME_VALIDATE("getXmlElement"); SmartPtrCXmlElement rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _xmlElement; } CAF_CM_EXIT; return rc; } std::string CDocument::findRequiredAttribute(const std::string& name) const { CAF_CM_FUNCNAME_VALIDATE("findRequiredAttribute"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _xmlElement->findRequiredAttribute(name); } CAF_CM_EXIT; return rc; } std::string CDocument::findOptionalAttribute(const std::string& name) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalAttribute"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _xmlElement->findOptionalAttribute(name); } CAF_CM_EXIT; return rc; } SmartPtrIDocument CDocument::findRequiredChild(const std::string& name) const { CAF_CM_FUNCNAME_VALIDATE("findRequiredChild"); SmartPtrIDocument rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCXmlElement child = _xmlElement->findRequiredChild(name); SmartPtrCDocument document; document.CreateInstance(); document->initialize(child); rc = document; } CAF_CM_EXIT; return rc; } SmartPtrIDocument CDocument::findOptionalChild(const std::string& name) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalChild"); SmartPtrIDocument rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCXmlElement child = _xmlElement->findOptionalChild(name); if (! child.IsNull()) { SmartPtrCDocument document; document.CreateInstance(); document->initialize(child); rc = document; } } CAF_CM_EXIT; return rc; } IDocument::SmartPtrCAttributeCollection CDocument::getAllAttributes() const { CAF_CM_FUNCNAME_VALIDATE("getAllAttributes"); IDocument::SmartPtrCAttributeCollection rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc.CreateInstance(); const CXmlElement::SmartPtrCAttributeCollection attributesXml = _xmlElement->getAllAttributes(); for (TConstIterator attributeXmlIter(*attributesXml); attributeXmlIter; attributeXmlIter++) { rc->insert(std::make_pair(attributeXmlIter->first, attributeXmlIter->second)); } } CAF_CM_EXIT; return rc; } IDocument::SmartPtrCChildCollection CDocument::getAllChildren() const { CAF_CM_FUNCNAME_VALIDATE("getAllChildren"); IDocument::SmartPtrCChildCollection rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc.CreateInstance(); const CXmlElement::SmartPtrCElementCollection childrenXml = _xmlElement->getAllChildren(); for (TConstIterator childXmlIter(*childrenXml); childXmlIter; childXmlIter++) { SmartPtrCDocument document; document.CreateInstance(); document->initialize(childXmlIter->second); rc->insert(std::make_pair(childXmlIter->first, document)); } } CAF_CM_EXIT; return rc; } IDocument::SmartPtrCOrderedChildCollection CDocument::getAllChildrenInOrder() const { CAF_CM_FUNCNAME_VALIDATE("getAllChildrenInOrder"); IDocument::SmartPtrCOrderedChildCollection rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc.CreateInstance(); const CXmlElement::SmartPtrCOrderedElementCollection childrenXml = _xmlElement->getAllChildrenInOrder(); for (TConstIterator childXmlIter(*childrenXml); childXmlIter; childXmlIter++) { SmartPtrCDocument document; document.CreateInstance(); document->initialize(*childXmlIter); rc->push_back(document); } } CAF_CM_EXIT; return rc; } std::string CDocument::getName() const { CAF_CM_FUNCNAME_VALIDATE("getName"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _xmlElement->getName(); } CAF_CM_EXIT; return rc; } std::string CDocument::getValue() const { CAF_CM_FUNCNAME_VALIDATE("getValue"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _xmlElement->getValue(); } CAF_CM_EXIT; return rc; } std::string CDocument::getPath() const { CAF_CM_FUNCNAME_VALIDATE("getPath"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _xmlElement->getPath(); } CAF_CM_EXIT; return rc; } void CDocument::saveToFile(const std::string& filename) const { CAF_CM_FUNCNAME_VALIDATE("saveToFile"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _xmlElement->saveToFile(filename); } CAF_CM_EXIT; } std::string CDocument::saveToString() const { CAF_CM_FUNCNAME_VALIDATE("saveToString"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _xmlElement->saveToString(); } CAF_CM_EXIT; return rc; } std::string CDocument::saveToStringRaw() const { CAF_CM_FUNCNAME_VALIDATE("saveToStringRaw"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _xmlElement->saveToStringRaw(); } CAF_CM_EXIT; return rc; } CErrorHandler.cpp000066400000000000000000000053711321503522500363650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IChannelResolver.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/IThrowable.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CIntMessageHeaders.h" #include "Integration/Core/MessageHeaders.h" using namespace Caf; CErrorHandler::CErrorHandler() : _isInitialized(false), CAF_CM_INIT_LOG("CErrorHandler") { } CErrorHandler::~CErrorHandler() { } void CErrorHandler::initialize( const SmartPtrIChannelResolver& channelResolver, const SmartPtrIMessageChannel& errorMessageChannel) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(channelResolver); CAF_CM_VALIDATE_INTERFACE(errorMessageChannel); _channelResolver = channelResolver; _errorMessageChannel = errorMessageChannel; _isInitialized = true; } CAF_CM_EXIT; } void CErrorHandler::handleError( const SmartPtrIThrowable& throwable, const SmartPtrIIntMessage& message) const { CAF_CM_FUNCNAME_VALIDATE("handleError"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(throwable); // message is optional bool isThrowable = false; if (! message.IsNull()) { const std::string isThrowableStr = message->findOptionalHeaderAsString(MessageHeaders::_sIS_THROWABLE); isThrowable = (isThrowableStr.empty() || (isThrowableStr.compare("false") == 0)) ? false : true; } if (isThrowable) { CAF_CM_LOG_ERROR_VA2("Error already handled - MsgErr: %s, Thrown: %s", message->getPayloadStr().c_str(), throwable->getFullMsg().c_str()); } else { CIntMessageHeaders messageHeaders; messageHeaders.insertString(MessageHeaders::_sIS_THROWABLE, "true"); const IIntMessage::SmartPtrCHeaders origHeaders = message.IsNull() ? IIntMessage::SmartPtrCHeaders() : message->getHeaders(); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(throwable->getFullMsg(), messageHeaders.getHeaders(), origHeaders); const SmartPtrIIntMessage newMessage = messageImpl; const std::string errorChannelRef = newMessage->findOptionalHeaderAsString(MessageHeaders::_sERROR_CHANNEL); SmartPtrIMessageChannel errorMessageChannel = _errorMessageChannel; if (! errorChannelRef.empty()) { CAF_CM_LOG_INFO_VA1("Using alternate error channel - %s", errorChannelRef.c_str()); errorMessageChannel = _channelResolver->resolveChannelName(errorChannelRef); } errorMessageChannel->send(newMessage); } } CAF_CM_EXIT; } CExpressionHandler.cpp000066400000000000000000000067511321503522500374360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Created on: Jul 23, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppConfig.h" #include "Common/IAppContext.h" #include "IBean.h" #include "IVariant.h" #include "Integration/Core/CExpressionHandler.h" #include "Common/CCafRegex.h" #include "Exception/CCafException.h" using namespace Caf; CExpressionHandler::CExpressionHandler() : _isInitialized(false), CAF_CM_INIT("CExpressionHandler") { } CExpressionHandler::~CExpressionHandler() { } void CExpressionHandler::init( const SmartPtrIAppConfig& appConfig, const SmartPtrIAppContext& appContext, const std::string& expression) { CAF_CM_FUNCNAME("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appConfig); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_STRING(expression); CCafRegex regex; regex.initialize("\\@(\\w+)\\.(\\w+)\\((.*)\\)"); if (!regex.isMatched(expression)) { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "Invalid expression syntax '%s'", expression.c_str()); } _beanName = regex.match(expression, 1); _methodName = regex.match(expression, 2); if (!_beanName.length() || !_methodName.length()) { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "Invalid expression syntax '%s'", expression.c_str()); } SmartPtrIBean bean = appContext->getBean(_beanName); _invoker.QueryInterface(bean, false); if (!_invoker) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "bean '%s' does not support the IExpressionInvoker interface", _beanName.c_str()); } const std::string paramSubstr = regex.match(expression, 3); Cdeqstr paramExprs = CStringUtils::split(paramSubstr, ','); CCafRegex regexLiteral; regexLiteral.initialize("'(.*)'"); for (TConstIterator paramExpr(paramExprs); paramExpr; paramExpr++) { std::string trimmedExpr = CStringUtils::trim(*paramExpr); if (regexLiteral.isMatched(trimmedExpr)) { std::string val = regexLiteral.match(trimmedExpr, 1); if (val.length()) { _methodParams.push_back(appConfig->resolveValue(val)); } else { _methodParams.push_back(""); } } else { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "Invalid expression syntax '%s'", expression.c_str()); } } _isInitialized = true; } SmartPtrIVariant CExpressionHandler::evaluate(const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("evaluate"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _invoker->invokeExpression(_methodName, _methodParams, message); } std::string CExpressionHandler::getBeanName() const { CAF_CM_FUNCNAME_VALIDATE("getBeanName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _beanName; } std::string CExpressionHandler::getMethodName() const { CAF_CM_FUNCNAME_VALIDATE("getMethodName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _methodName; } Cdeqstr CExpressionHandler::getMethodParameters() const { CAF_CM_FUNCNAME_VALIDATE("getMethodParameters"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _methodParams; } std::string CExpressionHandler::toString() const { std::stringstream result; result << "invoke @" << _beanName << '.' << _methodName << '('; bool first = true; for (TConstIterator param(_methodParams); param; param++) { if (!first) { result << ", "; } result << '\'' << *param << '\''; first = false; } result << ')'; return result.str(); } CIntException.cpp000066400000000000000000000046761321503522500364160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntException.h" #define CAF_CM_DEFINE_INTEGRATION_EXCEPTION_CLASS(_exclass_) \ _exclass_::_exclass_() : CCafException( #_exclass_ ) {} \ _exclass_::~_exclass_() {} \ void _exclass_::throwSelf() { throw this; } using namespace Caf; CAF_CM_DEFINE_INTEGRATION_EXCEPTION_CLASS(FatalListenerStartupException) CAF_CM_DEFINE_INTEGRATION_EXCEPTION_CLASS(ListenerExecutionFailedException) CAF_CM_DEFINE_INTEGRATION_EXCEPTION_CLASS(MessageDeliveryException) CIntException::CIntException() : _isInitialized(false), _errorCode(0), _backtrace(NULL), CAF_CM_INIT("CIntException") { } CIntException::~CIntException() { } void CIntException::initialize(const CCafException* cafException) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_PTR(cafException); _exceptionClassName = cafException->getExceptionClassName(); _message = cafException->getMsg(); _className = cafException->getClassName(); _funcName = cafException->getFuncName(); _errorCode = cafException->getError(); _backtrace = cafException->getBacktrace(); _fullMsg = cafException->getFullMsg(); _isInitialized = true; } std::string CIntException::getExceptionClassName() const { CAF_CM_FUNCNAME_VALIDATE("getExceptionClassName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _exceptionClassName; } std::string CIntException::getMsg() const { CAF_CM_FUNCNAME_VALIDATE("getMsg"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _message; } std::string CIntException::getClassName() const { CAF_CM_FUNCNAME_VALIDATE("getClassName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _className; } std::string CIntException::getFuncName() const { CAF_CM_FUNCNAME_VALIDATE("getFuncName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _funcName; } HRESULT CIntException::getError() const { CAF_CM_FUNCNAME_VALIDATE("getError"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _errorCode; } std::deque* CIntException::getBacktrace() const { CAF_CM_FUNCNAME_VALIDATE("getBacktrace"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _backtrace; } std::string CIntException::getFullMsg() const { CAF_CM_FUNCNAME_VALIDATE("getFullMsg"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _fullMsg; } CIntMessage.cpp000066400000000000000000000135361321503522500360370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "ICafObject.h" #include "IVariant.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Integration/Core/CIntMessage.h" #include "Exception/CCafException.h" using namespace Caf; CIntMessage::CIntMessage() : _isInitialized(false), _messageId(CAFCOMMON_GUID_NULL), CAF_CM_INIT("CIntMessage") { } CIntMessage::~CIntMessage() { } CIntMessage::SmartPtrCHeaders CIntMessage::mergeHeaders( const SmartPtrCHeaders& newHeaders, const SmartPtrCHeaders& origHeaders) { CIntMessage::SmartPtrCHeaders headers; headers.CreateInstance(); if (newHeaders) { std::copy( newHeaders->begin(), newHeaders->end(), std::inserter( *headers, headers->end())); } if (origHeaders) { std::copy( origHeaders->begin(), origHeaders->end(), std::inserter( *headers, headers->end())); } return headers; } void CIntMessage::initializeStr( const std::string& payloadStr, const SmartPtrCHeaders& newHeaders, const SmartPtrCHeaders& origHeaders) { CAF_CM_FUNCNAME_VALIDATE("initializeStr"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); std::string payloadStrTmp = payloadStr; if (payloadStr.empty()) { payloadStrTmp = ""; } SmartPtrCDynamicByteArray payload; payload.CreateInstance(); payload->allocateBytes(payloadStrTmp.length()); payload->memCpy(payloadStrTmp.c_str(), payloadStrTmp.length()); initialize(payload, newHeaders, origHeaders); } void CIntMessage::initialize( const SmartPtrCDynamicByteArray& payload, const SmartPtrCHeaders& newHeaders, const SmartPtrCHeaders& origHeaders) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); // payload is optional // newHeaders are optional // origHeaders are optional _payload = payload; ::UuidCreate(&_messageId); _headers = mergeHeaders(newHeaders, origHeaders); IIntMessage::CHeaders::iterator header = _headers->find(MessageHeaders::_sID); if (_headers->end() == header) { _headers->insert(std::make_pair(MessageHeaders::_sID, std::make_pair(CVariant::createString(CStringUtils::createRandomUuid()), SmartPtrICafObject()))); } header = _headers->find(MessageHeaders::_sTIMESTAMP); if (_headers->end() == header) { _headers->insert(std::make_pair(MessageHeaders::_sTIMESTAMP, std::make_pair(CVariant::createUint64(CDateTimeUtils::getTimeMs()), SmartPtrICafObject()))); } _isInitialized = true; } CAF_CM_EXIT; } SmartPtrCDynamicByteArray CIntMessage::getPayload() const { CAF_CM_FUNCNAME_VALIDATE("getPayload"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _payload; } std::string CIntMessage::getPayloadStr() const { CAF_CM_FUNCNAME_VALIDATE("getPayloadStr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return reinterpret_cast(_payload->getPtr()); } UUID CIntMessage::getMessageId() const { CAF_CM_FUNCNAME_VALIDATE("getMessageId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _messageId; } std::string CIntMessage::getMessageIdStr() const { CAF_CM_FUNCNAME_VALIDATE("getMessageIdStr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return BasePlatform::UuidToString(_messageId); } IIntMessage::SmartPtrCHeaders CIntMessage::getHeaders() const { CAF_CM_FUNCNAME_VALIDATE("getHeaders"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _headers; } SmartPtrIVariant CIntMessage::findOptionalHeader( const std::string& key) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalHeader"); SmartPtrIVariant value; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(key); CHeaders::const_iterator headerIter = _headers->find(key); if (headerIter != _headers->end()) { value = headerIter->second.first; } } CAF_CM_EXIT; return value; } SmartPtrIVariant CIntMessage::findRequiredHeader( const std::string& key) const { CAF_CM_FUNCNAME("findRequiredHeader"); SmartPtrIVariant value; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(key); CHeaders::const_iterator headerIter = _headers->find(key); if (headerIter == _headers->end()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Key not found in headers - %s", key.c_str()); } value = headerIter->second.first; } CAF_CM_EXIT; return value; } std::string CIntMessage::findOptionalHeaderAsString( const std::string& key) const { std::string valueStr; SmartPtrIVariant value = findOptionalHeader(key); if (value) { valueStr = value->toString(); } return valueStr; } std::string CIntMessage::findRequiredHeaderAsString( const std::string& key) const { std::string valueStr; SmartPtrIVariant value = findRequiredHeader(key); if (value) { valueStr = value->toString(); } return valueStr; } SmartPtrICafObject CIntMessage::findOptionalObjectHeader( const std::string& key) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalObjectHeader"); SmartPtrICafObject value; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(key); CHeaders::const_iterator headerIter = _headers->find(key); if (headerIter != _headers->end()) { value = headerIter->second.second; } } CAF_CM_EXIT; return value; } SmartPtrICafObject CIntMessage::findRequiredObjectHeader( const std::string& key) const { CAF_CM_FUNCNAME("findRequiredObjectHeader"); SmartPtrICafObject value; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(key); CHeaders::const_iterator headerIter = _headers->find(key); if (headerIter == _headers->end()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Key not found in headers - %s", key.c_str()); } value = headerIter->second.second; } CAF_CM_EXIT; return value; } CIntMessageHeaders.cpp000066400000000000000000000076331321503522500373340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "ICafObject.h" #include "IVariant.h" #include "Integration/IIntMessage.h" #include "Integration/Core/CIntMessageHeaders.h" using namespace Caf; CIntMessageHeaders::CIntMessageHeaders() : CAF_CM_INIT("CIntMessageHeaders") { _headers.CreateInstance(); } CIntMessageHeaders::~CIntMessageHeaders() { } IIntMessage::SmartPtrCHeaders CIntMessageHeaders::getHeaders() const { return _headers; } void CIntMessageHeaders::clear() { _headers.CreateInstance(); } void CIntMessageHeaders::insertString( const std::string& key, const std::string& value) { CAF_CM_FUNCNAME_VALIDATE("insertString"); CAF_CM_VALIDATE_STRING(key); CAF_CM_VALIDATE_STRING(value); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createString(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertStringOpt( const std::string& key, const std::string& value) { CAF_CM_FUNCNAME_VALIDATE("insertStringOpt"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createString(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertInt64( const std::string& key, const int64& value) { CAF_CM_FUNCNAME_VALIDATE("insertInt64"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createInt64(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertUint64( const std::string& key, const uint64& value) { CAF_CM_FUNCNAME_VALIDATE("insertUint64"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createUint64(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertInt32( const std::string& key, const int32& value) { CAF_CM_FUNCNAME_VALIDATE("insertInt32"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createInt32(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertUint32( const std::string& key, const uint32& value) { CAF_CM_FUNCNAME_VALIDATE("insertUint32"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createUint32(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertInt16( const std::string& key, const int16& value) { CAF_CM_FUNCNAME_VALIDATE("insertInt16"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createInt16(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertUint16( const std::string& key, const uint16& value) { CAF_CM_FUNCNAME_VALIDATE("insertUint16"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createUint16(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertUint8( const std::string& key, const uint8& value) { CAF_CM_FUNCNAME_VALIDATE("insertUint8"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createUint8(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertBool( const std::string& key, const bool& value) { CAF_CM_FUNCNAME_VALIDATE("insertBool"); CAF_CM_VALIDATE_STRING(key); _headers->insert(std::make_pair(key, std::make_pair(CVariant::createBool(value), SmartPtrICafObject()))); } void CIntMessageHeaders::insertVariant( const std::string& key, const SmartPtrIVariant& variant) { CAF_CM_FUNCNAME_VALIDATE("insertVariant"); CAF_CM_VALIDATE_STRING(key); CAF_CM_VALIDATE_SMARTPTR(variant); _headers->insert(std::make_pair(key, std::make_pair(variant, SmartPtrICafObject()))); } void CIntMessageHeaders::insertObject( const std::string& key, const SmartPtrICafObject& cafObject) { CAF_CM_FUNCNAME_VALIDATE("insertObject"); CAF_CM_VALIDATE_STRING(key); CAF_CM_VALIDATE_SMARTPTR(cafObject); _headers->insert(std::make_pair(key, std::make_pair(SmartPtrIVariant(), cafObject))); } CIntegrationAppContext.cpp000066400000000000000000000557661321503522500403040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "Integration/Core/CChannelResolver.h" #include "Integration/Core/CDocument.h" #include "Integration/IChannelInterceptor.h" #include "Integration/IChannelInterceptorInstance.h" #include "Integration/IChannelInterceptorSupport.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationAppContext.h" #include "Integration/IIntegrationAppContextAware.h" #include "Integration/IIntegrationComponent.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" #include "Integration/IMessageChannel.h" #include "Integration/IMessageProducer.h" #include "Integration/IPhased.h" #include "Integration/ISmartLifecycle.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Integration/Core/CIntegrationAppContext.h" #include "Exception/CCafException.h" using namespace Caf; CIntegrationAppContext::CIntegrationAppContext() : _isInitialized(false), _isIntegrationObjectCollectionReady(false), _lifecycleBeansStarted(false), _timeoutMs(0), CAF_CM_INIT_LOG("CIntegrationAppContext") { } CIntegrationAppContext::~CIntegrationAppContext() { if (_weakSelfReference) { _weakSelfReference->set(NULL); } } void CIntegrationAppContext::initialize( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); const std::string beanConfigPath = getDefaultBeanConfigPath(); initializeRaw(timeoutMs, beanConfigPath, true); } void CIntegrationAppContext::initialize( const uint32 timeoutMs, const std::string& beanConfigPath) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(beanConfigPath); initializeRaw(timeoutMs, beanConfigPath, true); } void CIntegrationAppContext::initializeTwoPhase( const uint32 timeoutMs, const std::string& beanConfigPath) { CAF_CM_FUNCNAME_VALIDATE("initializeTwoPhase"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(beanConfigPath); initializeRaw(timeoutMs, beanConfigPath, false); } void CIntegrationAppContext::initializeRaw( const uint32 timeoutMs, const std::string& beanConfigPath, const bool startLifecycleBeans) { CAF_CM_FUNCNAME("initializeRaw"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(beanConfigPath); _timeoutMs = timeoutMs; _weakSelfReference.CreateInstance(); _weakSelfReference->set(this); const Cdeqstr beanConfigPathCollection = getBeanConfigFiles(beanConfigPath); _applicationContext.CreateInstance(); _applicationContext->initialize(beanConfigPathCollection); const IAppContext::SmartPtrCBeans contextBeans = _applicationContext->getBeans(); _integrationObjectCollection = assign(contextBeans, beanConfigPathCollection); // Set context aware objects' appContext reference for (TSmartConstMapIterator object(*_integrationObjectCollection); object; object++) { SmartPtrIIntegrationAppContextAware contextAwareObj; contextAwareObj.QueryInterface(*object, false); if (contextAwareObj) { contextAwareObj->setIntegrationAppContext(_weakSelfReference); } } // Inject channel interceptors injectChannelInterceptors(_integrationObjectCollection); _isIntegrationObjectCollectionReady = true; // Create the channel resolver and wire up the integration objects SmartPtrCChannelResolver channelResolver; channelResolver.CreateInstance(); channelResolver->initialize(_integrationObjectCollection); _channelResolver = channelResolver; wire(_applicationContext, _integrationObjectCollection, _channelResolver); // Build up the collection of ILifecycle objects and determine // the startup order. // // ISmartLifecycle objects will provide a phase number to state their // desired relative load order. // // ILifecycle objects do not provide phase and will be set to order: // 0 - non-message producing // 1 - message producing for (TSmartConstMapIterator object(*_integrationObjectCollection); object; object++) { SmartPtrILifecycle lifecycleObj; lifecycleObj.QueryInterface(*object, false); if (lifecycleObj) { SmartPtrISmartLifecycle smartLifecycleObj; smartLifecycleObj.QueryInterface(*object, false); if (smartLifecycleObj) { SmartPtrIPhased phasedObj; phasedObj.QueryInterface(*object, false); if (phasedObj) { _lifecycleBeans.insert( LifecycleBeans::value_type( phasedObj->getPhase(), lifecycleObj)); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "ISmartLifecycle object '%s' must also " "support the IPhased interface.", object.getKey().c_str()); } } else { SmartPtrIMessageProducer messageProducer; messageProducer.QueryInterface(*object, false); _lifecycleBeans.insert( LifecycleBeans::value_type( messageProducer && messageProducer->isMessageProducer() ? 1 : 0, lifecycleObj)); } } } if (_lifecycleBeans.size() && CAF_CM_IS_LOG_DEBUG_ENABLED) { CAF_CM_LOG_DEBUG_VA0("Lifecycle startup order:"); for (TSmartConstMultimapIterator lcBean(_lifecycleBeans); lcBean; lcBean++) { SmartPtrIIntegrationObject obj; obj.QueryInterface(*lcBean); CAF_CM_LOG_DEBUG_VA2( " [phase=%d][id=%s]", lcBean.getKey(), obj->getId().c_str()); } } // Start the lifecycle objects if (startLifecycleBeans) { _lifecycleBeansStarted = true; startStop(_lifecycleBeans, _timeoutMs, true); } _isInitialized = true; } void CIntegrationAppContext::startLifecycleBeans() { CAF_CM_FUNCNAME_VALIDATE("startLifecycleBeans"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_PRECOND_ISNOTINITIALIZED(_lifecycleBeansStarted); _lifecycleBeansStarted = true; startStop(_lifecycleBeans, _timeoutMs, true); } void CIntegrationAppContext::terminate(const uint32 timeoutMs) { CAF_CM_FUNCNAME("terminate"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_PRECOND_ISINITIALIZED(_lifecycleBeansStarted); try { _weakSelfReference->set(NULL); startStop(_lifecycleBeans, timeoutMs, false); _isInitialized = false; _isIntegrationObjectCollectionReady = false; _channelResolver = NULL; _integrationObjectCollection->clear(); _integrationObjectCollection = NULL; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; try { _applicationContext->terminate(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; try { _applicationContext = NULL; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } SmartPtrIIntegrationObject CIntegrationAppContext::getIntegrationObject( const std::string& id) const { CAF_CM_FUNCNAME("getIntegrationObject"); CAF_CM_VALIDATE_STRING(id); CAF_CM_PRECOND_ISINITIALIZED(_isIntegrationObjectCollectionReady); CIntegrationObjectCollection::const_iterator objIter = _integrationObjectCollection->find(id); SmartPtrIIntegrationObject object; if (objIter != _integrationObjectCollection->end()) { object = objIter->second; } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Integration object [id=%s] is not in the collection", id.c_str()); } return object; } void CIntegrationAppContext::getIntegrationObject(const IID& iid, void **ppv) const { CAF_CM_FUNCNAME("getIntegrationObject"); CAF_CM_PRECOND_ISINITIALIZED(_isIntegrationObjectCollectionReady); CAF_CM_VALIDATE_PTR(ppv); for (TSmartConstMapIterator objIter(*_integrationObjectCollection); objIter; objIter++) { void *result; (*objIter).QueryInterface(iid, &result); if (result) { if (*ppv) { CAF_CM_EXCEPTIONEX_VA1( DuplicateElementException, 0, "More than one integration object [iid=%s] was found.", BasePlatform::UuidToString(iid).c_str()); } else { *ppv = result; } } } if (!*ppv) { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Integration object [iid=%s] is not in the collection", BasePlatform::UuidToString(iid).c_str()); } } IIntegrationAppContext::SmartPtrCObjectCollection CIntegrationAppContext::getIntegrationObjects(const IID& iid) const { CAF_CM_FUNCNAME_VALIDATE("getIntegrationObjects"); SmartPtrCObjectCollection collection; collection.CreateInstance(); CAF_CM_PRECOND_ISINITIALIZED(_isIntegrationObjectCollectionReady); for (TSmartMapIterator objIter(*_integrationObjectCollection); objIter; objIter++) { void *result; (*objIter).QueryInterface(iid, &result); if (result) { collection->push_back(*objIter); objIter->Release(); } } return collection; } SmartPtrIBean CIntegrationAppContext::getBean(const std::string& name) const { CAF_CM_FUNCNAME_VALIDATE("getBean"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); return _applicationContext->getBean(name); } SmartPtrIMessageChannel CIntegrationAppContext::resolveChannelName( const std::string& channelName) const { CAF_CM_FUNCNAME_VALIDATE("resolveChannelName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(channelName); return _channelResolver->resolveChannelName(channelName); } SmartPtrIIntegrationObject CIntegrationAppContext::resolveChannelNameToObject( const std::string& channelName) const { CAF_CM_FUNCNAME_VALIDATE("resolveChannelNameToObject"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(channelName); return _channelResolver->resolveChannelNameToObject(channelName); } SmartPtrCIntegrationObjectCollection CIntegrationAppContext::assign( const IAppContext::SmartPtrCBeans& contextBeans, const Cdeqstr& beanConfigPathCollection) const { CAF_CM_FUNCNAME("assign"); CAF_CM_VALIDATE_SMARTPTR(contextBeans); CAF_CM_VALIDATE_STL(beanConfigPathCollection); SmartPtrCIntegrationObjectCollection integrationObjectCollection; integrationObjectCollection.CreateInstance(); addBuiltIn("nullChannelBean", contextBeans, integrationObjectCollection); addBuiltIn("errorChannelBean", contextBeans, integrationObjectCollection); // Parse the bean config file for (TConstIterator beanConfigPathIter(beanConfigPathCollection); beanConfigPathIter; beanConfigPathIter++) { const std::string beanConfigPath = *beanConfigPathIter; const SmartPtrCXmlElement configBeanRoot = CXmlUtils::parseFile(beanConfigPath, "caf:beans"); const CXmlElement::SmartPtrCElementCollection configBeanChildren = configBeanRoot->getAllChildren(); for (TSmartConstMapIterator configBeanIter(*configBeanChildren); configBeanIter; configBeanIter++) { const SmartPtrCXmlElement configBean = *configBeanIter; // if the child is anything but a bean... if ((configBean->getName() != "bean") && (configBean->getName() != "import")) { SmartPtrCDocument document; document.CreateInstance(); document->initialize(configBean); const SmartPtrIDocument configSection = document; SmartPtrIIntegrationObject integrationObject; for (TSmartConstMapIterator contextBeanIter(*contextBeans); contextBeanIter; contextBeanIter++) { const SmartPtrIBean contextBean = *contextBeanIter; SmartPtrIIntegrationComponent integrationComponent; integrationComponent.QueryInterface(contextBean, false); if (!integrationComponent.IsNull() && integrationComponent->isResponsible(configSection)) { integrationObject = integrationComponent->createObject(configSection); if (!integrationObject) { CAF_CM_EXCEPTIONEX_VA2( NullPointerException, 0, "Component took responsibility for section - beanId: %s," " section: %s - but createObject() returned NULL", contextBeanIter.getKey().c_str(), configSection->getName().c_str()); } CAF_CM_LOG_DEBUG_VA3( "Component took responsibility for section - beanId: %s, section: %s, id: %s", contextBeanIter.getKey().c_str(), configSection->getName().c_str(), integrationObject->getId().c_str()); break; } } if (integrationObject.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Nothing took responsibility for the section: %s", configBean->saveToStringRaw().c_str()); } const std::string id = integrationObject->getId(); if (integrationObjectCollection->find(id) != integrationObjectCollection->end()) { CAF_CM_EXCEPTIONEX_VA1(DuplicateElementException, ERROR_ALREADY_EXISTS, "Duplicate id: %s", id.c_str()); } integrationObjectCollection->insert(std::make_pair(id, integrationObject)); } } } return integrationObjectCollection; } void CIntegrationAppContext::injectChannelInterceptors( const SmartPtrCIntegrationObjectCollection& integrationObjectCollection) const { CAF_CM_FUNCNAME("injectChannelInterceptors"); CAF_CM_VALIDATE_SMARTPTR(integrationObjectCollection); CAF_CM_LOG_DEBUG_VA0("Searching for Channels and ChannelInterceptors"); // Build two collections: Channels and ChannelInterceptors // ChannelInterceptors are wired in order, if specified. // Order does not need to be unique. Multiple interceptors at the same // order will be wired in first-seen order. typedef std::multimap CChannelInterceptorMap; CChannelInterceptorMap channelInterceptors; typedef std::list CChannelList; CChannelList channels; for (TSmartConstMapIterator object(*integrationObjectCollection); object; object++) { SmartPtrIMessageChannel channel; channel.QueryInterface(*object, false); if (channel) { channels.push_back(channel); } else { SmartPtrIChannelInterceptorInstance interceptorInstance; interceptorInstance.QueryInterface(*object, false); if (interceptorInstance) { channelInterceptors.insert( CChannelInterceptorMap::value_type( interceptorInstance->getOrder(), interceptorInstance)); } } } if (channelInterceptors.size()) { // For each channel create a list of ChannelInterceptors that // apply to it and add the list to the channel. for (TSmartConstIterator channel(channels); channel; channel++) { // Get the channel id SmartPtrIIntegrationObject integrationObj; integrationObj.QueryInterface(*channel); const std::string channelId = integrationObj->getId(); // Channels must support the IChannelInterceptorSupport interface SmartPtrIChannelInterceptorSupport interceptorSupport; interceptorSupport.QueryInterface(*channel, false); if (!interceptorSupport) { CAF_CM_EXCEPTIONEX_VA1( UnsupportedOperationException, E_NOINTERFACE, "Channel [%s] does not support the required " "IChannelInterceptorSupport interface", channelId.c_str()); } IChannelInterceptorSupport::InterceptorCollection interceptors; for (TSmartConstMultimapIterator interceptorInstance(channelInterceptors); interceptorInstance; interceptorInstance++) { integrationObj.QueryInterface(*interceptorInstance); const std::string interceptorId = integrationObj->getId(); if (interceptorInstance->isChannelIdMatched(channelId)) { CAF_CM_LOG_DEBUG_VA3( "Adding interceptor [id=%s order=%d] to channel [%s]", interceptorId.c_str(), interceptorInstance->getOrder(), channelId.c_str()); SmartPtrIChannelInterceptor interceptor; interceptor.QueryInterface(*interceptorInstance); interceptors.push_back(interceptor); } } if (interceptors.size()) { interceptorSupport->setInterceptors(interceptors); } } } else { CAF_CM_LOG_DEBUG_VA0("No ChannelInterceptors were found"); } } void CIntegrationAppContext::wire( const SmartPtrIAppContext& appContext, const SmartPtrCIntegrationObjectCollection& integrationObjectCollection, const SmartPtrCChannelResolver& channelResolver) const { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_SMARTPTR(integrationObjectCollection); for (TSmartConstMapIterator integrationObjectIter(*integrationObjectCollection); integrationObjectIter; integrationObjectIter++) { const SmartPtrIIntegrationObject integrationObject = *integrationObjectIter; SmartPtrIIntegrationComponentInstance integrationComponentInstance; integrationComponentInstance.QueryInterface(integrationObject, false); if (integrationComponentInstance) { CAF_CM_LOG_DEBUG_VA1( "Wiring - id: %s", integrationObject->getId().c_str()); integrationComponentInstance->wire(appContext, channelResolver); } } } void CIntegrationAppContext::startStop( const LifecycleBeans& lifecycleBeans, const uint32 timeoutMs, const bool isStart) const { CAF_CM_FUNCNAME("startStop"); if (isStart) { for (LifecycleBeans::const_iterator lifecycleObjIter = lifecycleBeans.begin(); lifecycleObjIter != lifecycleBeans.end(); ++lifecycleObjIter) { SmartPtrILifecycle lifecycleObj = lifecycleObjIter->second; SmartPtrIIntegrationObject integrationObj; integrationObj.QueryInterface(lifecycleObj, true); bool bAutoStart = true; SmartPtrISmartLifecycle smartLifecycleObj; smartLifecycleObj.QueryInterface(lifecycleObj, false); if (smartLifecycleObj) { bAutoStart = smartLifecycleObj->isAutoStartup(); } if (bAutoStart) { CAF_CM_LOG_DEBUG_VA2( "Starting lifecycle object [phase:%d][id:%s]", lifecycleObjIter->first, integrationObj->getId().c_str()); lifecycleObj->start(timeoutMs); } else { CAF_CM_LOG_DEBUG_VA2( "Skipping lifecycle object start [phase:%d][id:%s] " "because isAutoStartup=false", lifecycleObjIter->first, integrationObj->getId().c_str()); } } } else { for (LifecycleBeans::const_reverse_iterator lifecycleObjIter = lifecycleBeans.rbegin(); lifecycleObjIter != lifecycleBeans.rend(); ++lifecycleObjIter) { try { SmartPtrILifecycle lifecycleObj = lifecycleObjIter->second; SmartPtrIIntegrationObject integrationObj; integrationObj.QueryInterface(lifecycleObj, true); CAF_CM_LOG_DEBUG_VA2( "Stopping lifecycle object [phase:%d][id:%s]", lifecycleObjIter->first, integrationObj->getId().c_str()); lifecycleObj->stop(timeoutMs); } CAF_CM_CATCH_ALL; CAF_CM_LOG_ERROR_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } } } void CIntegrationAppContext::addBuiltIn( const std::string& beanId, const IAppContext::SmartPtrCBeans& beans, SmartPtrCIntegrationObjectCollection& integrationObjectCollection) const { CAF_CM_FUNCNAME_VALIDATE("addBuiltIn"); CAF_CM_VALIDATE_STRING(beanId); CAF_CM_VALIDATE_SMARTPTR(beans); CAF_CM_VALIDATE_SMARTPTR(integrationObjectCollection); const SmartPtrIDocument configSection; const IAppContext::CBeans::const_iterator beanIter = beans->find(beanId); if (beanIter != beans->end()) { const SmartPtrIBean bean = beanIter->second; SmartPtrIIntegrationComponent integrationComponent; integrationComponent.QueryInterface(bean, false); if (!integrationComponent.IsNull()) { const SmartPtrIIntegrationObject integrationObject = integrationComponent->createObject(configSection); const std::string id = integrationObject->getId(); integrationObjectCollection->insert(std::make_pair(id, integrationObject)); } } } std::string CIntegrationAppContext::getDefaultBeanConfigPath() const { CAF_CM_FUNCNAME("getDefaultBeanConfigPath"); // Get the bean config file const std::string appConfigKey = "bean_config_file"; std::string beanConfigPath = AppConfigUtils::getRequiredString(appConfigKey); beanConfigPath = CStringUtils::expandEnv(beanConfigPath); if (!FileSystemUtils::doesFileExist(beanConfigPath)) { CAF_CM_EXCEPTIONEX_VA2(FileNotFoundException, ERROR_FILE_NOT_FOUND, "The bean config file does not exist - appConfigKey: %s, file: %s", appConfigKey.c_str(), beanConfigPath.c_str()); } return beanConfigPath; } Cdeqstr CIntegrationAppContext::getBeanConfigFiles( const std::string& beanConfigPath) const { CAF_CM_FUNCNAME("getBeanConfigFiles"); CAF_CM_VALIDATE_STRING(beanConfigPath); // Get the bean config file const std::string beanConfigPathExp = CStringUtils::expandEnv(beanConfigPath); if (!FileSystemUtils::doesFileExist(beanConfigPathExp)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "The bean config file does not exist - file: %s", beanConfigPathExp.c_str()); } CAF_CM_LOG_DEBUG_VA1("Adding bean file - %s", beanConfigPathExp.c_str()); Cdeqstr beanConfigPathCollection; beanConfigPathCollection.push_front(beanConfigPathExp); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(beanConfigPathExp, "caf:beans"); const CXmlElement::SmartPtrCElementCollection beanChildrenXml = rootXml->getAllChildren(); CAF_CM_VALIDATE_SMARTPTR(beanChildrenXml); const std::string beanConfigDirname = FileSystemUtils::getDirname(beanConfigPathExp); for (TSmartConstMapIterator beanXmlIter(*beanChildrenXml); beanXmlIter; beanXmlIter++) { if (beanXmlIter.getKey().compare("import") == 0) { const SmartPtrCXmlElement importXml = *beanXmlIter; const std::string import = importXml->findRequiredAttribute("resource"); const std::string importExp = CStringUtils::expandEnv(import); std::string importPath = FileSystemUtils::buildPath(beanConfigDirname, importExp); if (! FileSystemUtils::doesFileExist(importPath)) { importPath = importExp; if (! FileSystemUtils::doesFileExist(importPath)) { CAF_CM_EXCEPTIONEX_VA2(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Import does not exist - origFile: %s, importPath: %s", beanConfigPath.c_str(), importPath.c_str()); } } CAF_CM_LOG_DEBUG_VA1("Adding bean file - %s", importPath.c_str()); beanConfigPathCollection.push_front(importPath); } } return beanConfigPathCollection; } CIntegrationAppContext:: CIntegrationAppContextWeakReference::CIntegrationAppContextWeakReference() : _context(NULL), CAF_CM_INIT("CIntegrationAppContext") { CAF_CM_INIT_THREADSAFE; } void CIntegrationAppContext:: CIntegrationAppContextWeakReference::set(CIntegrationAppContext *context) { CAF_CM_LOCK_UNLOCK; _context = context; } SmartPtrIIntegrationObject CIntegrationAppContext:: CIntegrationAppContextWeakReference::getIntegrationObject( const std::string& id) const { CAF_CM_FUNCNAME_VALIDATE("getIntegrtationObject"); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_context); return _context->getIntegrationObject(id); } void CIntegrationAppContext:: CIntegrationAppContextWeakReference::getIntegrationObject( const IID& iid, void **ppv) const { CAF_CM_FUNCNAME_VALIDATE("getIntegrtationObject"); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_context); _context->getIntegrationObject(iid, ppv); } IIntegrationAppContext::SmartPtrCObjectCollection CIntegrationAppContext:: CIntegrationAppContextWeakReference::getIntegrationObjects( const IID& iid) const { CAF_CM_FUNCNAME_VALIDATE("getIntegrtationObjects"); CAF_CM_LOCK_UNLOCK; CAF_CM_VALIDATE_PTR(_context); return _context->getIntegrationObjects(iid); } CMessageHandler.cpp000066400000000000000000000123311321503522500366520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "ICafObject.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/Core/CMessageHandler.h" #include "Exception/CCafException.h" using namespace Caf; CMessageHandler::CMessageHandler() : _isInitialized(false), CAF_CM_INIT_LOG("CMessageHandler") { } CMessageHandler::~CMessageHandler() { } void CMessageHandler::initialize( const std::string& inputId, const SmartPtrIMessageChannel& outputMessageChannel, const SmartPtrICafObject& messageHandlerObj) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(inputId); // outputMessageChannel is optional // // messageHandlerObj optional but if provided must be one of // ITransformer // IMessageProcessor // IMessageSplitter // IMessageRouter // IMessageHandler // // messageHandlerObj may also support IErrorProcessor _inputId = inputId; _outputMessageChannel = outputMessageChannel; if (messageHandlerObj) { _transformer.QueryInterface(messageHandlerObj, false); _errorProcessor.QueryInterface(messageHandlerObj, false); _messageProcessor.QueryInterface(messageHandlerObj, false); _messageSplitter.QueryInterface(messageHandlerObj, false); _messageRouter.QueryInterface(messageHandlerObj, false); _messageHandler.QueryInterface(messageHandlerObj, false); if (!_transformer && !_errorProcessor && !_messageProcessor && !_messageSplitter && !_messageRouter && !_messageHandler) { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "The messageHandler object '%s' does not have " "a supported endpoint interface", _inputId.c_str()); } } _isInitialized = true; } std::string CMessageHandler::getInputId() const { CAF_CM_FUNCNAME_VALIDATE("getInputId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _inputId; } void CMessageHandler::handleMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _savedMessage = message; const std::string isThrowableStr = message->findOptionalHeaderAsString(MessageHeaders::_sIS_THROWABLE); const bool isThrowable = (isThrowableStr.empty() || (isThrowableStr.compare("false") == 0)) ? false : true; if (isThrowable) { if (! _errorProcessor.IsNull()) { _savedMessage = _errorProcessor->processErrorMessage(message); if (_savedMessage.IsNull()) { CAF_CM_LOG_WARN_VA1( "Error processing did not return a message - %s", _inputId.c_str()); } else { CAF_CM_VALIDATE_INTERFACE(_outputMessageChannel); _outputMessageChannel->send(_savedMessage); } } else { CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, ERROR_INVALID_STATE, "Nothing handled the throwable message - %s", _inputId.c_str()); } } else { if (_inputId.compare("errorChannel") == 0) { CAF_CM_LOG_WARN_VA1( "Received non-error on error channel - %s", _inputId.c_str()); } else if (! _messageSplitter.IsNull()) { const IMessageSplitter::SmartPtrCMessageCollection outputMessageCollection = _messageSplitter->splitMessage(message); if (outputMessageCollection.IsNull() || outputMessageCollection->empty()) { CAF_CM_LOG_WARN_VA1( "Splitter did not split the message - %s", _inputId.c_str()); } else { CAF_CM_VALIDATE_INTERFACE(_outputMessageChannel); for (TSmartConstIterator outputMessageIter(*outputMessageCollection); outputMessageIter; outputMessageIter++) { _savedMessage = *outputMessageIter; _outputMessageChannel->send(_savedMessage); } } } else if (! _messageRouter.IsNull()) { CAF_CM_VALIDATE_BOOL(_outputMessageChannel.IsNull()); _messageRouter->routeMessage(message); } else if (! _messageProcessor.IsNull()) { _savedMessage = _messageProcessor->processMessage(message); if (_savedMessage.IsNull()) { CAF_CM_LOG_WARN_VA1( "Message processing did not return a message - %s", _inputId.c_str()); } else { CAF_CM_VALIDATE_INTERFACE(_outputMessageChannel); _outputMessageChannel->send(_savedMessage); } } else if (! _transformer.IsNull()) { _savedMessage = _transformer->transformMessage(message); if (_savedMessage.IsNull()) { CAF_CM_LOG_WARN_VA1( "Transform did not return a message - %s", _inputId.c_str()); } else { CAF_CM_VALIDATE_INTERFACE(_outputMessageChannel); _outputMessageChannel->send(_savedMessage); } } else if (! _messageHandler.IsNull()) { _messageHandler->handleMessage(message); } else if (! _outputMessageChannel.IsNull()) { _outputMessageChannel->send(message); } else { CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, ERROR_INVALID_STATE, "Nothing handled the message - %s", _inputId.c_str()); } } } SmartPtrIIntMessage CMessageHandler::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _savedMessage; } void CMessageHandler::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _savedMessage = NULL; } CMessageHeaderUtils.cpp000066400000000000000000000132431321503522500375110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: April 6, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "Integration/Core/CMessageHeaderUtils.h" using namespace Caf; std::string CMessageHeaderUtils::getStringReq( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { CAF_CM_STATIC_FUNC("CMessageHeaderUtils", "getStringReq"); if (headers->find(tag) == headers->end()) { CAF_CM_EXCEPTION_VA1(ERROR_NOT_FOUND, "Header not found: %s", tag.c_str()); } return getStringOpt(headers, tag); } std::string CMessageHeaderUtils::getStringOpt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { std::string rc = 0; IIntMessage::CHeaders::const_iterator iter = headers->find(tag); if (iter != headers->end()) { rc = iter->second.first->toString(); } return rc; } uint8 CMessageHeaderUtils::getUint8Req( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { CAF_CM_STATIC_FUNC("CMessageHeaderUtils", "getUint8Req"); if (headers->find(tag) == headers->end()) { CAF_CM_EXCEPTION_VA1(ERROR_NOT_FOUND, "Header not found: %s", tag.c_str()); } return getUint8Opt(headers, tag); } uint8 CMessageHeaderUtils::getUint8Opt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { uint8 rc = 0; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_BYTE)) { rc = g_variant_get_byte(header->second.first->get()); } else { rc = CStringConv::fromString(header->second.first->toString()); } } return rc; } uint16 CMessageHeaderUtils::getUint16Req( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { CAF_CM_STATIC_FUNC("CMessageHeaderUtils", "getUint16Req"); if (headers->find(tag) == headers->end()) { CAF_CM_EXCEPTION_VA1(ERROR_NOT_FOUND, "Header not found: %s", tag.c_str()); } return getUint16Opt(headers, tag); } uint16 CMessageHeaderUtils::getUint16Opt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { uint16 rc = 0; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_UINT16)) { rc = g_variant_get_uint16(header->second.first->get()); } else { rc = CStringConv::fromString(header->second.first->toString()); } } return rc; } uint32 CMessageHeaderUtils::getUint32Req( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { CAF_CM_STATIC_FUNC("CMessageHeaderUtils", "getUint32Req"); if (headers->find(tag) == headers->end()) { CAF_CM_EXCEPTION_VA1(ERROR_NOT_FOUND, "Header not found: %s", tag.c_str()); } return getUint32Opt(headers, tag); } uint32 CMessageHeaderUtils::getUint32Opt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { uint32 rc = 0; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_UINT32)) { rc = g_variant_get_uint32(header->second.first->get()); } else { rc = CStringConv::fromString(header->second.first->toString()); } } return rc; } uint64 CMessageHeaderUtils::getUint64Req( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { CAF_CM_STATIC_FUNC("CMessageHeaderUtils", "getUint64Req"); if (headers->find(tag) == headers->end()) { CAF_CM_EXCEPTION_VA1(ERROR_NOT_FOUND, "Header not found: %s", tag.c_str()); } return getUint64Opt(headers, tag); } uint64 CMessageHeaderUtils::getUint64Opt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { uint64 rc = 0; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_UINT64)) { rc = g_variant_get_uint64(header->second.first->get()); } else { rc = CStringConv::fromString(header->second.first->toString()); } } return rc; } bool CMessageHeaderUtils::getBoolReq( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { CAF_CM_STATIC_FUNC("CMessageHeaderUtils", "getBoolReq"); if (headers->find(tag) == headers->end()) { CAF_CM_EXCEPTION_VA1(ERROR_NOT_FOUND, "Header not found: %s", tag.c_str()); } return getBoolOpt(headers, tag); } bool CMessageHeaderUtils::getBoolOpt( const IIntMessage::SmartPtrCHeaders& headers, const std::string& tag) { bool rc = false; IIntMessage::CHeaders::const_iterator header = headers->find(tag); if (header != headers->end()) { if (g_variant_is_of_type(header->second.first->get(), G_VARIANT_TYPE_BOOLEAN)) { rc = g_variant_get_boolean(header->second.first->get()); } else { const std::string val = header->second.first->toString(); rc = true; if ((val == "0") || (g_ascii_strncasecmp(val.c_str(), "false", val.length()) == 0)) { rc = false; } } } return rc; } void CMessageHeaderUtils::log( const IIntMessage::SmartPtrCHeaders& headers, const log4cpp::Priority::PriorityLevel priorityLevel) { CAF_CM_STATIC_FUNC_LOG_ONLY("CMessageHeaderUtils", "log"); if (_logger.isPriorityEnabled(priorityLevel)) { for (IIntMessage::CHeaders::const_iterator headerIter = headers->begin(); headerIter != headers->end(); headerIter++) { std::stringstream logMessage; logMessage << '[' << headerIter->first << '=' << headerIter->second.first->toString() << ']'; _logger.logVA(priorityLevel, _cm_funcName_, __LINE__, logMessage.str().c_str()); } } } CMessagingTemplate.cpp000066400000000000000000000121251321503522500374020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "ICafObject.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CMessageHandler.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/Core/CSourcePollingChannelAdapter.h" #include "Integration/IChannelResolver.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" #include "Integration/IPollableChannel.h" #include "Integration/ITaskExecutor.h" #include "Integration/Core/CMessagingTemplate.h" #include "Exception/CCafException.h" using namespace Caf; CMessagingTemplate::CMessagingTemplate() : _isInitialized(false), _isRunning(false), CAF_CM_INIT_LOG("CMessagingTemplate") { } CMessagingTemplate::~CMessagingTemplate() { } void CMessagingTemplate::initialize( const SmartPtrIChannelResolver& channelResolver, const SmartPtrIIntegrationObject& inputIntegrationObject, const SmartPtrIMessageChannel& errorMessageChannel, const SmartPtrIMessageChannel& outputMessageChannel, const SmartPtrICafObject& messageHandlerObj) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(channelResolver); CAF_CM_VALIDATE_INTERFACE(inputIntegrationObject); CAF_CM_VALIDATE_INTERFACE(errorMessageChannel); // outputMessageChannel is optional // // messageHandlerObj optional but if provided must be one of // ITransformer // IMessageProcessor // IMessageSplitter // IMessageRouter // IMessageHandler // // messageHandlerObj may also support IErrorProcessor _inputId = inputIntegrationObject->getId(); SmartPtrCMessageHandler messageHandler; messageHandler.CreateInstance(); messageHandler->initialize( _inputId, outputMessageChannel, messageHandlerObj); SmartPtrIPollableChannel inputPollableChannel; inputPollableChannel.QueryInterface(inputIntegrationObject, false); _inputSubscribableChannel.QueryInterface(inputIntegrationObject, false); if (! _inputSubscribableChannel.IsNull()) { _messagingTemplateHandler.CreateInstance(); _messagingTemplateHandler->initialize(messageHandler); } else if (! inputPollableChannel.IsNull()) { _taskExecutor = createTaskExecutor( channelResolver, messageHandler, inputPollableChannel, errorMessageChannel); } else { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Input object does not support any required interfaces - %s", _inputId.c_str()); } _isInitialized = true; } void CMessagingTemplate::start(const uint32 timeoutMs) { CAF_CM_FUNCNAME("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (! _taskExecutor.IsNull()) { CAF_CM_LOG_DEBUG_VA1("Executing task - %s", _inputId.c_str()); _taskExecutor->execute(timeoutMs); } else if (! _inputSubscribableChannel.IsNull()) { CAF_CM_LOG_DEBUG_VA1("Subscribing handler - %s", _inputId.c_str()); _inputSubscribableChannel->subscribe(_messagingTemplateHandler); } else { CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, E_UNEXPECTED, "Nothing to start: %s", _inputId.c_str()); } } void CMessagingTemplate::stop(const uint32 timeoutMs) { CAF_CM_FUNCNAME("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Stopping"); if (! _taskExecutor.IsNull()) { CAF_CM_LOG_DEBUG_VA1("Canceling task - %s", _inputId.c_str()); _taskExecutor->cancel(timeoutMs); } else if (! _inputSubscribableChannel.IsNull()) { CAF_CM_LOG_DEBUG_VA1("Unsubscribing handler - %s", _inputId.c_str()); _inputSubscribableChannel->unsubscribe(_messagingTemplateHandler); } else { CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, E_UNEXPECTED, "Nothing to stop: %s", _inputId.c_str()); } } bool CMessagingTemplate::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); bool isRunning = true; if (! _taskExecutor.IsNull()) { isRunning = (_taskExecutor->getState() == ITaskExecutor::ETaskStateStarted); } return isRunning; } SmartPtrITaskExecutor CMessagingTemplate::createTaskExecutor( const SmartPtrIChannelResolver& channelResolver, const SmartPtrCMessageHandler& messageHandler, const SmartPtrIPollableChannel& inputPollableChannel, const SmartPtrIMessageChannel& errorMessageChannel) const { CAF_CM_FUNCNAME_VALIDATE("createTaskExecutor"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(channelResolver); CAF_CM_VALIDATE_SMARTPTR(messageHandler); CAF_CM_VALIDATE_INTERFACE(inputPollableChannel); CAF_CM_VALIDATE_INTERFACE(errorMessageChannel); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, errorMessageChannel); SmartPtrCSourcePollingChannelAdapter sourcePollingChannelAdapter; sourcePollingChannelAdapter.CreateInstance(); sourcePollingChannelAdapter->initialize(messageHandler, inputPollableChannel, errorHandler); SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor; simpleAsyncTaskExecutor.CreateInstance(); simpleAsyncTaskExecutor->initialize(sourcePollingChannelAdapter, errorHandler); return simpleAsyncTaskExecutor; } CMessagingTemplateHandler.cpp000066400000000000000000000026721321503522500407060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" #include "Integration/Core/CMessagingTemplateHandler.h" using namespace Caf; CMessagingTemplateHandler::CMessagingTemplateHandler() : _isInitialized(false), CAF_CM_INIT("CMessagingTemplateHandler") { } CMessagingTemplateHandler::~CMessagingTemplateHandler() { } void CMessagingTemplateHandler::initialize( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(messageHandler); _messageHandler = messageHandler; _isInitialized = true; } void CMessagingTemplateHandler::handleMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _messageHandler->handleMessage(message); } SmartPtrIIntMessage CMessagingTemplateHandler::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _messageHandler->getSavedMessage(); } void CMessagingTemplateHandler::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _messageHandler->clearSavedMessage();; } CSimpleAsyncTaskExecutor.cpp000066400000000000000000000137721321503522500405730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CAutoMutex.h" #include "Integration/Core/CIntException.h" #include "Integration/Core/CSimpleAsyncTaskExecutorState.h" #include "Integration/IErrorHandler.h" #include "Integration/IRunnable.h" #include "Integration/ITaskExecutor.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Exception/CCafException.h" using namespace Caf; CSimpleAsyncTaskExecutor::CSimpleAsyncTaskExecutor() : _isInitialized(false), _thread(NULL), CAF_CM_INIT_LOG("CSimpleAsyncTaskExecutor") { CAF_CM_FUNCNAME("CSimpleAsyncTaskExecutor"); try { CAF_CM_INIT_THREADSAFE; CAF_THREADSIGNAL_INIT; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } CSimpleAsyncTaskExecutor::~CSimpleAsyncTaskExecutor() { CAF_CM_FUNCNAME("~CSimpleAsyncTaskExecutor"); try { cancel(0); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; try { if (_thread) { CThreadUtils::join(_thread); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } void CSimpleAsyncTaskExecutor::initialize( const SmartPtrIRunnable& runnable, const SmartPtrIErrorHandler& errorHandler) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(runnable); CAF_CM_VALIDATE_INTERFACE(errorHandler); _state.CreateInstance(); _state->initialize(runnable, errorHandler); _isInitialized = true; } void CSimpleAsyncTaskExecutor::execute( const uint32 timeoutMs) { CAF_CM_FUNCNAME("execute"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (ITaskExecutor::ETaskStateNotStarted == _state->getState()) { // The mutex must be locked before calling waitForStart // and before letting the thread spin up to avoid // a race condition. See g_cond_timed_wait() // // Scope the CAF_THREADSIGNAL_LOCK_UNLOCK so that the // mutex is guaranteed to unlock { CAF_CM_LOG_DEBUG_VA0("Starting the thread"); CAF_THREADSIGNAL_LOCK_UNLOCK; CThreadData threadData = std::make_pair( CAF_THREADSIGNAL_MUTEX, _state.GetNonAddRefedInterface()); CAF_CM_VALIDATE_NULLPTR(_thread); _thread = CThreadUtils::startJoinable(threadFunc, &threadData); CAF_CM_UNLOCK_LOCK; _state->waitForStart(CAF_THREADSIGNAL_MUTEX, timeoutMs); } if (_state->getState() != ITaskExecutor::ETaskStateStarted) { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE, "Not Started: %s", _state->getStateStr().c_str()); } } else if (ITaskExecutor::ETaskStateStarted != _state->getState()) { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE, "Invalid State: %s", _state->getStateStr().c_str()); } CAF_CM_LOG_INFO_VA0("Started"); } void CSimpleAsyncTaskExecutor::cancel( const uint32 timeoutMs) { CAF_CM_FUNCNAME("cancel"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (ITaskExecutor::ETaskStateStarted == _state->getState()) { CAF_CM_LOG_INFO_VA0("Stopping"); _state->setState(ITaskExecutor::ETaskStateStopping); } if (ITaskExecutor::ETaskStateStopping == _state->getState()) { _state->getRunnable()->cancel(); // The mutex must be locked before calling waitForStop // and before letting the thread spin up to avoid // a race condition. See g_cond_timed_wait() // // Scope the CAF_THREADSIGNAL_LOCK_UNLOCK so that the // mutex is guaranteed to unlock { CAF_THREADSIGNAL_LOCK_UNLOCK; CAF_CM_UNLOCK_LOCK; while (! _state->getHasThreadExited()) { _state->waitForStop(CAF_THREADSIGNAL_MUTEX, timeoutMs); } } if (_thread) { CThreadUtils::join(_thread); _thread = NULL; } if (_state->getState() != ITaskExecutor::ETaskStateFinished) { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE, "Not Stopped: %s", _state->getStateStr().c_str()); } } else if (!((ITaskExecutor::ETaskStateFinished == _state->getState()) || (ITaskExecutor::ETaskStateFailed == _state->getState()))) { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE, "Invalid State: %s", _state->getStateStr().c_str()); } CAF_CM_LOG_INFO_VA0("Stopped"); } ITaskExecutor::ETaskState CSimpleAsyncTaskExecutor::getState() const { CAF_CM_FUNCNAME_VALIDATE("getState"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _state->getState(); } void* CSimpleAsyncTaskExecutor::threadFunc(void* data) { CAF_CM_STATIC_FUNC_LOG("CSimpleAsyncTaskExecutor", "threadFunc"); SmartPtrCSimpleAsyncTaskExecutorState state; SmartPtrCAutoMutex mutex; ITaskExecutor::ETaskState stateState = ITaskExecutor::ETaskStateFailed; try { CAF_CM_VALIDATE_PTR(data); CThreadData *threadData = static_cast(data); CAF_CM_VALIDATE_PTR(threadData->first); CAF_CM_VALIDATE_PTR(threadData->second); mutex = threadData->first; state = static_cast(threadData->second); CAF_CM_VALIDATE_SMARTPTR(state); try { state->setState(ITaskExecutor::ETaskStateStarted); CAF_CM_LOCK_UNLOCK1(mutex); state->signalStart(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; if (!CAF_CM_ISEXCEPTION) { try { state->getRunnable()->run(); stateState = ITaskExecutor::ETaskStateFinished; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; } try { if (CAF_CM_ISEXCEPTION) { SmartPtrCIntException intException; intException.CreateInstance(); intException->initialize(CAF_CM_GETEXCEPTION); state->getErrorHandler()->handleError(intException, SmartPtrIIntMessage()); CAF_CM_CLEAREXCEPTION; } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (! state.IsNull()) { try { state->setState(stateState); state->setThreadExited(); CAF_CM_LOCK_UNLOCK1(mutex); state->signalStop(); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } CAF_CM_LOG_INFO_VA0("**** Thread exiting ****"); return NULL; } CSimpleAsyncTaskExecutorState.cpp000066400000000000000000000102311321503522500415570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CAutoMutex.h" #include "Integration/IErrorHandler.h" #include "Integration/IRunnable.h" #include "Integration/Core/CSimpleAsyncTaskExecutorState.h" using namespace Caf; CSimpleAsyncTaskExecutorState::CSimpleAsyncTaskExecutorState() : _isInitialized(false), _hasThreadExited(false), _runnableState(ITaskExecutor::ETaskStateNotStarted), CAF_CM_INIT_LOG("CSimpleAsyncTaskExecutorState") { CAF_CM_INIT_THREADSAFE; } CSimpleAsyncTaskExecutorState::~CSimpleAsyncTaskExecutorState() { } void CSimpleAsyncTaskExecutorState::initialize( const SmartPtrIRunnable& runnable, const SmartPtrIErrorHandler& errorHandler) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(runnable); CAF_CM_VALIDATE_INTERFACE(errorHandler); _runnable = runnable; _errorHandler = errorHandler; _threadSignalStart.initialize("Start"); _threadSignalStop.initialize("Stop"); _isInitialized = true; } ITaskExecutor::ETaskState CSimpleAsyncTaskExecutorState::getState() const { CAF_CM_FUNCNAME_VALIDATE("getState"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _runnableState; } std::string CSimpleAsyncTaskExecutorState::getStateStr() const { CAF_CM_FUNCNAME_VALIDATE("getStateStr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rc; switch(getState()) { case ITaskExecutor::ETaskStateNotStarted: rc = "NotStarted"; break; case ITaskExecutor::ETaskStateStarted: rc = "Started"; break; case ITaskExecutor::ETaskStateStopping: rc = "Stopping"; break; case ITaskExecutor::ETaskStateFinished: rc = "Finished"; break; case ITaskExecutor::ETaskStateFailed: rc = "Failed"; break; default: rc = "Unknown"; break; } return rc; } void CSimpleAsyncTaskExecutorState::setState( const ITaskExecutor::ETaskState runnableState) { CAF_CM_FUNCNAME_VALIDATE("setState"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _runnableState = runnableState; } bool CSimpleAsyncTaskExecutorState::getHasThreadExited() { CAF_CM_FUNCNAME_VALIDATE("getHasThreadExited"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _hasThreadExited; } void CSimpleAsyncTaskExecutorState::setThreadExited() { CAF_CM_FUNCNAME_VALIDATE("setThreadExited"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _hasThreadExited = true; } SmartPtrIRunnable CSimpleAsyncTaskExecutorState::getRunnable() const { CAF_CM_FUNCNAME_VALIDATE("getRunnable"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _runnable; } SmartPtrIErrorHandler CSimpleAsyncTaskExecutorState::getErrorHandler() const { CAF_CM_FUNCNAME_VALIDATE("getErrorHandler"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _errorHandler; } void CSimpleAsyncTaskExecutorState::signalStart() { CAF_CM_FUNCNAME_VALIDATE("signalStart"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA2("Signal (%s) - %p", _threadSignalStart.getName().c_str(), this); _threadSignalStart.signal(); } void CSimpleAsyncTaskExecutorState::waitForStart( SmartPtrCAutoMutex& mutex, const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("waitForStart"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA2("Wait (%s) - waitMs: %d", _threadSignalStart.getName().c_str(), timeoutMs); _threadSignalStart.wait(mutex, timeoutMs); } void CSimpleAsyncTaskExecutorState::signalStop() { CAF_CM_FUNCNAME_VALIDATE("signalStop"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA1("Signal (%s)", _threadSignalStop.getName().c_str()); _threadSignalStop.signal(); } void CSimpleAsyncTaskExecutorState::waitForStop( SmartPtrCAutoMutex& mutex, const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("waitForStop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA2("Wait (%s) - waitMs: %d", _threadSignalStop.getName().c_str(), timeoutMs); _threadSignalStop.wait(mutex, timeoutMs); } CSourcePollingChannelAdapter.cpp000066400000000000000000000071021321503522500413470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntException.h" #include "Integration/IErrorHandler.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" #include "Integration/IPollableChannel.h" #include "Integration/Core/CSourcePollingChannelAdapter.h" using namespace Caf; CSourcePollingChannelAdapter::CSourcePollingChannelAdapter() : _isInitialized(false), _isCancelled(false), _isTimeoutSet(false), _timeout(0), CAF_CM_INIT_LOG("CSourcePollingChannelAdapter") { CAF_CM_INIT_THREADSAFE; CAF_THREADSIGNAL_INIT; } CSourcePollingChannelAdapter::~CSourcePollingChannelAdapter() { } void CSourcePollingChannelAdapter::initialize( const SmartPtrIMessageHandler& messageHandler, const SmartPtrIPollableChannel& inputPollableChannel, const SmartPtrIErrorHandler& errorHandler) { initialize( messageHandler, inputPollableChannel, errorHandler, 0); _isTimeoutSet = false; } void CSourcePollingChannelAdapter::initialize( const SmartPtrIMessageHandler& messageHandler, const SmartPtrIPollableChannel& inputPollableChannel, const SmartPtrIErrorHandler& errorHandler, const int32 timeout) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); CAF_CM_VALIDATE_INTERFACE(inputPollableChannel); CAF_CM_VALIDATE_INTERFACE(errorHandler); _messageHandler = messageHandler; _inputPollableChannel = inputPollableChannel; _pollerMetadata = inputPollableChannel->getPollerMetadata(); _errorHandler = errorHandler; _timeout = timeout; _isTimeoutSet = true; _threadSignalCancel.initialize("Cancel"); _isInitialized = true; } void CSourcePollingChannelAdapter::run() { CAF_CM_FUNCNAME("run"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); uint32 messageCount = 0; SmartPtrIIntMessage message; while (! getIsCancelled()) { try { message = NULL; if (_isTimeoutSet) { message = _inputPollableChannel->receive(_timeout); } else { message = _inputPollableChannel->receive(); } if (! message.IsNull()) { messageCount++; _messageHandler->handleMessage(message); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; if (CAF_CM_ISEXCEPTION) { SmartPtrIIntMessage savedMessage = _messageHandler->getSavedMessage(); if (savedMessage.IsNull()) { savedMessage = message; } SmartPtrCIntException intException; intException.CreateInstance(); intException->initialize(CAF_CM_GETEXCEPTION); _errorHandler->handleError(intException, savedMessage); CAF_CM_CLEAREXCEPTION; } if (message.IsNull() || (messageCount >= _pollerMetadata->getMaxMessagesPerPoll())) { { CAF_THREADSIGNAL_LOCK_UNLOCK; // CAF_CM_LOG_DEBUG_VA2("Wait (%s) - waitMs: %d", // _threadSignalCancel.getName().c_str(), // _pollerMetadata->getFixedRate()); _threadSignalCancel.waitOrTimeout( CAF_THREADSIGNAL_MUTEX, _pollerMetadata->getFixedRate()); } messageCount = 0; } } CAF_CM_LOG_DEBUG_VA0("Finished"); } void CSourcePollingChannelAdapter::cancel() { CAF_CM_FUNCNAME_VALIDATE("cancel"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA1("Signal (%s)", _threadSignalCancel.getName().c_str()); _isCancelled = true; _threadSignalCancel.signal(); } bool CSourcePollingChannelAdapter::getIsCancelled() const { CAF_CM_FUNCNAME_VALIDATE("getIsCancelled"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _isCancelled; } CUnicastingDispatcher.cpp000066400000000000000000000063261321503522500401120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntException.h" #include "Integration/IErrorHandler.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" #include "Integration/Core/CUnicastingDispatcher.h" using namespace Caf; CUnicastingDispatcher::CUnicastingDispatcher() : _isInitialized(false), CAF_CM_INIT_LOG("CUnicastingDispatcher") { } CUnicastingDispatcher::~CUnicastingDispatcher() { } void CUnicastingDispatcher::initialize( const SmartPtrIErrorHandler& errorHandler) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(errorHandler); _errorHandler = errorHandler; _messageHandlerCollection.CreateInstance(); _isInitialized = true; } void CUnicastingDispatcher::addHandler( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("addHandler"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); const void* handlerPtr = messageHandler.GetNonAddRefedInterface(); _messageHandlerCollection->insert(std::make_pair(handlerPtr, messageHandler)); #ifdef __x86_64__ CAF_CM_LOG_DEBUG_VA1("Added handler - %llX", handlerPtr); #else CAF_CM_LOG_DEBUG_VA1("Added handler - %X", handlerPtr); #endif } void CUnicastingDispatcher::removeHandler( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("removeHandler"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); const void* handlerPtr = messageHandler.GetNonAddRefedInterface(); _messageHandlerCollection->erase(handlerPtr); #ifdef __x86_64__ CAF_CM_LOG_DEBUG_VA1("Removed handler - %llX", handlerPtr); #else CAF_CM_LOG_DEBUG_VA1("Removed handler - %X", handlerPtr); #endif } bool CUnicastingDispatcher::dispatch( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("dispatch"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); bool isMessageHandled = false; for (TSmartConstMapIterator messageHandlerIter(*_messageHandlerCollection); ! isMessageHandled && messageHandlerIter; messageHandlerIter++) { const SmartPtrIMessageHandler messageHandler = *messageHandlerIter; #ifdef __x86_64__ CAF_CM_LOG_DEBUG_VA1("Dispatching to handler - %llX", messageHandlerIter.getKey()); #else CAF_CM_LOG_DEBUG_VA1("Dispatching to handler - %X", messageHandlerIter.getKey()); #endif try { messageHandler->handleMessage(message); isMessageHandled = true; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; try { if (CAF_CM_ISEXCEPTION) { CAF_CM_VALIDATE_INTERFACE(messageHandler); SmartPtrIIntMessage savedMessage = messageHandler->getSavedMessage(); if (savedMessage.IsNull()) { savedMessage = message; } SmartPtrCIntException intException; intException.CreateInstance(); intException->initialize(CAF_CM_GETEXCEPTION); _errorHandler->handleError(intException, savedMessage); CAF_CM_CLEAREXCEPTION; } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } return isMessageHandled; } FileHeaders.cpp000066400000000000000000000005301321503522500360360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: 10/19/2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/FileHeaders.h" namespace Caf { namespace FileHeaders { const char* _sFILENAME = "file_name"; const char* _sORIGINAL_FILE = "file_originalFile"; } } MessageHeaders.cpp000066400000000000000000000022441321503522500365470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: 10/19/2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/MessageHeaders.h" namespace Caf { namespace MessageHeaders { // UUID stored as a string const char* _sID = "id"; // int64 const char* _sTIMESTAMP = "timestamp"; // string const char* _sCORRELATION_ID = "correlationId"; // string const char* _sREPLY_CHANNEL = "replyChannel"; // string const char* _sERROR_CHANNEL = "errorChannel"; // int64 const char* _sEXPIRATION_DATE = "expirationDate"; // int32 const char* _sPRIORITY = "priority"; // int32 const char* _sSEQUENCE_NUMBER = "sequenceNumber"; // int32 const char* _sSEQUENCE_SIZE = "sequenceSize"; const char* _sIS_THROWABLE = "_isThrowable_"; // string const char* _sREQUEST_ID = "caf.msg.requestid"; // boolean const char* _sMULTIPART = "caf.msg.multipart"; // string const char* _sMULTIPART_WORKING_DIR = "cafcomm.internal.multipart-working-dir"; // string const char* _sPROTOCOL_TYPE = "caf.protocolType"; // string const char* _sPROTOCOL_CONNSTR = "caf.connStr"; } } stdafx.h000066400000000000000000000007131321503522500346240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Integration/Core/* * Author: bwilliams * Created: Oct 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define INTEGRATIONCORE_LINKAGE __declspec(dllexport) #else #define INTEGRATIONCORE_LINKAGE #endif #include #include #include "Integration/Core/FileHeaders.h" #include "Integration/Core/MessageHeaders.h" #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Logging/000077500000000000000000000000001321503522500314535ustar00rootroot00000000000000CLogger.cpp000066400000000000000000000054701321503522500334300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Logging/* * Author: bwilliams * Created: 1/14/2011 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CLogger.h" using namespace Caf; CLogger::CLogger(const char* className) : _category(log4cpp::Category::getInstance(className)) { } CLogger::~CLogger() { } void CLogger::log( const log4cpp::Priority::PriorityLevel priority, const char* funcName, const int32 lineNumber, const CCafException* cafException) const { if(_category.isPriorityEnabled(priority) && (NULL != cafException)) { logVA(priority, funcName, lineNumber, "0x%08X %s", cafException->getError(), cafException->getFullMsg().c_str()); logBacktrace(log4cpp::Priority::INFO, funcName, lineNumber, *cafException->getBacktrace()); } } void CLogger::logMessage( const log4cpp::Priority::PriorityLevel priority, const char* funcName, const int32 lineNumber, const char* message) const { if(_category.isPriorityEnabled(priority)) { std::stringstream fullMsg; fullMsg << funcName << "|" << lineNumber << "|" << message; _category.log(priority, fullMsg.str()); } } void CLogger::logVA( const log4cpp::Priority::PriorityLevel priority, const char* funcName, const int32 lineNumber, const char* format, ...) const { const int16 logLineLen = 1024; if(_category.isPriorityEnabled(priority)) { char buffer [logLineLen]; va_list args; va_start(args, format); #ifdef WIN32 // Returns -1 if the buffer is truncated. const int rc = vsnprintf_s(buffer, logLineLen, _TRUNCATE, format, args); if (! ((rc > 0) || (rc == -1))) { ::strcpy_s(buffer, "*** INTERNAL ERROR: UNABLE TO FORMAT MESSAGE ***"); #else const int rc = vsnprintf(buffer, logLineLen, format, args); if (! (rc > 0)) { ::strcpy(buffer, "*** INTERNAL ERROR: UNABLE TO FORMAT MESSAGE ***"); #endif } std::stringstream fullMsg; fullMsg << funcName << "|" << lineNumber << "|" << buffer; _category.log(priority, fullMsg.str()); va_end(args); } } bool CLogger::isPriorityEnabled(const log4cpp::Priority::Value priority) const { return _category.isPriorityEnabled(priority); } log4cpp::Priority::Value CLogger::getPriority() const { return _category.getPriority(); } void CLogger::setPriority(const log4cpp::Priority::Value priority) const { _category.setPriority(priority); } void CLogger::logBacktrace( const log4cpp::Priority::PriorityLevel priority, const char* funcName, const int32 lineNumber, const std::deque& backtrace) const { if (backtrace.empty()) { logVA(priority, funcName, lineNumber, "Backtrace is empty"); } else { for (std::deque::const_iterator iter = backtrace.begin(); iter != backtrace.end(); iter++) { std::string name = *iter; if (!name.empty()) { logVA(priority, funcName, lineNumber, "%s", name.c_str()); } } } } open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Logging/CLogger.h000066400000000000000000000023751321503522500331550ustar00rootroot00000000000000/* * Author: bwilliams * Created: 1/14/2011 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CLogger_h_ #define CLogger_h_ namespace Caf { class LOGGING_LINKAGE CLogger { public: CLogger(const char* className); virtual ~CLogger(); public: void log( const log4cpp::Priority::PriorityLevel priority, const char* funcName, const int32 lineNumber, const CCafException* cafException) const; void logMessage( const log4cpp::Priority::PriorityLevel priority, const char* funcName, const int32 lineNumber, const char* message) const; void logVA( const log4cpp::Priority::PriorityLevel priority, const char* funcName, const int32 lineNumber, const char* format, ...) const; void logBacktrace( const log4cpp::Priority::PriorityLevel priority, const char* funcName, const int32 lineNumber, const std::deque& backtrace) const; public: bool isPriorityEnabled(const log4cpp::Priority::Value priority) const; log4cpp::Priority::Value getPriority() const; void setPriority(const log4cpp::Priority::Value priority) const; private: log4cpp::Category& _category; private: CLogger(const CLogger&); CLogger& operator=(const CLogger&); }; } #endif // #define CLogger_h_ LoggingLink.h000066400000000000000000000015151321503522500337530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Logging/* * Author: bwilliams * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef LOGGINGLINK_H_ #define LOGGINGLINK_H_ #ifndef LOGGING_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define LOGGING_LINKAGE __declspec(dllexport) #else #define LOGGING_LINKAGE __declspec(dllimport) #endif #else #define LOGGING_LINKAGE #endif #endif #include #include #define LOG4CPP_FIX_ERROR_COLLISION 1 #include #include #include #include #include #include "../Exception/ExceptionLink.h" #include "CLogger.h" #include "LoggingMacros.h" #endif /* LOGGINGLINK_H_ */ LoggingMacros.h000066400000000000000000000225051321503522500343040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Logging/* * Author: bwilliams * Created: 1/14/2011 * * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef LoggingMacros_h_ #define LoggingMacros_h_ #define CAF_CM_CREATE_LOG \ private: \ CLogger _logger #define CAF_CM_INIT_LOG( _className_ ) \ _cm_className_( _className_ ), \ _logger(_className_) #define CAF_CM_STATIC_FUNC_LOG_VALIDATE( _scope_, _funcName_ ) \ CLogger _logger(_scope_); \ CAF_CM_STATIC_FUNC_VALIDATE( _scope_, _funcName_ ) #define CAF_CM_STATIC_FUNC_LOG_ONLY( _scope_, _funcName_ ) \ CLogger _logger(_scope_); \ CAF_CM_FUNCNAME_VALIDATE( _funcName_ ) #define CAF_CM_STATIC_FUNC_LOG( _scope_, _funcName_ ) \ CLogger _logger(_scope_); \ CAF_CM_STATIC_FUNC( _scope_, _funcName_ ) #define CAF_CM_LOG_GET_PRIORITY (_logger.getPriority()) #define CAF_CM_LOG_SET_PRIORITY(_priorityLevel_) (_logger.setPriority(_priorityLevel_)) #define CAF_CM_IS_LOG_ENABLED(_priorityLevel_) (_logger.isPriorityEnabled(_priorityLevel_)) #define CAF_CM_IS_LOG_DEBUG_ENABLED (_logger.isPriorityEnabled(log4cpp::Priority::DEBUG)) #define CAF_CM_IS_LOG_INFO_ENABLED (_logger.isPriorityEnabled(log4cpp::Priority::INFO)) #define CAF_CM_IS_LOG_WARN_ENABLED (_logger.isPriorityEnabled(log4cpp::Priority::WARN)) #define CAF_CM_IS_LOG_ERROR_ENABLED (_logger.isPriorityEnabled(log4cpp::Priority::ERROR)) #define CAF_CM_IS_LOG_CRIT_ENABLED (_logger.isPriorityEnabled(log4cpp::Priority::CRIT)) /* * Provide priority level */ #define CAF_CM_LOG_CAFEXCEPTION(_priorityLevel_) { \ _logger.log(_priorityLevel_, _cm_funcName_, __LINE__, _cm_exception_); \ } #define CAF_CM_LOG_VA0(_priorityLevel_, _msg_) { \ _logger.logMessage(_priorityLevel_, _cm_funcName_, __LINE__, _msg_); \ } #define CAF_CM_LOG_VA1(_priorityLevel_, _fmt_, _arg1_) { \ _logger.logVA(_priorityLevel_, _cm_funcName_, __LINE__, _fmt_, _arg1_); \ } #define CAF_CM_LOG_VA2(_priorityLevel_, _fmt_, _arg1_, _arg2_) { \ _logger.logVA(_priorityLevel_, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_); \ } #define CAF_CM_LOG_VA3(_priorityLevel_, _fmt_, _arg1_, _arg2_, _arg3_) { \ _logger.logVA(_priorityLevel_, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_); \ } #define CAF_CM_LOG_VA4(_priorityLevel_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_) { \ _logger.logVA(_priorityLevel_, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_); \ } #define CAF_CM_LOG_VA5(_priorityLevel_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_) { \ _logger.logVA(_priorityLevel_, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_); \ } #define CAF_CM_LOG_VA6(_priorityLevel_, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_) { \ _logger.logVA(_priorityLevel_, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_); \ } /* * Debug Macros */ #define CAF_CM_LOG_DEBUG_CAFEXCEPTION { \ _logger.log(log4cpp::Priority::DEBUG, _cm_funcName_, __LINE__, _cm_exception_); \ } #define CAF_CM_LOG_DEBUG_VA0(_msg_) { \ _logger.logMessage(log4cpp::Priority::DEBUG, _cm_funcName_, __LINE__, _msg_); \ } #define CAF_CM_LOG_DEBUG_VA1(_fmt_, _arg1_) { \ _logger.logVA(log4cpp::Priority::DEBUG, _cm_funcName_, __LINE__, _fmt_, _arg1_); \ } #define CAF_CM_LOG_DEBUG_VA2(_fmt_, _arg1_, _arg2_) { \ _logger.logVA(log4cpp::Priority::DEBUG, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_); \ } #define CAF_CM_LOG_DEBUG_VA3(_fmt_, _arg1_, _arg2_, _arg3_) { \ _logger.logVA(log4cpp::Priority::DEBUG, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_); \ } #define CAF_CM_LOG_DEBUG_VA4(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_) { \ _logger.logVA(log4cpp::Priority::DEBUG, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_); \ } #define CAF_CM_LOG_DEBUG_VA5(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_) { \ _logger.logVA(log4cpp::Priority::DEBUG, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_); \ } #define CAF_CM_LOG_DEBUG_VA6(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_) { \ _logger.logVA(log4cpp::Priority::DEBUG, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_); \ } /* * Info Macros */ #define CAF_CM_LOG_INFO_CAFEXCEPTION { \ _logger.log(log4cpp::Priority::INFO, _cm_funcName_, __LINE__, _cm_exception_); \ } #define CAF_CM_LOG_INFO_VA0(_msg_) { \ _logger.logMessage(log4cpp::Priority::INFO, _cm_funcName_, __LINE__, _msg_); \ } #define CAF_CM_LOG_INFO_VA1(_fmt_, _arg1_) { \ _logger.logVA(log4cpp::Priority::INFO, _cm_funcName_, __LINE__, _fmt_, _arg1_); \ } #define CAF_CM_LOG_INFO_VA2(_fmt_, _arg1_, _arg2_) { \ _logger.logVA(log4cpp::Priority::INFO, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_); \ } #define CAF_CM_LOG_INFO_VA3(_fmt_, _arg1_, _arg2_, _arg3_) { \ _logger.logVA(log4cpp::Priority::INFO, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_); \ } #define CAF_CM_LOG_INFO_VA4(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_) { \ _logger.logVA(log4cpp::Priority::INFO, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_); \ } #define CAF_CM_LOG_INFO_VA5(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_) { \ _logger.logVA(log4cpp::Priority::INFO, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_); \ } #define CAF_CM_LOG_INFO_VA6(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_) { \ _logger.logVA(log4cpp::Priority::INFO, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_); \ } /* * Warn Macros */ #define CAF_CM_LOG_WARN_CAFEXCEPTION { \ _logger.log(log4cpp::Priority::WARN, _cm_funcName_, __LINE__, _cm_exception_); \ } #define CAF_CM_LOG_WARN_VA0(_msg_) { \ _logger.logMessage(log4cpp::Priority::WARN, _cm_funcName_, __LINE__, _msg_); \ } #define CAF_CM_LOG_WARN_VA1(_fmt_, _arg1_) { \ _logger.logVA(log4cpp::Priority::WARN, _cm_funcName_, __LINE__, _fmt_, _arg1_); \ } #define CAF_CM_LOG_WARN_VA2(_fmt_, _arg1_, _arg2_) { \ _logger.logVA(log4cpp::Priority::WARN, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_); \ } #define CAF_CM_LOG_WARN_VA3(_fmt_, _arg1_, _arg2_, _arg3_) { \ _logger.logVA(log4cpp::Priority::WARN, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_); \ } #define CAF_CM_LOG_WARN_VA4(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_) { \ _logger.logVA(log4cpp::Priority::WARN, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_); \ } #define CAF_CM_LOG_WARN_VA5(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_) { \ _logger.logVA(log4cpp::Priority::WARN, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_); \ } #define CAF_CM_LOG_WARN_VA6(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_) { \ _logger.logVA(log4cpp::Priority::WARN, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_); \ } /* * Error Macros */ #define CAF_CM_LOG_ERROR_CAFEXCEPTION { \ _logger.log(log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, _cm_exception_); \ } #define CAF_CM_LOG_ERROR_VA0(_msg_) { \ _logger.logMessage(log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, _msg_); \ } #define CAF_CM_LOG_ERROR_VA1(_fmt_, _arg1_) { \ _logger.logVA(log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, _fmt_, _arg1_); \ } #define CAF_CM_LOG_ERROR_VA2(_fmt_, _arg1_, _arg2_) { \ _logger.logVA(log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_); \ } #define CAF_CM_LOG_ERROR_VA3(_fmt_, _arg1_, _arg2_, _arg3_) { \ _logger.logVA(log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_); \ } #define CAF_CM_LOG_ERROR_VA4(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_) { \ _logger.logVA(log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_); \ } #define CAF_CM_LOG_ERROR_VA5(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_) { \ _logger.logVA(log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_); \ } #define CAF_CM_LOG_ERROR_VA6(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_) { \ _logger.logVA(log4cpp::Priority::ERROR, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_); \ } /* * Crit Macros */ #define CAF_CM_LOG_CRIT_CAFEXCEPTION { \ _logger.log(log4cpp::Priority::CRIT, _cm_funcName_, __LINE__, _cm_exception_); \ } #define CAF_CM_LOG_CRIT_VA0(_msg_) { \ _logger.logMessage(log4cpp::Priority::CRIT, _cm_funcName_, __LINE__, _msg_); \ } #define CAF_CM_LOG_CRIT_VA1(_fmt_, _arg1_) { \ _logger.logVA(log4cpp::Priority::CRIT, _cm_funcName_, __LINE__, _fmt_, _arg1_); \ } #define CAF_CM_LOG_CRIT_VA2(_fmt_, _arg1_, _arg2_) { \ _logger.logVA(log4cpp::Priority::CRIT, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_); \ } #define CAF_CM_LOG_CRIT_VA3(_fmt_, _arg1_, _arg2_, _arg3_) { \ _logger.logVA(log4cpp::Priority::CRIT, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_); \ } #define CAF_CM_LOG_CRIT_VA4(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_) { \ _logger.logVA(log4cpp::Priority::CRIT, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_); \ } #define CAF_CM_LOG_CRIT_VA5(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_) { \ _logger.logVA(log4cpp::Priority::CRIT, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_); \ } #define CAF_CM_LOG_CRIT_VA6(_fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_) { \ _logger.logVA(log4cpp::Priority::CRIT, _cm_funcName_, __LINE__, _fmt_, _arg1_, _arg2_, _arg3_, _arg4_, _arg5_, _arg6_); \ } #endif // #define LoggingMacros_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Logging/stdafx.h000066400000000000000000000014051321503522500331150ustar00rootroot00000000000000/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define LOGGING_LINKAGE __declspec(dllexport) #define COMMONAGGREGATOR_LINKAGE __declspec(dllexport) #else #define LOGGING_LINKAGE #define COMMONAGGREGATOR_LINKAGE #endif #include #include #include #define LOG4CPP_FIX_ERROR_COLLISION 1 #include //#include //#include //#include //#include #include "../Exception/ExceptionLink.h" #include "CLogger.h" #include "LoggingMacros.h" #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/PlatformIID.cpp000066400000000000000000000103211321503522500327000ustar00rootroot00000000000000/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "PlatformIID.h" #include #include #ifndef WIN32 #include #include #endif GMutex BasePlatform::gs_BaseIIDInitMutex; using namespace std; namespace BasePlatform { BASEPLATFORM_LINKAGE std::string UuidToString(const UUID& uuid) { stringstream str; str.fill('0'); str.setf(ios_base::uppercase); str.setf(ios_base::hex, ios_base::basefield); str << setw(8) << uuid.Data1; str << '-' << setw(4) << uuid.Data2; str << '-' << setw(4) << uuid.Data3; str << '-' << setw(2) << (int32)uuid.Data4[0]; str << setw(2) << (int32)uuid.Data4[1]; str << '-' << setw(2) << (int32)uuid.Data4[2]; str << setw(2) << (int32)uuid.Data4[3]; str << setw(2) << (int32)uuid.Data4[4]; str << setw(2) << (int32)uuid.Data4[5]; str << setw(2) << (int32)uuid.Data4[6]; str << setw(2) << (int32)uuid.Data4[7]; return str.str(); } unsigned char Char2Bin(const unsigned char cucValue) { unsigned char ucBinValue = 0; if ('0' <= cucValue && '9' >= cucValue) { ucBinValue = cucValue - '0'; } else { ucBinValue = ::tolower(cucValue) - 'a' + 10; } return ucBinValue; } BASEPLATFORM_LINKAGE HRESULT UuidFromString(const char* pszUuid, UUID& uuid) { if (pszUuid) { // Check to see if the guid is surrounded by '{' '}' if (*pszUuid == '{') { pszUuid = &pszUuid[1]; } if (::strlen(pszUuid) >= 36) { if (('-' != pszUuid[8]) || ('-' != pszUuid[13]) || ('-' != pszUuid[18]) || ('-' != pszUuid[23])) { return E_INVALIDARG; } for (int32 iLoop = 0; iLoop < 36; ++iLoop) { if (8 != iLoop && 13 != iLoop && 18 != iLoop && 23 != iLoop) { #if defined (__APPLE__) || defined (__hpux__) || defined (__sun__) || (defined (__linux__) && OS_RELEASE_MAJOR == 2) if (!isxdigit(pszUuid[iLoop])) #else if (!::isxdigit(pszUuid[iLoop])) #endif { return E_INVALIDARG; } } } // so we've validated the string, so now we need to BCD it into // the UUID structure - make a temporary and then memcpy it uuid.Data1 = Char2Bin(pszUuid[0]) << 28; uuid.Data1 |= Char2Bin(pszUuid[1]) << 24; uuid.Data1 |= Char2Bin(pszUuid[2]) << 20; uuid.Data1 |= Char2Bin(pszUuid[3]) << 16; uuid.Data1 |= Char2Bin(pszUuid[4]) << 12; uuid.Data1 |= Char2Bin(pszUuid[5]) << 8; uuid.Data1 |= Char2Bin(pszUuid[6]) << 4; uuid.Data1 |= Char2Bin(pszUuid[7]); uuid.Data2 = Char2Bin(pszUuid[9]) << 12; uuid.Data2 |= Char2Bin(pszUuid[10]) << 8; uuid.Data2 |= Char2Bin(pszUuid[11]) << 4; uuid.Data2 |= Char2Bin(pszUuid[12]); uuid.Data3 = Char2Bin(pszUuid[14]) << 12; uuid.Data3 |= Char2Bin(pszUuid[15]) << 8; uuid.Data3 |= Char2Bin(pszUuid[16]) << 4; uuid.Data3 |= Char2Bin(pszUuid[17]); uuid.Data4[0] = Char2Bin(pszUuid[19]) << 4; uuid.Data4[0] |= Char2Bin(pszUuid[20]); uuid.Data4[1] = Char2Bin(pszUuid[21]) << 4; uuid.Data4[1] |= Char2Bin(pszUuid[22]); uuid.Data4[2] = Char2Bin(pszUuid[24]) << 4; uuid.Data4[2] |= Char2Bin(pszUuid[25]); uuid.Data4[3] = Char2Bin(pszUuid[26]) << 4; uuid.Data4[3] |= Char2Bin(pszUuid[27]); uuid.Data4[4] = Char2Bin(pszUuid[28]) << 4; uuid.Data4[4] |= Char2Bin(pszUuid[29]); uuid.Data4[5] = Char2Bin(pszUuid[30]) << 4; uuid.Data4[5] |= Char2Bin(pszUuid[31]); uuid.Data4[6] = Char2Bin(pszUuid[32]) << 4; uuid.Data4[6] |= Char2Bin(pszUuid[33]); uuid.Data4[7] = Char2Bin(pszUuid[34]) << 4; uuid.Data4[7] |= Char2Bin(pszUuid[35]); return S_OK; } else { return E_INVALIDARG; } } return E_INVALIDARG; } } #ifndef WIN32 HRESULT UuidCreate(UUID* uuid) { if (uuid) { // a uuid is 16 bytes - we'll fill them with a // random number (1st 4 bytes) // the current time in seconds (2nd 4 bytes) // the hostid of the machine (3rd 4 bytes) // the current micro seconds (last 4 bytes) int32 iRand = ::rand(); struct timeval stTimeVal; ::gettimeofday(&stTimeVal, NULL); int32 iHostId = ::gethostid(); byte * pbUuid = reinterpret_cast(uuid); ::memcpy(pbUuid, &iRand, 4); ::memcpy(pbUuid+4, &stTimeVal.tv_sec, 4); ::memcpy(pbUuid+8, &iHostId, 4); ::memcpy(pbUuid+12, &stTimeVal.tv_usec, 4); return S_OK; } else { return OLE_E_BLANK; } } #endif PlatformStringFunc.cpp000066400000000000000000000014361321503522500343050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/* * Author: mdonahue * Created: Jan 13, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "PlatformStringFunc.h" #include using namespace std; namespace BasePlatform { #ifdef fix std::wstring A2W(const std::string& str) { wstringstream wstm ; const ctype& ctfacet = use_facet< ctype >(wstm.getloc()); for (size_t i = 0; i < str.size(); ++i) { wstm << ctfacet.widen(str[i]); } return wstm.str(); } std::string W2A(const std::wstring& str) { ostringstream stm; const ctype& ctfacet = use_facet< ctype >(stm.getloc()); for (size_t i = 0; i < str.size(); ++i) { stm << ctfacet.narrow(str[i], 0); } return stm.str(); } #endif } open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/000077500000000000000000000000001321503522500326165ustar00rootroot00000000000000CAutoMutexLockUnlockRaw.cpp000066400000000000000000000000001321503522500377260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBaseCAutoMutexLockUnlockRaw.h000066400000000000000000000000001321503522500373730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBaseCEcmDllManager.cpp000066400000000000000000000522771321503522500360160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CEcmDllManager.h" #ifndef WIN32 #include #include #include #include #endif #define _MAX_PATH_LARGE 32768 using namespace Caf; GRecMutex CEcmDllManager::ms_mutex; #if !defined( WIN32 ) std::map CEcmDllManager::ms_mapLoadedModuleRefCounts; std::map CEcmDllManager::ms_mapLoadedModules; #endif // Here is where we work out which Unix OS style of dl functions we are // going to use // 1. we have all dl functions we need dlopen, dlclose, dladdr and dlsym // 2. we have all dl functions except dladdr (AIX) #if defined ( __sun__ ) || defined ( __linux__ ) || defined ( WIN32 ) || defined ( __hpux__ ) || defined (__APPLE__) // we have everything we need #elif defined ( _AIX ) #include #include #include extern "C" { extern int32 getargs(struct procsinfo*, int32, char*, int32); } #else #error "Not yet ported to this platform" #endif typedef BOOL (*DllMainPtr) (HINSTANCE, uint32, LPVOID); static const char *gs_cszDllMainFunctionName = "DllMain"; static const char *gs_cszMainFunctionName = "main"; #ifdef _AIX static const char *gs_cszInitFunctionName = "_GLOBAL__DI"; #else static const char *gs_cszInitFunctionName = "_init"; #endif ////////////////////////////////////////////////////////////////////////////// // // LoadLibrary // Loads a shared library from any OS // ////////////////////////////////////////////////////////////////////////////// HMODULE CEcmDllManager::LoadLibrary( const char * cszLibName, bool bMustInvokeDllMain, bool bThrowExceptionUponFailure/* = true */) { CAF_CM_STATIC_FUNC( "CEcmDllManager", "LoadLibrary" ); CAF_CM_VALIDATE_STRINGPTRA( cszLibName ); HMODULE hRetModule = NULL; bool bIsLoaded = false; #if defined (WIN32) const char* libPrefix = NULL; const char* libSuffix = ".dll"; #elif defined (__APPLE__) const char* libPrefix = "lib"; const char* libSuffix = ".dylib"; #elif defined (__linux__) const char* libPrefix = "lib"; const char* libSuffix = ".so"; #else #error 'NOT IMPLEMENTED FOR THIS OPERATING SYSTEM' #endif std::string libName(cszLibName); if (libPrefix != NULL && libName.compare(0, std::string::npos, libPrefix) != 0) { libName.insert(0, libPrefix); } if (libName.find(libSuffix) == std::string::npos) { libName += libSuffix; } try { #if defined ( WIN32 ) hRetModule = ::LoadLibraryExA( libName.c_str(), NULL, 0 ); uint32 rc = ::GetLastError(); if ( NULL != hRetModule ) { bIsLoaded = true; } else { std::string strSystemMessage; if ( ERROR_SUCCESS != rc ) { strSystemMessage = BasePlatform::PlatformApi::GetApiErrorMessage(rc); } else { strSystemMessage = "GetLastError() returned ERROR_SUCCESS but hRetModule is NULL"; } CAF_CM_EXCEPTION_VA2( rc, "Failed to load library: %s Error: %s", libName.c_str(), strSystemMessage.c_str()); } #else bool bLogLoading = ( ::getenv( "SYSLOG_DLOPENS" ) != NULL ); // this needs to be thread safe so that we dont lose the last error // generated if a new thread also calls dlerror - unlike windows, the // error message is not per thread. CAutoMutexLockUnlockRaw oCS( &ms_mutex ); if ( bLogLoading ) ::syslog(LOG_DEBUG, "---- Loading %s", libName.c_str() ); // Let's see if we've already loaded it std::map::iterator it = ms_mapLoadedModuleRefCounts.find( libName.c_str() ); if ( it != ms_mapLoadedModuleRefCounts.end() ) { it->second.m_iRefCount++; hRetModule = it->second.m_hModule; if ( bLogLoading ) #ifdef __x86_64__ ::syslog(LOG_DEBUG," ------ Already loaded as %p count is now %d", hRetModule, it->second.m_iRefCount ); #else ::syslog(LOG_DEBUG," ------ Already loaded as %p count is now %d", hRetModule, it->second.m_iRefCount ); #endif } else { hRetModule = ::dlopen( libName.c_str(), RTLD_NOW | RTLD_LOCAL ); if ( bLogLoading ) #ifdef __x86_64__ ::syslog(LOG_DEBUG," ------ Loaded as %p" , hRetModule); #else ::syslog(LOG_DEBUG," ------ Loaded as %p" , hRetModule); #endif if ( NULL == hRetModule ) { std::string strSystemMessage; const char * pszMessage = dlerror(); if ( NULL != pszMessage ) { strSystemMessage = pszMessage; } else { strSystemMessage = "dlerror() returned NULL"; } CAF_CM_EXCEPTIONEX_VA2( LibraryFailedToLoadException, 0, "Failed to load library: %s Error: %s", libName.c_str(), strSystemMessage.c_str()); } else { bIsLoaded = true; std::string strSubErrorMessage; // not all compilers will call a method on initializing // a shared library, so we will force ourselves to call one // we will mimic the Windows DllMain functionality DllMainPtr pfnDllMain = (DllMainPtr) CEcmDllManager::GetFunctionAddress( hRetModule, gs_cszDllMainFunctionName, strSubErrorMessage ); if ( NULL != pfnDllMain ) { BOOL result = ( *pfnDllMain )( hRetModule, DLL_PROCESS_ATTACH, NULL ); if ( false == result ) { CAF_CM_EXCEPTION_VA2(E_FAIL, "%s in library %s returned false - library not loaded", gs_cszDllMainFunctionName, libName.c_str()); } } else if ( bMustInvokeDllMain ) { CAF_CM_EXCEPTION_VA3(E_FAIL, "Unable to find %s in library %s, Error: %s - library not loaded", gs_cszDllMainFunctionName, libName.c_str(), strSubErrorMessage.c_str()); } SModuleRefCount stRefCount; stRefCount.m_iRefCount = 1; stRefCount.m_hModule = hRetModule; std::string strModuleName( libName.c_str() ); ms_mapLoadedModuleRefCounts.insert( std::make_pair(strModuleName, stRefCount ) ); ms_mapLoadedModules.insert( std::make_pair( hRetModule, strModuleName ) ); } } #endif } catch (CCafException *e) { _cm_exception_ = e; } if ( _cm_exception_ ) { try { if ( bIsLoaded ) { CEcmDllManager::UnloadLibrary( hRetModule, false ); } } catch (CCafException *e) { e->Release(); } // If we were told to eat the exception then do so hRetModule = NULL; if( !bThrowExceptionUponFailure ) { _cm_exception_->Release(); } else { _cm_exception_->throwSelf(); } } return hRetModule; } ////////////////////////////////////////////////////////////////////////////// // // UnloadLibrary // Unloads a shared library from any OS // ////////////////////////////////////////////////////////////////////////////// void CEcmDllManager::UnloadLibrary( HMODULE hLibraryHandle, bool bMustInvokeDllMain ) { CAF_CM_STATIC_FUNC( "CEcmDllManager", "UnloadLibrary" ); CAF_CM_VALIDATE_PTR( hLibraryHandle ); #if defined ( WIN32 ) if ( ! ::FreeLibrary( hLibraryHandle ) ) { uint32 rc = ::GetLastError(); std::string strSystemMessage; if ( ERROR_SUCCESS != rc ) { strSystemMessage = BasePlatform::PlatformApi::GetApiErrorMessage(rc); } else { strSystemMessage = "GetLastError() returned ERROR_SUCCESS"; } CAF_CM_EXCEPTION_VA1( rc, "::FreeLibrary failed: %s", strSystemMessage.c_str()); } #else // this needs to be thread safe so that we dont lose the last error // generated if a new thread also calls dlerror - unlike windows, the // error message is not per thread. bool bLogLoading = ( ::getenv( "SYSLOG_DLOPENS" ) != NULL ); CAutoMutexLockUnlockRaw oCS( &ms_mutex ); if ( bLogLoading ) #ifdef __x86_64__ ::syslog( LOG_DEBUG, "---- Unloading %p", hLibraryHandle ); #else ::syslog( LOG_DEBUG, "---- Unloading %p", hLibraryHandle ); #endif // look for the specific library in our loaded list - // we'll unload if the ref count hits 0 or if it doesn't exist int32 iRefCount = 0; std::map::iterator it = ms_mapLoadedModules.find( hLibraryHandle ); if ( it != ms_mapLoadedModules.end() ) { if ( bLogLoading ) { ::syslog( LOG_DEBUG, "------ Is Library %s", it->second.c_str() ); } std::map::iterator itCnt = ms_mapLoadedModuleRefCounts.find (it->second); if ( itCnt != ms_mapLoadedModuleRefCounts.end() ) { iRefCount = --itCnt->second.m_iRefCount; if ( iRefCount == 0 ) ms_mapLoadedModuleRefCounts.erase( itCnt ); } if ( iRefCount == 0 ) { ms_mapLoadedModules.erase( it ); } } if ( bLogLoading ) ::syslog( LOG_DEBUG, "------ ref count is %d", iRefCount ); if ( iRefCount == 0 ) { // not all compilers will call a method on initializing // a shared library, so we will force ourselves to call one // we will mimic the Windows DllMain functionality std::string strSubErrorMessage; DllMainPtr pfnDllMain = (DllMainPtr) CEcmDllManager::GetFunctionAddress( hLibraryHandle, gs_cszDllMainFunctionName, strSubErrorMessage ); if ( NULL != pfnDllMain ) { BOOL result = ( *pfnDllMain )( hLibraryHandle, DLL_PROCESS_DETACH, NULL ); if ( false == result ) { CAF_CM_EXCEPTION_VA1(E_FAIL, "%s returned false - library not unloaded", gs_cszDllMainFunctionName); } } else if ( bMustInvokeDllMain ) { CAF_CM_EXCEPTION_VA2(E_FAIL, "Unable to find %s, Error: %s, returned false - library not unloaded", gs_cszDllMainFunctionName, strSubErrorMessage.c_str()); } if ( 0 != ::dlclose( hLibraryHandle ) ) { CAF_CM_EXCEPTION_VA1(E_FAIL, "Unable to unload library %s", ::dlerror()); } } #endif } ////////////////////////////////////////////////////////////////////////////// // // GetFunctionAddress // // Finds the specified symbol in a library // ////////////////////////////////////////////////////////////////////////////// void * CEcmDllManager::GetFunctionAddress( HMODULE hLibraryHandle, const char * cszFunctionName, std::string & rstrErrorMessage ) { CAF_CM_STATIC_FUNC_VALIDATE( "CEcmDllManager", "GetFunctionAddress" ); CAF_CM_VALIDATE_STRINGPTRA( cszFunctionName ); // It is legal for a NULL handle to be passed in - NULL is the // executable void * pvRetAddress = NULL; rstrErrorMessage = ""; #if defined ( WIN32 ) pvRetAddress = ::GetProcAddress( hLibraryHandle, cszFunctionName ); if ( NULL == pvRetAddress ) { uint32 rc = ::GetLastError(); rstrErrorMessage = "Unable to locate function "; rstrErrorMessage += cszFunctionName; rstrErrorMessage += ", Error : "; if ( ERROR_SUCCESS != rc ) { rstrErrorMessage += BasePlatform::PlatformApi::GetApiErrorMessage(rc); } else { rstrErrorMessage += "GetLastError() returned ERROR_SUCCESS"; } } #else CAutoMutexLockUnlockRaw oCS( &ms_mutex ); try { pvRetAddress = ::dlsym( hLibraryHandle, cszFunctionName ); } catch (...) { // if we were passed a bad handle, this can cause a seg // violation - so treat it as a regular error // Note : Sometimes we can do nothing about it and the // program will crash pvRetAddress = NULL; } if ( NULL == pvRetAddress ) { rstrErrorMessage = "Unable to locate function "; rstrErrorMessage += cszFunctionName; rstrErrorMessage += ", Error : "; const char * pszError = ::dlerror(); if ( NULL != pszError ) { rstrErrorMessage += pszError; } else { rstrErrorMessage += "dlerror() returned NULL"; } } #endif return pvRetAddress; } ////////////////////////////////////////////////////////////////////////////// // // GetLibraryNameFromHandle // Determines the name of a library from its handle. // We are going to need to add functionality here for AIX 4.3.3 and HPUX10.20 // ////////////////////////////////////////////////////////////////////////////// void CEcmDllManager::GetLibraryNameFromHandle ( HMODULE hLibraryHandle, std::string & rstrLibName ) { CAF_CM_STATIC_FUNC( "CEcmDllManager", "GetLibraryNameFromHandle" ); // it is legal for hLibraryModule to be NULL (it's the executable) // so don't validate it rstrLibName = ""; #if defined ( WIN32 ) char szFilePath[ _MAX_PATH_LARGE ] = {0}; if (0 != ::GetModuleFileNameA( hLibraryHandle, szFilePath, _MAX_PATH_LARGE - 1)) { rstrLibName = szFilePath; } else { uint32 rc = ::GetLastError(); std::string strErrorMessage( "Error Getting Module Name " ); strErrorMessage += ", Error : "; if ( ERROR_SUCCESS != rc ) { strErrorMessage += BasePlatform::PlatformApi::GetApiErrorMessage(rc); } else { strErrorMessage += "GetLastError() returned ERROR_SUCCESS"; } CAF_CM_EXCEPTION_VA0(rc, strErrorMessage.c_str()); } #else // we know that all of our libs must have a DllMain function // so look it up in the specified library and then // use its address to find the name std::string strSubErrorMessage; void * vpAddress = NULL; if ( NULL == hLibraryHandle ) { // if its the NULL handle, we really want to look // at the main program, on AIX we need to get the 1st entry from // loadquery, otherwise we can use dlopen on NULL GetMainProgramName( rstrLibName ); } else { // In a dll we need to look for DllMain vpAddress = CEcmDllManager::GetFunctionAddress( hLibraryHandle, gs_cszDllMainFunctionName, strSubErrorMessage ); if ( NULL == vpAddress ) { // try looking for main as well vpAddress = CEcmDllManager::GetFunctionAddress( hLibraryHandle, gs_cszMainFunctionName, strSubErrorMessage ); } if ( NULL == vpAddress ) { // try looking for _init as well vpAddress = CEcmDllManager::GetFunctionAddress( hLibraryHandle, gs_cszInitFunctionName, strSubErrorMessage ); } if ( vpAddress ) { CEcmDllManager::GetLibraryNameFromAddress( vpAddress, rstrLibName ); } else { CAF_CM_EXCEPTION_VA1(E_FAIL, "Cannot find symbol in library, cannot resolve library handle to file name: %s", strSubErrorMessage.c_str()); } } #endif } ////////////////////////////////////////////////////////////////////////////// // // GetLibraryNameFromAddress // Determines which library/exe contains the specific address (Unix only). // We are going to need to add functionality here for AIX 4.3.3 and HPUX10.20 // ////////////////////////////////////////////////////////////////////////////// void CEcmDllManager::GetLibraryNameFromAddress( const void * cpvAddressInLibrary, std::string & rstrLibName ) { CAF_CM_STATIC_FUNC( "CEcmDllManager", "GetLibraryNameFromAddress" ); char * szBuffer = NULL; try { #if defined ( WIN32 ) CAF_CM_EXCEPTION_VA0( E_NOTIMPL, "CEcmDllManager::GetLibraryNameFromAddress not implemented"); #elif defined ( __sun__ ) || defined ( __linux__ ) || defined ( __hpux__ ) || defined (__APPLE__) CAutoMutexLockUnlockRaw oCS( &ms_mutex ); Dl_info stDlInfo; if ( 0 != ::dladdr( const_cast( cpvAddressInLibrary ), &stDlInfo ) ) { char szFilePath[ 32768 ]; ::realpath( stDlInfo.dli_fname, szFilePath ); rstrLibName = szFilePath; } else { std::string strErrorMessage( "Unable to locate address in library " ); strErrorMessage += ", Error : "; const char * pszError = ::dlerror(); if ( NULL != pszError ) { strErrorMessage += pszError; } else { strErrorMessage += "dlerror() returned NULL"; } CAF_CM_EXCEPTION_EFAIL(strErrorMessage.c_str()); } #elif defined ( _AIX ) szBuffer = static_cast( ::malloc(1024) ); int32 iSize = 1024; int32 iRc = ::loadquery( L_GETINFO, static_cast( szBuffer ),iSize); while ( ( -1 == iRc ) && ( ENOMEM == errno ) ) { ::free( szBuffer ); iSize += 1024; szBuffer = static_cast( ::malloc( iSize ) ); iRc = ::loadquery( L_GETINFO, static_cast( szBuffer ),iSize); } if ( -1 == iRc ) { ::free( szBuffer ); szBuffer = NULL; CAF_CM_EXCEPTION( "::loadquery failed", errno ); } ld_info * pLdInfo = reinterpret_cast( szBuffer ); while ( pLdInfo ) { void * pvUpper = reinterpret_cast( reinterpret_cast( pLdInfo->ldinfo_dataorg) + pLdInfo->ldinfo_datasize ); if ( ( cpvAddressInLibrary >= pLdInfo->ldinfo_dataorg ) && ( cpvAddressInLibrary < pvUpper ) ) { char szFilePath[ _MAX_PATH ]; ::realpath( pLdInfo->ldinfo_filename, szFilePath ); rstrLibName = szFilePath; break; } else { if ( pLdInfo->ldinfo_next == 0 ) pLdInfo = NULL; else pLdInfo = reinterpret_cast ( reinterpret_cast( pLdInfo ) + pLdInfo->ldinfo_next ); } } ::free( szBuffer ); szBuffer = NULL; if ( rstrLibName.length() == 0 ) { CAF_CM_EXCEPTION_EFAIL("Unable to locate address in library"); } #else #error "Not yet implemented on this platform"; #endif } catch(CCafException *e) { _cm_exception_ = e; } if ( szBuffer ) { ::free( szBuffer ); } if ( _cm_exception_ ) { throw _cm_exception_; } } ////////////////////////////////////////////////////////////////////////////// // // GetMainProgramName // Determines the name of the current program. // We are going to need to add functionality here for AIX 4.3.3 and HPUX10.20 // ////////////////////////////////////////////////////////////////////////////// void CEcmDllManager::GetMainProgramName ( std::string & rstrProgName ) { CAF_CM_STATIC_FUNC( "CEcmDllManager", "GetMainProgramName" ); char * szBuffer = NULL; HMODULE hSearchModule = NULL; std::string strSubErrorMessage; try { rstrProgName = ""; #if defined ( WIN32 ) char szFilePath[ _MAX_PATH_LARGE] = {0}; if ( 0 != ::GetModuleFileNameA( NULL, szFilePath, _MAX_PATH_LARGE-1) ) { rstrProgName = szFilePath; } else { uint32 rc = ::GetLastError(); std::string strErrorMessage( "Error Getting Module Name " ); strErrorMessage += ", Error : "; if ( ERROR_SUCCESS != rc ) { strErrorMessage += BasePlatform::PlatformApi::GetApiErrorMessage(rc); } else { strErrorMessage += "GetLastError() returned ERROR_SUCCESS"; } CAF_CM_EXCEPTION_VA0(rc, strErrorMessage.c_str()); } #elif defined ( _AIX ) // on AIX we need to get the 1st entry from // loadquery, otherwise we can use dlopen on NULL szBuffer = static_cast( ::malloc(1024) ); int32 iSize = 1024; int32 iRc = ::loadquery( L_GETINFO, static_cast( szBuffer ),iSize); while ( ( -1 == iRc ) && ( ENOMEM == errno ) ) { ::free( szBuffer ); iSize += 1024; szBuffer = static_cast( ::malloc( iSize ) ); iRc = ::loadquery( L_GETINFO, static_cast( szBuffer ),iSize); } if ( -1 == iRc ) { ::free( szBuffer ); szBuffer = NULL; CAF_CM_EXCEPTION( "::loadquery failed", errno ); } ld_info * pLdInfo = reinterpret_cast( szBuffer ); char szFilePath[ _MAX_PATH ]; if ( NULL == ::realpath( pLdInfo->ldinfo_filename, szFilePath ) ) { std::string strError( "::realpath failed for " ); strError += pLdInfo->ldinfo_filename; strError += " attempting ::getargs"; CAF_CM_WARNING( static_cast( strError ) ); // use getargs to get arg 0 struct procsinfo stProcInfo; stProcInfo.pi_pid = ::getpid(); char aszArgs[_MAX_PATH * 2]; if ( 0 == ::getargs( &stProcInfo, sizeof(procsinfo), aszArgs, _MAX_PATH * 2 ) ) { if ( NULL == ::realpath( aszArgs, szFilePath ) ) { std::string strError( "::realpath failed - using result of getargs "); strError += pLdInfo->ldinfo_filename ; CAF_CM_ERROR( static_cast( strError ), errno ); } else { rstrProgName = szFilePath; } } else { std::string strError( "::getargs failed - using result of loadquery " ); strError += pLdInfo->ldinfo_filename; CAF_CM_ERROR( static_cast( strError ), errno ); } } else { // set from the realpath command rstrProgName = szFilePath; } ::free( szBuffer ); szBuffer = NULL; #elif defined ( __linux__ ) || defined ( __sun__ ) // we know that all of our libs must have a DllMain function // so look it up in the specified library and then // use its address to find the name void * vpAddress = NULL; hSearchModule = ::dlopen( NULL, RTLD_LAZY | RTLD_LOCAL ); if ( ! hSearchModule ) { CAF_CM_EXCEPTION_EFAIL(::dlerror()); } // In a dll we need to look for DllMain vpAddress = CEcmDllManager::GetFunctionAddress( hSearchModule, gs_cszDllMainFunctionName, strSubErrorMessage ); if ( NULL == vpAddress ) { // try looking for main as well vpAddress = CEcmDllManager::GetFunctionAddress( hSearchModule, gs_cszMainFunctionName, strSubErrorMessage ); } if ( NULL == vpAddress ) { // try looking for _init as well vpAddress = CEcmDllManager::GetFunctionAddress( hSearchModule, gs_cszInitFunctionName, strSubErrorMessage ); } if ( vpAddress ) { CEcmDllManager::GetLibraryNameFromAddress( vpAddress, rstrProgName ); } else { std::string strErrorMessage( "Cannot find symbol in library, cannot resolve library handle to file name" ); strErrorMessage += strSubErrorMessage; CAF_CM_EXCEPTION_EFAIL(strErrorMessage.c_str()); } #else CAF_CM_EXCEPTION_VA0(E_NOTIMPL, "Not Yet Ported to this platform"); #endif } catch (CCafException* e) { _cm_exception_ = e; } #ifndef WIN32 if ( hSearchModule ) { ::dlclose(hSearchModule); } #endif if ( szBuffer ) { ::free( szBuffer ); } if ( _cm_exception_ ) { throw _cm_exception_; } } CEcmDllManager.h000066400000000000000000000025451321503522500354540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _CEcmDllManager_H #define _CEcmDllManager_H #include #include namespace Caf { class SUBSYSTEMBASE_LINKAGE CEcmDllManager { public: static HMODULE LoadLibrary( const char * cpszLibName, bool bMustInvokeDllMain,bool bThrowExceptionUponFailure = true ); static void UnloadLibrary( HMODULE hLibraryHandle, bool bMustInvokeDllMain ); static void * GetFunctionAddress( HMODULE hLibraryHandle, const char * cpszFunctionName, std::string & rstrErrorMessage ); static void GetLibraryNameFromHandle ( HMODULE hLibraryHandle, std::string & rstrLibName ); private: // a purely static class CEcmDllManager(); ~CEcmDllManager(); CEcmDllManager( const CEcmDllManager& ); CEcmDllManager& operator=( const CEcmDllManager& ); private: // used internally on Unix platforms static void GetLibraryNameFromAddress( const void * cpvAddressInLibrary, std::string & rstrLibName ); static void GetMainProgramName( std::string & rstrProgName ); private: static GRecMutex ms_mutex; #ifndef WIN32 struct SModuleRefCount { HMODULE m_hModule; int32 m_iRefCount; }; static std::map ms_mapLoadedModuleRefCounts; static std::map ms_mapLoadedModules; #endif }; } #endif // _CEcmDllManager_H CEcmSubSystem.cpp000066400000000000000000000230021321503522500357260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CEcmSubSystem.h" #include "EcmSubSystemBase.h" #include "CEcmSubSystemRegistry.h" #ifdef WIN32 #ifdef CFC_AS_STATIC_LIB #define IStream ::IStream #endif #include #ifdef CFC_AS_STATIC_LIB #undef IStream #endif #endif #include "CEcmDllManager.h" using namespace Caf; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// std::map CEcmSubSystem::m_mapModuleCache; GRecMutex CEcmSubSystem::m_oModuleCacheMutex; CEcmSubSystem::CEcmSubSystem(bool bIsUnloadable) : CAF_CM_INIT_LOG("CEcmSubSystem"), m_bIsUnloadable(bIsUnloadable), m_hModule(NULL), m_pfnCreateInstance(NULL), m_pfnCanUnloadNow(NULL) { } CEcmSubSystem::~CEcmSubSystem() { } bool CEcmSubSystem::IsRegistered( const std::string & rstrSubSystemIdentifier ) { CAF_CM_FUNCNAME_VALIDATE("IsRegistered"); bool bRetVal = false; CAF_CM_VALIDATE_STRINGPTRA(rstrSubSystemIdentifier.c_str()); bRetVal = CEcmSubSystemRegistry::IsRegistered( rstrSubSystemIdentifier ); return bRetVal; } void CEcmSubSystem::Load(const std::string& rstrSubSystemIdentifier) { CAF_CM_FUNCNAME("Load"); // Make sure that we have sub-system name. CAF_CM_VALIDATE_STRINGPTRA(rstrSubSystemIdentifier.c_str()); // If this is an unloadable sub-system... if(m_bIsUnloadable) { // make sure it is unlaoded before loading the next one. Unload(); } // Otherwise... else { // if there is already a module loaded by this sub-system // object... if(NULL != m_hModule) { CAF_CM_EXCEPTION_VA1(E_FAIL, "The sub-system %s is already loaded. Load may not be called again.", rstrSubSystemIdentifier.c_str()); } } // Create a helper to make sure we unlock the critical section. CAutoMutexLockUnlockRaw oCS( &m_oModuleCacheMutex ); // Before we do the lookup again, lets check the cache to see if we // already have the module. std::map::iterator iterModule = m_mapModuleCache.find(rstrSubSystemIdentifier); // If we found the module in the cache... if(iterModule != m_mapModuleCache.end()) { // set from the cache, and we're done. m_hModule = iterModule->second; m_strSubSystemIdentifier = rstrSubSystemIdentifier; //CAF_CM_LOG_DEBUG_VA2("Found the subsystem in the cache - id: %s, module: %p", // m_strSubSystemIdentifier.c_str(), m_hModule); } // Otherwise, look in the registry for the sub-system module. else { // Create a registry object. if (CEcmSubSystemRegistry::IsRegistered( rstrSubSystemIdentifier )) { std::string modulePath = CEcmSubSystemRegistry::GetModulePath( rstrSubSystemIdentifier ); if ( modulePath.length() ) { // load the DLL. m_hModule = CEcmDllManager::LoadLibrary( modulePath.c_str(), true ); // Record the sub-system identifier. m_strSubSystemIdentifier = rstrSubSystemIdentifier; // Insert the sub-system id to module mapping entry. m_mapModuleCache.insert( std::pair (rstrSubSystemIdentifier, m_hModule)); //CAF_CM_LOG_DEBUG_VA3("Loaded the subsystem - id: %s, path: %s, module: %p", // m_strSubSystemIdentifier.c_str(), modulePath.c_str(), m_hModule); } else { CAF_CM_EXCEPTION_VA1(E_FAIL, "Failed to load subsystem %s - Registered but modulePath is empty", rstrSubSystemIdentifier.c_str()); } } else { CAF_CM_EXCEPTION_VA1(E_FAIL, "Failed to load subsystem %s - Not registered", rstrSubSystemIdentifier.c_str()); } } } bool CEcmSubSystem::Unload( const bool cbMustUnloadNow /* = true */ ) { CAF_CM_FUNCNAME("Unload"); bool bSubsystemWasUnloaded = false; // If the sub-system is unloadable... if(m_bIsUnloadable) { // and there is a module actually loaded... if(NULL != m_hModule) { // if we don't already have it... if(NULL == m_pfnCanUnloadNow) { std::string strErrorMessage; // get the address of the sub-system's can unload function. m_pfnCanUnloadNow = (CanUnloadNowFunc) CEcmDllManager::GetFunctionAddress(m_hModule, CAN_UNLOAD_NOW, strErrorMessage ); // If we did not got the function pointer... if(NULL == m_pfnCanUnloadNow) { // throw an exception indicating that the can unload // function could not be found. CAF_CM_EXCEPTION_EFAIL(strErrorMessage); } } if(m_pfnCanUnloadNow()) { // free the library, and CEcmDllManager::UnloadLibrary( m_hModule, true ); // Create a helper to make sure we unlock the critical section. CAutoMutexLockUnlockRaw oCS( &m_oModuleCacheMutex ); // try to find the module entry. std::map::iterator iterModule = m_mapModuleCache.find(m_strSubSystemIdentifier); // If we found the module in the cache... if(iterModule != m_mapModuleCache.end()) { // remove if from the cache. m_mapModuleCache.erase(iterModule); } bSubsystemWasUnloaded = true; // Reset the member variables to an initialized state. m_hModule = NULL; m_pfnCreateInstance = NULL; m_pfnCanUnloadNow = NULL; m_strSubSystemIdentifier = ""; } // Otherwise, the sub-system is telling us it cannot safely be // unloaded at this time, if the caller indicated that it must // unload now we fail unload else if ( cbMustUnloadNow ) { // throw an exception indicating the condition. CAF_CM_EXCEPTION_EFAIL("Unable to safely unload the sub-system at this time."); } } // Otherwise, they are trying to unload nothing, so let them. } // If the sub-system is not unloadable... else { // and there is a module actually loaded... if(NULL != m_hModule) { // throw an exception. CAF_CM_EXCEPTION_EFAIL("Unable to unload an unloadable sub-system."); } // Otherwise, they are trying to unload nothing, so let them. } return bSubsystemWasUnloaded; } void CEcmSubSystem::CreateInstance( const std::string & rstrIdentifier, const IID & riid, void ** ppv ) { CAF_CM_FUNCNAME( "CreateInstance" ); // If the sub-system is not loaded... if(NULL == m_hModule) { // throw an exception indicating that the sub-system must be // loaded before object instance can be created from it. CAF_CM_EXCEPTION_EFAIL("No sub-system is loaded. You must call Load before " "object instances can be created."); } // If we don't already have a pointer to the CreateInstance // function provided by the sub-system DLL... if(NULL == m_pfnCreateInstance) { //CAF_CM_LOG_DEBUG_VA2("Getting CreateInstance - id: %s, module: %p", // rstrIdentifier.c_str(), m_hModule); std::string strErrorMessage; // get the address of the CreateInstance function. m_pfnCreateInstance = (void (*)( const char* rstrIdentifier, const IID & riid, void ** ppv )) CEcmDllManager::GetFunctionAddress(m_hModule, CREATE_INSTANCE, strErrorMessage ); // If we did not get the function pointer... if(NULL == m_pfnCreateInstance) { // throw an exception indicating that the create instance // could not be found. CAF_CM_EXCEPTION_EFAIL(strErrorMessage); } } // Call the function, passing in the supplied arguments. m_pfnCreateInstance(rstrIdentifier.c_str(), riid, ppv); } //////////////////////////////////////////////////////////////////////// // // CEcmSubSystem::CEcmSubSystem( CEcmSubSystem ) // // overloaded copy constructor // //////////////////////////////////////////////////////////////////////// CEcmSubSystem::CEcmSubSystem( const CEcmSubSystem& crCEcmSubSystem ) : CAF_CM_INIT_LOG("CEcmSubSystem") { m_bIsUnloadable = crCEcmSubSystem.m_bIsUnloadable; m_strSubSystemIdentifier = crCEcmSubSystem.m_strSubSystemIdentifier; m_hModule = crCEcmSubSystem.m_hModule; m_pfnCreateInstance = crCEcmSubSystem.m_pfnCreateInstance; m_pfnCanUnloadNow = crCEcmSubSystem.m_pfnCanUnloadNow; } //////////////////////////////////////////////////////////////////////// // // CEcmSubSystem::operator=() // // overloaded = operator // //////////////////////////////////////////////////////////////////////// CEcmSubSystem& CEcmSubSystem::operator=( const CEcmSubSystem& crCEcmSubSystem ) { m_bIsUnloadable = crCEcmSubSystem.m_bIsUnloadable; m_strSubSystemIdentifier = crCEcmSubSystem.m_strSubSystemIdentifier; m_hModule = crCEcmSubSystem.m_hModule; m_pfnCreateInstance = crCEcmSubSystem.m_pfnCreateInstance; m_pfnCanUnloadNow = crCEcmSubSystem.m_pfnCanUnloadNow; return *this; } //////////////////////////////////////////////////////////////////////// // // CEcmSubSystem::IsUnloadable() // // returns true if this subsystem is unloadable, false if it isn't // //////////////////////////////////////////////////////////////////////// bool CEcmSubSystem::IsUnloadable() const { return m_bIsUnloadable; } //////////////////////////////////////////////////////////////////////// // // CEcmSubSystem::GetSubSystemID() // // returns the subystem identifier // //////////////////////////////////////////////////////////////////////// std::string CEcmSubSystem::GetSubSystemID() const { return m_strSubSystemIdentifier; } //////////////////////////////////////////////////////////////////////// // // CEcmSubSystem::operator<() // // overloaded < operator // //////////////////////////////////////////////////////////////////////// bool CEcmSubSystem::operator< ( const CEcmSubSystem& crCEcmSubsystemRight ) const { return (::strcmp(m_strSubSystemIdentifier.c_str(), crCEcmSubsystemRight.GetSubSystemID().c_str()) < 0); } CEcmSubSystem.h000066400000000000000000000035521321503522500354030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _CEcmSubSystem_H_ #define _CEcmSubSystem_H_ #include namespace Caf { // Typedef the function pointers. typedef void ( * CreateInstanceFunc )( const char*, const IID & riid, void ** ppv ) ; typedef bool( * CanUnloadNowFunc )(); // Class declaration class SUBSYSTEMBASE_LINKAGE CEcmSubSystem { public: CEcmSubSystem( bool bIsUnloadable = false ); virtual ~ CEcmSubSystem(); bool IsRegistered( const std::string & rstrSubSystemIdentifier ); void Load( const std::string & rstrSubSystemIdentifier ); bool IsUnloadable() const; std::string GetSubSystemID() const; bool Unload( const bool cbMustUnloadNow = true ); void GetVersionInfo(); void CreateInstance( const std::string & rstrIdentifier, const IID & riid, void ** ppv ); public: // copy constructor and assignment operator CEcmSubSystem( const CEcmSubSystem& crCEcmSubSystem); CEcmSubSystem& operator= ( const CEcmSubSystem& crCEcmSubSystem ); public: // less than, allows use in associative containers bool operator< ( const CEcmSubSystem& ) const; private: // Standard ECM macro for a standard object. CAF_CM_CREATE; CAF_CM_CREATE_LOG; // Flag indicating whether a sub-system is able to be unloaded. bool m_bIsUnloadable; // Sub-system identifier. std::string m_strSubSystemIdentifier; // Sub-system DLL module handle. HMODULE m_hModule; // A map to hold a module cache. static std::map m_mapModuleCache; // A critical section to protect the module cache. static GRecMutex m_oModuleCacheMutex; // A pointer to the create instance of the function of the sub-system. CreateInstanceFunc m_pfnCreateInstance; // A pointer to the can unload function of the sub-system. CanUnloadNowFunc m_pfnCanUnloadNow; }; } #endif // _CEcmSubSystem_H_ CEcmSubSystemModule.cpp000066400000000000000000000200701321503522500370760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CEcmSubSystemModule.h" #include "CEcmSubSystemRegistry.h" #include "CEcmDllManager.h" #include "TCafSubSystemCreator.h" using namespace Caf; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CEcmSubSystemModule::CEcmSubSystemModule() : CAF_CM_INIT_LOG("CEcmSubSystemModule"), m_pObjectEntries(NULL), m_hInstance(NULL), m_lLockCount(0) { } CEcmSubSystemModule::~CEcmSubSystemModule() { } void CEcmSubSystemModule::Init(const _CAF_OBJECT_ENTRY* const pObjectEntries, const HINSTANCE hInstance) { CAF_CM_FUNCNAME("Init"); try { // Initialize the QI maps of all registered objects // to prevent multithreading problems uint32 dwIdx = 0; while (pObjectEntries[dwIdx].pfnGetEntries) { // Ignore the return value - we are just causing // the QI map to initialize by calling the func (void)pObjectEntries[dwIdx].pfnGetEntries(); CAF_CM_LOG_DEBUG_VA3("Initializing object entries - index: %d, objId: %s, module: %p", dwIdx, pObjectEntries[dwIdx].pfnIdentifier(), hInstance); ++dwIdx; } // Initialize the member variables m_pObjectEntries = pObjectEntries; m_hInstance = hInstance; } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; } void CEcmSubSystemModule::Term() { CAF_CM_FUNCNAME("Term"); try { // Loop through the Object Entries table and release the singletons uint32 dwIndex = 0; while(m_pObjectEntries && m_pObjectEntries[dwIndex].pfnCreator) { // If this is a sub-system... if(m_pObjectEntries[dwIndex].bIsSingleton && m_pObjectEntries[dwIndex].pCachedObject) { ( m_pObjectEntries[dwIndex].pCachedObject )->Release(); m_pObjectEntries[dwIndex].pCachedObject = NULL; } // Increment the index. ++ dwIndex; } } CAF_CM_CATCH_ALL; CAF_CM_CLEAREXCEPTION; // Set the instance handle to NULL. m_hInstance = NULL; // Set the object entries pointer to NULL. m_pObjectEntries = NULL; } void CEcmSubSystemModule::Lock() { g_atomic_int_inc(&m_lLockCount); } void CEcmSubSystemModule::Unlock() { (void)g_atomic_int_dec_and_test(&m_lLockCount); } void CEcmSubSystemModule::CreateInstance(const char* crstrIdentifier, const IID& criid, void** ppv) { CAF_CM_FUNCNAME("CreateInstance"); CAF_CM_VALIDATE_STRINGPTRA(crstrIdentifier); CAF_CM_VALIDATE_PTR(ppv); // Initialize the out-param *ppv = NULL; // Declare flag indicating that the identifier was found in the map. bool bFoundIdentifier = false; // Declare and index for iterating over the object map. uint32 dwIndex = 0; // Loop through the Object Entries table... CAF_CM_LOG_DEBUG_VA1("Looking for ID - %s", crstrIdentifier); while(m_pObjectEntries && m_pObjectEntries[dwIndex].pfnCreator) { // comparing the supplied identifier to the identifier in the // table. If we find a match... CAF_CM_LOG_DEBUG_VA2("Comparing to - index: %d, objId: %s", dwIndex, m_pObjectEntries[dwIndex].pfnIdentifier()); if(::strcmp(crstrIdentifier, m_pObjectEntries[dwIndex].pfnIdentifier()) == 0) { // indicate we found the identifier bFoundIdentifier = true; #ifdef IMPLEMENT_SINGLETONS // If this is the subsystem singleton manager... if(::strcmp(crstrIdentifier, _sObjIdSubsystemSingletonManager) == 0) { // Check for a cached object. if(m_pObjectEntries[dwIndex].pCachedObject) { // Use the cached object. m_pObjectEntries[dwIndex].pCachedObject->QueryInterface(criid, ppv); } else { // Call the creator function associated with the identifier. createInstanceException = true; ICafObject* pEcmObject = 0; TCafSubSystemCreator::CreateInstance( m_pObjectEntries[dwIndex].pfnCreator, CAF_IIDOF(ICafObject), reinterpret_cast(&pEcmObject)); // Cache the object. pEcmObject->QueryInterface(criid, ppv); m_pObjectEntries[dwIndex].pCachedObject = pEcmObject; createInstanceException = false; } } // If this is a singleton... else if(m_pObjectEntries[dwIndex].bIsSingleton) { // Create a pointer to a subsystem singleton manager. IEcmSubsystemSingletonManager* piSingletonMgr = NULL; CAF_CM_TRY { // Create a subsystem object. CEcmSubSystem oSubSystem; // See if the subsystem is registered before trying to load it. if(oSubSystem.IsRegistered(gs_cstrObjIdEcmSubsystemSingletonManagerSubsystem)) { // Load the subsystem singleton manager subsystem. oSubSystem.Load(gs_cstrObjIdEcmSubsystemSingletonManagerSubsystem); // Create an instance of the subsystem singleton manager object. oSubSystem.CreateInstance(gs_cstrObjIdEcmSubsystemSingletonManagerSubsystem, CSI_IIDOF(IEcmSubsystemSingletonManager), reinterpret_cast(&piSingletonMgr)); } } CAF_CM_CATCH_KEEPEXCEPTION; // If we did not get an exception or is the singleton manager not registered. if(!(CAF_CM_ISEXCEPTION) && piSingletonMgr) { // Declare a IEcmObject pointer for local use. IEcmObject* pObject = NULL; // Check for a cached object. piSingletonMgr->GetSingleton(crstrIdentifier, &pObject); // Make sure the pointer is good. if(pObject) { // Query for the interface. pObject->QueryInterface(criid, ppv); // Release the object. pObject->Release(); pObject = NULL; } // No cached object, so... else { // Call the creator function associated with the identifier. createInstanceException = true; TCafSubSystemCreator::CreateInstance( m_pObjectEntries[dwIndex].pfnCreator, CSI_IIDOF(IEcmObject), reinterpret_cast(&pObject)); // Query for the interface. pObject->QueryInterface(criid, ppv); createInstanceException = false; // Cache the object. piSingletonMgr->RegisterSingleton(crstrIdentifier, pObject); // Release the object we got back from CreateInstance. pObject->Release(); pObject = NULL; } // Release the singleton manager. piSingletonMgr->Release(); piSingletonMgr = NULL; } // We got an exception or the subsystem singleton manager is not registered. else { // Clean up the exception. if(CAF_CM_ISEXCEPTION) { CAF_CM_CLEAREXCEPTION; } // Release the piSingletonMgr if it is not null if(piSingletonMgr) { piSingletonMgr->Release(); piSingletonMgr = NULL; } // Check for a cached object. if(m_pObjectEntries[dwIndex].pCachedObject) { // Use the cached object. m_pObjectEntries[dwIndex].pCachedObject->QueryInterface(criid, ppv); } else { // Call the creator function associated with the identifier. createInstanceException = true; IEcmObject* pEcmObject = 0; TCafSubSystemCreator::CreateInstance( m_pObjectEntries[dwIndex].pfnCreator, CSI_IIDOF(IEcmObject), reinterpret_cast(&pEcmObject)); // Cache the object. pEcmObject->QueryInterface(criid, ppv); m_pObjectEntries[dwIndex].pCachedObject = pEcmObject; createInstanceException = false; } } } else #endif // IMPLEMENT_SINGLETONS { // call the creator function associated with the identifier. TCafSubSystemCreator::CreateInstance( m_pObjectEntries[dwIndex].pfnCreator, criid, ppv); } // If we are here then an object was created break; } // Increment the index. ++ dwIndex; } // If we were unable to find the identifier in the map... if(!bFoundIdentifier) { CAF_CM_EXCEPTION_VA1(E_FAIL, "Unable to find object with provided identifier [%s]", crstrIdentifier); } } bool CEcmSubSystemModule::CanUnload() { gint value = g_atomic_int_get(&m_lLockCount); return (value == 0 ); } HINSTANCE CEcmSubSystemModule::GetModuleHandle() { return m_hInstance; } CEcmSubSystemModule.h000066400000000000000000000014251321503522500365460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _CEcmSubSystemModule_H_ #define _CEcmSubSystemModule_H_ namespace Caf { struct _CAF_OBJECT_ENTRY; class SUBSYSTEMBASE_LINKAGE CEcmSubSystemModule { public: CEcmSubSystemModule(); virtual ~CEcmSubSystemModule(); void Init(const _CAF_OBJECT_ENTRY* const pObjectEntries, const HINSTANCE hInstance); void Term(); void Lock(); void Unlock(); void CreateInstance(const char* crstrIdentifier, const IID& criid, void** ppv); bool CanUnload(); HINSTANCE GetModuleHandle(); private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; const _CAF_OBJECT_ENTRY* m_pObjectEntries; HINSTANCE m_hInstance; gint m_lLockCount; }; } #endif // _CEcmSubSystemModule_H_ CEcmSubSystemRegistry.cpp000066400000000000000000000014061321503522500374630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppConfig.h" #include "CEcmSubSystemRegistry.h" #include "CEcmDllManager.h" #include using namespace Caf; bool CEcmSubSystemRegistry::IsRegistered( const std::string & crstrSubSystemIdentifier ) { std::string modulePath; return getAppConfig()->getString("subsystems", crstrSubSystemIdentifier, modulePath, IConfigParams::PARAM_OPTIONAL); } std::string CEcmSubSystemRegistry::GetModulePath( const std::string & crstrSubSystemIdentifier ) { std::string modulePath; getAppConfig()->getString("subsystems", crstrSubSystemIdentifier, modulePath, IConfigParams::PARAM_REQUIRED); return modulePath; } CEcmSubSystemRegistry.h000066400000000000000000000007341321503522500371330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _CEcmSubSystemRegistry_H_ #define _CEcmSubSystemRegistry_H_ #include namespace Caf { class SUBSYSTEMBASE_LINKAGE CEcmSubSystemRegistry { public: static bool IsRegistered( const std::string & crstrSubSystemIdentifier ); static std::string GetModulePath( const std::string & crstrSubSystemIdentifier ); }; } #endif // _CEcmSubSystem_H_ EcmSubSystemBase.cpp000066400000000000000000000055521321503522500364300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "EcmSubSystemBase.h" #include #include using namespace Caf; ////////////////////////////////////////////////////////////////////////////// // ECM Sub-System Constant Definitions ////////////////////////////////////////////////////////////////////////////// // The value name for retrieving the module's path const char* Caf::MODULE_PATH_VALUE_NAME = "ModulePath"; // The DLL exported function names const char* Caf::CREATE_INSTANCE = "CafCreateInstance"; const char* Caf::CAN_UNLOAD_NOW = "CafDllCanUnloadNow"; //////////////////////////////////////////////////////////////////////// // // Global implementation of CreateObject - helper functions for // TEcmSmartPtr that can't go inside of TEcmSmartPtr because gcc barfs. // //////////////////////////////////////////////////////////////////////// // Suppress warning about throwing an exception: we want C linkage, // but we also want to throw exceptions #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4297) // function assumed not to throw an exception but does #endif // The function is extern "C" and /EHc is specified extern "C" SUBSYSTEMBASE_LINKAGE void Caf::CreateObject (const char *cszObjectId, const IID &criid, void **ppv) { CAF_CM_STATIC_FUNC_VALIDATE( "SubSystemBase", "CreateObject" ); CAF_CM_VALIDATE_STRINGPTRA(cszObjectId); CAF_CM_VALIDATE_PTR(ppv); #ifdef WIN32 char* objId = ::_strdup(cszObjectId); #else char* objId = ::strdup(cszObjectId); #endif try { // Determine the type of object to create based on Id. // QI object id's are of the form :ClassName. // char *szColon = ::strchr(objId, ':'); // // if (szColon) // { // // Create a QI object // *szColon = NULL; // CreateQIObject(objId, szColon + 1, criid, ppv); // } // else // { // Create a subsystem object CEcmSubSystem oSubSystem; oSubSystem.Load(cszObjectId); oSubSystem.CreateInstance(cszObjectId, criid, ppv); // } } catch (CCafException *e) { ::free(objId); throw e; } catch (std::exception& e) { ::free(objId); throw e; } catch (...) { ::free(objId); throw; } ::free(objId); } //extern "C" SUBSYSTEMBASE_LINKAGE void Caf::CreateQIObject (const char *cszFactoryId, const char* cszClassName, const IID &criid, void **ppv) //{ // CAF_CM_STATIC_FUNC( "SubSystemBase", "CreateObject" ); // CAF_CM_VALIDATE_STRINGPTRA(cszFactoryId); // CAF_CM_VALIDATE_STRINGPTRA(cszClassName); // CAF_CM_VALIDATE_PTR(ppv); // //// SmartSbICfcClassFactory spsFactory; //// spsFactory.CreateInstance(cwszFactoryId); //// *ppv = NULL; //// spsFactory->CreateObject(cwszClassName, criid, ppv); //// CAF_CM_ASSERT_MSG(*ppv, "Failed to create object"); //} #ifdef _MSC_VER #pragma warning(pop) #endif EcmSubSystemBase.h000066400000000000000000000114241321503522500360700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 09, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _EcmSubSystemBase_H_ #define _EcmSubSystemBase_H_ namespace Caf { ////////////////////////////////////////////////////////////////////// // Forward Declarations ////////////////////////////////////////////////////////////////////// struct _CAF_INTMAP_ENTRY; ////////////////////////////////////////////////////////////////////////////// // ECM Sub-System Constants ////////////////////////////////////////////////////////////////////////////// // The value name for retrieving the module's path extern SUBSYSTEMBASE_LINKAGE const char* MODULE_PATH_VALUE_NAME; // The DLL exported function names extern SUBSYSTEMBASE_LINKAGE const char* CREATE_INSTANCE; extern SUBSYSTEMBASE_LINKAGE const char* CAN_UNLOAD_NOW; ////////////////////////////////////////////////////////////////////////////// // ECM Object Map Support ////////////////////////////////////////////////////////////////////////////// struct _CAF_OBJECT_ENTRY { const char* (*pfnIdentifier)(); const UUID* cpclsidClassId; uint32 (*pfnCreator)(const IID& riid, void** ppv); mutable ICafObject* pCachedObject; bool bIsSingleton; const _CAF_INTMAP_ENTRY* (*pfnGetEntries)(); }; } #define CAF_BEGIN_OBJECT_MAP(x) static _CAF_OBJECT_ENTRY x[] = { #define CAF_END_OBJECT_MAP() { NULL, NULL, NULL, NULL, false, NULL }}; #define CAF_OBJECT_ENTRY(className)\ { className::GetObjectIdentifier,\ NULL,\ className::Creator,\ NULL,\ false,\ className::_GetEntries }, #define CAF_OBJECT_ENTRY2(className, objectIdentifier)\ { objectIdentifier,\ NULL,\ className::Creator,\ NULL,\ false,\ className::_GetEntries }, /*#define CAF_OBJECT_ENTRY_SINGLETON(className)\ { className::GetObjectIdentifier,\ NULL,\ className::Creator,\ NULL,\ true,\ className::_GetEntries },*/ ////////////////////////////////////////////////////////////////////////////// // ECM Interface Map Support ////////////////////////////////////////////////////////////////////////////// namespace Caf { struct _CAF_INTMAP_ENTRY { const IID* cpiid; SUBSYS_INTPTR offset; }; } #define _CAF_PACKING 8 #define CAF_offsetofclass(base, derived)\ ((SUBSYS_INTPTR)(static_cast((derived*)_CAF_PACKING))-_CAF_PACKING) #define CAF_BEGIN_INTERFACE_MAP(x) public: \ typedef x _CafMapClass; \ ICafObject* _GetRawObjectInterface() \ { return (ICafObject*)((SUBSYS_INTPTR)this+_GetEntries()->offset); } \ ICafObject* GetObjectInterface() { return _GetRawObjectInterface(); }\ void _InternalQueryInterface(const IID& iid, void** ppv) \ { InternalQueryInterface(this, _GetEntries(), iid, ppv); } \ static const _CAF_INTMAP_ENTRY* _GetEntries() \ { static const _CAF_INTMAP_ENTRY _entries[] = { #define CAF_END_INTERFACE_MAP() {NULL, SUBSYS_INTPTR_INVALID}}; return _entries;} \ virtual void AddRef() = 0;\ virtual void Release() = 0;\ virtual void QueryInterface(const IID&, void**) = 0; #define CAF_INTERFACE_ENTRY(x)\ {&CAF_IIDOF(x), \ CAF_offsetofclass(x, _CafMapClass)}, #define CAF_INTERFACE_ENTRY_IID(iid, x)\ {&iid,\ offsetofclass(x, _CafMapClass)}, #define CAF_INTERFACE_ENTRY2(x, x2)\ {&CSI_IIDOF(x),\ (SUBSYS_INTPTR)((x*)(x2*)((_CafMapClass*)_CAF_PACKING))-_CAF_PACKING}, #define CAF_INTERFACE_ENTRY2_IID(iid, x, x2)\ {&iid,\ (SUBSYS_INTPTR)((x*)(x2*)((_CafMapClass*)_CAF_PACKING))-_CAF_PACKING}, ////////////////////////////////////////////////////////////////////////////// // ECM Helper Macros ////////////////////////////////////////////////////////////////////////////// // Place in class to be exposed from a sub-system in order to // specify its identifier. #define CAF_DECLARE_OBJECT_IDENTIFIER(x)\ public: \ static const char* GetObjectIdentifier()\ {\ return x;\ } \ const char* GetObjectId () const \ { \ return x;\ } ////////////////////////////////////////////////////////////////////////////// // ECM Sub-System Standard Function Exports ////////////////////////////////////////////////////////////////////////////// // Place in module that contains DllMain #define CAF_DECLARE_SUBSYSTEM_EXPORTS()\ extern "C" void __declspec(dllexport) CafCreateInstance(\ const char* rstrIdentifier, const IID & riid, void ** ppv )\ {\ _Module.CreateInstance(rstrIdentifier, riid, ppv);\ }\ extern "C" bool __declspec(dllexport) EcmDllCanUnloadNow()\ {\ return _Module.CanUnload();\ } ////////////////////////////////////////////////////////////////////////////// // ECM Sub-System Standard Includes ////////////////////////////////////////////////////////////////////////////// #include "CEcmSubSystemModule.h" #ifdef CAF_SUBSYSTEM extern Caf::CEcmSubSystemModule _Module; #endif #include "TCafSubSystemObject.h" #include "TCafSubSystemObjectRoot.h" #include "CEcmSubSystem.h" #endif // _EcmSubSystemBase_H_ SubSystemBaseInc.h000066400000000000000000000004441321503522500360750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Mar 11, 2004 * * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _SubSystemBaseInc_h_ #define _SubSystemBaseInc_h_ #include "TCafSubSystemObjectRoot.h" #include "TCafSubSystemSmartCl.h" #endif // #ifndef _SubSystemBaseInc_h_ SubSystemBaseLink.h000066400000000000000000000012451321503522500362610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Nov 21, 2003 * * Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef SubSystemBaseLink_h_ #define SubSystemBaseLink_h_ #ifndef SUBSYSTEMBASE_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define SUBSYSTEMBASE_LINKAGE __declspec(dllexport) #else #define SUBSYSTEMBASE_LINKAGE __declspec(dllimport) #endif #else #define SUBSYSTEMBASE_LINKAGE #endif #endif #include "SubSystemBaseInc.h" #include "CEcmDllManager.h" #include "CEcmSubSystem.h" #include "CEcmSubSystemModule.h" #include "CEcmSubSystemRegistry.h" #endif // #ifndef SubSystemBaseLink_h_ TCafSubSystemCreator.h000066400000000000000000000076721321503522500367400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Jan 30, 2003 * * Copyright (C) 2003-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _TCafSubSystemCreator_H_ #define _TCafSubSystemCreator_H_ #include "Exception/CCafException.h" namespace Caf { template< typename Derived, typename SmartPtr = TCafSmartPtr< Derived > > class TCafSubSystemCreator { public: static SmartPtr CreateInstance(); static void CreateInstance( uint32(*pfn)(const IID& criid, void** ppv), const IID& criid, void** ppv ); private: static void ValidateResultCode(const uint32 cdwRc); }; //////////////////////////////////////////////////////// // // CreateInstance() // // Creates an instance of the object and returns is as // the supplied smart class type. // ////////////////////////////////////////////////////////template template SmartPtr TCafSubSystemCreator::CreateInstance() { CAF_CM_STATIC_FUNC( "TCafSubSystemCreator", "CreateInstance()" ); // This local smart class object is transient. // If the lvalue is of the proper type then the // reference count will go to 2. When the trasient // object dies then count will go to 1. Perfect. // // If the lvalue is not the proper type then // the reference count will remain at 1. When the // transient object dies the count will go to 0 // and the Derived object will be destroyed. Perfect. SmartPtr spcReturn; // Verify that the smart class template argument // is really a smart class object by calling // a method on it that must exist (void)spcReturn.GetNonAddRefedInterface(); // Create a derived raw pointer Derived* pDerived = NULL; ValidateResultCode( Derived::Creator( &pDerived ) ); // Assign it to the smart class which // will do an AddRef - count now = 2 spcReturn = pDerived; // Release the raw pointer - count now = 1 pDerived->Release(); return spcReturn; } //////////////////////////////////////////////////////// // // CreateInstance() // // Creates an instance of the object QI'd to the requested interface // using the supplied creator function. // ////////////////////////////////////////////////////////template template void TCafSubSystemCreator::CreateInstance( uint32(*pfn)(const IID& criid, void** ppv), const IID& criid, void** ppv ) { ValidateResultCode( (*pfn)( criid, ppv ) ); } //////////////////////////////////////////////////////// // // ValidateResultCode() // // Maps the TCafSubSystemObjectRoot<>::Creator function result code // to an exception and throw it. // ////////////////////////////////////////////////////////template template void TCafSubSystemCreator::ValidateResultCode(const uint32 cdwRc) { CAF_CM_STATIC_FUNC( "TCafSubSystemCreator", "ValidateResultCode" ); if(TCafSubSystemObjectRoot::Success == cdwRc) { // No point in evalulating the remaining clauses } // Otherwise, if the interface was not supported... else if(TCafSubSystemObjectRoot::InterfaceNotSupported == cdwRc) { // throw an exception. CAF_CM_EXCEPTION_VA0(E_NOINTERFACE, "The requested interface is not supported by the object requested."); } // Otherwise, if we are out of memory... else if(TCafSubSystemObjectRoot::OutOfMemory == cdwRc) { // throw an exception. CAF_CM_EXCEPTION_EFAIL("Out of memory."); } // Otherwise, if the ppv was null... else if(TCafSubSystemObjectRoot::InvalidPointerValue == cdwRc) { // throw an exception. CAF_CM_EXCEPTION_EFAIL("The ppv argument must not be NULL."); } // Otherwise, if something unexpected happened... else if(TCafSubSystemObjectRoot::UnknownFailure == cdwRc) { // throw an exception. CAF_CM_EXCEPTION_EFAIL("An unexpected exception occurred while " "trying to create requested object."); } } } #endif // #ifndef _TCafSubSystemCreator_H_ TCafSubSystemObject.h000066400000000000000000000025031321503522500365330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 9, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _TCafSubSystemObject_H_ #define _TCafSubSystemObject_H_ namespace Caf { template class TCafSubSystemObject : public Base { public: // Constructor / Destructor TCafSubSystemObject() : m_lRefCnt( 0 ) { // There is no module to lock if we are not in a sub-system // project, so conditionally define. #ifdef CAF_SUBSYSTEM // Lock the module. _Module.Lock(); #endif } virtual ~TCafSubSystemObject() { // There is no module to unlock if we are not in a sub-system // project, so conditionally define. #ifdef CAF_SUBSYSTEM // Unlock the module. _Module.Unlock(); #endif } public: // IEcmSubSystemObject Implementations virtual void AddRef() { g_atomic_int_inc(&m_lRefCnt); } virtual void Release() { // If the ref-count is greater than 0... if (g_atomic_int_dec_and_test(&m_lRefCnt)) { // delete self. delete this; } } virtual void QueryInterface(const IID& riid, void** ppv) { this->_InternalQueryInterface(riid, ppv); } private: gint m_lRefCnt; private: // Deny copy and assignment TCafSubSystemObject(const TCafSubSystemObject&); TCafSubSystemObject& operator=(const TCafSubSystemObject&); }; } #endif // _TCafSubSystemObject_H_ TCafSubSystemObjectRoot.h000066400000000000000000000122531321503522500374020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 9, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _TCafSubSystemObjectRoot_H_ #define _TCafSubSystemObjectRoot_H_ #include "EcmSubSystemBase.h" namespace Caf { template > class TCafSubSystemObjectRoot { public: enum ReturnCodes { Success = 0x0, // The call succeeded InvalidPointerValue, // An invalid pointer was passed OutOfMemory, // We're out of memory InterfaceNotSupported, // The interface requested in not supported UnknownFailure // Something happened that we didn't expect }; // Creator Function static uint32 Creator(const IID& criid, void** ppv); static uint32 Creator(Derived** ppDerived); protected: static void InternalQueryInterface(const void* cpThis, const _CAF_INTMAP_ENTRY* cpEntries, const IID& criid, void** ppv); protected: TCafSubSystemObjectRoot() {;} virtual ~TCafSubSystemObjectRoot() {;} private: TCafSubSystemObjectRoot(const TCafSubSystemObjectRoot&) {;} TCafSubSystemObjectRoot& operator=(const TCafSubSystemObjectRoot&) { return *this; } }; // Default Creator Function (can be overridden in Derived) - returns a QI'd void* template uint32 TCafSubSystemObjectRoot::Creator(const IID& criid, void** ppv) { uint32 dwRetCode = Success; try { // Make sure the outer pointer seems valid. if(ppv != NULL) { // Initialize the out-param *ppv = NULL; // Create a new derived object Derived* pObj = NULL; dwRetCode = Creator( &pObj ); if( Success == dwRetCode ) { // QI to the requested interface pObj->QueryInterface(criid, ppv); // if *ppv is NULL... if(NULL == *ppv) { // then the interface requested is not supported. dwRetCode = InterfaceNotSupported; } // decrement the reference count. pObj->Release(); } } // Otherwise... else { // set the return code to indicate an invalid pointer was passed. dwRetCode = InvalidPointerValue; } } // No exceptions should be thrown, but if one is... catch(...) { // set the return code to unknown failure occurred. dwRetCode = UnknownFailure; } return dwRetCode; } // Creator Function (can be overridden in Derived) - returns a pDerived template uint32 TCafSubSystemObjectRoot::Creator(Derived** ppDerived) { uint32 dwRetCode = Success; try { // Make sure the outer pointer seems valid. if(ppDerived != NULL) { // Create the out-param *ppDerived = new LifetimeManager; // If we were able to allocate and create... if(NULL != *ppDerived) { // Increment the ref count (*ppDerived)->AddRef(); } else { // set the return code to indicate out of memory. dwRetCode = OutOfMemory; } } // Otherwise... else { // set the return code to indicate an invalid pointer was passed. dwRetCode = InvalidPointerValue; } } // No exceptions should be thrown, but if one is... catch(...) { // set the return code to unknown failure occurred. dwRetCode = UnknownFailure; } return dwRetCode; } // Table driven query interface template void TCafSubSystemObjectRoot::InternalQueryInterface(const void* cpThis, const _CAF_INTMAP_ENTRY* cpEntries, const IID& criid, void** ppv) { if(NULL != cpThis) { if(cpEntries != NULL) { if(ppv != NULL) { // Initialize the out-param *ppv = NULL; // If the iid passed in is the iid of IEcmObject... if(::IsEqualIID(criid, CAF_IIDOF(ICafObject))) { // get the first interface in the map, ICafObject* pObj = reinterpret_cast( (SUBSYS_INTPTR)cpThis+cpEntries->offset); // increment the reference count, pObj->AddRef(); // set the out-param equal to the interface pointer. *ppv = pObj; } // Otherwise, we are looking for something other than // IEcmObject, so... else { // get a copy of the pointer to the entries so we can // increment it, _CAF_INTMAP_ENTRY* pEntries = const_cast<_CAF_INTMAP_ENTRY*>(cpEntries); // loop through the interface map entries... while((pEntries->cpiid != NULL) && (pEntries->offset != SUBSYS_INTPTR_INVALID)) { // if we find a matching IID... if ((NULL != pEntries->cpiid) && (::IsEqualIID(*(pEntries->cpiid), criid))) { // get the interface at the offset from the map, ICafObject* pObj = reinterpret_cast( (SUBSYS_INTPTR)cpThis+pEntries->offset); // increment the reference count, pObj->AddRef(); // set the out-param equal to the interface // pointer, and *ppv = pObj; // break out of the loop. break; } // Move to the next entry in the interface map. pEntries++; } } } } } } } #endif // _TCafSubSystemObjectRoot_H_ TCafSubSystemSmartCl.h000066400000000000000000000310171321503522500366740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Oct 9, 2002 * * Copyright (C) 2002-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _TCafSubSystemSmartCl_H #define _TCafSubSystemSmartCl_H #include "EcmSubSystemBase.h" #include "Exception/CCafException.h" #include "CEcmSubSystem.h" #include namespace Caf { struct CafSubSystemSmartClToken { ICafObject *m_pCl; CafSubSystemSmartClToken(ICafObject* p) : m_pCl(p) {} }; // this routine should really be moved to a real extern inline BOOL CafSubSystemSmartClIsSameObject(ICafObject *pObj1, ICafObject *pObj2) { BOOL bResult = TRUE; if( pObj1 != pObj2) { ICafObject *p1 = 0, *p2 = 0; pObj1->QueryInterface(CAF_IIDOF(ICafObject), (void**)&p1); if( p1 ) p1->Release(); else p1 = 0; pObj2->QueryInterface(CAF_IIDOF(ICafObject), (void**)&p2); if( p2 ) p2->Release(); else p2 = 0; bResult = (p1 == p2); // values do not change after release } return bResult; } inline BOOL CafSubSystemSmartClIsSameObject(ICafObject *pObj1, const CafSubSystemSmartClToken& pObj2) { return CafSubSystemSmartClIsSameObject(pObj1, pObj2.m_pCl); } inline BOOL CafSubSystemSmartClIsSameObject(const CafSubSystemSmartClToken& pObj1, ICafObject *pObj2) { return CafSubSystemSmartClIsSameObject(pObj1.m_pCl, pObj2); } inline BOOL CafSubSystemSmartClIsSameObject(const CafSubSystemSmartClToken& pObj1, const CafSubSystemSmartClToken& pObj2) { return CafSubSystemSmartClIsSameObject(pObj1.m_pCl, pObj2.m_pCl); } /** * @brief Template for classes exposed as subsystem objects */ template class TCafSubSystemSmartCl { private: typedef TCafSubSystemSmartCl SameSmartType; public: // constructors/destructors // default constructor TCafSubSystemSmartCl(void) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl( 0 ) { } // homogeneous raw constructor TCafSubSystemSmartCl(Cl* rhs) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl( rhs ) { if( NULL != m_pCl ) m_pCl->AddRef(); } // homogeneous smart constructor TCafSubSystemSmartCl(const SameSmartType& rhs) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl( rhs.m_pCl ) { if( NULL != m_pCl ) m_pCl->AddRef(); } // heterogeneous raw constructor TCafSubSystemSmartCl(ICafObject* rhs) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl( 0 ) { if( rhs ) { // Do QueryInterface (throws exception if QI fails) rhs->QueryInterface( GetIID(), ( void ** ) &m_pCl ); } } // heterogeneous smart constructor TCafSubSystemSmartCl(const CafSubSystemSmartClToken& rhs) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl( 0 ) { if( rhs.m_pCl ) { // Do QueryInterface (throws exception if QI fails) rhs.m_pCl->QueryInterface( GetIID(), ( void ** ) &m_pCl ); } } // destructor ~TCafSubSystemSmartCl(void) { SafeRelease(); } operator CafSubSystemSmartClToken(void) const { return CafSubSystemSmartClToken( m_pCl ); } public: // Attach operations // homogeneous raw attachment void Attach(Cl* rhs) { if( rhs != m_pCl ) { SafeRelease(); if( m_pCl = rhs ) m_pCl->AddRef(); } } // homogeneous smart attachment void Attach(const SameSmartType& rhs) { Attach( rhs.m_pCl ); } // heterogeneous raw attachment void Attach(ICafObject* rhs) { SafeRelease(); if( rhs ) { rhs->QueryInterface( GetIID(), ( void ** ) &m_pCl ); } } // heterogeneous smart attachment void Attach(const CafSubSystemSmartClToken& rhs) { Attach( rhs.m_pCl ); } public: // assignment operators // homogeneous raw assignment SameSmartType& operator = (Cl *rhs) { Attach( rhs ); return *this; } // homogeneous smart assignment SameSmartType& operator = (const SameSmartType& rhs) { Attach( rhs ); return *this; } // heterogeneous raw assignment SameSmartType& operator = (ICafObject * rhs) { Attach( rhs ); return *this; } // heterogeneous smart assignment SameSmartType& operator = (const CafSubSystemSmartClToken& rhs) { Attach( rhs ); return *this; } public: // equivalence operators (note - no identity tests performed here!) BOOL operator == (Cl * rhs) { return m_pCl == rhs; } BOOL operator == (const SameSmartType& rhs) { return m_pCl == rhs.m_pCl; } BOOL operator != (Cl *rhs) { return m_pCl != rhs; } BOOL operator != (const SameSmartType& rhs) { return m_pCl != rhs.m_pCl; } public: // CoCreateInstance wrappers void CreateInstance(const std::string& strClassIdentifier, const bool cbIsExceptionOnFailure = true) { CCafException* _cm_exception_ = NULL; SafeRelease(); try { CEcmSubSystem oSubSystem; oSubSystem.Load(strClassIdentifier); oSubSystem.CreateInstance(strClassIdentifier, GetIID(), AsPPVArg()); } catch (CCafException *e) { _cm_exception_ = e; } if( _cm_exception_ ) { if( cbIsExceptionOnFailure ) { _cm_exception_->throwSelf(); } else { _cm_exception_->Release(); } } } private: const IID& GetIID(void) const { return CAF_IIDOF(Cl); } void** AsPPVArg(void) { SafeRelease(); return (void **)&m_pCl; } public: // operations // note: no Cl * operator is allowed, as it makes it very // easy to break the protocol of COM. Instead, these // four operations require the user to be explicit Cl* GetAddRefedInterface(void) const { if( m_pCl) m_pCl->AddRef(); return m_pCl; } Cl* GetNonAddRefedInterface(void) const { return m_pCl; } Cl** GetReleasedInterfaceReference(void) { SafeRelease(); return &m_pCl; } Cl** GetNonReleasedInterfaceReference(void) { return &m_pCl; } BOOL operator ! (void) const { return m_pCl == 0; } BOOL IsOK(void) const { return m_pCl != 0; } // instead of operator bool, we return a fake ptr type to allow if( pFoo) usage // but to disallow if( pFoo == pBar) which is probably wrong class PseudoBool {}; operator PseudoBool * (void) const { return (PseudoBool *)m_pCl; } // the arrow operator returns a pointer with AddRef and Release disabled class NoAddRefOrRelease : public Cl { private: virtual void AddRef() = 0; virtual void Release() = 0; }; NoAddRefOrRelease *operator ->(void) { return (NoAddRefOrRelease *)m_pCl; } NoAddRefOrRelease *operator ->(void) const { return (NoAddRefOrRelease *)m_pCl; } static Cl* GetAddRefedQueryInterface(ICafObject* pICafObject) { CAF_CM_STATIC_FUNC( "TCafSubSystemSmartC", "GetAddRefedQueryInterface" ); CAF_CM_VALIDATE_INTERFACEPTR( pICafObject ); // QI to the interface and validate that the QI was successful. Cl* pCl = 0; pICafObject->QueryInterface( CAF_IIDOF(Cl), ( void ** ) &pCl ); return pCl; } static Cl* GetNonAddRefedQueryInterface(ICafObject* pICafObject) { CAF_CM_STATIC_FUNC( "TCafSubSystemSmartC", "GetNonAddRefedQueryInterface" ); CAF_CM_VALIDATE_INTERFACEPTR( pICafObject ); // QI to the interface and validate that the QI was successful. Cl* pCl = 0; pICafObject->QueryInterface( CAF_IIDOF(Cl), ( void ** ) &pCl ); // QueryInterface automatically AddRefs the interface, so it must be released. if( pCl ) pCl->Release(); return pCl; } private: CAF_CM_CREATE; Cl* m_pCl; private: void SafeRelease(void) { if( m_pCl ) m_pCl->Release(); m_pCl = 0; } }; template <> class TCafSubSystemSmartCl { private: typedef ICafObject Cl; typedef TCafSubSystemSmartCl SameSmartType; public: // constructors/destructors // default constructor TCafSubSystemSmartCl(void) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl(0) { } // homogeneous raw constructor TCafSubSystemSmartCl(Cl *rhs) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl(rhs) { if (NULL != m_pCl) m_pCl->AddRef(); } // homogeneous smart constructor TCafSubSystemSmartCl(const SameSmartType& rhs) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl(rhs.m_pCl) { if (NULL != m_pCl) m_pCl->AddRef(); } operator CafSubSystemSmartClToken (void) const { return CafSubSystemSmartClToken(m_pCl); } // heterogeneous smart constructor (AddRef's instead of QI) TCafSubSystemSmartCl(const CafSubSystemSmartClToken& rhs) : CAF_CM_INIT( "TCafSubSystemSmartC" ), m_pCl(0) { if ( rhs.m_pCl ) { m_pCl = rhs.m_pCl; m_pCl->AddRef(); } } // destructor ~TCafSubSystemSmartCl(void) { SafeRelease(); } public: // Attach operations // homogeneous raw attachment void Attach(Cl * rhs) { if (rhs != m_pCl) { SafeRelease(); if ( rhs ) { m_pCl = rhs; m_pCl->AddRef(); } } } // homogeneous smart attachment void Attach(const SameSmartType& rhs) { Attach(rhs.m_pCl); } // heterogeneous smart attachment void Attach(const CafSubSystemSmartClToken& rhs) { Attach(rhs.m_pCl); } public: // assignment operators // homogeneous raw assignment SameSmartType& operator = (Cl *rhs) { Attach(rhs); return *this; } // homogeneous smart assignment SameSmartType& operator = (const SameSmartType& rhs) { Attach(rhs); return *this; } // heterogeneous smart assignment SameSmartType& operator = (const CafSubSystemSmartClToken& rhs) { Attach(rhs); return *this; } // equivalence operators (note - no identity tests performed here!) BOOL operator == (Cl * rhs) { return m_pCl == rhs; } BOOL operator == (const SameSmartType& rhs) { return m_pCl == rhs.m_pCl; } BOOL operator != (Cl *rhs) { return m_pCl != rhs; } BOOL operator != (const SameSmartType& rhs) { return m_pCl != rhs.m_pCl; } public: // CoCreateInstance wrappers void CreateInstance(const std::string& strClassIdentifier, const bool cbIsExceptionOnFailure = true) { CCafException* _cm_exception_ = NULL; SafeRelease(); try { CEcmSubSystem oSubSystem; oSubSystem.Load(strClassIdentifier); oSubSystem.CreateInstance(strClassIdentifier, GetIID(), AsPPVArg()); } catch (CCafException* e) { _cm_exception_ = e; } if(_cm_exception_) { if( cbIsExceptionOnFailure ) { _cm_exception_->throwSelf(); } else { _cm_exception_->Release(); } } } public: // Interface pointer accessors // note: no If * operator is allowed, as it makes it very // easy to break the protocol of COM. Instead, these // four operations require the user to be explicit Cl * GetAddRefedInterface(void) const { if (m_pCl) m_pCl->AddRef(); return m_pCl; } Cl * GetNonAddRefedInterface(void) const { return m_pCl; } Cl **GetReleasedInterfaceReference(void) { SafeRelease(); return &m_pCl; } Cl **GetNonReleasedInterfaceReference(void) { return &m_pCl; } public: // operations const IID GetIID(void) const { return CAF_IIDOF(ICafObject); } void * * AsPPVArg(void) { SafeRelease(); return (void **)&m_pCl; } BOOL operator ! (void) const { return m_pCl == 0; } BOOL IsOK(void) const { return m_pCl != 0; } // instead of operator bool, we return a fake ptr type to allow if (pFoo) usage // but to disallow if (pFoo == pBar) which is probably wrong class PseudoBool {}; operator PseudoBool * (void) const { return (PseudoBool *)m_pCl; } // the arrow operator returns a pointer with AddRef and Release disabled class NoAddRefOrRelease : public Cl { private: virtual void AddRef() = 0; virtual void Release() = 0; }; NoAddRefOrRelease *operator ->(void) { CAF_CM_FUNCNAME_VALIDATE( "operator ->" ); CAF_CM_VALIDATE_PTR( m_pCl ); return (NoAddRefOrRelease *)m_pCl; } NoAddRefOrRelease *operator ->(void) const { CAF_CM_FUNCNAME_VALIDATE( "operator ->" ); CAF_CM_VALIDATE_PTR( m_pCl ); return (NoAddRefOrRelease *)m_pCl; } private: CAF_CM_CREATE; Cl* m_pCl; private: void SafeRelease(void) { if( m_pCl ) m_pCl->Release(); m_pCl = 0; } }; } #endif stdafx.h000066400000000000000000000005601321503522500342020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/SubSystemBase/* * Created: Mar 21, 2004 * * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ #ifdef WIN32 #define SUBSYSTEMBASE_LINKAGE __declspec(dllexport) #else #define SUBSYSTEMBASE_LINKAGE #endif #include #include "../Common/CommonAggregatorLink.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/000077500000000000000000000000001321503522500306255ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/MarkupParser/000077500000000000000000000000001321503522500332415ustar00rootroot00000000000000CMarkupParser.cpp000066400000000000000000000136701321503522500364140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/MarkupParser/* * Author: mdonahue * Created: Jan 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Xml/MarkupParser/CMarkupParser.h" #include "Exception/CCafException.h" #include #include namespace Caf { namespace MarkupParser { std::string _xml; struct SParserState { SParserState() : depth(0) { } SmartPtrElement root; std::deque stack; uint32 depth; private: CAF_CM_DECLARE_NOCOPY(SParserState); }; void cb_start_element(GMarkupParseContext *context, const gchar *element_name, const gchar **attribute_names, const gchar **attribute_values, gpointer user_data, GError **error) { CAF_CM_STATIC_FUNC("MarkupParser", "cb_start_element"); try { SParserState& state = *(reinterpret_cast(user_data)); CAF_CM_ASSERT(state.depth == state.stack.size()); if (state.depth == 0) { //TODO-BLW: For some reason the root is already created, so temporarily // remove the assert and re-create the root. //CAF_CM_ASSERT(!state.root); state.root.CreateInstance(); state.stack.push_back(state.root); } else { SmartPtrElement element; element.CreateInstance(); state.stack.back()->children.push_back(element); state.stack.push_back(element); } ++state.depth; SmartPtrElement element = state.stack.back(); element->name = element_name; const gchar **attr_name_cursor = attribute_names; const gchar **attr_value_cursor = attribute_values; while (*attr_name_cursor) { element->attributes.push_back(Attribute(*attr_name_cursor, *attr_value_cursor)); ++attr_name_cursor; ++attr_value_cursor; } } catch(CCafException *e) { std::string msg(e->getFullMsg()); e->Release(); *error = g_error_new_literal(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, msg.c_str()); } } void cb_text(GMarkupParseContext *context, const gchar *text, gsize text_len, gpointer user_data, GError **error) { SParserState& state = *(reinterpret_cast(user_data)); if (text_len) { state.stack.back()->value.append(text, text_len); } } void cb_end_element(GMarkupParseContext *context, const gchar *element_name, gpointer user_data, GError **error) { CAF_CM_STATIC_FUNC("MarkupParser", "cb_end_element"); try { SParserState& state = *(reinterpret_cast(user_data)); CAF_CM_ASSERT((state.depth) && (state.depth == state.stack.size())); --state.depth; state.stack.pop_back(); } catch(CCafException *e) { std::string msg(e->getFullMsg()); e->Release(); *error = g_error_new_literal(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, msg.c_str()); } } void cb_destroy_user_data(gpointer data) { delete (SParserState*)data; } static GMarkupParser _markupParser = { cb_start_element, cb_end_element, cb_text, NULL, NULL }; SmartPtrElement parseString(const std::string& xml) { CAF_CM_STATIC_FUNC("MarkupParser", "parseString"); CAF_CM_VALIDATE_STRINGPTRA(xml.c_str()); _xml = xml; SParserState *parserState = new SParserState(); GError *parserError = NULL; GMarkupParseContext *context = g_markup_parse_context_new(&_markupParser, G_MARKUP_TREAT_CDATA_AS_TEXT, parserState, cb_destroy_user_data); SmartPtrElement root; try { if (g_markup_parse_context_parse(context, xml.c_str(), xml.length(), &parserError)) { root = parserState->root; } else { CAF_CM_EXCEPTION_VA0(parserError->code, parserError->message); } } catch (...) { if (parserError) { g_error_free(parserError); } if (context) { g_markup_parse_context_free(context); } throw; } if (parserError) { g_error_free(parserError); } if (context) { g_markup_parse_context_free(context); } return root; } SmartPtrElement parseFile(const std::string& file) { CAF_CM_STATIC_FUNC("MarkupParser", "parseFile"); CAF_CM_VALIDATE_STRINGPTRA(file.c_str()); gchar* text = NULL; GError *fileError = NULL; SmartPtrElement root; try { if (g_file_get_contents(file.c_str(), &text, NULL, &fileError)) { if (! text || (text[ 0 ] == L'\0' )) { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_DATA, "File is empty - %s", file.c_str()); } root = parseString(text); } else { CAF_CM_EXCEPTION_VA0(fileError->code, fileError->message); } } catch (...) { if (fileError) { g_error_free(fileError); } if (text) { g_free(text); } throw; } if (fileError) { g_error_free(fileError); } if (text) { g_free(text); } return root; } ChildIterator findChild(SmartPtrElement& element, const std::string& name) { CAF_CM_STATIC_FUNC_VALIDATE("MarkupParser", "findChild"); CAF_CM_VALIDATE_SMARTPTR(element); CAF_CM_VALIDATE_STRING(name); ChildIterator rc = element->children.end(); for(ChildIterator childIter = element->children.begin(); childIter != element->children.end(); childIter++) { if((*childIter)->name.compare(name) == 0) { rc = childIter; } } return rc; /* return std::find_if(element->children.begin(), element->children.end(), std::bind2nd(ElementName(), name)); */ } AttributeIterator findAttribute(Attributes& attributes, const std::string& name) { CAF_CM_STATIC_FUNC_VALIDATE("MarkupParser", "findAttribute"); CAF_CM_VALIDATE_STRING(name); return std::find_if(attributes.begin(), attributes.end(), std::bind2nd(AttributeName(), name)); } std::string getAttributeValue(SmartPtrElement& element, const std::string& name) { CAF_CM_STATIC_FUNC("MarkupParser", "getAttributeValue"); CAF_CM_VALIDATE_SMARTPTR(element); CAF_CM_VALIDATE_STRING(name); std::string rc; AttributeIterator iter = findAttribute(element->attributes, name); if (iter != element->attributes.end()) { rc = iter->second; } else { CAF_CM_EXCEPTION_VA2(ERROR_TAG_NOT_FOUND, "Element %s does not contain attribute %s", element->name.c_str(), name.c_str()); } return rc; } }} MarkupParserLink.h000066400000000000000000000010241321503522500365620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/MarkupParser/* * Author: mdonahue * Created: Jan 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef MARKUPPARSERLINK_H_ #define MARKUPPARSERLINK_H_ #ifndef MARKUPPARSER_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define MARKUPPARSER_LINKAGE __declspec(dllexport) #else #define MARKUPPARSER_LINKAGE __declspec(dllimport) #endif #else #define MARKUPPARSER_LINKAGE #endif #endif #endif /* MARKUPPARSERLINK_H_ */ stdafx.h000066400000000000000000000010431321503522500346220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/MarkupParser/* * Author: mdonahue * Created: Jan 20, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define MARKUPPARSER_LINKAGE __declspec(dllexport) #define COMMONAGGREGATOR_LINKAGE __declspec(dllexport) #else #define MARKUPPARSER_LINKAGE #define COMMONAGGREGATOR_LINKAGE #endif #include #include #include "../../Common/CAutoMutexLockUnlock.h" #include "../../Exception/ExceptionLink.h" #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/XmlUtils/000077500000000000000000000000001321503522500324065ustar00rootroot00000000000000CXmlElement.cpp000066400000000000000000000270541321503522500352200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/XmlUtils/* * Author: mdonahue * Created: Dec 3, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Exception/CCafException.h" using namespace Caf; const std::string CXmlElement::CDATA_BEG = ""; CXmlElement::CXmlElement() : _isInitialized(false), CAF_CM_INIT_LOG("CXmlElement") { } CXmlElement::~CXmlElement() { } void CXmlElement::initialize( const MarkupParser::SmartPtrElement& element, const std::string& path) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_PTR(element); CAF_CM_VALIDATE_STRING(path); _element = element; _path = path; _isInitialized = true; } MarkupParser::SmartPtrElement CXmlElement::getInternalElement() { return _element; } std::string CXmlElement::findRequiredAttribute(const std::string& name) const { CAF_CM_FUNCNAME("findRequiredAttribute"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); CAF_CM_VALIDATE_COND_VA3(!_element->attributes.empty(), "element (%s) does not contain any attributes (%s) in %s", _element->name.c_str(), name.c_str(), _path.c_str()); MarkupParser::AttributeIterator iter = MarkupParser::findAttribute( _element->attributes, name); CAF_CM_VALIDATE_COND_VA3(iter != _element->attributes.end(), "element (%s) does not contain required attribute (%s) in %s", _element->name.c_str(), name.c_str(), _path.c_str()); std::string rc = iter->second; CAF_CM_VALIDATE_STRING(rc); return rc; } std::string CXmlElement::findOptionalAttribute(const std::string& name) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalAttribute"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); std::string rc; if (!_element->attributes.empty()) { MarkupParser::AttributeIterator iter = MarkupParser::findAttribute( _element->attributes, name); if (iter != _element->attributes.end()) { rc = iter->second; } } return rc; } SmartPtrCXmlElement CXmlElement::findRequiredChild(const std::string& name) const { CAF_CM_FUNCNAME("findRequiredChild"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); const MarkupParser::ChildIterator iter = MarkupParser::findChild(_element, name); if (iter == _element->children.end()) { CAF_CM_LOG_INFO_VA1("Child not found: %s", name.c_str()); } CAF_CM_VALIDATE_COND_VA3(iter != _element->children.end(), "element (%s) does not contain required child (%s) in %s", _element->name.c_str(), name.c_str(), _path.c_str()); SmartPtrCXmlElement rc; rc.CreateInstance(); rc->initialize(*iter, _path); return rc; } SmartPtrCXmlElement CXmlElement::findOptionalChild(const std::string& name) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalChild"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); SmartPtrCXmlElement rc; const MarkupParser::ChildIterator iter = MarkupParser::findChild(_element, name); if (iter != _element->children.end()) { rc.CreateInstance(); rc->initialize(*iter, _path); } return rc; } CXmlElement::SmartPtrCAttributeCollection CXmlElement::getAllAttributes() const { CAF_CM_FUNCNAME_VALIDATE("getAllAttributes"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrCAttributeCollection rc; rc.CreateInstance(); for (TConstIterator attribute(_element->attributes); attribute; attribute++) { rc->insert(std::make_pair((*attribute).first, (*attribute).second)); } return rc; } CXmlElement::SmartPtrCElementCollection CXmlElement::getAllChildren() const { CAF_CM_FUNCNAME_VALIDATE("getAllChildren"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrCElementCollection rc; rc.CreateInstance(); SmartPtrCXmlElement xmlElement; for (TConstIterator child(_element->children); child; child++) { xmlElement.CreateInstance(); xmlElement->initialize(*child, _path); rc->insert(std::make_pair((*child)->name, xmlElement)); } return rc; } CXmlElement::SmartPtrCOrderedElementCollection CXmlElement::getAllChildrenInOrder() const { CAF_CM_FUNCNAME_VALIDATE("getAllChildrenInOrder"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrCOrderedElementCollection rc; rc.CreateInstance(); SmartPtrCXmlElement xmlElement; for (TConstIterator child(_element->children); child; child++) { xmlElement.CreateInstance(); xmlElement->initialize(*child, _path); rc->push_back(xmlElement); } return rc; } CXmlElement::SmartPtrCElementCollection CXmlElement::findRequiredChildren( const std::string& name) const { CAF_CM_FUNCNAME("findRequiredChildren"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); SmartPtrCElementCollection rc = findOptionalChildren(name); if (rc.IsNull() || rc->empty()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Children not found: %s", name.c_str()); } return rc; } CXmlElement::SmartPtrCElementCollection CXmlElement::findOptionalChildren( const std::string& name) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalChildren"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); SmartPtrCElementCollection rc; rc.CreateInstance(); SmartPtrCXmlElement xmlElement; for (TConstIterator child(_element->children); child; child++) { if (((*child)->name).compare(name) == 0) { xmlElement.CreateInstance(); xmlElement->initialize(*child, _path); rc->insert(std::make_pair((*child)->name, xmlElement)); } } return rc; } std::string CXmlElement::getName() const { CAF_CM_FUNCNAME_VALIDATE("getName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _element->name; } std::string CXmlElement::getValue() const { CAF_CM_FUNCNAME_VALIDATE("getValue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _element->value; } std::string CXmlElement::getCDataValue() const { CAF_CM_FUNCNAME_VALIDATE("getCDataValue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rc = _element->value; if (! rc.empty()) { const std::string::size_type cdataBegPos = rc.find(CDATA_BEG); const std::string::size_type cdataEndPos = rc.find(CDATA_END); if ((0 == cdataBegPos) && (std::string::npos != cdataEndPos)) { rc = rc.substr(0, cdataEndPos); rc = rc.substr(cdataBegPos + CDATA_BEG.length()); } } return rc; } std::string CXmlElement::getPath() const { CAF_CM_FUNCNAME_VALIDATE("getPath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _path; } void CXmlElement::addAttribute(const std::string& name, const std::string& value) { CAF_CM_FUNCNAME("addAttribute"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); CAF_CM_VALIDATE_STRING(value); if (!_element->attributes.empty()) { MarkupParser::AttributeIterator iter = MarkupParser::findAttribute( _element->attributes, name); CAF_CM_VALIDATE_COND_VA3(iter == _element->attributes.end(), "element (%s) already contains attribute (%s) in %s", _element->name.c_str(), name.c_str(), _path.c_str()); } _element->attributes.push_back(std::make_pair(name, value)); } void CXmlElement::removeAttribute(const std::string& name) { CAF_CM_FUNCNAME_VALIDATE("removeAttribute"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); if (!_element->attributes.empty()) { MarkupParser::AttributeIterator iter = MarkupParser::findAttribute( _element->attributes, name); if (iter != _element->attributes.end()) { _element->attributes.erase(iter); } } } void CXmlElement::setAttribute(const std::string& name, const std::string& value) { CAF_CM_FUNCNAME("setAttribute"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); CAF_CM_VALIDATE_STRING(value); CAF_CM_VALIDATE_COND_VA3(!_element->attributes.empty(), "element (%s) does not contain any attributes (%s) in %s", _element->name.c_str(), name.c_str(), _path.c_str()); MarkupParser::AttributeIterator iter = MarkupParser::findAttribute( _element->attributes, name); CAF_CM_VALIDATE_COND_VA3(iter != _element->attributes.end(), "element (%s) does not contain required attribute (%s) in %s", _element->name.c_str(), name.c_str(), _path.c_str()); iter->second = value; } SmartPtrCXmlElement CXmlElement::createAndAddElement(const std::string& name) { CAF_CM_FUNCNAME_VALIDATE("createAndAddElement"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); MarkupParser::SmartPtrElement element; element.CreateInstance(); element->name = name; SmartPtrCXmlElement rc; rc.CreateInstance(); rc->initialize(element, _path); _element->children.push_back(element); return rc; } void CXmlElement::addChild(const SmartPtrCXmlElement& xmlElement) { CAF_CM_FUNCNAME_VALIDATE("addChild"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(xmlElement); _element->children.push_back(xmlElement->getInternalElement()); } void CXmlElement::removeChild(const std::string& name) { CAF_CM_FUNCNAME_VALIDATE("removeChild"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); const MarkupParser::ChildIterator iter = MarkupParser::findChild(_element, name); if (iter != _element->children.end()) { _element->children.erase(iter); } } void CXmlElement::setValue(const std::string& value) { CAF_CM_FUNCNAME_VALIDATE("setValue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(value); _element->value = value; } void CXmlElement::setCDataValue(const std::string& value) { CAF_CM_FUNCNAME_VALIDATE("setCDataValue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(value); if (std::string::npos == value.find(CDATA_BEG)) { _element->value = CDATA_BEG + value + CDATA_END; } else { _element->value = value; } } void CXmlElement::appendValue(const std::string& value) { CAF_CM_FUNCNAME_VALIDATE("appendValue"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(value); if (_element->value.empty()) { _element->value = ""; } _element->value += value; } void CXmlElement::saveToFile(const std::string& filename) const { CAF_CM_FUNCNAME_VALIDATE("saveToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(filename); CAF_CM_LOG_INFO_VA1("Saving XML to file \"%s\"", filename.c_str()); const std::string xml = saveToString(); FileSystemUtils::saveTextFile(filename, xml); } std::string CXmlElement::saveToString() const { CAF_CM_FUNCNAME_VALIDATE("saveToString"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rc = ""; saveToString(_element, rc); return rc; } std::string CXmlElement::saveToStringRaw() const { CAF_CM_FUNCNAME_VALIDATE("saveToStringRaw"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::string rc; saveToString(_element, rc); return rc; } void CXmlElement::saveToString( const MarkupParser::SmartPtrElement& element, std::string& xml) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CXmlElement", "saveToString"); CAF_CM_VALIDATE_PTR(element); xml += "<" + element->name; for (TConstIterator attribute(element->attributes); attribute; attribute++) { xml += " " + attribute->first + "=\"" + attribute->second + "\""; } if (element->value.empty() && element->children.empty()) { xml += "/>"; } else { xml += ">" + element->value; for (TConstIterator child(element->children); child; child++) { saveToString(*child, xml); } xml += "name + ">"; } } CXmlUtils.cpp000066400000000000000000000066531321503522500347310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/XmlUtils/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Xml/MarkupParser/CMarkupParser.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Exception/CCafException.h" #include "CXmlUtils.h" using namespace Caf; SmartPtrCXmlElement CXmlUtils::parseFile( const std::string& path, const std::string& rootName) { CAF_CM_STATIC_FUNC("CXmlUtils", "parseFile"); CAF_CM_VALIDATE_STRING(path); // rootName is optional if (!FileSystemUtils::doesFileExist(path)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "File not found: %s", path.c_str()); } const MarkupParser::SmartPtrElement element = MarkupParser::parseFile(path); CAF_CM_VALIDATE_SMARTPTR(element); CAF_CM_VALIDATE_STRING(element->name); if (!rootName.empty()) { CAF_CM_VALIDATE_COND_VA3(element->name == rootName, "root not valid (\"%s\" != \"%s\") in %s", rootName.c_str(), element->name.c_str(), path.c_str()); } SmartPtrCXmlElement xmlElement; xmlElement.CreateInstance(); xmlElement->initialize(element, path); return xmlElement; } SmartPtrCXmlElement CXmlUtils::parseString( const std::string& xml, const std::string& rootName) { CAF_CM_STATIC_FUNC("CXmlUtils", "parseString"); CAF_CM_VALIDATE_STRING(xml); // rootName is optional const std::string path = "fromString"; const MarkupParser::SmartPtrElement element = MarkupParser::parseString(xml); CAF_CM_VALIDATE_SMARTPTR(element); CAF_CM_VALIDATE_STRING(element->name); if (!rootName.empty()) { CAF_CM_VALIDATE_COND_VA3(element->name == rootName, "root not valid (\"%s\" != \"%s\") in %s", rootName.c_str(), element->name.c_str(), path.c_str()); } SmartPtrCXmlElement xmlElement; xmlElement.CreateInstance(); xmlElement->initialize(element, path); return xmlElement; } SmartPtrCXmlElement CXmlUtils::createRootElement( const std::string& rootName, const std::string& rootNamespace) { CAF_CM_STATIC_FUNC_VALIDATE("CXmlUtils", "createRootElement"); CAF_CM_VALIDATE_STRING(rootName); CAF_CM_VALIDATE_STRING(rootNamespace); return createRootElement(rootName, rootNamespace, std::string()); } SmartPtrCXmlElement CXmlUtils::createRootElement( const std::string& rootName, const std::string& rootNamespace, const std::string& schemaLocation) { CAF_CM_STATIC_FUNC_VALIDATE("CXmlUtils", "createRootElement"); CAF_CM_VALIDATE_STRING(rootName); CAF_CM_VALIDATE_STRING(rootNamespace); // schemaLocation is optional MarkupParser::SmartPtrElement element; element.CreateInstance(); SmartPtrCXmlElement xmlElement; xmlElement.CreateInstance(); xmlElement->initialize(element, "createRootElement"); xmlElement->addAttribute("xmlns:caf", rootNamespace); if (!schemaLocation.empty()) { const std::string fullSchemaLocation = rootNamespace + " " + schemaLocation; xmlElement->addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xmlElement->addAttribute("xsi:schemaLocation", fullSchemaLocation); } element->name = "caf:" + rootName; return xmlElement; } std::string CXmlUtils::escape(const std::string& text) { CAF_CM_STATIC_FUNC("CXmlUtils", "escape"); std::string rc; gchar* gRc = NULL; try { CAF_CM_VALIDATE_STRING(text); gRc = g_markup_escape_text(text.c_str(), -1); if (gRc) { rc = gRc; g_free(gRc); gRc = NULL; } } CAF_CM_CATCH_DEFAULT try { if (gRc) { g_free(gRc); } } CAF_CM_CATCH_DEFAULT CAF_CM_THROWEXCEPTION; return rc; } CXmlUtils.h000066400000000000000000000015741321503522500343730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/XmlUtils/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CXmlUtils_H_ #define CXmlUtils_H_ #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { class XMLUTILS_LINKAGE CXmlUtils { public: static SmartPtrCXmlElement parseFile( const std::string& path, const std::string& rootName); static SmartPtrCXmlElement parseString( const std::string& xml, const std::string& rootName); static SmartPtrCXmlElement createRootElement( const std::string& rootName, const std::string& rootNamespace); static SmartPtrCXmlElement createRootElement( const std::string& rootName, const std::string& rootNamespace, const std::string& schemaLocation); static std::string escape( const std::string& text); private: CAF_CM_DECLARE_NOCREATE(CXmlUtils); }; } #endif /* CXmlUtils_H_ */ XmlUtilsLink.h000066400000000000000000000007711321503522500351040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/XmlUtils/* * Author: mdonahue * Created: Sep 28, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef XMLUTILSLINK_H_ #define XMLUTILSLINK_H_ #ifndef XMLUTILS_LINKAGE #ifdef WIN32 #ifdef FRAMEWORK_BUILD #define XMLUTILS_LINKAGE __declspec(dllexport) #else #define XMLUTILS_LINKAGE __declspec(dllimport) #endif #else #define XMLUTILS_LINKAGE #endif #endif #include "CXmlUtils.h" #endif stdafx.h000066400000000000000000000012401321503522500337660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/Xml/XmlUtils/* * Author: mdonahue * Created: Sep 28, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef STDAFX_H_ #define STDAFX_H_ #ifdef WIN32 #define XMLUTILS_LINKAGE __declspec(dllexport) #define COMMONAGGREGATOR_LINKAGE __declspec(dllexport) #else #define XMLUTILS_LINKAGE #define COMMONAGGREGATOR_LINKAGE #endif #include #include #include "../../Exception/ExceptionLink.h" #include "../../Logging/LoggingLink.h" #include "../../Collections/Iterators/IteratorsInc.h" #include "../../Common/CFileSystemUtils.h" #include "../MarkupParser/MarkupParserLink.h" #endif /* STDAFX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Framework/src/stdafx.h000066400000000000000000000005021321503522500315240ustar00rootroot00000000000000/* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ #ifdef WIN32 #define BASEPLATFORM_LINKAGE __declspec(dllexport) #else #define BASEPLATFORM_LINKAGE #endif #include #include "BasePlatformInc.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Makefile.am000066400000000000000000001026561321503522500274070ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ AUTOMAKE_OPTIONS = subdir-objects subsysdir = @CAF_SUBSYS_DIR@ subsys_LTLIBRARIES = caflibdir = @CAF_PME_LIB_DIR@ caflib_LTLIBRARIES = caflib_LTLIBRARIES += libFramework.la libFramework_la_SOURCES= libFramework_la_SOURCES += Framework/src/BasePlatform.cpp libFramework_la_SOURCES += Framework/src/Common/AppConfigUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CAppConfig.cpp libFramework_la_SOURCES += Framework/src/Common/CApplicationContext.cpp libFramework_la_SOURCES += Framework/src/Common/CAutoCondition.cpp libFramework_la_SOURCES += Framework/src/Common/CAutoFileUnlock.cpp libFramework_la_SOURCES += Framework/src/Common/CAutoMutex.cpp libFramework_la_SOURCES += Framework/src/Common/CAutoMutexLockUnlock.cpp libFramework_la_SOURCES += Framework/src/Common/CAutoMutexLockUnlockRaw.cpp libFramework_la_SOURCES += Framework/src/Common/CAutoMutexUnlockLock.cpp libFramework_la_SOURCES += Framework/src/Common/CAutoRecMutex.cpp libFramework_la_SOURCES += Framework/src/Common/CCafRegex.cpp libFramework_la_SOURCES += Framework/src/Common/CCmdLineOptions.cpp libFramework_la_SOURCES += Framework/src/Common/CConfigParams.cpp libFramework_la_SOURCES += Framework/src/Common/CConfigParamsChain.cpp libFramework_la_SOURCES += Framework/src/Common/CDaemonUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CDateTimeUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CEnvironmentUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CFileLock.cpp libFramework_la_SOURCES += Framework/src/Common/CFileSystemUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CHexCodec.cpp libFramework_la_SOURCES += Framework/src/Common/CIniFile.cpp libFramework_la_SOURCES += Framework/src/Common/CLoggingSetter.cpp libFramework_la_SOURCES += Framework/src/Common/CLoggingUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CManagedThreadPool.cpp libFramework_la_SOURCES += Framework/src/Common/CPersistenceUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CProcessUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CStringUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CThreadPool.cpp libFramework_la_SOURCES += Framework/src/Common/CThreadSignal.cpp libFramework_la_SOURCES += Framework/src/Common/CThreadUtils.cpp libFramework_la_SOURCES += Framework/src/Common/CTimeUnit.cpp libFramework_la_SOURCES += Framework/src/Common/CVariant.cpp libFramework_la_SOURCES += Framework/src/Common/CafInitialize.cpp libFramework_la_SOURCES += Framework/src/Common/UriUtils.cpp libFramework_la_SOURCES += Framework/src/CommonGlobals.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CAddInCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CAddInsDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CAttachmentCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CAttachmentDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CAuthnAuthzCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CAuthnAuthzDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CClassFiltersDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CClassSpecifierDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CInlineAttachmentCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CInlineAttachmentDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CLoggingLevelCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CLoggingLevelElemDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/COperationDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CParameterCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CPropertyCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CPropertyDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CProtocolCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CProtocolDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CRequestConfigDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CRequestHeaderDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CRequestInstanceParameterDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CRequestParameterDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafCoreTypesDoc/CStatisticsDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CFullPackageElemDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CGetInventoryJobDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CInstallBatchDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CInstallPackageSpecDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CInstallProviderJobDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CInstallProviderSpecDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CInstallRequestDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CMinPackageElemDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CPackageDefnDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/CafInstallRequestDoc/CUninstallProviderJobDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/DiagRequestDoc/CDiagRequestDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/DiagTypesDoc/CDiagBatchDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/DiagTypesDoc/CDiagCollectInstancesDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/DiagTypesDoc/CDiagDeleteValueDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/DiagTypesDoc/CDiagSetValueCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/DiagTypesDoc/CDiagSetValueDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MgmtRequestDoc/CMgmtRequestDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MgmtTypesDoc/CMgmtBatchDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MgmtTypesDoc/CMgmtCollectInstancesDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MgmtTypesDoc/CMgmtCollectSchemaDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MgmtTypesDoc/CMgmtInvokeOperationDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtBatchDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/CMultiPmeMgmtRequestDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/MultiPmeMgmtRequestDoc/CPmeIdCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PersistenceDoc/CCertCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PersistenceDoc/CCertPathCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PersistenceDoc/CLocalSecurityDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PersistenceDoc/CPersistenceDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PersistenceDoc/CPersistenceProtocolCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PersistenceDoc/CPersistenceProtocolDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PersistenceDoc/CRemoteSecurityCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/PersistenceDoc/CRemoteSecurityDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderInfraDoc/CClassCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderInfraDoc/CProviderRegDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderInfraDoc/CSchemaSummaryDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderBatchDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderCollectInstancesDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderInvokeOperationDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderRequestConfigDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderRequestDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderRequestDoc/CProviderRequestHeaderDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderResultsDoc/CCdifDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderResultsDoc/CDefinitionObjectCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderResultsDoc/CRequestIdentifierDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ProviderResultsDoc/CSchemaDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CErrorResponseDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CEventKeyCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CEventKeyDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CEventManifestDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CManifestCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CManifestDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CProviderEventResponseDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CProviderResponseDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CResponseDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/ResponseDoc/CResponseHeaderDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CActionClassDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CActionClassInstanceCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CActionClassInstanceDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CClassCardinalityDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CClassFieldDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CClassIdentifierDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CClassInstancePropertyDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CClassPropertyDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CCmdlMetadataDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CCmdlUnionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CCollectMethodDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CDataClassDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CDataClassInstanceCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CDataClassInstanceDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CDataClassPropertyDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CDataClassSubInstanceDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CInstanceOperationCollectionDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CInstanceOperationDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CInstanceParameterDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CJoinTypeDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CLogicalRelationshipDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CMethodDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CMethodParameterDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CPhysicalRelationshipDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocDoc/SchemaTypesDoc/CRelationshipDoc.cpp libFramework_la_SOURCES += Framework/src/Doc/DocUtils/AttachmentUtils.cpp libFramework_la_SOURCES += Framework/src/Doc/DocUtils/DefnObjectConverter.cpp libFramework_la_SOURCES += Framework/src/Doc/DocUtils/DocXmlUtils.cpp libFramework_la_SOURCES += Framework/src/Doc/DocUtils/EnumConvertersXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocUtils/ParameterUtils.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/AddInCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/AddInsXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/AttachmentCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/AttachmentNameCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/AttachmentXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/AuthnAuthzCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/AuthnAuthzXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/ClassFiltersXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/ClassSpecifierXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/FullyQualifiedClassGroupXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/LoggingLevelCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/LoggingLevelElemXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/OperationXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/ParameterCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/PropertyCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/PropertyXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/ProtocolCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/ProtocolXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/RequestConfigXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/RequestHeaderXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/RequestInstanceParameterXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/RequestParameterXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/RequestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafCoreTypesXml/StatisticsXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/FullPackageElemXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/GetInventoryJobXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/InstallBatchXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/InstallPackageSpecXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/InstallProviderJobXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/InstallProviderSpecXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/InstallRequestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/MinPackageElemXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/PackageDefnXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/CafInstallRequestXml/UninstallProviderJobXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/DiagRequestXml/DiagRequestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/DiagRequestXml/DiagRequestXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/DiagTypesXml/DiagBatchXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/DiagTypesXml/DiagCollectInstancesXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/DiagTypesXml/DiagDeleteValueCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/DiagTypesXml/DiagDeleteValueXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/DiagTypesXml/DiagSetValueCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/DiagTypesXml/DiagSetValueXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MgmtRequestXml/MgmtRequestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MgmtRequestXml/MgmtRequestXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MgmtTypesXml/MgmtBatchXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MgmtTypesXml/MgmtCollectInstancesCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MgmtTypesXml/MgmtCollectInstancesXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MgmtTypesXml/MgmtCollectSchemaXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MgmtTypesXml/MgmtInvokeOperationCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MgmtTypesXml/MgmtInvokeOperationXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtBatchCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtBatchXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/MultiPmeMgmtRequestXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/MultiPmeMgmtRequestXml/PmeIdCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PayloadEnvelopeXml/PayloadEnvelopeXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/CertCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/CertPathCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/LocalSecurityXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/PersistenceProtocolCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/PersistenceProtocolXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/PersistenceXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/PersistenceXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/RemoteSecurityCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/PersistenceXml/RemoteSecurityXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderInfraXml/ClassCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderInfraXml/ProviderInfraXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderInfraXml/ProviderRegXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderInfraXml/SchemaSummaryXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderBatchXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderCollectInstancesCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderCollectInstancesXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderCollectSchemaRequestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderInvokeOperationCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderInvokeOperationXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderRequestConfigXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderRequestHeaderXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderRequestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderRequestXml/ProviderRequestXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderResultsXml/CdifXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderResultsXml/DefinitionObjectCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderResultsXml/ProviderResultsXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderResultsXml/RequestIdentifierXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ProviderResultsXml/SchemaXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/ErrorResponseXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/EventKeyCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/EventKeyXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/EventManifestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/ManifestCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/ManifestXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/ProviderEventResponseXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/ProviderResponseXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/ResponseHeaderXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/ResponseXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/ResponseXml/ResponseXmlRoots.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/ActionClassInstanceCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/ActionClassInstanceXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/ActionClassXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/ClassCardinalityXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/ClassFieldXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/ClassIdentifierXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/ClassInstancePropertyXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/ClassPropertyXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/CmdlMetadataXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/CmdlUnionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/CollectMethodXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/DataClassInstanceCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/DataClassInstanceXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/DataClassPropertyXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/DataClassSubInstanceXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/DataClassXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/InstanceOperationCollectionXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/InstanceOperationXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/InstanceParameterXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/JoinTypeXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/LogicalRelationshipXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/MethodParameterXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/MethodXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/PhysicalRelationshipXml.cpp libFramework_la_SOURCES += Framework/src/Doc/DocXml/SchemaTypesXml/RelationshipXml.cpp libFramework_la_SOURCES += Framework/src/Exception/CBacktraceUtils.cpp libFramework_la_SOURCES += Framework/src/Exception/CCafException.cpp libFramework_la_SOURCES += Framework/src/Exception/CCafExceptionEx.cpp libFramework_la_SOURCES += Framework/src/Exception/CValidate.cpp libFramework_la_SOURCES += Framework/src/Integration/Caf/CBeanPropertiesHelper.cpp libFramework_la_SOURCES += Framework/src/Integration/Caf/CCafMessageCreator.cpp libFramework_la_SOURCES += Framework/src/Integration/Caf/CCafMessageHeaders.cpp libFramework_la_SOURCES += Framework/src/Integration/Caf/CCafMessageHeadersWriter.cpp libFramework_la_SOURCES += Framework/src/Integration/Caf/CCafMessagePayload.cpp libFramework_la_SOURCES += Framework/src/Integration/Caf/CCafMessagePayloadParser.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CAbstractMessageChannel.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CAbstractMessageRouter.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CAbstractPollableChannel.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CBroadcastingDispatcher.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CChannelInterceptorAdapter.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CChannelResolver.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CDocument.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CErrorHandler.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CExpressionHandler.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CIntException.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CIntMessage.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CIntMessageHeaders.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CIntegrationAppContext.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CMessageHandler.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CMessageHeaderUtils.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CMessagingTemplate.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CMessagingTemplateHandler.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CSimpleAsyncTaskExecutor.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CSimpleAsyncTaskExecutorState.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CSourcePollingChannelAdapter.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/CUnicastingDispatcher.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/FileHeaders.cpp libFramework_la_SOURCES += Framework/src/Integration/Core/MessageHeaders.cpp libFramework_la_SOURCES += Framework/src/Logging/CLogger.cpp libFramework_la_SOURCES += Framework/src/PlatformIID.cpp libFramework_la_SOURCES += Framework/src/PlatformStringFunc.cpp libFramework_la_SOURCES += Framework/src/SubSystemBase/CEcmDllManager.cpp libFramework_la_SOURCES += Framework/src/SubSystemBase/CEcmSubSystem.cpp libFramework_la_SOURCES += Framework/src/SubSystemBase/CEcmSubSystemModule.cpp libFramework_la_SOURCES += Framework/src/SubSystemBase/CEcmSubSystemRegistry.cpp libFramework_la_SOURCES += Framework/src/SubSystemBase/EcmSubSystemBase.cpp libFramework_la_SOURCES += Framework/src/Xml/MarkupParser/CMarkupParser.cpp libFramework_la_SOURCES += Framework/src/Xml/XmlUtils/CXmlElement.cpp libFramework_la_SOURCES += Framework/src/Xml/XmlUtils/CXmlUtils.cpp libFramework_la_CPPFLAGS = libFramework_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libFramework_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libFramework_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libFramework_la_LIBADD = libFramework_la_LIBADD += @GLIB2_LIBS@ libFramework_la_LIBADD += @LOG4CPP_LIBS@ libFramework_la_LIBADD += -ldl libFramework_la_LDFLAGS = -shared subsys_LTLIBRARIES += libIntegrationSubsys.la libIntegrationSubsys_la_LDFLAGS = @CAF_SUBSYS_LDFLAGS@ libIntegrationSubsys_la_SOURCES= libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CDirectChannelInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CErrorChannel.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CErrorChannelInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CFileInboundChannelAdapterInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CFileOutboundChannelAdapterInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CFileReadingMessageSource.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CFileToStringTransformerInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CHeaderEnricherTransformerInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CHeaderExpressionInvoker.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CHeaderValueRouterInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CIntegrationObjectFactory.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CLoggingChannelAdapterInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CMessageHandlerChainInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CNullChannel.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CNullChannelInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CObjectFactoryTables.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CPayloadContentRouterInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CPublishSubscribeChannelInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CQueueChannelInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CRecipientListRouterInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CRouterInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CServiceActivatorInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CWireTapInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CXPathHeaderEnricherItem.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/CXPathHeaderEnricherTransformerInstance.cpp libIntegrationSubsys_la_SOURCES += Subsystems/Integration/src/Integration.cpp libIntegrationSubsys_la_CPPFLAGS = libIntegrationSubsys_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libIntegrationSubsys_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Subsystems/Integration/include libIntegrationSubsys_la_LIBADD = libIntegrationSubsys_la_LIBADD += @GLIB2_LIBS@ libIntegrationSubsys_la_LIBADD += @LOG4CPP_LIBS@ libIntegrationSubsys_la_LIBADD += -ldl libIntegrationSubsys_la_LIBADD += ../Framework/libFramework.la libIntegrationSubsys_la_LDFLAGS += -shared subsys_LTLIBRARIES += libCafIntegrationSubsys.la libCafIntegrationSubsys_la_LDFLAGS = @CAF_SUBSYS_LDFLAGS@ libCafIntegrationSubsys_la_SOURCES= libCafIntegrationSubsys_la_SOURCES += Subsystems/CafIntegration/src/CEnvelopeToPayloadTransformer.cpp libCafIntegrationSubsys_la_SOURCES += Subsystems/CafIntegration/src/CEnvelopeToPayloadTransformerInstance.cpp libCafIntegrationSubsys_la_SOURCES += Subsystems/CafIntegration/src/CErrorToResponseTransformer.cpp libCafIntegrationSubsys_la_SOURCES += Subsystems/CafIntegration/src/CErrorToResponseTransformerInstance.cpp libCafIntegrationSubsys_la_SOURCES += Subsystems/CafIntegration/src/CPayloadHeaderEnricher.cpp libCafIntegrationSubsys_la_SOURCES += Subsystems/CafIntegration/src/CPayloadHeaderEnricherInstance.cpp libCafIntegrationSubsys_la_SOURCES += Subsystems/CafIntegration/src/CafIntegration.cpp libCafIntegrationSubsys_la_CPPFLAGS = libCafIntegrationSubsys_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libCafIntegrationSubsys_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libCafIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libCafIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Subsystems/CafIntegration/include libCafIntegrationSubsys_la_LIBADD = libCafIntegrationSubsys_la_LIBADD += @GLIB2_LIBS@ libCafIntegrationSubsys_la_LIBADD += @LOG4CPP_LIBS@ libCafIntegrationSubsys_la_LIBADD += -ldl libCafIntegrationSubsys_la_LIBADD += ../Framework/libFramework.la libCafIntegrationSubsys_la_LDFLAGS += -shared open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/000077500000000000000000000000001321503522500275225ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/000077500000000000000000000000001321503522500324175ustar00rootroot00000000000000include/000077500000000000000000000000001321503522500337635ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegrationCEnvelopeToPayloadTransformerInstance.h000066400000000000000000000047471321503522500435550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CEnvelopeToPayloadTransformerInstance_h_ #define CEnvelopeToPayloadTransformerInstance_h_ #include "Common/IAppContext.h" #include "CafIntegrationSubsys.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Integration/IErrorProcessor.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CEnvelopeToPayloadTransformerInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer, public IErrorProcessor { public: struct SExpandedFileAlias { std::string _filePath; std::string _encoding; }; CAF_DECLARE_SMART_POINTER(SExpandedFileAlias); public: CEnvelopeToPayloadTransformerInstance(); virtual ~CEnvelopeToPayloadTransformerInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdEnvelopeToPayloadTransformerInstance) CAF_BEGIN_INTERFACE_MAP(CEnvelopeToPayloadTransformerInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_INTERFACE_ENTRY(IErrorProcessor) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); public: // IErrorProcessor SmartPtrIIntMessage processErrorMessage( const SmartPtrIIntMessage& message); private: SmartPtrCDynamicByteArray findPayload( const std::deque& attachmentCollection) const; std::deque removePayload( const std::deque& attachmentCollection) const; private: bool _isInitialized; std::string _id; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CEnvelopeToPayloadTransformerInstance); }; } #endif // #ifndef CEnvelopeToPayloadTransformerInstance_h_ CafIntegrationSubsys.h000066400000000000000000000011521321503522500402410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CafIntegrationSubsys_h_ #define CafIntegrationSubsys_h_ namespace Caf { extern const char* _sObjIdErrorToResponseTransformerInstance; extern const char* _sObjIdErrorToResponseTransformer; extern const char* _sObjIdPayloadHeaderEnricherInstance; extern const char* _sObjIdPayloadHeaderEnricher; extern const char* _sObjIdEnvelopeToPayloadTransformerInstance; extern const char* _sObjIdEnvelopeToPayloadTransformer; } #endif // #ifndef CafIntegrationSubsys_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/000077500000000000000000000000001321503522500332065ustar00rootroot00000000000000CEnvelopeToPayloadTransformer.cpp000066400000000000000000000033721321503522500415600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CEnvelopeToPayloadTransformer.h" using namespace Caf; CEnvelopeToPayloadTransformer::CEnvelopeToPayloadTransformer() : _isInitialized(false), CAF_CM_INIT("CEnvelopeToPayloadTransformer") { } CEnvelopeToPayloadTransformer::~CEnvelopeToPayloadTransformer() { } void CEnvelopeToPayloadTransformer::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } void CEnvelopeToPayloadTransformer::terminateBean() { } void CEnvelopeToPayloadTransformer::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } bool CEnvelopeToPayloadTransformer::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); return false; } SmartPtrIIntegrationObject CEnvelopeToPayloadTransformer::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); SmartPtrIIntegrationObject rc; rc.CreateInstance(_sObjIdEnvelopeToPayloadTransformerInstance); rc->initialize(_ctorArgs, _properties, configSection); return rc; } CEnvelopeToPayloadTransformer.h000066400000000000000000000027321321503522500412240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CEnvelopeToPayloadTransformer_h_ #define CEnvelopeToPayloadTransformer_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CEnvelopeToPayloadTransformer : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CEnvelopeToPayloadTransformer(); virtual ~CEnvelopeToPayloadTransformer(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdEnvelopeToPayloadTransformer) CAF_BEGIN_INTERFACE_MAP(CEnvelopeToPayloadTransformer) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CEnvelopeToPayloadTransformer); }; } #endif // #ifndef CEnvelopeToPayloadTransformer_h_ CEnvelopeToPayloadTransformerInstance.cpp000066400000000000000000000110031321503522500432330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CEnvelopeToPayloadTransformerInstance.h" #include "Exception/CCafException.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Caf/CCafMessageCreator.h" using namespace Caf; CEnvelopeToPayloadTransformerInstance::CEnvelopeToPayloadTransformerInstance() : _isInitialized(false), CAF_CM_INIT("CEnvelopeToPayloadTransformerInstance") { } CEnvelopeToPayloadTransformerInstance::~CEnvelopeToPayloadTransformerInstance() { } void CEnvelopeToPayloadTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CEnvelopeToPayloadTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CEnvelopeToPayloadTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } SmartPtrIIntMessage CEnvelopeToPayloadTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); const std::deque attachmentCollection = payloadEnvelope->getAttachmentCollection()->getAttachment(); const SmartPtrCDynamicByteArray payload= findPayload(attachmentCollection); const std::deque attachmentCollectionRm = removePayload(attachmentCollection); return CCafMessageCreator::create( payload, attachmentCollectionRm, message->getHeaders()); } SmartPtrIIntMessage CEnvelopeToPayloadTransformerInstance::processErrorMessage( const SmartPtrIIntMessage& message) { return transformMessage(message); } SmartPtrCDynamicByteArray CEnvelopeToPayloadTransformerInstance::findPayload( const std::deque& attachmentCollection) const { CAF_CM_FUNCNAME("findPayload"); CAF_CM_VALIDATE_STL(attachmentCollection); std::string payloadPath; for (TConstIterator > attachmentIter(attachmentCollection); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; if (attachment->getName().compare("_EnvelopePayload_") == 0) { UriUtils::SUriRecord sourceUriRecord; UriUtils::parseUriString(attachment->getUri(), sourceUriRecord); if (sourceUriRecord.protocol.compare("file") != 0) { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_STATE, "Payload attachment must be a file - uri: %s", attachment->getUri().c_str()); } UriUtils::SFileUriRecord sourceFileUriRecord; UriUtils::parseFileAddress(sourceUriRecord.address, sourceFileUriRecord); payloadPath = sourceFileUriRecord.path; if (!FileSystemUtils::doesFileExist(payloadPath)) { CAF_CM_EXCEPTION_VA1(ERROR_FILE_NOT_FOUND, "File not found - %s", payloadPath.c_str()); } } } if (payloadPath.empty()) { CAF_CM_EXCEPTION_VA0(ERROR_NOT_FOUND, "Payload attachment not found"); } return FileSystemUtils::loadByteFile(payloadPath); } std::deque CEnvelopeToPayloadTransformerInstance::removePayload( const std::deque& attachmentCollection) const { CAF_CM_FUNCNAME_VALIDATE("removePayload"); CAF_CM_VALIDATE_STL(attachmentCollection); std::deque rc; for (TConstIterator > attachmentIter(attachmentCollection); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; if (attachment->getName().compare("_EnvelopePayload_") != 0) { rc.push_back(attachment); } } return rc; } CErrorToResponseTransformer.cpp000066400000000000000000000035701321503522500413010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CErrorToResponseTransformer.h" using namespace Caf; CErrorToResponseTransformer::CErrorToResponseTransformer() : _isInitialized(false), CAF_CM_INIT("CErrorToResponseTransformer") { } CErrorToResponseTransformer::~CErrorToResponseTransformer() { } void CErrorToResponseTransformer::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CErrorToResponseTransformer::terminateBean() { } void CErrorToResponseTransformer::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CErrorToResponseTransformer::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CErrorToResponseTransformer::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); rc.CreateInstance(_sObjIdErrorToResponseTransformerInstance); rc->initialize(_ctorArgs, _properties, configSection); } CAF_CM_EXIT; return rc; } CErrorToResponseTransformer.h000066400000000000000000000027061321503522500407460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CErrorToResponseTransformer_h_ #define CErrorToResponseTransformer_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CErrorToResponseTransformer : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CErrorToResponseTransformer(); virtual ~CErrorToResponseTransformer(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdErrorToResponseTransformer) CAF_BEGIN_INTERFACE_MAP(CErrorToResponseTransformer) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CErrorToResponseTransformer); }; } #endif // #ifndef CErrorToResponseTransformer_h_ CErrorToResponseTransformerInstance.cpp000066400000000000000000000072021321503522500427620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Caf/CCafMessageHeaders.h" #include "Common/IAppContext.h" #include "Doc/ResponseDoc/CErrorResponseDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CErrorToResponseTransformerInstance.h" #include "Integration/Caf/CCafMessageCreator.h" using namespace Caf; CErrorToResponseTransformerInstance::CErrorToResponseTransformerInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CErrorToResponseTransformerInstance") { } CErrorToResponseTransformerInstance::~CErrorToResponseTransformerInstance() { } void CErrorToResponseTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _isInitialized = true; } CAF_CM_EXIT; } std::string CErrorToResponseTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CErrorToResponseTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } CAF_CM_EXIT; } SmartPtrIIntMessage CErrorToResponseTransformerInstance::processErrorMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("processErrorMessage"); SmartPtrIIntMessage newMessage; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA1("Called - %s", _id.c_str()); const SmartPtrCCafMessageHeaders cafMessageHeaders = CCafMessageHeaders::create(message->getHeaders()); const std::string errorMessage = message->getPayloadStr(); const UUID clientId = cafMessageHeaders->getClientIdOpt(); const UUID requestId = cafMessageHeaders->getRequestIdOpt(); const std::string pmeIdStr = cafMessageHeaders->getPmeIdOpt(); const UUID sessionId = cafMessageHeaders->getSessionIdOpt(); const std::string version = "1.0"; const std::string createdDateTime = CDateTimeUtils::getCurrentDateTime(); const uint32 sequenceNumber = 0; const bool isFinalResponse = true; SmartPtrCResponseHeaderDoc responseHeader; responseHeader.CreateInstance(); responseHeader->initialize( version, createdDateTime, sequenceNumber, isFinalResponse, sessionId); SmartPtrCErrorResponseDoc errorResponse; errorResponse.CreateInstance(); errorResponse->initialize( clientId, requestId, pmeIdStr, responseHeader, errorMessage); const std::string randomUuidStr = CStringUtils::createRandomUuid(); const std::string relFilename = randomUuidStr + "_" + _sErrorResponseFilename; newMessage = CCafMessageCreator::createPayloadEnvelope( errorResponse, relFilename, message->getHeaders()); // Writing the error response for debugging purposes const std::string tmpDir = AppConfigUtils::getRequiredString(_sConfigTmpDir); FileSystemUtils::saveTextFile(tmpDir, _sErrorResponseFilename, newMessage->getPayloadStr()); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; return newMessage; } CErrorToResponseTransformerInstance.h000066400000000000000000000034631321503522500424340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CErrorToResponseTransformerInstance_h_ #define CErrorToResponseTransformerInstance_h_ #include "CafIntegrationSubsys.h" #include "Common/IAppContext.h" #include "Integration/IErrorProcessor.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" namespace Caf { class CErrorToResponseTransformerInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public IErrorProcessor { public: CErrorToResponseTransformerInstance(); virtual ~CErrorToResponseTransformerInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdErrorToResponseTransformerInstance) CAF_BEGIN_INTERFACE_MAP(CErrorToResponseTransformerInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(IErrorProcessor) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // IErrorProcessor SmartPtrIIntMessage processErrorMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CErrorToResponseTransformerInstance); }; } #endif // #ifndef CErrorToResponseTransformerInstance_h_ CPayloadHeaderEnricher.cpp000066400000000000000000000034251321503522500401240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CPayloadHeaderEnricher.h" using namespace Caf; CPayloadHeaderEnricher::CPayloadHeaderEnricher() : _isInitialized(false), CAF_CM_INIT("CPayloadHeaderEnricher") { } CPayloadHeaderEnricher::~CPayloadHeaderEnricher() { } void CPayloadHeaderEnricher::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CPayloadHeaderEnricher::terminateBean() { } void CPayloadHeaderEnricher::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CPayloadHeaderEnricher::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CPayloadHeaderEnricher::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); rc.CreateInstance(_sObjIdPayloadHeaderEnricherInstance); rc->initialize(_ctorArgs, _properties, configSection); } CAF_CM_EXIT; return rc; } CPayloadHeaderEnricher.h000066400000000000000000000026331321503522500375710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPayloadHeaderEnricher_h_ #define CPayloadHeaderEnricher_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CPayloadHeaderEnricher : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CPayloadHeaderEnricher(); virtual ~CPayloadHeaderEnricher(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdPayloadHeaderEnricher) CAF_BEGIN_INTERFACE_MAP(CPayloadHeaderEnricher) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CPayloadHeaderEnricher); }; } #endif // #ifndef CPayloadHeaderEnricher_h_ CPayloadHeaderEnricherInstance.cpp000066400000000000000000000071341321503522500416120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Caf/CBeanPropertiesHelper.h" #include "Integration/Caf/CCafMessageHeadersWriter.h" #include "Common/IAppContext.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CPayloadHeaderEnricherInstance.h" #include "Integration/Caf/CCafMessagePayloadParser.h" using namespace Caf; CPayloadHeaderEnricherInstance::CPayloadHeaderEnricherInstance() : _isInitialized(false), _includeFilename(false), CAF_CM_INIT_LOG("CPayloadHeaderEnricherInstance") { } CPayloadHeaderEnricherInstance::~CPayloadHeaderEnricherInstance() { } void CPayloadHeaderEnricherInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); const SmartPtrCBeanPropertiesHelper beanProperties = CBeanPropertiesHelper::create(properties); _includeFilename = beanProperties->getOptionalBool("includeFilename", true); _isInitialized = true; } std::string CPayloadHeaderEnricherInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CPayloadHeaderEnricherInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } SmartPtrIIntMessage CPayloadHeaderEnricherInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); const std::string payloadType = payloadEnvelope->getPayloadType(); const std::string clientIdStr = BasePlatform::UuidToString(payloadEnvelope->getClientId()); const std::string requestIdStr = BasePlatform::UuidToString(payloadEnvelope->getRequestId()); const std::string pmeIdStr = payloadEnvelope->getPmeId(); const std::string version = payloadEnvelope->getVersion(); const std::string payloadVersion = payloadEnvelope->getPayloadVersion(); SmartPtrCCafMessageHeadersWriter messageHeadersWriter = CCafMessageHeadersWriter::create(); messageHeadersWriter->setPayloadType(payloadType); messageHeadersWriter->setClientId(clientIdStr); messageHeadersWriter->setRequestId(requestIdStr); messageHeadersWriter->setPmeId(pmeIdStr); messageHeadersWriter->setVersion(version); messageHeadersWriter->setPayloadVersion(payloadVersion); if (_includeFilename) { std::string relFilename = FileSystemUtils::buildPath( clientIdStr, requestIdStr, pmeIdStr); relFilename = FileSystemUtils::buildPath(relFilename, _sPayloadRequestFilename); messageHeadersWriter->setRelFilename(relFilename); CAF_CM_LOG_DEBUG_VA2( "Enhanced the headers - payloadType: \"%s\", filename: \"%s\"", payloadType.c_str(), relFilename.c_str()); } SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initialize(message->getPayload(), messageHeadersWriter->getHeaders(), message->getHeaders()); return messageImpl; } CPayloadHeaderEnricherInstance.h000066400000000000000000000033521321503522500412550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPayloadHeaderEnricherInstance_h_ #define CPayloadHeaderEnricherInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CPayloadHeaderEnricherInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CPayloadHeaderEnricherInstance(); virtual ~CPayloadHeaderEnricherInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdPayloadHeaderEnricherInstance) CAF_BEGIN_INTERFACE_MAP(CPayloadHeaderEnricherInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; bool _includeFilename; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CPayloadHeaderEnricherInstance); }; } #endif // #ifndef CPayloadHeaderEnricherInstance_h_ CafIntegration.cpp000066400000000000000000000034431321503522500365340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CEnvelopeToPayloadTransformerInstance.h" using namespace Caf; namespace Caf { const char* _sObjIdErrorToResponseTransformerInstance = "com.vmware.commonagent.cafintegration.errortoresponsetransformerinstance"; const char* _sObjIdErrorToResponseTransformer = "com.vmware.commonagent.cafintegration.errortoresponsetransformer"; const char* _sObjIdPayloadHeaderEnricherInstance = "com.vmware.commonagent.cafintegration.payloadheaderenricherinstance"; const char* _sObjIdPayloadHeaderEnricher = "com.vmware.commonagent.cafintegration.payloadheaderenricher"; const char* _sObjIdEnvelopeToPayloadTransformerInstance = "com.vmware.commonagent.cafintegration.envelopetopayloadtransformerinstance"; const char* _sObjIdEnvelopeToPayloadTransformer = "com.vmware.commonagent.cafintegration.envelopetopayloadtransformer"; } CEcmSubSystemModule _Module; CAF_BEGIN_OBJECT_MAP(ObjectMap) CAF_OBJECT_ENTRY(CErrorToResponseTransformer) CAF_OBJECT_ENTRY(CErrorToResponseTransformerInstance) CAF_OBJECT_ENTRY(CPayloadHeaderEnricher) CAF_OBJECT_ENTRY(CPayloadHeaderEnricherInstance) CAF_OBJECT_ENTRY(CEnvelopeToPayloadTransformer) CAF_OBJECT_ENTRY(CEnvelopeToPayloadTransformerInstance) CAF_END_OBJECT_MAP() CAF_DECLARE_SUBSYSTEM_EXPORTS() extern "C" BOOL APIENTRY DllMain(HINSTANCE hModule, uint32 dwReason, LPVOID) { try { if (DLL_PROCESS_ATTACH == dwReason) { // initialize the sub-system module _Module.Init(ObjectMap, hModule); } else if (DLL_PROCESS_DETACH == dwReason) { // Terminate the sub-system module _Module.Term(); } } catch (std::runtime_error) { ::exit(2); } catch (...) { ::exit(2); } return TRUE; } stdafx.h000066400000000000000000000010111321503522500345620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/CafIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ //{{CAF_SUBSYSTEM}} #include #include #include #include "CErrorToResponseTransformerInstance.h" #include "CErrorToResponseTransformer.h" #include "CPayloadHeaderEnricherInstance.h" #include "CPayloadHeaderEnricher.h" #include "CEnvelopeToPayloadTransformer.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/000077500000000000000000000000001321503522500320055ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/include/000077500000000000000000000000001321503522500334305ustar00rootroot00000000000000CFileReadingMessageSource.h000066400000000000000000000033341321503522500404670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CFileReadingMessageSource_h_ #define CFileReadingMessageSource_h_ #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/Core/CAbstractPollableChannel.h" namespace Caf { class CFileReadingMessageSource : public CAbstractPollableChannel { private: typedef std::map CFileCollection; CAF_DECLARE_SMART_POINTER(CFileCollection); public: CFileReadingMessageSource(); virtual ~CFileReadingMessageSource(); public: void initialize( const SmartPtrIDocument& configSection); protected: // CAbstractPollableChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); SmartPtrIIntMessage doReceive(const int32 timeout); private: SmartPtrCFileCollection itemsInDirectory( const std::string& directory, const std::string& filenameRegex) const; SmartPtrCFileCollection merge( const SmartPtrCFileCollection& newFileCollection, const SmartPtrCFileCollection& existingFileCollection) const; std::string calcNextFile( SmartPtrCFileCollection& fileCollection) const; uint64 getTimeSec() const; bool isRefreshNecessary( const uint32 refreshSec, const uint64 lastRefreshSec) const; private: bool _isInitialized; std::string _id; std::string _directory; std::string _filenameRegex; bool _preventDuplicates; uint32 _refreshSec; uint64 _lastRefreshSec; SmartPtrCFileCollection _fileCollection; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CFileReadingMessageSource); }; CAF_DECLARE_SMART_POINTER(CFileReadingMessageSource); } #endif // #ifndef CFileReadingMessageSource_h_ CMessageHandlerChainInstance.h000066400000000000000000000106211321503522500411370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/include/* * Created on: Aug 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMessageHandlerChainInstance_h #define CMessageHandlerChainInstance_h #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "ICafObject.h" #include "Integration/Core/CMessageHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/ISubscribableChannel.h" #include "Integration/ITaskExecutor.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" #include "Integration/IMessageChannel.h" #include "Integration/IMessageHandler.h" namespace Caf { class CMessageHandlerChainInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle, public IMessageHandler { public: CMessageHandlerChainInstance(); virtual ~CMessageHandlerChainInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(IMessageHandler) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // IMessageHandler void handleMessage( const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); private: void logMessage(const SmartPtrIIntMessage& message) const; private: class ChainedMessageHandler { public: ChainedMessageHandler(); void init( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); void setId(const std::string& id); void setOutputChannel(const SmartPtrIMessageChannel& channel); void setMessageHandler(const SmartPtrICafObject& handlerObj); void handleMessage(const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); private: void logMessage(const SmartPtrIIntMessage& message) const; private: bool _isInitialized; std::string _id; SmartPtrIMessageChannel _outputChannel; SmartPtrICafObject _messageHandlerObj; SmartPtrCMessageHandler _messageHandler; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(ChainedMessageHandler); }; CAF_DECLARE_SMART_POINTER(ChainedMessageHandler); typedef std::deque MessageHandlers; class InterconnectChannel : public IMessageChannel { public: InterconnectChannel(); virtual ~InterconnectChannel(); void init(const SmartPtrChainedMessageHandler& nextHandler); bool send( const SmartPtrIIntMessage& message); bool send( const SmartPtrIIntMessage& message, const int32 timeout); private: SmartPtrChainedMessageHandler _nextHandler; CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(InterconnectChannel); }; CAF_DECLARE_SMART_POINTER(InterconnectChannel); struct ChainLink { CMessageHandlerChainInstance::SmartPtrChainedMessageHandler handler; std::string id; bool isMessageProducer; }; CAF_DECLARE_SMART_POINTER(ChainLink); typedef std::vector ChainLinks; class SelfWeakReference : public IMessageHandler { public: SelfWeakReference(); void setReference(IMessageHandler *handler); public: // IMessageHandler void handleMessage( const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); private: IMessageHandler *_reference; CAF_CM_CREATE_THREADSAFE; }; CAF_DECLARE_SMART_POINTER(SelfWeakReference); private: bool _isInitialized; bool _isRunning; IBean::Cargs _ctorArgs; IBean::Cprops _properties; SmartPtrIDocument _configSection; std::string _id; SmartPtrISubscribableChannel _subscribableInputChannel; SmartPtrITaskExecutor _taskExecutor; SmartPtrSelfWeakReference _weakRefSelf; MessageHandlers _messageHandlers; SmartPtrIIntMessage _savedMessage; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CMessageHandlerChainInstance); }; CAF_DECLARE_SMART_QI_POINTER(CMessageHandlerChainInstance); } #endif /* CMessageHandlerChainInstance_h */ CXPathHeaderEnricherItem.h000066400000000000000000000021531321503522500402620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CXPathHeaderEnricherItem_h_ #define CXPathHeaderEnricherItem_h_ #include "Integration/IDocument.h" namespace Caf { class CXPathHeaderEnricherItem { private: typedef std::map CFileCollection; CAF_DECLARE_SMART_POINTER(CFileCollection); public: CXPathHeaderEnricherItem(); virtual ~CXPathHeaderEnricherItem(); public: void initialize( const SmartPtrIDocument& configSection, const bool& defaultOverwrite); public: std::string getName() const; std::string getEvaluationType() const; bool getOverwrite() const; std::string getXpathExpression() const; std::string getXpathExpressionRef() const; private: bool _isInitialized; std::string _name; std::string _evaluationType; bool _overwrite; std::string _xpathExpression; std::string _xpathExpressionRef; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CXPathHeaderEnricherItem); }; CAF_DECLARE_SMART_POINTER(CXPathHeaderEnricherItem); } #endif // #ifndef CXPathHeaderEnricherItem_h_ IntegrationSubsys.h000066400000000000000000000007311321503522500372170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef IntegrationSubsys_h_ #define IntegrationSubsys_h_ namespace Caf { // Integration Contracts extern const char* _sObjIdIntegrationObjectFactory; extern const char* _sObjIdErrorChannel; extern const char* _sObjIdNullChannel; extern const char* _sObjIdHeaderExpressionInvoker; } #endif // #ifndef IntegrationSubsys_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/000077500000000000000000000000001321503522500325745ustar00rootroot00000000000000CDirectChannelInstance.cpp000066400000000000000000000063561321503522500375260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CUnicastingDispatcher.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/IMessageHandler.h" #include "Exception/CCafException.h" #include "CDirectChannelInstance.h" using namespace Caf; CDirectChannelInstance::CDirectChannelInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CDirectChannelInstance"){ } CDirectChannelInstance::~CDirectChannelInstance() { } void CDirectChannelInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CDirectChannelInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CDirectChannelInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, errorMessageChannel); SmartPtrCUnicastingDispatcher unicastingDispatcher; unicastingDispatcher.CreateInstance(); unicastingDispatcher->initialize(errorHandler); _messageDispatcher = unicastingDispatcher; } void CDirectChannelInstance::subscribe( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("subscribe"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); _messageDispatcher->addHandler(messageHandler); } void CDirectChannelInstance::unsubscribe( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("unsubscribe"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); _messageDispatcher->removeHandler(messageHandler); } bool CDirectChannelInstance::doSend( const SmartPtrIIntMessage& message, int32 timeout) { CAF_CM_FUNCNAME("doSend"); bool sent = false; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Timeout not currently supported: %s", _id.c_str()); } else { CAF_CM_LOG_DEBUG_VA1("Dispatching message - %s", _id.c_str()); sent = _messageDispatcher->dispatch(message); if (!sent) { CAF_CM_LOG_WARN_VA1("Nothing handled the message - channel: %s", _id.c_str()); } } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; return sent; } CDirectChannelInstance.h000066400000000000000000000041031321503522500371570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CDirectChannelInstance_h_ #define CDirectChannelInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageDispatcher.h" #include "Integration/IMessageHandler.h" #include "Integration/IIntegrationObject.h" #include "Integration/ISubscribableChannel.h" #include "Integration/Core/CAbstractMessageChannel.h" namespace Caf { /// Sends responses/errors back to the client. class CDirectChannelInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ISubscribableChannel, public CAbstractMessageChannel { public: CDirectChannelInstance(); virtual ~CDirectChannelInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ISubscribableChannel) CAF_QI_ENTRY(IMessageChannel) CAF_QI_ENTRY(IChannelInterceptorSupport) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ISubscribableChannel void subscribe( const SmartPtrIMessageHandler& messageHandler); void unsubscribe( const SmartPtrIMessageHandler& messageHandler); protected: // CAbstractMessageChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); private: bool _isInitialized; SmartPtrIDocument _configSection; std::string _id; SmartPtrIMessageDispatcher _messageDispatcher; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CDirectChannelInstance); }; CAF_DECLARE_SMART_QI_POINTER(CDirectChannelInstance); } #endif // #ifndef CDirectChannelInstance_h_ CErrorChannel.cpp000066400000000000000000000035101321503522500357050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CErrorChannel.h" #include "CErrorChannelInstance.h" using namespace Caf; CErrorChannel::CErrorChannel() : _isInitialized(false), CAF_CM_INIT("CErrorChannel"){ } CErrorChannel::~CErrorChannel() { } void CErrorChannel::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CErrorChannel::terminateBean() { } void CErrorChannel::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CErrorChannel::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CErrorChannel::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // configSection is optional SmartPtrCErrorChannelInstance instance; instance.CreateInstance(); instance->initialize(_ctorArgs, _properties, configSection); rc.QueryInterface(instance, false); CAF_CM_VALIDATE_INTERFACE(rc); } CAF_CM_EXIT; return rc; } CErrorChannel.h000066400000000000000000000025001321503522500353500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CErrorChannel_h_ #define CErrorChannel_h_ #include "IBean.h" #include "IntegrationSubsys.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CErrorChannel : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CErrorChannel(); virtual ~CErrorChannel(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdErrorChannel) CAF_BEGIN_INTERFACE_MAP(CErrorChannel) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: void initialize(); public: // IBean void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CErrorChannel); }; } #endif // #ifndef CErrorChannel_h_ CErrorChannelInstance.cpp000066400000000000000000000065621321503522500374040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CUnicastingDispatcher.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/IMessageHandler.h" #include "Exception/CCafException.h" #include "CErrorChannelInstance.h" using namespace Caf; CErrorChannelInstance::CErrorChannelInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CErrorChannelInstance") { } CErrorChannelInstance::~CErrorChannelInstance() { } void CErrorChannelInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); // configSection is optional _id = "errorChannel"; _isInitialized = true; } CAF_CM_EXIT; } std::string CErrorChannelInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CErrorChannelInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const SmartPtrIMessageChannel nullMessageChannel = channelResolver->resolveChannelName("nullChannel"); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, nullMessageChannel); SmartPtrCUnicastingDispatcher unicastingDispatcher; unicastingDispatcher.CreateInstance(); unicastingDispatcher->initialize(errorHandler); _messageDispatcher = unicastingDispatcher; } CAF_CM_EXIT; } void CErrorChannelInstance::subscribe(const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("subscribe"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); _messageDispatcher->addHandler(messageHandler); } CAF_CM_EXIT; } void CErrorChannelInstance::unsubscribe(const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("unsubscribe"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); _messageDispatcher->removeHandler(messageHandler); } CAF_CM_EXIT; } bool CErrorChannelInstance::doSend( const SmartPtrIIntMessage& message, int32 timeout) { CAF_CM_FUNCNAME("doSend"); bool sent = false; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Timeout not currently supported: %s", _id.c_str()); } else { CAF_CM_LOG_DEBUG_VA1("Dispatching message - %s", _id.c_str()); sent = _messageDispatcher->dispatch(message); if (!sent) { CAF_CM_LOG_WARN_VA1("Nothing handled the message - channel: %s", _id.c_str()); } } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; return sent; } CErrorChannelInstance.h000066400000000000000000000040251321503522500370410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CErrorChannelInstance_h_ #define CErrorChannelInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageDispatcher.h" #include "Integration/IMessageHandler.h" #include "Integration/IIntegrationObject.h" #include "Integration/ISubscribableChannel.h" #include "Integration/Core/CAbstractMessageChannel.h" namespace Caf { /// Sends responses/errors back to the client. class CErrorChannelInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ISubscribableChannel, public CAbstractMessageChannel { public: CErrorChannelInstance(); virtual ~CErrorChannelInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ISubscribableChannel) CAF_QI_ENTRY(IMessageChannel) CAF_QI_ENTRY(IChannelInterceptorSupport) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ISubscribableChannel void subscribe( const SmartPtrIMessageHandler& messageHandler); void unsubscribe( const SmartPtrIMessageHandler& messageHandler); protected: // CAbstractMessageChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); private: bool _isInitialized; std::string _id; SmartPtrIMessageDispatcher _messageDispatcher; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CErrorChannelInstance); }; CAF_DECLARE_SMART_QI_POINTER(CErrorChannelInstance); } #endif // #ifndef CErrorChannelInstance_h_ CFileInboundChannelAdapterInstance.cpp000066400000000000000000000101231321503522500417760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CFileReadingMessageSource.h" #include "Common/IAppContext.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CMessageHandler.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/Core/CSourcePollingChannelAdapter.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IMessageChannel.h" #include "CFileInboundChannelAdapterInstance.h" using namespace Caf; CFileInboundChannelAdapterInstance::CFileInboundChannelAdapterInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CFileInboundChannelAdapterInstance") { } CFileInboundChannelAdapterInstance::~CFileInboundChannelAdapterInstance() { } void CFileInboundChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); _isInitialized = true; } CAF_CM_EXIT; } std::string CFileInboundChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CFileInboundChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const std::string outputChannelStr = _configSection->findRequiredAttribute("channel"); SmartPtrCFileReadingMessageSource fileReadingMessageSource; fileReadingMessageSource.CreateInstance(); fileReadingMessageSource->initialize(_configSection); const SmartPtrIMessageChannel outputMessageChannel = channelResolver->resolveChannelName(outputChannelStr); const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); SmartPtrCMessageHandler messageHandler; messageHandler.CreateInstance(); messageHandler->initialize( _id, outputMessageChannel, SmartPtrICafObject()); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, errorMessageChannel); SmartPtrCSourcePollingChannelAdapter sourcePollingChannelAdapter; sourcePollingChannelAdapter.CreateInstance(); sourcePollingChannelAdapter->initialize( messageHandler, fileReadingMessageSource, errorHandler); SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor; simpleAsyncTaskExecutor.CreateInstance(); simpleAsyncTaskExecutor->initialize(sourcePollingChannelAdapter, errorHandler); _taskExecutor = simpleAsyncTaskExecutor; } CAF_CM_EXIT; } void CFileInboundChannelAdapterInstance::start(const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Starting the executor"); _taskExecutor->execute(timeoutMs); } CAF_CM_EXIT; } void CFileInboundChannelAdapterInstance::stop(const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Stopping the executor"); _taskExecutor->cancel(timeoutMs); } CAF_CM_EXIT; } bool CFileInboundChannelAdapterInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); bool rc = false; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = (_taskExecutor->getState() == ITaskExecutor::ETaskStateStarted); } CAF_CM_EXIT; return rc; } bool CFileInboundChannelAdapterInstance::isMessageProducer() const { CAF_CM_FUNCNAME_VALIDATE("isMessageProducer"); bool rc = false; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = true; } CAF_CM_EXIT; return rc; } CFileInboundChannelAdapterInstance.h000066400000000000000000000035331321503522500414520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CFileInboundChannelAdapterInstance_h_ #define CFileInboundChannelAdapterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/ITaskExecutor.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" #include "Integration/IMessageProducer.h" namespace Caf { class CFileInboundChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle, public IMessageProducer { public: CFileInboundChannelAdapterInstance(); virtual ~CFileInboundChannelAdapterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(IMessageProducer) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // IMessageProducer bool isMessageProducer() const; private: bool _isInitialized; SmartPtrIDocument _configSection; std::string _id; SmartPtrITaskExecutor _taskExecutor; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CFileInboundChannelAdapterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CFileInboundChannelAdapterInstance); } #endif // #ifndef CFileInboundChannelAdapterInstance_h_ CFileOutboundChannelAdapterInstance.cpp000066400000000000000000000140321321503522500422020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Exception/CCafException.h" #include "CFileOutboundChannelAdapterInstance.h" #include "CDirectChannelInstance.h" #include "Integration/Core/FileHeaders.h" using namespace Caf; CFileOutboundChannelAdapterInstance::CFileOutboundChannelAdapterInstance() : _isInitialized(false), _autoCreateDirectory(false), _deleteSourceFiles(false), CAF_CM_INIT_LOG("CFileOutboundChannelAdapterInstance") { } CFileOutboundChannelAdapterInstance::~CFileOutboundChannelAdapterInstance() { } void CFileOutboundChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); const std::string directoryStr = configSection->findRequiredAttribute("directory"); const std::string autoCreateDirectoryStr = configSection->findOptionalAttribute( "auto-create-directory"); const std::string deleteSourceFilesStr = configSection->findOptionalAttribute( "delete-source-files"); const std::string temporaryFileSuffixStr = configSection->findOptionalAttribute( "temporary-file-suffix"); _modeStr = configSection->findOptionalAttribute("mode"); _directory = CStringUtils::expandEnv(directoryStr); _deleteSourceFiles = (deleteSourceFilesStr.empty() || deleteSourceFilesStr.compare("false") == 0) ? false : true; _autoCreateDirectory = (autoCreateDirectoryStr.empty() || autoCreateDirectoryStr.compare("true") == 0) ? true : false; _temporaryFileSuffix = temporaryFileSuffixStr.empty() ? ".writing" : temporaryFileSuffixStr; _isInitialized = true; } std::string CFileOutboundChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CFileOutboundChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } void CFileOutboundChannelAdapterInstance::handleMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _savedMessage = message; savePayloadToFile(message); deleteSourceFiles(message); } SmartPtrIIntMessage CFileOutboundChannelAdapterInstance::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _savedMessage; } void CFileOutboundChannelAdapterInstance::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _savedMessage = NULL; } SmartPtrIIntMessage CFileOutboundChannelAdapterInstance::processErrorMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("processErrorMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _savedMessage = message; savePayloadToFile(message); deleteSourceFiles(message); return SmartPtrIIntMessage(); } void CFileOutboundChannelAdapterInstance::savePayloadToFile( const SmartPtrIIntMessage& message) const { CAF_CM_FUNCNAME("savePayloadToFile"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); const std::string relFilename = generateFilename(message); const std::string filePath = FileSystemUtils::buildPath(_directory, relFilename); const std::string fileDir = FileSystemUtils::getDirname(filePath); if (! _autoCreateDirectory && ! FileSystemUtils::doesDirectoryExist(fileDir)) { CAF_CM_EXCEPTION_VA1(ERROR_PATH_NOT_FOUND, "Directory does not exist - %s", fileDir.c_str()); } const SmartPtrCDynamicByteArray payload = message->getPayload(); FileSystemUtils::saveByteFile(filePath, payload->getPtr(), payload->getByteCount(), translateMode(_modeStr), _temporaryFileSuffix); } std::string CFileOutboundChannelAdapterInstance::generateFilename( const SmartPtrIIntMessage& message) const { CAF_CM_FUNCNAME_VALIDATE("generateFilename"); CAF_CM_VALIDATE_INTERFACE(message); std::string relFilename = message->findOptionalHeaderAsString( FileHeaders::_sFILENAME); if (relFilename.empty()) { relFilename = CStringUtils::createRandomUuid() + ".msg"; } return relFilename; } FileSystemUtils::FILE_MODE_TYPE CFileOutboundChannelAdapterInstance::translateMode( const std::string modeStr) const { CAF_CM_FUNCNAME("translateMode"); FileSystemUtils::FILE_MODE_TYPE modeType; if (modeStr.empty() || (modeStr.compare("REPLACE") == 0)) { modeType = FileSystemUtils::FILE_MODE_REPLACE; } else if (modeStr.compare("FAIL") == 0) { modeType = FileSystemUtils::FILE_MODE_FAIL; } else if (modeStr.compare("IGNORE") == 0) { modeType = FileSystemUtils::FILE_MODE_IGNORE; } else if (modeStr.compare("APPEND") == 0) { CAF_CM_EXCEPTION_VA0(ERROR_INVALID_DATA, "Invalid mode - APPEND not currently supported"); } else { CAF_CM_EXCEPTION_VA1(ERROR_INVALID_DATA, "Invalid mode - %s", modeStr.c_str()); } return modeType; } void CFileOutboundChannelAdapterInstance::deleteSourceFiles( const SmartPtrIIntMessage& message) const { CAF_CM_FUNCNAME_VALIDATE("deleteSourceFiles"); CAF_CM_VALIDATE_INTERFACE(message); if (_deleteSourceFiles) { const std::string originalFile = message->findOptionalHeaderAsString( FileHeaders::_sORIGINAL_FILE); if (!originalFile.empty()) { if (FileSystemUtils::doesFileExist(originalFile)) { CAF_CM_LOG_INFO_VA1("Removing original file - %s", originalFile.c_str()); FileSystemUtils::removeFile(originalFile); } } } } CFileOutboundChannelAdapterInstance.h000066400000000000000000000045411321503522500416530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CFileOutboundChannelAdapterInstance_h_ #define CFileOutboundChannelAdapterInstance_h_ #include "Integration/IErrorProcessor.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageHandler.h" namespace Caf { class CFileOutboundChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public IMessageHandler, public IErrorProcessor { public: CFileOutboundChannelAdapterInstance(); virtual ~CFileOutboundChannelAdapterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IMessageHandler) CAF_QI_ENTRY(IErrorProcessor) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // IMessageHandler void handleMessage( const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); public: // IErrorProcessor SmartPtrIIntMessage processErrorMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; std::string _directory; std::string _temporaryFileSuffix; std::string _modeStr; bool _autoCreateDirectory; bool _deleteSourceFiles; SmartPtrIIntMessage _savedMessage; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CFileOutboundChannelAdapterInstance); private: void savePayloadToFile( const SmartPtrIIntMessage& message) const; std::string generateFilename( const SmartPtrIIntMessage& message) const; FileSystemUtils::FILE_MODE_TYPE translateMode( const std::string modeStr) const; void deleteSourceFiles( const SmartPtrIIntMessage& message) const; }; CAF_DECLARE_SMART_QI_POINTER(CFileOutboundChannelAdapterInstance); } #endif // #ifndef CFileOutboundChannelAdapterInstance_h_ CFileReadingMessageSource.cpp000066400000000000000000000140301321503522500401610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CFileReadingMessageSource.h" #include "Exception/CCafException.h" using namespace Caf; CFileReadingMessageSource::CFileReadingMessageSource() : _isInitialized(false), _preventDuplicates(true), _refreshSec(0), _lastRefreshSec(0), CAF_CM_INIT_LOG("CFileReadingMessageSource") { } CFileReadingMessageSource::~CFileReadingMessageSource() { } void CFileReadingMessageSource::initialize( const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); const std::string directoryStr = configSection->findRequiredAttribute("directory"); const std::string filenameRegexStr = configSection->findOptionalAttribute("filename-regex"); const std::string preventDuplicatesStr = configSection->findOptionalAttribute("prevent-duplicates"); const std::string autoCreateDirectoryStr = configSection->findOptionalAttribute("auto-create-directory"); const SmartPtrIDocument pollerDoc = configSection->findOptionalChild("poller"); _refreshSec = 0; _directory = CStringUtils::expandEnv(directoryStr); setPollerMetadata(pollerDoc); _preventDuplicates = (preventDuplicatesStr.empty() || preventDuplicatesStr.compare("true") == 0) ? true : false; if (filenameRegexStr.empty()) { _filenameRegex = FileSystemUtils::REGEX_MATCH_ALL; } else { _filenameRegex = filenameRegexStr; } const bool autoCreateDirectory = (autoCreateDirectoryStr.empty() || autoCreateDirectoryStr.compare("true") == 0) ? true : false; if (autoCreateDirectory && ! FileSystemUtils::doesDirectoryExist(_directory)) { FileSystemUtils::createDirectory(_directory); } CAF_CM_LOG_DEBUG_VA2( "Monitoring inbound directory - dir: %s, fileRegex: %s", _directory.c_str(), _filenameRegex.c_str()); _fileCollection.CreateInstance(); _isInitialized = true; } bool CFileReadingMessageSource::doSend( const SmartPtrIIntMessage&, int32) { CAF_CM_FUNCNAME("doSend"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_EXCEPTIONEX_VA1( UnsupportedOperationException, E_NOTIMPL, "This is not a sending channel: %s", _id.c_str()); } SmartPtrIIntMessage CFileReadingMessageSource::doReceive(const int32 timeout) { CAF_CM_FUNCNAME("receive"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Timeout not currently supported: %s", _id.c_str()); } if (isRefreshNecessary(_refreshSec, _lastRefreshSec)) { const SmartPtrCFileCollection newFileCollection = itemsInDirectory(_directory, _filenameRegex); if (_preventDuplicates) { _fileCollection = merge(newFileCollection, _fileCollection); } else { _fileCollection = newFileCollection; } _lastRefreshSec = getTimeSec(); } SmartPtrIIntMessage message; const std::string filename = calcNextFile(_fileCollection); if (! filename.empty()) { CAF_CM_LOG_DEBUG_VA1("Creating message with filename - %s", filename.c_str()); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(filename, IIntMessage::SmartPtrCHeaders(), IIntMessage::SmartPtrCHeaders()); message = messageImpl; } return message; } CFileReadingMessageSource::SmartPtrCFileCollection CFileReadingMessageSource::itemsInDirectory( const std::string& directory, const std::string& filenameRegex) const { CAF_CM_FUNCNAME_VALIDATE("itemsInDirectory"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(directory); // filenameRegex defaults to FileSystemUtils::REGEX_MATCH_ALL SmartPtrCFileCollection rc; rc.CreateInstance(); const FileSystemUtils::DirectoryItems directoryItems = FileSystemUtils::itemsInDirectory(directory, filenameRegex); const FileSystemUtils::Files files = directoryItems.files; for (TConstIterator fileIter(files); fileIter; fileIter++) { const std::string filename = *fileIter; const std::string filePath = FileSystemUtils::buildPath( directory, filename); rc->insert(std::make_pair(filePath, false)); } return rc; } CFileReadingMessageSource::SmartPtrCFileCollection CFileReadingMessageSource::merge( const SmartPtrCFileCollection& newFileCollection, const SmartPtrCFileCollection& existingFileCollection) const { CAF_CM_FUNCNAME_VALIDATE("merge"); CAF_CM_VALIDATE_SMARTPTR(newFileCollection); CAF_CM_VALIDATE_SMARTPTR(existingFileCollection); SmartPtrCFileCollection newFileCollectionRc = newFileCollection; for (TMapIterator newFileIter(*newFileCollectionRc); newFileIter; newFileIter++) { const std::string newFile = newFileIter.getKey(); CFileCollection::const_iterator existingFileIter = existingFileCollection->find(newFile); if (existingFileIter != existingFileCollection->end()) { *newFileIter = existingFileIter->second; } } return newFileCollectionRc; } std::string CFileReadingMessageSource::calcNextFile( SmartPtrCFileCollection& fileCollection) const { CAF_CM_FUNCNAME_VALIDATE("calcNextFile"); CAF_CM_VALIDATE_SMARTPTR(fileCollection); std::string filename; for (TMapIterator fileIter(*fileCollection); filename.empty() && fileIter; fileIter++) { const bool isFileReceived = *fileIter; if (! isFileReceived) { filename = fileIter.getKey(); *fileIter = true; } } return filename; } bool CFileReadingMessageSource::isRefreshNecessary( const uint32 refreshSec, const uint64 lastRefreshSec) const { bool rc = false; if (refreshSec == 0) { rc = true; } else { const uint64 currentTimeSec = getTimeSec(); if ((currentTimeSec - lastRefreshSec) > refreshSec) { rc = true; } } return rc; } uint64 CFileReadingMessageSource::getTimeSec() const { GTimeVal curTime; ::g_get_current_time(&curTime); uint64 rc = curTime.tv_sec; return rc; } CFileToStringTransformerInstance.cpp000066400000000000000000000055641321503522500416170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/Core/CIntMessageHeaders.h" #include "CFileToStringTransformerInstance.h" #include "Integration/Core/FileHeaders.h" using namespace Caf; CFileToStringTransformerInstance::CFileToStringTransformerInstance() : _isInitialized(false), _deleteFiles(false), CAF_CM_INIT_LOG("CFileToStringTransformerInstance") { } CFileToStringTransformerInstance::~CFileToStringTransformerInstance() { } void CFileToStringTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); const std::string deleteFilesStr = configSection->findOptionalAttribute("delete-files"); _deleteFiles = (deleteFilesStr.empty() || deleteFilesStr.compare("true") == 0) ? true : false; CAF_CM_LOG_DEBUG_VA2("deleteFilesStr: %s, deleteFiles: %s", deleteFilesStr.c_str(), _deleteFiles ? "true" : "false"); _isInitialized = true; } CAF_CM_EXIT; } std::string CFileToStringTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CFileToStringTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } CAF_CM_EXIT; } SmartPtrIIntMessage CFileToStringTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); SmartPtrIIntMessage newMessage; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const std::string filename = message->getPayloadStr(); const std::string fileContents = FileSystemUtils::loadTextFile(filename); CIntMessageHeaders messageHeaders; if (_deleteFiles) { CAF_CM_LOG_INFO_VA1("Removing file - %s", filename.c_str()); FileSystemUtils::removeFile(filename); } else { messageHeaders.insertString(FileHeaders::_sORIGINAL_FILE, filename); } SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(fileContents, messageHeaders.getHeaders(), message->getHeaders()); newMessage = messageImpl; } CAF_CM_EXIT; return newMessage; } CFileToStringTransformerInstance.h000066400000000000000000000031441321503522500412540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CFileToStringTransformerInstance_h_ #define CFileToStringTransformerInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CFileToStringTransformerInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CFileToStringTransformerInstance(); virtual ~CFileToStringTransformerInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ITransformer) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; bool _deleteFiles; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CFileToStringTransformerInstance); }; CAF_DECLARE_SMART_QI_POINTER(CFileToStringTransformerInstance); } #endif // #ifndef CFileToStringTransformerInstance_h_ CHeaderEnricherTransformerInstance.cpp000066400000000000000000000144521321503522500421120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "IVariant.h" #include "Integration/Core/CExpressionHandler.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/ITransformer.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "CHeaderEnricherTransformerInstance.h" #include "Integration/Core/MessageHeaders.h" using namespace Caf; CHeaderEnricherTransformerInstance::CHeaderEnricherTransformerInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CHeaderEnricherTransformerInstance") { } CHeaderEnricherTransformerInstance::~CHeaderEnricherTransformerInstance() { } void CHeaderEnricherTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _configSection = configSection; if (_configSection->getAllChildren()->empty()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_INVALID_DATA, "Configuration section is empty - %s", _id.c_str()); } _isInitialized = true; } std::string CHeaderEnricherTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CHeaderEnricherTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); SmartPtrIAppConfig appConfig = getAppConfig(); const IDocument::SmartPtrCChildCollection configChildren = _configSection->getAllChildren(); for (TSmartConstMapIterator configIter(*configChildren); configIter; configIter++) { const SmartPtrIDocument config = *configIter; if (config->getName().compare("header") == 0) { const std::string headerName = config->findRequiredAttribute("name"); const std::string headerRef = config->findOptionalAttribute("ref"); const std::string headerValue = config->findOptionalAttribute("value"); const std::string expressionValue = config->findOptionalAttribute("expression"); if (! headerRef.empty()) { CAF_CM_LOG_DEBUG_VA2("Creating the header enricher bean - %s = %s", headerName.c_str(), headerRef.c_str()); SmartPtrIBean bean = appContext->getBean(headerRef); SmartPtrITransformer transformer; transformer.QueryInterface(bean, false); if (transformer.IsNull()) { CAF_CM_EXCEPTIONEX_VA1( NoSuchInterfaceException, 0, "Bean is not a transformer - %s", headerRef.c_str()); } _headerWithRef.insert(std::make_pair(headerName, transformer)); } else if (! headerValue.empty()) { CAF_CM_LOG_DEBUG_VA2("Creating the header enricher value - %s = %s", headerName.c_str(), headerValue.c_str()); _headerWithValue.insert(std::make_pair(headerName, headerValue)); } else if (! expressionValue.empty()) { CAF_CM_LOG_DEBUG_VA2("Creating the header enricher expression - %s = %s", headerName.c_str(), expressionValue.c_str()); SmartPtrCExpressionHandler expressionHandler; expressionHandler.CreateInstance(); expressionHandler->init( appConfig, appContext, expressionValue); _headerWithExpression.insert(std::make_pair(headerName, expressionHandler)); } else { CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, ERROR_INVALID_DATA, "Configuration error: unrecognized header value type attribute: [id='%s'][header='%s']", _id.c_str(), headerName.c_str()); } } else if (config->getName().compare("error-channel") == 0) { _errorChannelRef = config->findRequiredAttribute("ref"); } else { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_INVALID_DATA, "Configuration section contains unrecognized entry - %s", _id.c_str()); } } } SmartPtrIIntMessage CHeaderEnricherTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initialize(message->getPayload(), message->getHeaders(), IIntMessage::SmartPtrCHeaders()); SmartPtrIIntMessage newMessage = messageImpl; for (TSmartMapIterator headerWithRefIter(_headerWithRef); headerWithRefIter; headerWithRefIter++) { const SmartPtrIIntMessage transformMessage = headerWithRefIter->transformMessage(newMessage); SmartPtrCIntMessage tmpMessageImpl; tmpMessageImpl.CreateInstance(); tmpMessageImpl->initialize(message->getPayload(), transformMessage->getHeaders(), newMessage->getHeaders()); newMessage = tmpMessageImpl; } IIntMessage::SmartPtrCHeaders newHeaders = newMessage->getHeaders(); for (TSmartMapIterator expressionIter(_headerWithExpression); expressionIter; expressionIter++) { const SmartPtrIVariant value = expressionIter->evaluate(newMessage); CAF_CM_LOG_DEBUG_VA2( "Inserting/updating a header value - %s = %s", expressionIter.getKey().c_str(), value->toString().c_str()); (*newHeaders)[expressionIter.getKey()] = std::make_pair(value, SmartPtrICafObject()); } if (! _errorChannelRef.empty()) { CAF_CM_LOG_DEBUG_VA1("Inserting/updating a new error channel - %s", _errorChannelRef.c_str()); (*newHeaders)[MessageHeaders::_sERROR_CHANNEL] = std::make_pair(CVariant::createString(_errorChannelRef), SmartPtrICafObject()); } for (TConstMapIterator headerWithValueIter(_headerWithValue); headerWithValueIter; headerWithValueIter++) { const std::string name = headerWithValueIter.getKey(); const std::string value = *headerWithValueIter; CAF_CM_LOG_DEBUG_VA2("Inserting/updating a header value - %s = %s", name.c_str(), value.c_str()); (*newHeaders)[name] = std::make_pair(CVariant::createString(value), SmartPtrICafObject()); } return newMessage; } CHeaderEnricherTransformerInstance.h000066400000000000000000000036761321503522500415650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHeaderEnricherTransformerInstance_h_ #define CHeaderEnricherTransformerInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/Core/CExpressionHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/ITransformer.h" #include "Integration/IIntegrationObject.h" namespace Caf { class CHeaderEnricherTransformerInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CHeaderEnricherTransformerInstance(); virtual ~CHeaderEnricherTransformerInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ITransformer) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; std::string _errorChannelRef; SmartPtrIDocument _configSection; typedef std::map Transformers; Transformers _headerWithRef; typedef std::map Expressions; Expressions _headerWithExpression; Cmapstrstr _headerWithValue; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CHeaderEnricherTransformerInstance); }; CAF_DECLARE_SMART_QI_POINTER(CHeaderEnricherTransformerInstance); } #endif // #ifndef CHeaderEnricherTransformerInstance_h_ CHeaderExpressionInvoker.cpp000066400000000000000000000057441321503522500401440ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Jul 23, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "IVariant.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "CHeaderExpressionInvoker.h" using namespace Caf; CHeaderExpressionInvoker::CHeaderExpressionInvoker() : _isInitialized(false), CAF_CM_INIT("CHeaderExpressionInvoker") { } CHeaderExpressionInvoker::~CHeaderExpressionInvoker() { } void CHeaderExpressionInvoker::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_ASSERT(ctorArgs.size() == 0); CAF_CM_ASSERT(properties.size() == 0); _isInitialized = true; } void CHeaderExpressionInvoker::terminateBean() { } SmartPtrIVariant CHeaderExpressionInvoker::invokeExpression( const std::string& methodName, const Cdeqstr& methodParams, const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("invokeExpression"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(methodName); CAF_CM_VALIDATE_STL(methodParams); CAF_CM_VALIDATE_INTERFACE(message); SmartPtrIVariant result; const IIntMessage::SmartPtrCHeaders& headers = message->getHeaders(); if (methodName == "containsKey") { CAF_CM_ASSERT(1 == methodParams.size()); result = CVariant::createBool(headers->end() != headers->find(methodParams.front())); } else if (methodName == "notContainsKey") { CAF_CM_ASSERT(1 == methodParams.size()); result = CVariant::createBool(headers->end() == headers->find(methodParams.front())); } else if (methodName == "toString") { CAF_CM_ASSERT(1 == methodParams.size()); const SmartPtrIVariant value = message->findRequiredHeader(methodParams.front()); result = CVariant::createString(value->toString()); } else if (methodName == "prependToString") { CAF_CM_ASSERT(2 == methodParams.size()); const SmartPtrIVariant value = message->findRequiredHeader(methodParams.front()); result = CVariant::createString(methodParams.back() + value->toString()); } else if (methodName == "appendToString") { CAF_CM_ASSERT(2 == methodParams.size()); const SmartPtrIVariant value = message->findRequiredHeader(methodParams.front()); result = CVariant::createString(value->toString() + methodParams.back()); } else if (methodName == "isEqualString") { CAF_CM_ASSERT(2 == methodParams.size()); const SmartPtrIVariant value = message->findRequiredHeader(methodParams.front()); result = CVariant::createBool(value->toString().compare(methodParams.back()) == 0); } else if (methodName == "isNotEqualString") { CAF_CM_ASSERT(2 == methodParams.size()); const SmartPtrIVariant value = message->findRequiredHeader(methodParams.front()); result = CVariant::createBool(value->toString().compare(methodParams.back()) != 0); } else { CAF_CM_EXCEPTIONEX_VA1( NoSuchMethodException, 0, "%s", methodName.c_str()); } return result; } CHeaderExpressionInvoker.h000066400000000000000000000024031321503522500375760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Jul 23, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHEADEREXPRESSIONINVOKER_H_ #define CHEADEREXPRESSIONINVOKER_H_ #include "IBean.h" #include "IVariant.h" #include "IntegrationSubsys.h" #include "Integration/IIntMessage.h" #include "Integration/IExpressionInvoker.h" namespace Caf { class CHeaderExpressionInvoker : public TCafSubSystemObjectRoot, public IBean, public IExpressionInvoker { public: CHeaderExpressionInvoker(); virtual ~CHeaderExpressionInvoker(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdHeaderExpressionInvoker) CAF_BEGIN_INTERFACE_MAP(CHeaderExpressionInvoker) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IExpressionInvoker) CAF_END_INTERFACE_MAP() public: // IBean void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // IExpressionInvoker SmartPtrIVariant invokeExpression( const std::string& methodName, const Cdeqstr& methodParams, const SmartPtrIIntMessage& message); private: bool _isInitialized; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CHeaderExpressionInvoker); }; } #endif /* CHEADEREXPRESSIONINVOKER_H_ */ CHeaderValueRouterInstance.cpp000066400000000000000000000144021321503522500404000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Exception/CCafException.h" #include "CHeaderValueRouterInstance.h" using namespace Caf; CHeaderValueRouterInstance::CHeaderValueRouterInstance() : _isInitialized(false), _resolutionRequired(false), CAF_CM_INIT_LOG("CHeaderValueRouterInstance") { } CHeaderValueRouterInstance::~CHeaderValueRouterInstance() { } void CHeaderValueRouterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _headerName = configSection->findRequiredAttribute("header-name"); _defaultOutputChannelId = configSection->findOptionalAttribute("default-output-channel"); const std::string resolutionRequiredStr = configSection->findOptionalAttribute("resolution-required"); _resolutionRequired = (resolutionRequiredStr.empty() || resolutionRequiredStr.compare("true") == 0) ? true : false; const IDocument::SmartPtrCChildCollection childCollection = configSection->getAllChildren(); for(TConstIterator childIter(*childCollection); childIter; childIter++) { const std::string sectionName = childIter->first; if (sectionName.compare("mapping") == 0) { const SmartPtrIDocument document = childIter->second; const std::string value = document->findRequiredAttribute("value"); const std::string channel = document->findRequiredAttribute("channel"); _valueToChannelMapping.insert(std::make_pair(value, channel)); } } if (_valueToChannelMapping.empty()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "No mapping sections found - %s", _id.c_str()); } _isInitialized = true; } CAF_CM_EXIT; } std::string CHeaderValueRouterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CHeaderValueRouterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); _channelResolver = channelResolver; SmartPtrIMessageChannel defaultOutputChannel; if (_defaultOutputChannelId.length()) { try { defaultOutputChannel = _channelResolver->resolveChannelName(_defaultOutputChannelId); } CAF_CM_CATCH_ALL; CAF_CM_LOG_WARN_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (defaultOutputChannel) { CAF_CM_LOG_INFO_VA2( "Successfully resolved default channel - id: %s, defaultOutputChannelId: %s", _id.c_str(), _defaultOutputChannelId.c_str()); } else { CAF_CM_EXCEPTIONEX_VA2( NoSuchElementException, 0, "Failed to resolve default channel - id: %s, defaultChannelId: %s", _id.c_str(), _defaultOutputChannelId.c_str()); } } CAbstractMessageRouter::init(defaultOutputChannel, false, -1); } CAF_CM_EXIT; } CHeaderValueRouterInstance::ChannelCollection CHeaderValueRouterInstance::getTargetChannels( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("getTargetChannels"); ChannelCollection messageChannels; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const std::string outputChannel = calcOutputChannel(message); if (outputChannel.empty() && _defaultOutputChannelId.empty()) { CAF_CM_EXCEPTIONEX_VA2(NoSuchElementException, ERROR_NOT_FOUND, "Did not find output channel and default channel not " "provided - id: %s, headerName: %s", _id.c_str(), _headerName.c_str()); } SmartPtrIMessageChannel messageChannel; if (! outputChannel.empty()) { try { messageChannel = _channelResolver->resolveChannelName(outputChannel); } CAF_CM_CATCH_ALL; CAF_CM_LOG_WARN_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (messageChannel.IsNull() && _resolutionRequired) { CAF_CM_EXCEPTIONEX_VA3(NoSuchElementException, ERROR_NOT_FOUND, "Failed to resolve channel when resolution is required - id: %s, " "headerName: %s, outputChannel: %s", _id.c_str(), _headerName.c_str(), outputChannel.c_str()); } if (! messageChannel.IsNull()) { CAF_CM_LOG_INFO_VA3( "Successfully resolved channel - id: %s, headerName: %s, outputChannel: %s", _id.c_str(), _headerName.c_str(), outputChannel.c_str()); } } if (messageChannel.IsNull() && _defaultOutputChannelId.empty()) { CAF_CM_EXCEPTIONEX_VA3(NoSuchElementException, ERROR_NOT_FOUND, "Failed to resolve channel when resolution is not required and default " "channel is not available - id: %s, headerName: %s, outputChannel: %s", _id.c_str(), _headerName.c_str(), outputChannel.c_str()); } if (!messageChannel.IsNull()) { messageChannels.push_back(messageChannel); } } CAF_CM_EXIT; return messageChannels; } std::string CHeaderValueRouterInstance::calcOutputChannel( const SmartPtrIIntMessage& message) const { CAF_CM_FUNCNAME_VALIDATE("calcOutputChannel"); std::string outputChannel; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(message); const std::string headerValue = message->findOptionalHeaderAsString(_headerName); if (headerValue.empty()) { CAF_CM_LOG_WARN_VA2("Header name not found in headers - id: %s, headerName: %s", _id.c_str(), _headerName.c_str()); } else { const Cmapstrstr::const_iterator valueToChannelIter = _valueToChannelMapping.find(headerValue); if (valueToChannelIter == _valueToChannelMapping.end()) { CAF_CM_LOG_WARN_VA3("Header name found in headers, but not config - id: %s, name: %s, val: %s", _id.c_str(), _headerName.c_str(), headerValue.c_str()); } else { outputChannel = valueToChannelIter->second; } } } CAF_CM_EXIT; return outputChannel; } CHeaderValueRouterInstance.h000066400000000000000000000034531321503522500400510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CHeaderValueRouterInstance_h_ #define CHeaderValueRouterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/Core/CAbstractMessageRouter.h" namespace Caf { class CHeaderValueRouterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public CAbstractMessageRouter { public: CHeaderValueRouterInstance(); virtual ~CHeaderValueRouterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IMessageRouter) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); private: ChannelCollection getTargetChannels( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; std::string _defaultOutputChannelId; bool _resolutionRequired; std::string _headerName; Cmapstrstr _valueToChannelMapping; SmartPtrIChannelResolver _channelResolver; private: std::string calcOutputChannel( const SmartPtrIIntMessage& message) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CHeaderValueRouterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CHeaderValueRouterInstance); } #endif // #ifndef CHeaderValueRouterInstance_h_ CIntegrationObjectFactory.cpp000066400000000000000000000043331321503522500402710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 8, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Exception/CCafException.h" #include "CIntegrationObjectFactory.h" #include "CObjectFactoryTables.h" #include "CDirectChannelInstance.h" #include "CQueueChannelInstance.h" CIntegrationObjectFactory::CIntegrationObjectFactory() : CAF_CM_INIT("CIntegrationObjectFactory") { } CIntegrationObjectFactory::~CIntegrationObjectFactory() { } void CIntegrationObjectFactory::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; } void CIntegrationObjectFactory::terminateBean() { } bool CIntegrationObjectFactory::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_VALIDATE_INTERFACE(configSection); return CObjectFactoryTables::objectCreatorMap.find( configSection->getName()) != CObjectFactoryTables::objectCreatorMap.end(); } SmartPtrIIntegrationObject CIntegrationObjectFactory::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME("createObject"); ObjectCreatorMap::const_iterator entry = CObjectFactoryTables::objectCreatorMap.find(configSection->getName()); CAF_CM_ASSERT(entry != CObjectFactoryTables::objectCreatorMap.end()); SmartPtrIIntegrationObject object; if (entry->second) { object = (entry->second)(); } else if (configSection->getName() == "channel") { if (configSection->findOptionalChild("queue")) { SmartPtrCQueueChannelInstance channel; channel.CreateInstance(); object = channel; } else { SmartPtrCDirectChannelInstance channel; channel.CreateInstance(); object = channel; } } else { CAF_CM_EXCEPTIONEX_VA1( IllegalStateException, 0, "config section '%s' is not handled by this factory. report this as a bug.", configSection->getName().c_str()); } object->initialize(_ctorArgs, _properties, configSection); return object; } CIntegrationObjectFactory.h000066400000000000000000000025341321503522500377370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 8, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CIntegrationObjectFactory_h #define CIntegrationObjectFactory_h #include "IBean.h" #include "IntegrationSubsys.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { class CIntegrationObjectFactory : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CIntegrationObjectFactory(); virtual ~CIntegrationObjectFactory(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdIntegrationObjectFactory) CAF_BEGIN_INTERFACE_MAP(CIntegrationObjectFactory) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: // IBean void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CIntegrationObjectFactory); }; } #endif /* CIntegrationObjectFactory_h */ CLoggingChannelAdapterInstance.cpp000066400000000000000000000076371321503522500412060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Jan 31, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "CLoggingChannelAdapterInstance.h" using namespace Caf; CLoggingChannelAdapterInstance::CLoggingChannelAdapterInstance() : _isInitialized(false), _level(log4cpp::Priority::INFO), _logFullMessage(false), _category(NULL), CAF_CM_INIT("CLoggingChannelAdapterInstance") { } CLoggingChannelAdapterInstance::~CLoggingChannelAdapterInstance() { } void CLoggingChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _category = &log4cpp::Category::getInstance(_id.c_str()); std::string arg = configSection->findOptionalAttribute("level"); if (!arg.empty()) { if (g_ascii_strncasecmp(arg.c_str(), "crit", arg.length()) == 0) { _level = log4cpp::Priority::CRIT; } else if (g_ascii_strncasecmp(arg.c_str(), "error", arg.length()) == 0) { _level = log4cpp::Priority::ERROR; } else if (g_ascii_strncasecmp(arg.c_str(), "warn", arg.length()) == 0) { _level = log4cpp::Priority::WARN; } else if (g_ascii_strncasecmp(arg.c_str(), "info", arg.length()) == 0) { _level = log4cpp::Priority::INFO; } else if (g_ascii_strncasecmp(arg.c_str(), "debug", arg.length()) == 0) { _level = log4cpp::Priority::DEBUG; } else { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "'%s' is not a valid logging level. " "Choices are 'debug', 'info', 'warn', 'error' and 'crit'", arg.c_str()); } } arg = configSection->findOptionalAttribute("log-full-message"); if (!arg.empty()) { if (g_ascii_strncasecmp(arg.c_str(), "true", arg.length()) == 0) { _logFullMessage = true; } else if (g_ascii_strncasecmp(arg.c_str(), "false", arg.length()) == 0) { _logFullMessage = false; } else { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "'%s' is not a valid log-full-message value. " "Choices are 'true' and 'false'", arg.c_str()); } } _isInitialized = true; } std::string CLoggingChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CLoggingChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } void CLoggingChannelAdapterInstance::handleMessage(const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _savedMessage = message; _category->log(_level, message->getPayloadStr().c_str()); if (_logFullMessage) { IIntMessage::SmartPtrCHeaders headers = message->getHeaders(); for (IIntMessage::CHeaders::const_iterator headerIter = headers->begin(); headerIter != headers->end(); headerIter++) { std::stringstream logMessage; logMessage << '[' << headerIter->first << '=' << headerIter->second.first->toString() << ']'; _category->log(_level, logMessage.str()); } } } SmartPtrIIntMessage CLoggingChannelAdapterInstance::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _savedMessage; } void CLoggingChannelAdapterInstance::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _savedMessage = NULL; } CLoggingChannelAdapterInstance.h000066400000000000000000000033611321503522500406410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Jan 31, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CLOGGINGCHANNELADAPTERINSTANCE_H_ #define CLOGGINGCHANNELADAPTERINSTANCE_H_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageHandler.h" namespace Caf { class CLoggingChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public IMessageHandler { public: CLoggingChannelAdapterInstance(); virtual ~CLoggingChannelAdapterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IMessageHandler) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // IMessageHandler void handleMessage(const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); private: bool _isInitialized; std::string _id; log4cpp::Priority::PriorityLevel _level; bool _logFullMessage; log4cpp::Category* _category; SmartPtrIIntMessage _savedMessage; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CLoggingChannelAdapterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CLoggingChannelAdapterInstance); } #endif /* CLOGGINGCHANNELADAPTERINSTANCE_H_ */ CMessageHandlerChainInstance.cpp000066400000000000000000000372671321503522500406550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 10, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "ICafObject.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/Core/CSourcePollingChannelAdapter.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationComponent.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" #include "Integration/IPollableChannel.h" #include "CMessageHandlerChainInstance.h" #include "Exception/CCafException.h" #include "CObjectFactoryTables.h" #include "Integration/Core/CMessageHeaderUtils.h" using namespace Caf; CMessageHandlerChainInstance::CMessageHandlerChainInstance() : _isInitialized(false), _isRunning(false), CAF_CM_INIT_LOG("CMessageHandlerChainInstance") { } CMessageHandlerChainInstance::~CMessageHandlerChainInstance() { if (_weakRefSelf) { _weakRefSelf->setReference(NULL); _weakRefSelf = NULL; } } void CMessageHandlerChainInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _ctorArgs = ctorArgs; _properties = properties; _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CMessageHandlerChainInstance::getId() const { return _id; } void CMessageHandlerChainInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); // no point in doing a bunch of work if there are no chained components IDocument::SmartPtrCOrderedChildCollection handlerConfigs = _configSection->getAllChildrenInOrder(); if (!handlerConfigs->size()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, 0, "No message handlers are present in the chain '%s'", _id.c_str()); } // an input channel is required const std::string inputChannelId = _configSection->findRequiredAttribute( "input-channel"); SmartPtrIMessageChannel inputChannel = channelResolver->resolveChannelName( inputChannelId); SmartPtrIPollableChannel inputPollableChannel; inputPollableChannel.QueryInterface(inputChannel, false); _subscribableInputChannel.QueryInterface(inputChannel, false); if (!inputPollableChannel && !_subscribableInputChannel) { CAF_CM_EXCEPTIONEX_VA1(NoSuchInterfaceException, 0, "Input channel '%s' does not support any required interfaces", inputChannelId.c_str()); } // an output channel may be required - we'll figure it out in a bit const std::string outputChannelId = _configSection->findOptionalAttribute( "output-channel"); SmartPtrIMessageChannel outputChannel; if (outputChannelId.length()) { outputChannel = channelResolver->resolveChannelName(outputChannelId); } // build up a collection of messaging objects comprising the chain ChainLinks chainLinks; for (TSmartConstIterator handlerConfig( *handlerConfigs); handlerConfig; handlerConfig++) { CAF_CM_LOG_DEBUG_VA2("Found handler config '%s' chain '%s'", handlerConfig->getName().c_str(), _id.c_str()); const std::string& handlerType = handlerConfig->getName(); MessageHandlerObjectCreatorMap::const_iterator handlerMapEntry = CObjectFactoryTables::messageHandlerObjectCreatorMap.find(handlerType); if (handlerMapEntry == CObjectFactoryTables::messageHandlerObjectCreatorMap.end()) { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, 0, "Message handler type '%s' is not allowed to be part of a chain", handlerType.c_str()); } // Get the messaging object std::string messageHandlerId; SmartPtrICafObject messageHandlerObj; if (handlerMapEntry->second.first) { SmartPtrIIntegrationObject intObj; intObj = (handlerMapEntry->second.first)(); intObj->initialize(_ctorArgs, _properties, *handlerConfig); messageHandlerId = intObj->getId(); messageHandlerObj = intObj; } else { messageHandlerId = handlerConfig->findRequiredAttribute("id"); const std::string refStr = handlerConfig->findRequiredAttribute("ref"); SmartPtrIBean bean = appContext->getBean(refStr); SmartPtrIIntegrationComponent integrationComponent; integrationComponent.QueryInterface(bean, false); if (integrationComponent) { messageHandlerObj = integrationComponent->createObject(*handlerConfig); } else { messageHandlerObj = bean; } } // Create a partially initialized chain link. SmartPtrChainedMessageHandler handler; handler.CreateInstance(); handler->setId(messageHandlerId); handler->setMessageHandler(messageHandlerObj); SmartPtrChainLink chainLink; chainLink.CreateInstance(); chainLink->handler = handler; chainLink->id = messageHandlerId; chainLink->isMessageProducer = handlerMapEntry->second.second; chainLinks.push_back(chainLink); CAF_CM_LOG_DEBUG_VA2("Adding message handler '%s' to chain '%s'", messageHandlerId.c_str(), _id.c_str()); } // Configure the chain links. // All handlers in the chain except for the last one must be message producers. // If the last object is a message producer than the output-channel must be set. for (size_t i = 0; i < chainLinks.size(); ++i) { SmartPtrChainLink chainLink = chainLinks[i]; if (i < chainLinks.size() - 1) { if (!chainLink->isMessageProducer) { CAF_CM_EXCEPTIONEX_VA2(InvalidArgumentException, 0, "Handler '%s' in chain '%s' is not a message producer. " "All handlers except for the last one in the chain must " "be message producers.", chainLink->id.c_str(), _id.c_str()); } SmartPtrInterconnectChannel nextChannel; nextChannel.CreateInstance(); nextChannel->init(chainLinks[i + 1]->handler); chainLink->handler->setOutputChannel(nextChannel); } else { if (outputChannel && !chainLink->isMessageProducer) { CAF_CM_EXCEPTIONEX_VA2(InvalidArgumentException, 0, "Handler '%s' in chain '%s' - " "An output channel was provided but the last handler " "in the chain is not a message producer.", chainLink->id.c_str(), _id.c_str()); } else if (!outputChannel && chainLink->isMessageProducer) { CAF_CM_EXCEPTIONEX_VA2(InvalidArgumentException, 0, "Handler '%s' in chain '%s' - " "An output channel was not provided but the last handler " "in the chain is a message producer.", chainLink->id.c_str(), _id.c_str()); } if (chainLink->isMessageProducer) { chainLink->handler->setOutputChannel(outputChannel); } } } // Initialize the chain link handlers and store them // in this object's state for (TSmartConstIterator chainLink(chainLinks); chainLink; chainLink++) { chainLink->handler->init(appContext, channelResolver); _messageHandlers.push_back(chainLink->handler); } _weakRefSelf.CreateInstance(); _weakRefSelf->setReference(this); if (!_subscribableInputChannel) { SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, channelResolver->resolveChannelName("errorChannel")); SmartPtrCSourcePollingChannelAdapter channelAdapter; channelAdapter.CreateInstance(); channelAdapter->initialize(_weakRefSelf, inputPollableChannel, errorHandler); SmartPtrCSimpleAsyncTaskExecutor taskExecutor; taskExecutor.CreateInstance(); taskExecutor->initialize(channelAdapter, errorHandler); _taskExecutor = taskExecutor; } } void CMessageHandlerChainInstance::start(const uint32 timeoutMs) { CAF_CM_FUNCNAME("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (_subscribableInputChannel) { CAF_CM_LOG_DEBUG_VA1("Subscribing handler - %s", _id.c_str()); _subscribableInputChannel->subscribe(_weakRefSelf); } else if (_taskExecutor) { CAF_CM_LOG_DEBUG_VA1("Executing task - %s", _id.c_str()); _taskExecutor->execute(timeoutMs); } else { CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, 0, "handler '%s' : you should not see this. report this bug.", _id.c_str()); } _isRunning = true; } void CMessageHandlerChainInstance::stop(const uint32 timeoutMs) { CAF_CM_FUNCNAME("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); try { if (_subscribableInputChannel) { CAF_CM_LOG_DEBUG_VA1("Unsubscribing handler - %s", _id.c_str()); _subscribableInputChannel->subscribe(_weakRefSelf); } else if (_taskExecutor) { CAF_CM_LOG_DEBUG_VA1("Stopping task - %s", _id.c_str()); _taskExecutor->cancel(timeoutMs); } else { CAF_CM_EXCEPTIONEX_VA1(IllegalStateException, 0, "handler '%s' : you should not see this. report this bug.", _id.c_str()); } } CAF_CM_CATCH_ALL; _weakRefSelf->setReference(NULL); _isRunning = false; CAF_CM_THROWEXCEPTION; } bool CMessageHandlerChainInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _isRunning; } void CMessageHandlerChainInstance::handleMessage(const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("handleMessage"); try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL(_messageHandlers); CAF_CM_VALIDATE_INTERFACE(message); //logMessage(message); for (TSmartConstIterator messageHandlerIter(_messageHandlers); messageHandlerIter; messageHandlerIter++) { const SmartPtrChainedMessageHandler messageHandler = *messageHandlerIter; CAF_CM_VALIDATE_SMARTPTR(messageHandler); messageHandler->clearSavedMessage(); } _savedMessage = message; CAF_CM_VALIDATE_SMARTPTR(_messageHandlers.front()); _messageHandlers.front()->handleMessage(message); } CAF_CM_CATCH_ALL; try { for (TSmartConstIterator messageHandlerIter(_messageHandlers); messageHandlerIter; messageHandlerIter++) { const SmartPtrChainedMessageHandler messageHandler = *messageHandlerIter; CAF_CM_VALIDATE_SMARTPTR(messageHandler); const SmartPtrIIntMessage savedMessage = messageHandler->getSavedMessage(); if (!savedMessage.IsNull()) { _savedMessage = savedMessage; } } } CAF_CM_CATCH_ALL; CAF_CM_THROWEXCEPTION; } SmartPtrIIntMessage CMessageHandlerChainInstance::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _savedMessage; } void CMessageHandlerChainInstance::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _savedMessage = NULL; } CMessageHandlerChainInstance::ChainedMessageHandler::ChainedMessageHandler() : _isInitialized(false), CAF_CM_INIT("CMessageHandlerChainInstance::ChainedMessageHandler") { } void CMessageHandlerChainInstance::ChainedMessageHandler::init( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("init"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); CAF_CM_VALIDATE_STRING(_id); CAF_CM_VALIDATE_INTERFACE(_messageHandlerObj); // output channel is optional // The underlying component may need to be wired SmartPtrIIntegrationComponentInstance intInstance; intInstance.QueryInterface(_messageHandlerObj, false); if (intInstance) { intInstance->wire(appContext, channelResolver); } _messageHandler.CreateInstance(); _messageHandler->initialize(_id, _outputChannel, _messageHandlerObj); _isInitialized = true; } void CMessageHandlerChainInstance::ChainedMessageHandler::setId(const std::string& id) { CAF_CM_FUNCNAME_VALIDATE("setId"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(id); _id = id; } void CMessageHandlerChainInstance::ChainedMessageHandler::setOutputChannel( const SmartPtrIMessageChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("setOutputChannel"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(channel); _outputChannel = channel; } void CMessageHandlerChainInstance::ChainedMessageHandler::setMessageHandler( const SmartPtrICafObject& handlerObj) { CAF_CM_FUNCNAME_VALIDATE("setMessageHandler"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(handlerObj); _messageHandlerObj = handlerObj; } void CMessageHandlerChainInstance::ChainedMessageHandler::handleMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); //logMessage(message); _messageHandler->handleMessage(message); } SmartPtrIIntMessage CMessageHandlerChainInstance::ChainedMessageHandler::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _messageHandler->getSavedMessage(); } void CMessageHandlerChainInstance::ChainedMessageHandler::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _messageHandler->clearSavedMessage(); } CMessageHandlerChainInstance::InterconnectChannel::InterconnectChannel() : CAF_CM_INIT("CMessageHandlerChainInstance::InterconnectChannel") { } CMessageHandlerChainInstance::InterconnectChannel::~InterconnectChannel() { } void CMessageHandlerChainInstance::InterconnectChannel::init( const SmartPtrChainedMessageHandler& nextHandler) { _nextHandler = nextHandler; } bool CMessageHandlerChainInstance::InterconnectChannel::send( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("send"); CAF_CM_VALIDATE_SMARTPTR(_nextHandler); _nextHandler->handleMessage(message); return true; } bool CMessageHandlerChainInstance::InterconnectChannel::send( const SmartPtrIIntMessage& message, const int32 timeout) { return send(message); } CMessageHandlerChainInstance::SelfWeakReference::SelfWeakReference() : _reference(NULL) { CAF_CM_INIT_THREADSAFE; } void CMessageHandlerChainInstance::SelfWeakReference::setReference( IMessageHandler *handler) { CAF_CM_LOCK_UNLOCK; _reference = handler; } void CMessageHandlerChainInstance::SelfWeakReference::handleMessage( const SmartPtrIIntMessage& message) { CAF_CM_LOCK_UNLOCK; if (_reference) { _reference->handleMessage(message); } } SmartPtrIIntMessage CMessageHandlerChainInstance::SelfWeakReference::getSavedMessage() const { CAF_CM_LOCK_UNLOCK; SmartPtrIIntMessage savedMessage; if (_reference) { savedMessage = _reference->getSavedMessage(); } return savedMessage; } void CMessageHandlerChainInstance::SelfWeakReference::clearSavedMessage() { CAF_CM_LOCK_UNLOCK; if (_reference) { _reference->clearSavedMessage(); } } void CMessageHandlerChainInstance::logMessage( const SmartPtrIIntMessage& message) const { CAF_CM_FUNCNAME_VALIDATE("logMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const std::string prefix = _id.empty() ? "NULL" : _id; if (message.IsNull()) { CAF_CM_LOG_DEBUG_VA1("%s - NULL Message", prefix.c_str()); } else { CAF_CM_LOG_DEBUG_VA2("%s - payload: %s", prefix.c_str(), message->getPayloadStr().c_str()); CMessageHeaderUtils::log(message->getHeaders()); } } void CMessageHandlerChainInstance::ChainedMessageHandler::logMessage( const SmartPtrIIntMessage& message) const { CAF_CM_STATIC_FUNC_LOG_ONLY("ChainedMessageHandler", "logMessage"); const std::string prefix = _id.empty() ? "NULL" : _id; if (message.IsNull()) { CAF_CM_LOG_DEBUG_VA1("%s - NULL Message", prefix.c_str()); } else { CAF_CM_LOG_DEBUG_VA2("%s - payload: %s", prefix.c_str(), message->getPayloadStr().c_str()); CMessageHeaderUtils::log(message->getHeaders()); } } CNullChannel.cpp000066400000000000000000000034721321503522500355350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CNullChannel.h" #include "CNullChannelInstance.h" using namespace Caf; CNullChannel::CNullChannel() : _isInitialized(false), CAF_CM_INIT("CNullChannel") { } CNullChannel::~CNullChannel() { } void CNullChannel::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CNullChannel::terminateBean() { } void CNullChannel::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CNullChannel::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CNullChannel::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // configSection is optional SmartPtrCNullChannelInstance instance; instance.CreateInstance(); instance->initialize(_ctorArgs, _properties, configSection); rc.QueryInterface(instance, false); CAF_CM_VALIDATE_INTERFACE(rc); } CAF_CM_EXIT; return rc; } CNullChannel.h000066400000000000000000000024661321503522500352040ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CNullChannel_h_ #define CNullChannel_h_ #include "IBean.h" #include "IntegrationSubsys.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CNullChannel : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CNullChannel(); virtual ~CNullChannel(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdNullChannel) CAF_BEGIN_INTERFACE_MAP(CNullChannel) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: void initialize(); public: // IBean void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(CNullChannel); }; } #endif // #ifndef CNullChannel_h_ CNullChannelInstance.cpp000066400000000000000000000033731321503522500372220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CNullChannelInstance.h" using namespace Caf; CNullChannelInstance::CNullChannelInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CNullChannelInstance") { } CNullChannelInstance::~CNullChannelInstance() { } void CNullChannelInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); // configSection is optional _id = "nullChannel"; _isInitialized = true; } CAF_CM_EXIT; } std::string CNullChannelInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CNullChannelInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } CAF_CM_EXIT; } bool CNullChannelInstance::doSend( const SmartPtrIIntMessage& message, int32 timeout) { CAF_CM_FUNCNAME_VALIDATE("doSend"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); CAF_CM_LOG_DEBUG_VA1("Received message - %s", message->getPayloadStr().c_str()); } CAF_CM_EXIT; return true; } CNullChannelInstance.h000066400000000000000000000031571321503522500366670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CNullChannelInstance_h_ #define CNullChannelInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/Core/CAbstractMessageChannel.h" namespace Caf { /// Sends responses/errors back to the client. class CNullChannelInstance : public IIntegrationObject, public IIntegrationComponentInstance, public CAbstractMessageChannel { public: CNullChannelInstance(); virtual ~CNullChannelInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IMessageChannel) CAF_QI_ENTRY(IChannelInterceptorSupport) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); protected: // CAbstractMessageChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); private: bool _isInitialized; std::string _id; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CNullChannelInstance); }; CAF_DECLARE_SMART_QI_POINTER(CNullChannelInstance); } #endif // #ifndef CNullChannelInstance_h_ CObjectFactoryTables.cpp000066400000000000000000000132711321503522500372210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 13, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CMessageHandlerChainInstance.h" #include "CObjectFactoryTables.h" #include "CServiceActivatorInstance.h" #include "CWireTapInstance.h" #include "CPublishSubscribeChannelInstance.h" #include "CFileInboundChannelAdapterInstance.h" #include "CFileOutboundChannelAdapterInstance.h" #include "CFileToStringTransformerInstance.h" #include "CHeaderEnricherTransformerInstance.h" #include "CHeaderValueRouterInstance.h" #include "CPayloadContentRouterInstance.h" #include "CLoggingChannelAdapterInstance.h" #include "CRecipientListRouterInstance.h" #include "CRouterInstance.h" #include "CXPathHeaderEnricherTransformerInstance.h" using namespace Caf; const ObjectCreatorMap::value_type CObjectFactoryTables::objectCreatorEntries[] = { ObjectCreatorMap::value_type( "file-to-string-transformer", CreateIntegrationObject), ObjectCreatorMap::value_type( "header-enricher", CreateIntegrationObject), ObjectCreatorMap::value_type( "transformer", CreateIntegrationObject), ObjectCreatorMap::value_type( "header-value-router", CreateIntegrationObject), ObjectCreatorMap::value_type( "payload-content-router", CreateIntegrationObject), ObjectCreatorMap::value_type( "splitter", CreateIntegrationObject), ObjectCreatorMap::value_type( "service-activator", CreateIntegrationObject), ObjectCreatorMap::value_type( "logging-channel-adapter", CreateIntegrationObject), ObjectCreatorMap::value_type( "wire-tap", CreateIntegrationObject), ObjectCreatorMap::value_type( "publish-subscribe-channel", CreateIntegrationObject), ObjectCreatorMap::value_type( "file-inbound-channel-adapter", CreateIntegrationObject), ObjectCreatorMap::value_type( "file-outbound-channel-adapter", CreateIntegrationObject), ObjectCreatorMap::value_type( "channel", NULL), ObjectCreatorMap::value_type( "recipient-list-router", CreateIntegrationObject), ObjectCreatorMap::value_type( "chain", CreateIntegrationObject), ObjectCreatorMap::value_type( "router", CreateIntegrationObject), ObjectCreatorMap::value_type( "xpath-header-enricher", CreateIntegrationObject), }; const ObjectCreatorMap CObjectFactoryTables::objectCreatorMap( objectCreatorEntries, objectCreatorEntries + (sizeof(objectCreatorEntries)/sizeof(objectCreatorEntries[0]))); const MessageHandlerObjectCreatorMap::value_type CObjectFactoryTables::messageHandlerObjectCreatorEntries[] = { MessageHandlerObjectCreatorMap::value_type( "service-activator", MessageHandlerObjectCreatorMap::mapped_type( NULL, true)), MessageHandlerObjectCreatorMap::value_type( "file-to-string-transformer", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, true)), MessageHandlerObjectCreatorMap::value_type( "header-enricher", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, true)), MessageHandlerObjectCreatorMap::value_type( "header-value-router", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, false)), MessageHandlerObjectCreatorMap::value_type( "payload-content-router", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, false)), MessageHandlerObjectCreatorMap::value_type( "logging-channel-adapter", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, false)), MessageHandlerObjectCreatorMap::value_type( "splitter", MessageHandlerObjectCreatorMap::mapped_type( NULL, true)), MessageHandlerObjectCreatorMap::value_type( "transformer", MessageHandlerObjectCreatorMap::mapped_type( NULL, true)), MessageHandlerObjectCreatorMap::value_type( "recipient-list-router", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, false)), MessageHandlerObjectCreatorMap::value_type( "router", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, false)), MessageHandlerObjectCreatorMap::value_type( "file-outbound-channel-adapter", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, false)), MessageHandlerObjectCreatorMap::value_type( "xpath-header-enricher", MessageHandlerObjectCreatorMap::mapped_type( CreateIntegrationObject, true)) }; const MessageHandlerObjectCreatorMap CObjectFactoryTables::messageHandlerObjectCreatorMap( messageHandlerObjectCreatorEntries, messageHandlerObjectCreatorEntries + (sizeof(messageHandlerObjectCreatorEntries)/ sizeof(messageHandlerObjectCreatorEntries[0]))); CObjectFactoryTables.h000066400000000000000000000011211321503522500366550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 13, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CObjectFactoryTables_h #define CObjectFactoryTables_h namespace Caf { struct CObjectFactoryTables { static const ObjectCreatorMap objectCreatorMap; static const ObjectCreatorMap::value_type objectCreatorEntries[]; static const MessageHandlerObjectCreatorMap messageHandlerObjectCreatorMap; static const MessageHandlerObjectCreatorMap::value_type messageHandlerObjectCreatorEntries[]; }; } #endif /* CObjectFactoryTables_h */ CPayloadContentRouterInstance.cpp000066400000000000000000000142611321503522500411420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CCafRegex.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Exception/CCafException.h" #include "CPayloadContentRouterInstance.h" using namespace Caf; CPayloadContentRouterInstance::CPayloadContentRouterInstance() : _isInitialized(false), _resolutionRequired(false), CAF_CM_INIT_LOG("CPayloadContentRouterInstance") { } CPayloadContentRouterInstance::~CPayloadContentRouterInstance() { } void CPayloadContentRouterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _defaultOutputChannelId = configSection->findOptionalAttribute("default-output-channel"); const std::string resolutionRequiredStr = configSection->findOptionalAttribute("resolution-required"); _resolutionRequired = (resolutionRequiredStr.empty() || resolutionRequiredStr.compare("true") == 0) ? true : false; const IDocument::SmartPtrCChildCollection childCollection = configSection->getAllChildren(); for(TConstIterator childIter(*childCollection); childIter; childIter++) { const std::string sectionName = childIter->first; if (sectionName.compare("mapping") == 0) { const SmartPtrIDocument document = childIter->second; const std::string value = document->findRequiredAttribute("value"); const std::string channel = document->findRequiredAttribute("channel"); _valueToChannelMapping.insert(std::make_pair(value, channel)); } } if (_valueToChannelMapping.empty()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "No mapping sections found - %s", _id.c_str()); } _isInitialized = true; } CAF_CM_EXIT; } std::string CPayloadContentRouterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CPayloadContentRouterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); _channelResolver = channelResolver; SmartPtrIMessageChannel defaultOutputChannel; if (_defaultOutputChannelId.length()) { try { defaultOutputChannel = _channelResolver->resolveChannelName(_defaultOutputChannelId); } CAF_CM_CATCH_ALL; CAF_CM_LOG_WARN_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (defaultOutputChannel) { CAF_CM_LOG_INFO_VA2( "Successfully resolved default channel - id: %s, defaultOutputChannelId: %s", _id.c_str(), _defaultOutputChannelId.c_str()); } else { CAF_CM_EXCEPTIONEX_VA2( NoSuchElementException, 0, "Failed to resolve default channel - id: %s, defaultChannelId: %s", _id.c_str(), _defaultOutputChannelId.c_str()); } } CAbstractMessageRouter::init(defaultOutputChannel, false, -1); } CAF_CM_EXIT; } CPayloadContentRouterInstance::ChannelCollection CPayloadContentRouterInstance::getTargetChannels( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("getTargetChannels"); ChannelCollection messageChannels; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const IIntMessage::SmartPtrCHeaders headers = message->getHeaders(); const std::string outputChannel = calcOutputChannel(message->getPayload()); if (outputChannel.empty() && _defaultOutputChannelId.empty()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Did not find output channel and default channel not provided - id: %s", _id.c_str()); } SmartPtrIMessageChannel messageChannel; if (! outputChannel.empty()) { try { messageChannel = _channelResolver->resolveChannelName(outputChannel); } CAF_CM_CATCH_ALL; CAF_CM_LOG_WARN_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (messageChannel.IsNull() && _resolutionRequired) { CAF_CM_EXCEPTIONEX_VA2(NoSuchElementException, ERROR_NOT_FOUND, "Failed to resolve channel when resolution is required - id: %s, outputChannel: %s", _id.c_str(), outputChannel.c_str()); } if (! messageChannel.IsNull()) { CAF_CM_LOG_INFO_VA2( "Successfully resolved channel - id: %s, outputChannel: %s", _id.c_str(), outputChannel.c_str()); } } if (messageChannel.IsNull() && _defaultOutputChannelId.empty()) { CAF_CM_EXCEPTIONEX_VA2(NoSuchElementException, ERROR_NOT_FOUND, "Failed to resolve channel when resolution is not required and default channel is not available - id: %s, outputChannel: %s", _id.c_str(), outputChannel.c_str()); } if (!messageChannel.IsNull()) { messageChannels.push_back(messageChannel); } } CAF_CM_EXIT; return messageChannels; } std::string CPayloadContentRouterInstance::calcOutputChannel( const SmartPtrCDynamicByteArray& payload) const { CAF_CM_FUNCNAME_VALIDATE("calcOutputChannel"); std::string outputChannel; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(payload); const std::string payloadStr = reinterpret_cast(payload->getPtr()); CAF_CM_VALIDATE_STRING(payloadStr); for(TConstIterator valueToChannelIter(_valueToChannelMapping); valueToChannelIter; valueToChannelIter++) { const std::string value = valueToChannelIter->first; SmartPtrCCafRegex regex; regex.CreateInstance(); regex->initialize(value); if (regex->isMatched(payloadStr)) { outputChannel = valueToChannelIter->second; CAF_CM_LOG_DEBUG_VA2("Matched channel - regex: %s, channel: %s", value.c_str(), outputChannel.c_str()); break; } } } CAF_CM_EXIT; return outputChannel; } CPayloadContentRouterInstance.h000066400000000000000000000035721321503522500406120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPayloadContentRouterInstance_h_ #define CPayloadContentRouterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Integration/IIntegrationObject.h" #include "Integration/Core/CAbstractMessageRouter.h" namespace Caf { class CPayloadContentRouterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public CAbstractMessageRouter { public: CPayloadContentRouterInstance(); virtual ~CPayloadContentRouterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IMessageRouter) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); private: // CAbstractMessageRouter ChannelCollection getTargetChannels( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; std::string _defaultOutputChannelId; bool _resolutionRequired; Cmapstrstr _valueToChannelMapping; SmartPtrIChannelResolver _channelResolver; private: std::string calcOutputChannel( const SmartPtrCDynamicByteArray& payload) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CPayloadContentRouterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CPayloadContentRouterInstance); } #endif // #ifndef CPayloadContentRouterInstance_h_ CPublishSubscribeChannelInstance.cpp000066400000000000000000000070171321503522500415570ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/Core/CBroadcastingDispatcher.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/IMessageHandler.h" #include "Exception/CCafException.h" #include "CPublishSubscribeChannelInstance.h" using namespace Caf; CPublishSubscribeChannelInstance::CPublishSubscribeChannelInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CPublishSubscribeChannelInstance") { } CPublishSubscribeChannelInstance::~CPublishSubscribeChannelInstance() { } void CPublishSubscribeChannelInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); _isInitialized = true; } CAF_CM_EXIT; } std::string CPublishSubscribeChannelInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CPublishSubscribeChannelInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, errorMessageChannel); SmartPtrCBroadcastingDispatcher broadcastingDispatcher; broadcastingDispatcher.CreateInstance(); broadcastingDispatcher->initialize(errorHandler); _messageDispatcher = broadcastingDispatcher; } CAF_CM_EXIT; } void CPublishSubscribeChannelInstance::subscribe( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("subscribe"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); _messageDispatcher->addHandler(messageHandler); } CAF_CM_EXIT; } void CPublishSubscribeChannelInstance::unsubscribe( const SmartPtrIMessageHandler& messageHandler) { CAF_CM_FUNCNAME_VALIDATE("unsubscribe"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(messageHandler); _messageDispatcher->removeHandler(messageHandler); } CAF_CM_EXIT; } bool CPublishSubscribeChannelInstance::doSend( const SmartPtrIIntMessage& message, int32 timeout) { CAF_CM_FUNCNAME("doSend"); bool sent = false; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Timeout not currently supported: %s", _id.c_str()); } CAF_CM_LOG_DEBUG_VA1("Dispatching message - %s", _id.c_str()); sent = _messageDispatcher->dispatch(message); if (!sent) { CAF_CM_LOG_ERROR_VA1("Nothing handled the message - channel: %s", _id.c_str()); } } CAF_CM_EXIT; return sent; } CPublishSubscribeChannelInstance.h000066400000000000000000000042241321503522500412210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPublishSubscribeChannelInstance_h_ #define CPublishSubscribeChannelInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageDispatcher.h" #include "Integration/IMessageHandler.h" #include "Integration/IIntegrationObject.h" #include "Integration/ISubscribableChannel.h" #include "Integration/Core/CAbstractMessageChannel.h" namespace Caf { /// Sends responses/errors back to the client. class CPublishSubscribeChannelInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ISubscribableChannel, public CAbstractMessageChannel { public: CPublishSubscribeChannelInstance(); virtual ~CPublishSubscribeChannelInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ISubscribableChannel) CAF_QI_ENTRY(IMessageChannel) CAF_QI_ENTRY(IChannelInterceptorSupport) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ISubscribableChannel void subscribe( const SmartPtrIMessageHandler& messageHandler); void unsubscribe( const SmartPtrIMessageHandler& messageHandler); protected: // CAbstractMessageChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); private: bool _isInitialized; SmartPtrIDocument _configSection; std::string _id; SmartPtrIMessageDispatcher _messageDispatcher; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CPublishSubscribeChannelInstance); }; CAF_DECLARE_SMART_QI_POINTER(CPublishSubscribeChannelInstance); } #endif // #ifndef CPublishSubscribeChannelInstance_h_ CQueueChannelInstance.cpp000066400000000000000000000054461321503522500373770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "CQueueChannelInstance.h" using namespace Caf; CQueueChannelInstance::CQueueChannelInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CQueueChannelInstance") { CAF_CM_INIT_THREADSAFE; } CQueueChannelInstance::~CQueueChannelInstance() { } void CQueueChannelInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); setPollerMetadata(_configSection->findOptionalChild("poller")); _isInitialized = true; } CAF_CM_EXIT; } std::string CQueueChannelInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string id; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); id = _id; } CAF_CM_EXIT; return id; } void CQueueChannelInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } CAF_CM_EXIT; } bool CQueueChannelInstance::doSend( const SmartPtrIIntMessage& message, int32 timeout) { CAF_CM_FUNCNAME("doSend"); CAF_CM_ENTER_AND_LOCK { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Queue channel with timeout not currently supported: %s", _id.c_str()); } CAF_CM_LOG_DEBUG_VA2("Queueing message %d - %s", _messageQueue.size(), _id.c_str()); _messageQueue.push_front(message); } CAF_CM_UNLOCK_AND_EXIT; return true; } SmartPtrIIntMessage CQueueChannelInstance::doReceive(const int32 timeout) { CAF_CM_FUNCNAME("doReceive"); SmartPtrIIntMessage message; CAF_CM_ENTER_AND_LOCK { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Queue channel with timeout not currently supported: %s", _id.c_str()); } if (! _messageQueue.empty()) { CAF_CM_LOG_DEBUG_VA2("Receiving message %d - %s", _messageQueue.size(), _id.c_str()); message = _messageQueue.back(); _messageQueue.pop_back(); } } CAF_CM_UNLOCK_AND_EXIT; return message; } CQueueChannelInstance.h000066400000000000000000000034771321503522500370460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CQueueChannelInstance_h_ #define CQueueChannelInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/Core/CAbstractPollableChannel.h" namespace Caf { /// Sends responses/errors back to the client. class CQueueChannelInstance : public IIntegrationObject, public IIntegrationComponentInstance, public CAbstractPollableChannel { public: CQueueChannelInstance(); virtual ~CQueueChannelInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IPollableChannel) CAF_QI_ENTRY(IMessageChannel) CAF_QI_ENTRY(IChannelInterceptorSupport) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); protected: // CAbstractPollableChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); SmartPtrIIntMessage doReceive(const int32 timeout); private: bool _isInitialized; SmartPtrIDocument _configSection; std::string _id; std::deque _messageQueue; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CQueueChannelInstance); }; CAF_DECLARE_SMART_QI_POINTER(CQueueChannelInstance); } #endif // #ifndef CQueueChannelInstance_h_ CRecipientListRouterInstance.cpp000066400000000000000000000126101321503522500407700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IVariant.h" #include "Integration/Core/CExpressionHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "CRecipientListRouterInstance.h" using namespace Caf; CRecipientListRouterInstance::CRecipientListRouterInstance() : _isInitialized(false), _ignoreSendFailures(false), _timeout(-1), CAF_CM_INIT_LOG("CRecipientListRouterInstance") { } CRecipientListRouterInstance::~CRecipientListRouterInstance() { } void CRecipientListRouterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); std::string val = configSection->findOptionalAttribute("timeout"); if (val.length()) { _timeout = CStringConv::fromString(val); } val = configSection->findOptionalAttribute("ignore-send-failures"); _ignoreSendFailures = (val == "true"); Csetstr channelIds; const IDocument::SmartPtrCChildCollection childCollection = configSection->getAllChildren(); for(TSmartConstMultimapIterator childIter(*childCollection); childIter; childIter++) { const std::string sectionName = childIter.getKey(); if (sectionName == "recipient") { const SmartPtrIDocument document = *childIter; const std::string channelId = document->findRequiredAttribute("channel"); const std::string selectorExpression = document->findOptionalAttribute("selector-expression"); if (!channelIds.insert(channelId).second) { CAF_CM_EXCEPTIONEX_VA2( DuplicateElementException, 0, "Duplicate channelId '%s' in " "recipient-list-router definition '%s'", channelId.c_str(), _id.c_str()); } if (selectorExpression.length()) { _selectorDefinitions.insert( Cmapstrstr::value_type(channelId, selectorExpression)); } else { _staticChannelIds.push_back(channelId); } } } if (!_staticChannelIds.size() && !_selectorDefinitions.size()) { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "No recipients were listed in the definition of " "recipient-list-router '%s'", _id.c_str()); } _isInitialized = true; } CAF_CM_EXIT; } std::string CRecipientListRouterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CRecipientListRouterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); SmartPtrIAppConfig appConfig = getAppConfig(); for (TConstIterator channelId(_staticChannelIds); channelId; channelId++) { _staticChannels.push_back( channelResolver->resolveChannelName(*channelId)); } for (TConstMapIterator selectorPair(_selectorDefinitions); selectorPair; selectorPair++) { SmartPtrIMessageChannel channel = channelResolver->resolveChannelName(selectorPair.getKey()); SmartPtrCExpressionHandler handler; handler.CreateInstance(); handler->init( appConfig, appContext, *selectorPair); _selectorChannels.push_back(std::make_pair(handler, channel)); } CAbstractMessageRouter::init( SmartPtrIMessageChannel(), _ignoreSendFailures, _timeout); } CAF_CM_EXIT; } CRecipientListRouterInstance::ChannelCollection CRecipientListRouterInstance::getTargetChannels( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("getTargetChannels"); ChannelCollection channels; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // Static channels always get the message std::copy( _staticChannels.begin(), _staticChannels.end(), std::back_inserter(channels)); // Execute the selector expression(s) on the message // and add the channels for the expressions that return 'true' for (TConstIterator selector(_selectorChannels); selector; selector++) { SmartPtrIVariant evalResult = selector->first->evaluate(message); if (evalResult->isBool()) { if (CAF_CM_IS_LOG_DEBUG_ENABLED) { CAF_CM_LOG_DEBUG_VA3( "recipient-list-router [%s] selector-expression [%s] returned '%s'", _id.c_str(), selector->first->toString().c_str(), evalResult->toString().c_str()); } if (g_variant_get_boolean(evalResult->get())) { channels.push_back(selector->second); } } else { CAF_CM_EXCEPTIONEX_VA2( InvalidArgumentException, 0, "recipient-list-router [%s] illegal selector-expression [%s] : " "selector-expression results must return boolean values.", _id.c_str(), selector->first->toString().c_str()); } } } CAF_CM_EXIT; return channels; } CRecipientListRouterInstance.h000066400000000000000000000036701321503522500404430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 9, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CRecipientListRouterInstance_h #define CRecipientListRouterInstance_h #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/IIntegrationObject.h" #include "Integration/Core/CAbstractMessageRouter.h" namespace Caf { class CRecipientListRouterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public CAbstractMessageRouter { public: CRecipientListRouterInstance(); virtual ~CRecipientListRouterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IMessageRouter) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); private: // CAbstractMessageRouter ChannelCollection getTargetChannels( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; bool _ignoreSendFailures; int32 _timeout; Cdeqstr _staticChannelIds; Cmapstrstr _selectorDefinitions; std::deque _staticChannels; typedef std::deque > SelectorChannelCollection; SelectorChannelCollection _selectorChannels; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CRecipientListRouterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CRecipientListRouterInstance); } #endif /* CRecipientListRouterInstance_h */ CRouterInstance.cpp000066400000000000000000000131231321503522500362710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IVariant.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "CRouterInstance.h" using namespace Caf; CRouterInstance::CRouterInstance() : _isInitialized(false), _timeout(-1), _resolutionRequired(false), CAF_CM_INIT_LOG("CRouterInstance") { } CRouterInstance::~CRouterInstance() { } void CRouterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); std::string val = configSection->findOptionalAttribute("timeout"); if (val.length()) { _timeout = CStringConv::fromString(val); } _defaultOutputChannelId = configSection->findOptionalAttribute("default-output-channel"); _expressionStr = configSection->findRequiredAttribute("expression"); const std::string resolutionRequiredStr = configSection->findOptionalAttribute("resolution-required"); _resolutionRequired = (resolutionRequiredStr.empty() || resolutionRequiredStr.compare("true") == 0) ? true : false; const IDocument::SmartPtrCChildCollection childCollection = configSection->getAllChildren(); for(TConstIterator childIter(*childCollection); childIter; childIter++) { const std::string sectionName = childIter->first; if (sectionName.compare("mapping") == 0) { const SmartPtrIDocument document = childIter->second; const std::string value = document->findRequiredAttribute("value"); const std::string channel = document->findRequiredAttribute("channel"); _valueToChannelMapping.insert(std::make_pair(value, channel)); } } if (_valueToChannelMapping.empty()) { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "No mapping sections found - %s", _id.c_str()); } _isInitialized = true; } std::string CRouterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CRouterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); _channelResolver = channelResolver; SmartPtrIMessageChannel defaultOutputChannel; if (_defaultOutputChannelId.length()) { try { defaultOutputChannel = _channelResolver->resolveChannelName(_defaultOutputChannelId); } CAF_CM_CATCH_ALL; CAF_CM_LOG_WARN_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (defaultOutputChannel) { CAF_CM_LOG_INFO_VA2( "Successfully resolved default channel - id: %s, defaultOutputChannelId: %s", _id.c_str(), _defaultOutputChannelId.c_str()); } else { CAF_CM_EXCEPTIONEX_VA2( NoSuchElementException, 0, "Failed to resolve default channel - id: %s, defaultChannelId: %s", _id.c_str(), _defaultOutputChannelId.c_str()); } } _expressionHandler.CreateInstance(); _expressionHandler->init( getAppConfig(), appContext, _expressionStr); CAbstractMessageRouter::init(defaultOutputChannel, false, -1); } CRouterInstance::ChannelCollection CRouterInstance::getTargetChannels( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("getTargetChannels"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); ChannelCollection messageChannels; std::string exprValueStr; try { SmartPtrIVariant exprValue = _expressionHandler->evaluate(message); exprValueStr = exprValue->toString(); CAF_CM_VALIDATE_STRING(exprValueStr); CAF_CM_LOG_DEBUG_VA2( "router '%s' expression returned '%s'", _id.c_str(), exprValueStr.c_str()); } CAF_CM_CATCH_ALL; CAF_CM_LOG_ERROR_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; SmartPtrIMessageChannel outputChannel; std::string outputChannelId; if (exprValueStr.length()) { Cmapstrstr::const_iterator valueIter = _valueToChannelMapping.find(exprValueStr); if (valueIter != _valueToChannelMapping.end()) { outputChannelId = valueIter->second; try { outputChannel = _channelResolver->resolveChannelName(outputChannelId); CAF_CM_LOG_DEBUG_VA3( "Successfully resolved channel " "- id: %s, expression value: %s, outputChannel: %s", _id.c_str(), exprValueStr.c_str(), outputChannelId.c_str()); } CAF_CM_CATCH_ALL; CAF_CM_LOG_WARN_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } else { CAF_CM_LOG_WARN_VA2( "Expression value not found in mappings - " "id: '%s', value: '%s'", _id.c_str(), exprValueStr.c_str()); } } if (outputChannel) { messageChannels.push_back(outputChannel); } else { if (_resolutionRequired) { CAF_CM_EXCEPTIONEX_VA3( NoSuchElementException, 0, "Failed to resolve channel when resolution is required " "- id: %s, expression value: '%s', outputChannel: '%s'", _id.c_str(), exprValueStr.c_str(), outputChannelId.c_str()); } else if (_defaultOutputChannelId.empty()) { CAF_CM_EXCEPTIONEX_VA2( NoSuchElementException, 0, "Did not resolve output channel and default channel not provided " "- id: %s, expression value: %s", _id.c_str(), exprValueStr.c_str()); } } return messageChannels; } CRouterInstance.h000066400000000000000000000033501321503522500357370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Aug 15, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CRouterInstance_h #define CRouterInstnace_h #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/Core/CExpressionHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/Core/CAbstractMessageRouter.h" namespace Caf { class CRouterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public CAbstractMessageRouter { public: CRouterInstance(); virtual ~CRouterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(IMessageRouter) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); private: ChannelCollection getTargetChannels( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; int32 _timeout; std::string _defaultOutputChannelId; bool _resolutionRequired; std::string _expressionStr; SmartPtrCExpressionHandler _expressionHandler; Cmapstrstr _valueToChannelMapping; SmartPtrIChannelResolver _channelResolver; CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CRouterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CRouterInstance); } #endif /* CRouterInstance_h */ CServiceActivatorInstance.cpp000066400000000000000000000134751321503522500403000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "IBean.h" #include "ICafObject.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationComponent.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" #include "Exception/CCafException.h" #include "CServiceActivatorInstance.h" #include "CObjectFactoryTables.h" using namespace Caf; CServiceActivatorInstance::CServiceActivatorInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CServiceActivatorInstance") { } CServiceActivatorInstance::~CServiceActivatorInstance() { } void CServiceActivatorInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _ctorArgs = ctorArgs; _properties = properties; _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); _isInitialized = true; } CAF_CM_EXIT; } std::string CServiceActivatorInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CServiceActivatorInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); MessageHandlerObjectCreatorMap::const_iterator objectCreatorEntry = CObjectFactoryTables::messageHandlerObjectCreatorMap.find( _configSection->getName()); if (objectCreatorEntry == CObjectFactoryTables::messageHandlerObjectCreatorMap.end()) { CAF_CM_EXCEPTIONEX_VA1( NoSuchElementException, 0, "Configuration section '%s' is not handled by this object", _configSection->getName().c_str()); } const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); std::string inputChannelStr; SmartPtrIMessageChannel outputMessageChannel; if (objectCreatorEntry->second.second) { inputChannelStr = _configSection->findRequiredAttribute("input-channel"); const std::string outputChannelStr = _configSection->findRequiredAttribute("output-channel"); outputMessageChannel = channelResolver->resolveChannelName(outputChannelStr); } else { inputChannelStr = _configSection->findOptionalAttribute("channel"); if (inputChannelStr.empty()) { inputChannelStr = _configSection->findRequiredAttribute("input-channel"); } } const SmartPtrIIntegrationObject inputIntegrationObject = channelResolver->resolveChannelNameToObject(inputChannelStr); SmartPtrICafObject messageHandlerObj; if (_configSection->getName().compare("service-activator") == 0) { const std::string refStr = _configSection->findRequiredAttribute("ref"); CAF_CM_LOG_DEBUG_VA1("Creating the message processor - %s", refStr.c_str()); const SmartPtrIBean bean = appContext->getBean(refStr); messageHandlerObj.QueryInterface(bean, false); CAF_CM_VALIDATE_INTERFACE(messageHandlerObj); SmartPtrIIntegrationComponentInstance integrationComponentInstance; integrationComponentInstance.QueryInterface(bean, false); if (!integrationComponentInstance.IsNull()) { // Bean is also an integration component instance...wire integrationComponentInstance->wire(appContext, channelResolver); } } else { SmartPtrIIntegrationObject integrationObject; if (objectCreatorEntry->second.first) { integrationObject = (objectCreatorEntry->second.first)(); integrationObject->initialize(_ctorArgs, _properties, _configSection); } else { const std::string& beanId = _configSection->findRequiredAttribute("ref"); const SmartPtrIBean bean = appContext->getBean(beanId); SmartPtrIIntegrationComponent integrationComponent; integrationComponent.QueryInterface(bean, false); if (!integrationComponent) { CAF_CM_EXCEPTIONEX_VA1( InvalidArgumentException, 0, "Bean is not an integration component - %s", beanId.c_str()); } integrationObject = integrationComponent->createObject(_configSection); } SmartPtrIIntegrationComponentInstance integrationComponentInstance; integrationComponentInstance.QueryInterface(integrationObject, false); CAF_CM_VALIDATE_INTERFACE(integrationComponentInstance); integrationComponentInstance->wire(appContext, channelResolver); messageHandlerObj.QueryInterface(integrationObject, false); CAF_CM_VALIDATE_INTERFACE(messageHandlerObj); } _messagingTemplate.CreateInstance(); _messagingTemplate->initialize( channelResolver, inputIntegrationObject, errorMessageChannel, outputMessageChannel, messageHandlerObj); } CAF_CM_EXIT; } void CServiceActivatorInstance::start( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Starting"); _messagingTemplate->start(timeoutMs); } CAF_CM_EXIT; } void CServiceActivatorInstance::stop( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Stopping"); _messagingTemplate->stop(timeoutMs); } CAF_CM_EXIT; } bool CServiceActivatorInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); bool rc = false; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _messagingTemplate->isRunning(); } CAF_CM_EXIT; return rc; } CServiceActivatorInstance.h000066400000000000000000000032251321503522500377350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CServiceActivatorInstance_h_ #define CServiceActivatorInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/Core/CMessagingTemplate.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" namespace Caf { class CServiceActivatorInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle { public: CServiceActivatorInstance(); virtual ~CServiceActivatorInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; SmartPtrIDocument _configSection; std::string _id; SmartPtrCMessagingTemplate _messagingTemplate; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CServiceActivatorInstance); }; CAF_DECLARE_SMART_QI_POINTER(CServiceActivatorInstance); } #endif // #ifndef CServiceActivatorInstance_h_ CWireTapInstance.cpp000066400000000000000000000103501321503522500363630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Jan 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "CWireTapInstance.h" CWireTapInstance::CWireTapInstance() : _order(0), _timeout(0), _isRunning(false), _pattern(NULL), _isInitialized(false), CAF_CM_INIT_LOG("CWireTapInstance") { } CWireTapInstance::~CWireTapInstance() { if (_pattern) { g_regex_unref(_pattern); } } void CWireTapInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); const std::string orderAttr = _configSection->findOptionalAttribute("order"); if (!orderAttr.empty()) { _order = CStringConv::fromString(orderAttr); } const std::string timeoutAttr = _configSection->findOptionalAttribute("timeout"); if (!timeoutAttr.empty()) { _timeout = CStringConv::fromString(timeoutAttr); } const std::string pattern = _configSection->findRequiredAttribute("pattern"); GError *error = NULL; _pattern = g_regex_new( pattern.c_str(), (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_UNGREEDY | G_REGEX_RAW), (GRegexMatchFlags)(G_REGEX_MATCH_ANCHORED | G_REGEX_MATCH_NOTEMPTY), &error); if (error) { throw error; } _channelId = _configSection->findRequiredAttribute("channel"); _isInitialized = true; } CAF_CM_EXIT; } std::string CWireTapInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CWireTapInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); _channel = channelResolver->resolveChannelName(_channelId); } CAF_CM_EXIT; } void CWireTapInstance::start(const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _isRunning = true; } CAF_CM_EXIT; } void CWireTapInstance::stop(const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _isRunning = false; } CAF_CM_EXIT; } bool CWireTapInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); bool rc = false; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _isRunning; } CAF_CM_EXIT; return rc; } SmartPtrIIntMessage& CWireTapInstance::preSend( SmartPtrIIntMessage& message, SmartPtrIMessageChannel& channel) { CAF_CM_FUNCNAME_VALIDATE("preSend"); CAF_CM_ENTER { CAF_CM_VALIDATE_INTERFACE(message); CAF_CM_VALIDATE_INTERFACE(channel); // If the channel passed in is the // output channel for this wire-tap then // log a message and no-op this. if (_channel == channel) { CAF_CM_LOG_DEBUG_VA2( "WireTap (%s) will not intercept its own " "channel (%s),", _id.c_str(), _channelId.c_str()); } else if (_isRunning) { if (_timeout) { _channel->send(message); } else { _channel->send(message, _timeout); } } } CAF_CM_EXIT; return message; } uint32 CWireTapInstance::getOrder() const { CAF_CM_FUNCNAME_VALIDATE("getOrder"); uint32 rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _order; } CAF_CM_EXIT; return rc; } bool CWireTapInstance::isChannelIdMatched(const std::string& channelId) const { CAF_CM_FUNCNAME_VALIDATE("isChannelIdMatched"); bool rc = false; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(channelId); rc = g_regex_match( _pattern, channelId.c_str(), (GRegexMatchFlags)0, NULL); } CAF_CM_EXIT; return rc; } CWireTapInstance.h000066400000000000000000000042701321503522500360340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Created on: Jan 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CWIRETAPINSTANCE_H_ #define CWIRETAPINSTANCE_H_ #include "Integration/IChannelInterceptorInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageChannel.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" #include "Integration/Core/CChannelInterceptorAdapter.h" namespace Caf { class CWireTapInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle, public IChannelInterceptorInstance, public CChannelInterceptorAdapter { public: CWireTapInstance(); virtual ~CWireTapInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(IChannelInterceptor) CAF_QI_ENTRY(IChannelInterceptorInstance) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // IChannelIntercepter SmartPtrIIntMessage& preSend( SmartPtrIIntMessage& message, SmartPtrIMessageChannel& channel); public: // IChannelInterceptorInstance uint32 getOrder() const; bool isChannelIdMatched(const std::string& channelId) const; private: SmartPtrIDocument _configSection; std::string _id; uint32 _order; int32 _timeout; bool _isRunning; std::string _channelId; SmartPtrIMessageChannel _channel; GRegex* _pattern; bool _isInitialized; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CWireTapInstance); }; CAF_DECLARE_SMART_QI_POINTER(CWireTapInstance); } #endif /* CWIRETAPINSTANCE_H_ */ CXPathHeaderEnricherItem.cpp000066400000000000000000000033351321503522500377640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "CXPathHeaderEnricherItem.h" using namespace Caf; CXPathHeaderEnricherItem::CXPathHeaderEnricherItem() : _isInitialized(false), _overwrite(true), CAF_CM_INIT("CXPathHeaderEnricherItem") { } CXPathHeaderEnricherItem::~CXPathHeaderEnricherItem() { } void CXPathHeaderEnricherItem::initialize( const SmartPtrIDocument& configSection, const bool& defaultOverwrite) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _name = configSection->findRequiredAttribute("name"); _evaluationType = configSection->findOptionalAttribute("evaluation-type"); _xpathExpression = configSection->findOptionalAttribute("xpath-expression"); _xpathExpressionRef = configSection->findOptionalAttribute("xpath-expression-ref"); _overwrite = defaultOverwrite; const std::string overwriteStr = configSection->findOptionalAttribute("overwrite"); if (! overwriteStr.empty()) { _overwrite = (overwriteStr.compare("true") == 0); } if (_evaluationType.empty()) { _evaluationType = "STRING_RESULT"; } _isInitialized = true; } std::string CXPathHeaderEnricherItem::getName() const { return _name; } std::string CXPathHeaderEnricherItem::getEvaluationType() const { return _evaluationType; } bool CXPathHeaderEnricherItem::getOverwrite() const { return _overwrite; } std::string CXPathHeaderEnricherItem::getXpathExpression() const { return _xpathExpression; } std::string CXPathHeaderEnricherItem::getXpathExpressionRef() const { return _xpathExpressionRef; } CXPathHeaderEnricherTransformerInstance.cpp000066400000000000000000000154071321503522500430600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CXPathHeaderEnricherItem.h" #include "Common/IAppContext.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "CXPathHeaderEnricherTransformerInstance.h" using namespace Caf; CXPathHeaderEnricherTransformerInstance::CXPathHeaderEnricherTransformerInstance() : _isInitialized(false), _defaultOverwrite(true), _shouldSkipNulls(true), CAF_CM_INIT_LOG("CXPathHeaderEnricherTransformerInstance") { } CXPathHeaderEnricherTransformerInstance::~CXPathHeaderEnricherTransformerInstance() { } void CXPathHeaderEnricherTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _configSection = configSection; if (_configSection->getAllChildren()->empty()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_INVALID_DATA, "Configuration section is empty - %s", _id.c_str()); } _isInitialized = true; } std::string CXPathHeaderEnricherTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CXPathHeaderEnricherTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); SmartPtrIAppConfig appConfig = getAppConfig(); const std::string defaultOverwriteStr = _configSection->findOptionalAttribute("default-overwrite"); const std::string shouldSkipNullsStr = _configSection->findOptionalAttribute("should-skip-nulls"); _defaultOverwrite = (defaultOverwriteStr.empty() || defaultOverwriteStr.compare("true") == 0) ? true : false; _shouldSkipNulls = (shouldSkipNullsStr.empty() || shouldSkipNullsStr.compare("true") == 0) ? true : false; const IDocument::SmartPtrCChildCollection configChildren = _configSection->getAllChildren(); for (TSmartConstMapIterator configIter(*configChildren); configIter; configIter++) { const SmartPtrIDocument config = *configIter; if (config->getName().compare("header") == 0) { SmartPtrCXPathHeaderEnricherItem item; item.CreateInstance(); item->initialize(config, _defaultOverwrite); _headerItems.insert(std::make_pair(item->getName(), item)); } else { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_INVALID_DATA, "Configuration section contains unrecognized entry - %s", _id.c_str()); } } } SmartPtrIIntMessage CXPathHeaderEnricherTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initialize(message->getPayload(), message->getHeaders(), IIntMessage::SmartPtrCHeaders()); SmartPtrIIntMessage newMessage = messageImpl; IIntMessage::SmartPtrCHeaders newHeaders = newMessage->getHeaders(); const std::string payloadXmlStr = newMessage->getPayloadStr(); for (TConstMapIterator headerItemIter(_headerItems); headerItemIter; headerItemIter++) { const std::string name = headerItemIter.getKey(); const SmartPtrCXPathHeaderEnricherItem value = *headerItemIter; if (isInsertable(name, value, newHeaders)) { const std::string xpathRc = evaluateXPathExpression(name, value, payloadXmlStr); if (xpathRc.empty()) { if (! _shouldSkipNulls) { CAF_CM_LOG_INFO_VA1("Removing header from unresolvable expression - %s", name.c_str()); newHeaders->erase(name); } } else { CAF_CM_LOG_DEBUG_VA2("Inserting/updating a header value - %s = %s", name.c_str(), xpathRc.c_str()); (*newHeaders)[name] = std::make_pair(CVariant::createString(xpathRc), SmartPtrICafObject()); } } } return newMessage; } bool CXPathHeaderEnricherTransformerInstance::isInsertable( const std::string& name, const SmartPtrCXPathHeaderEnricherItem& value, const IIntMessage::SmartPtrCHeaders& headers) { CAF_CM_FUNCNAME_VALIDATE("isInsertable"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); CAF_CM_VALIDATE_SMARTPTR(value); CAF_CM_VALIDATE_SMARTPTR(headers); bool rc = false; if (value->getEvaluationType().compare("STRING_RESULT") == 0) { if (headers->find(name) == headers->end()) { rc = true; } else { if (value->getOverwrite()) { CAF_CM_LOG_DEBUG_VA1("Existing header will be overwritten - name: %s", name.c_str()); rc = true; } else { CAF_CM_LOG_WARN_VA1("Existing header will not be overwritten - name: %s", name.c_str()); } } } else { CAF_CM_LOG_ERROR_VA2("Evaluation type not supported - name: %s, type: %s", name.c_str(), value->getEvaluationType().c_str()); } return rc; } std::string CXPathHeaderEnricherTransformerInstance::evaluateXPathExpression( const std::string& name, const SmartPtrCXPathHeaderEnricherItem& value, const std::string& payloadXmlStr) { CAF_CM_FUNCNAME_VALIDATE("isInsertable"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(name); CAF_CM_VALIDATE_SMARTPTR(value); CAF_CM_VALIDATE_STRING(payloadXmlStr); std::string rc; const std::string expr = value->getXpathExpression(); if (expr.empty()) { CAF_CM_LOG_ERROR_VA1( "xpath-expression is required until xpath-expression-ref is supported - name: %s", name.c_str()); } else { if (! value->getXpathExpressionRef().empty()) { CAF_CM_LOG_WARN_VA1( "Both xpath-expression and xpath-expression-ref cannot be specified... Using xpath-expression - name: %s", name.c_str()); } if (expr.find_first_of('@') != 0) { CAF_CM_LOG_ERROR_VA2( "Currently, only root-level attributes are supported - name: %s, xpath-expression: %s", name.c_str(), expr.c_str()); } else { const std::string attr = expr.substr(1); const SmartPtrCXmlElement rootXml = CXmlUtils::parseString(payloadXmlStr, std::string()); const std::string payloadType = rootXml->getName(); const std::string attrVal = rootXml->findOptionalAttribute(attr); if (attrVal.empty()) { CAF_CM_LOG_WARN_VA2( "Attribute not found at root level: %s", name.c_str(), expr.c_str()); } else { rc = attrVal; } } } return rc; } CXPathHeaderEnricherTransformerInstance.h000066400000000000000000000042231321503522500425170ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CXPathHeaderEnricherTransformerInstance_h_ #define CXPathHeaderEnricherTransformerInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "CXPathHeaderEnricherItem.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CXPathHeaderEnricherTransformerInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CXPathHeaderEnricherTransformerInstance(); virtual ~CXPathHeaderEnricherTransformerInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ITransformer) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: bool isInsertable( const std::string& name, const SmartPtrCXPathHeaderEnricherItem& value, const IIntMessage::SmartPtrCHeaders& headers); std::string evaluateXPathExpression( const std::string& name, const SmartPtrCXPathHeaderEnricherItem& value, const std::string& payloadXmlStr); private: bool _isInitialized; std::string _id; SmartPtrIDocument _configSection; bool _defaultOverwrite; bool _shouldSkipNulls; typedef std::map Items; Items _headerItems; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CXPathHeaderEnricherTransformerInstance); }; CAF_DECLARE_SMART_QI_POINTER(CXPathHeaderEnricherTransformerInstance); } #endif // #ifndef CXPathHeaderEnricherTransformerInstance_h_ Integration.cpp000066400000000000000000000026301321503522500355050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CIntegrationObjectFactory.h" #include "CErrorChannel.h" #include "CNullChannel.h" #include "CHeaderExpressionInvoker.h" using namespace Caf; namespace Caf { const char* _sObjIdIntegrationObjectFactory = "com.vmware.commonagent.integration.objectfactory"; const char* _sObjIdErrorChannel = "com.vmware.commonagent.integration.channels.errorchannel"; const char* _sObjIdNullChannel = "com.vmware.commonagent.integration.channels.nullchannel"; const char* _sObjIdHeaderExpressionInvoker = "com.vmware.commonagent.integration.headerexpressioninvoker"; } CEcmSubSystemModule _Module; CAF_BEGIN_OBJECT_MAP(ObjectMap) CAF_OBJECT_ENTRY(CIntegrationObjectFactory) CAF_OBJECT_ENTRY(CErrorChannel) CAF_OBJECT_ENTRY(CNullChannel) CAF_OBJECT_ENTRY(CHeaderExpressionInvoker) CAF_END_OBJECT_MAP() CAF_DECLARE_SUBSYSTEM_EXPORTS() extern "C" BOOL APIENTRY DllMain(HINSTANCE hModule, uint32 dwReason, LPVOID) { try { if (DLL_PROCESS_ATTACH == dwReason) { // initialize the sub-system module _Module.Init(ObjectMap, hModule); } else if (DLL_PROCESS_DETACH == dwReason) { // Terminate the sub-system module _Module.Term(); } } catch (std::runtime_error) { ::exit(2); } catch (...) { ::exit(2); } return TRUE; } stdafx.h000066400000000000000000000021211321503522500341530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/Framework/Subsystems/Integration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ //{{CAF_SUBSYSTEM}} #include #include "Integration/IIntegrationObject.h" #include namespace Caf { // template function to create integration objects template SmartPtrIIntegrationObject CreateIntegrationObject() { Object object; object.CreateInstance(); return object; }; // function pointer for integration object creation typedef SmartPtrIIntegrationObject(*FNOBJECT_CREATOR)(); // map of configuration section names to function pointers that create the // integration object typedef std::map ObjectCreatorMap; // map of configuration section names to a pair: // pair.first - function pointer that creates the integration object // pair.second - true if the integration object produces messages typedef std::map< std::string, std::pair > MessageHandlerObjectCreatorMap; } #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/000077500000000000000000000000001321503522500270565ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_Provider/000077500000000000000000000000001321503522500321355ustar00rootroot00000000000000include/000077500000000000000000000000001321503522500335015ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_ProviderCIniFileWithoutSection.h000066400000000000000000000042011321503522500402020ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_Provider/include/* * Author: bwilliams * Created: May 18, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CINIFILEWITHOUTSECTION_H_ #define CINIFILEWITHOUTSECTION_H_ #include "Common/CCafRegex.h" #include "Common/CIniFile.h" namespace Caf { class CIniFileWithoutSection { public: struct SIniEntry { std::string _name; std::string _valueRaw; std::string _valueExpanded; }; CAF_DECLARE_SMART_POINTER(SIniEntry); public: CIniFileWithoutSection(); virtual ~CIniFileWithoutSection(); public: void initialize(const std::string& configFilePath); std::deque getEntryCollection(); SmartPtrSIniEntry findOptionalEntry( const std::string& keyName); SmartPtrSIniEntry findRequiredEntry( const std::string& keyName); std::string findOptionalString( const std::string& keyName); std::string findRequiredString( const std::string& keyName); std::string findOptionalRawString( const std::string& keyName); std::string findRequiredRawString( const std::string& keyName); void log(); void setValue( const std::string valueName, const std::string valueValue); void deleteValue( const std::string valueName); private: struct SReplacement { SmartPtrCCafRegex _regex; std::string _value; }; CAF_DECLARE_SMART_POINTER(SReplacement); private: std::deque parse( const std::string& configFilePath) const; SmartPtrSReplacement createReplacement( const std::string& keyName, const std::string& value) const; SmartPtrSIniEntry createIniEntry( const std::string& keyName, const std::string& valueRaw, const std::string& valueExpanded) const; std::deque loadTextFileIntoCollection( const std::string& filePath) const; void saveTextFile( const std::deque fileContents, const std::string filePath) const; private: bool _isInitialized; std::string _configFilePath; std::deque _entryCollection; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CIniFileWithoutSection); }; CAF_DECLARE_SMART_POINTER(CIniFileWithoutSection); } #endif /* CINIFILEWITHOUTSECTION_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_Provider/src/000077500000000000000000000000001321503522500327245ustar00rootroot00000000000000CConfigProvider.cpp000066400000000000000000000446571321503522500364140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CIniFileWithoutSection.h" #include "Common/CIniFile.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Integration/IDocument.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Exception/CCafException.h" #include "CConfigProvider.h" #include "IProviderRequest.h" #include "IProviderResponse.h" using namespace Caf; CConfigProvider::CConfigProvider() : _fileAliasPrefix("diagFileAlias_"), _keyPathDelimStr("/"), _keyPathDelimChar('/'), CAF_CM_INIT_LOG("CConfigProvider") { } CConfigProvider::~CConfigProvider() { } const SmartPtrCSchemaDoc CConfigProvider::getSchema() const { std::deque dc1Props; dc1Props.push_back(CProviderDocHelper::createClassProperty("name", PROPERTY_STRING, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("value", PROPERTY_STRING, true)); std::deque dc2Props; dc2Props.push_back(CProviderDocHelper::createClassProperty("filePath", PROPERTY_STRING, true)); dc2Props.push_back(CProviderDocHelper::createClassProperty("encoding", PROPERTY_STRING, true)); std::deque instanceProperties; instanceProperties.push_back(CProviderDocHelper::createClassInstanceProperty( "configEntry", CProviderDocHelper::createClassIdentifier("caf", "ConfigEntry", "1.0.0"), true, false, true)); std::deque dataClasses; dataClasses.push_back(CProviderDocHelper::createDataClass("caf", "ConfigEntry", "1.0.0", dc1Props)); dataClasses.push_back(CProviderDocHelper::createDataClass("caf", "ConfigData", "1.0.0", dc2Props, instanceProperties)); std::deque collectMethodParams; collectMethodParams.push_back(CProviderDocHelper::createMethodParameter("filePath", PARAMETER_STRING, false)); collectMethodParams.push_back(CProviderDocHelper::createMethodParameter("encoding", PARAMETER_STRING, false)); std::deque m1Params; m1Params.push_back(CProviderDocHelper::createMethodParameter("filePath", PARAMETER_STRING, false)); m1Params.push_back(CProviderDocHelper::createMethodParameter("encoding", PARAMETER_STRING, false)); m1Params.push_back(CProviderDocHelper::createMethodParameter("valueName", PARAMETER_STRING, false)); m1Params.push_back(CProviderDocHelper::createMethodParameter("valueData", PARAMETER_STRING, false)); std::deque m2Params; m2Params.push_back(CProviderDocHelper::createMethodParameter("filePath", PARAMETER_STRING, false)); m2Params.push_back(CProviderDocHelper::createMethodParameter("encoding", PARAMETER_STRING, false)); m2Params.push_back(CProviderDocHelper::createMethodParameter("valueName", PARAMETER_STRING, false)); std::deque methods; methods.push_back(CProviderDocHelper::createMethod("setValue", m1Params)); methods.push_back(CProviderDocHelper::createMethod("deleteValue", m2Params)); std::deque actionClasses; actionClasses.push_back( CProviderDocHelper::createActionClass( "caf", "ConfigActions", "1.0.0", CProviderDocHelper::createCollectMethod("collectInstances", collectMethodParams), methods)); return CProviderDocHelper::createSchema(dataClasses, actionClasses); } void CConfigProvider::collect(const IProviderRequest& request, IProviderResponse& response) const { CAF_CM_FUNCNAME("collect"); CAF_CM_ENTER { SmartPtrCProviderCollectInstancesDoc doc = request.getCollectInstances(); CAF_CM_VALIDATE_SMARTPTR(doc); const SmartPtrCParameterCollectionDoc parameterCollection = doc->getParameterCollection(); const std::string filePath = ParameterUtils::findRequiredParameterAsString( "filePath", parameterCollection); const std::string encoding = ParameterUtils::findRequiredParameterAsString( "encoding", parameterCollection); if (FileSystemUtils::doesFileExist(filePath)) { CAF_CM_LOG_DEBUG_VA2("Parsing file - path: %s, encoding: %s", filePath.c_str(), encoding.c_str()); std::deque > propertyCollection; if (encoding.compare("iniFileWithoutSection") == 0) { propertyCollection = createIniFileWithoutSectionPropertyCollection(filePath); } else if (encoding.compare("iniFile") == 0) { propertyCollection = createIniFilePropertyCollection(filePath); } else if (encoding.compare("xmlFile") == 0) { propertyCollection = createXmlFilePropertyCollection(filePath); } else { CAF_CM_EXCEPTIONEX_VA2(InvalidArgumentException, E_INVALIDARG, "URI encoding is not recognized - path: %s, encoding: %s", filePath.c_str(), encoding.c_str()); } const SmartPtrCDataClassInstanceDoc dataClassInstance = createDataClassInstance(filePath, encoding, propertyCollection); response.addInstance(dataClassInstance); } else { CAF_CM_LOG_WARN_VA2( "File not found - path: %s, encoding: %s", filePath.c_str(), encoding.c_str()); } } CAF_CM_EXIT; } void CConfigProvider::invoke(const IProviderRequest& request, IProviderResponse& response) const { CAF_CM_FUNCNAME("invoke"); CAF_CM_ENTER { SmartPtrCProviderInvokeOperationDoc doc = request.getInvokeOperations(); CAF_CM_VALIDATE_SMARTPTR(doc); const SmartPtrCOperationDoc operation = doc->getOperation(); const std::string operationName = operation->getName(); const SmartPtrCParameterCollectionDoc parameterCollection = operation->getParameterCollection(); const std::string filePath = ParameterUtils::findRequiredParameterAsString( "filePath", parameterCollection); const std::string encoding = ParameterUtils::findRequiredParameterAsString( "encoding", parameterCollection); const std::string valueName = ParameterUtils::findRequiredParameterAsString( "valueName", parameterCollection); if (operationName.compare("setValue") == 0) { const std::string valueData = ParameterUtils::findRequiredParameterAsString( "valueData", parameterCollection); setValue(filePath, encoding, valueName, valueData); } else if (operationName.compare("deleteValue") == 0) { deleteValue(filePath, encoding, valueName); } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Invalid operation name (must be \'setValue\' or \'deleteValue\') - %s", operationName.c_str()) } } CAF_CM_EXIT; } SmartPtrCDataClassInstanceDoc CConfigProvider::createDataClassInstance( const std::string& filePath, const std::string& encoding, const std::deque >& propertyCollection) const { CAF_CM_FUNCNAME_VALIDATE("createDataClassInstance"); CAF_CM_VALIDATE_STRING(filePath); CAF_CM_VALIDATE_STRING(encoding); CAF_CM_VALIDATE_STL(propertyCollection); std::deque subInstances; for(TConstIterator > > propertyIter(propertyCollection); propertyIter; propertyIter++) { std::deque siProperties; siProperties.push_back(CProviderDocHelper::createDataClassProperty("name", propertyIter->first)); siProperties.push_back(CProviderDocHelper::createDataClassProperty("value", propertyIter->second)); subInstances.push_back(CProviderDocHelper::createDataClassSubInstance( "configEntry", siProperties)); } std::deque dataClassProperties; dataClassProperties.push_back(CProviderDocHelper::createDataClassProperty("filePath", filePath)); dataClassProperties.push_back(CProviderDocHelper::createDataClassProperty("encoding", encoding)); return CProviderDocHelper::createDataClassInstance( "caf", "ConfigData", "1.0.0", dataClassProperties, subInstances); } void CConfigProvider::setValue( const std::string& filePath, const std::string& encoding, const std::string& valueName, const std::string& valueData) const { CAF_CM_FUNCNAME("setValue"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); CAF_CM_VALIDATE_STRING(encoding); CAF_CM_VALIDATE_STRING(valueName); CAF_CM_VALIDATE_STRING(valueData); if (encoding.compare("iniFileWithoutSection") == 0) { SmartPtrCIniFileWithoutSection iniFileWithoutSection; iniFileWithoutSection.CreateInstance(); iniFileWithoutSection->initialize(filePath); iniFileWithoutSection->setValue(valueName, valueData); } else if (encoding.compare("iniFile") == 0) { std::string sectionName; std::string keyName; parseIniFileValuePath(valueName, sectionName, keyName); SmartPtrCIniFile iniFile; iniFile.CreateInstance(); iniFile->initialize(filePath); iniFile->setValue(sectionName, keyName, valueData); } else if (encoding.compare("xmlFile") == 0) { std::string keyName; std::deque keyPathCollection; parseKeyPath(valueName, keyPathCollection, keyName); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, std::string()); const SmartPtrCXmlElement parentXml = findXmlElement(keyPathCollection, rootXml); const SmartPtrCXmlElement foundElement = parentXml->findOptionalChild(keyName); if (! foundElement.IsNull()) { foundElement->setValue(valueData); } else { const std::string foundAttribute = parentXml->findOptionalAttribute(keyName); if (! foundAttribute.empty()) { parentXml->setAttribute(keyName, valueData); } else { const SmartPtrCXmlElement createdElement = parentXml->createAndAddElement(keyName); createdElement->setValue(valueData); } } rootXml->saveToFile(filePath); } else { CAF_CM_EXCEPTIONEX_VA2(InvalidArgumentException, E_INVALIDARG, "URI encoding is not recognized - filePath: %s, encoding: %s", filePath.c_str(), encoding.c_str()); } } CAF_CM_EXIT; } void CConfigProvider::deleteValue( const std::string& filePath, const std::string& encoding, const std::string& valueName) const { CAF_CM_FUNCNAME("deleteValue"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); CAF_CM_VALIDATE_STRING(encoding); CAF_CM_VALIDATE_STRING(valueName); if (encoding.compare("iniFileWithoutSection") == 0) { SmartPtrCIniFileWithoutSection iniFileWithoutSection; iniFileWithoutSection.CreateInstance(); iniFileWithoutSection->initialize(filePath); iniFileWithoutSection->deleteValue(valueName); } else if (encoding.compare("iniFile") == 0) { std::string sectionName; std::string keyName; parseIniFileValuePath(valueName, sectionName, keyName); SmartPtrCIniFile iniFile; iniFile.CreateInstance(); iniFile->initialize(filePath); iniFile->deleteValue(sectionName, keyName); } else if (encoding.compare("xmlFile") == 0) { std::string keyName; std::deque keyPathCollection; parseKeyPath(valueName, keyPathCollection, keyName); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, std::string()); const SmartPtrCXmlElement parentXml = findXmlElement(keyPathCollection, rootXml); const SmartPtrCXmlElement foundElement = parentXml->findOptionalChild(keyName); if (! foundElement.IsNull()) { parentXml->removeChild(keyName); } else { parentXml->removeAttribute(keyName); } rootXml->saveToFile(filePath); } else { CAF_CM_EXCEPTIONEX_VA2(InvalidArgumentException, E_INVALIDARG, "URI encoding is not recognized - filePath: %s, encoding: %s", filePath.c_str(), encoding.c_str()); } } CAF_CM_EXIT; } std::deque > CConfigProvider::createIniFileWithoutSectionPropertyCollection( const std::string& filePath) const { CAF_CM_FUNCNAME_VALIDATE("createIniFileWithoutSectionPropertyCollection"); std::deque > propertyCollection; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); SmartPtrCIniFileWithoutSection iniFileWithoutSection; iniFileWithoutSection.CreateInstance(); iniFileWithoutSection->initialize(filePath); const std::deque entryCollection = iniFileWithoutSection->getEntryCollection(); for(TConstIterator > iniEntryIter(entryCollection); iniEntryIter; iniEntryIter++) { const CIniFileWithoutSection::SmartPtrSIniEntry iniEntry = *iniEntryIter; propertyCollection.push_back(std::make_pair(iniEntry->_name, iniEntry->_valueExpanded)); } } CAF_CM_EXIT; return propertyCollection; } std::deque > CConfigProvider::createIniFilePropertyCollection( const std::string& filePath) const { CAF_CM_FUNCNAME_VALIDATE("createIniFilePropertyCollection"); std::deque > propertyCollection; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); SmartPtrCIniFile iniFile; iniFile.CreateInstance(); iniFile->initialize(filePath); const std::deque sectionCollection = iniFile->getSectionCollection(); for (TConstIterator > iniSectionIter(sectionCollection); iniSectionIter; iniSectionIter++) { const CIniFile::SmartPtrSIniSection iniSection = *iniSectionIter; const std::string sectionName = iniSection->_sectionName; for (TConstIterator > iniEntryIter(iniSection->_entryCollection); iniEntryIter; iniEntryIter++) { const CIniFile::SmartPtrSIniEntry iniEntry = *iniEntryIter; const std::string keyName = iniEntry->_name; const std::string value = iniEntry->_valueRaw; const std::string keyPath = sectionName + _keyPathDelimStr + keyName; propertyCollection.push_back(std::make_pair(keyPath, value)); } } } CAF_CM_EXIT; return propertyCollection; } std::deque > CConfigProvider::createXmlFilePropertyCollection( const std::string& filePath) const { CAF_CM_FUNCNAME_VALIDATE("createXmlFilePropertyCollection"); std::deque > propertyCollection; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(filePath); const SmartPtrCXmlElement rootXml = CXmlUtils::parseFile(filePath, std::string()); const std::string keyPath = rootXml->getName(); createXmlPropertyCollection(keyPath, rootXml, propertyCollection); } CAF_CM_EXIT; return propertyCollection; } void CConfigProvider::createXmlPropertyCollection( const std::string& keyPath, const SmartPtrCXmlElement& thisXml, std::deque >& propertyCollection) const { CAF_CM_FUNCNAME_VALIDATE("createXmlPropertyCollection"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(keyPath); CAF_CM_VALIDATE_SMARTPTR(thisXml); // propertyCollection is optional const CXmlElement::SmartPtrCAttributeCollection attributeCollection = thisXml->getAllAttributes(); if (! attributeCollection.IsNull() && ! attributeCollection->empty()) { for (TConstIterator attributeXmlIter(*attributeCollection); attributeXmlIter; attributeXmlIter++) { const std::string attributeName = attributeXmlIter->first; const std::string attributeValue = attributeXmlIter->second; const std::string newKeyPath = keyPath + _keyPathDelimStr + attributeName; propertyCollection.push_back(std::make_pair(newKeyPath, attributeValue)); } } const CXmlElement::SmartPtrCElementCollection childrenXml = thisXml->getAllChildren(); if (! childrenXml.IsNull() && ! childrenXml->empty()) { for (TConstIterator childrenXmlIter(*childrenXml); childrenXmlIter; childrenXmlIter++) { const SmartPtrCXmlElement childXml = childrenXmlIter->second; const std::string newKeyPath = keyPath + _keyPathDelimStr + childXml->getName(); const std::string value = childXml->getValue(); if (! value.empty()) { propertyCollection.push_back(std::make_pair(newKeyPath, value)); } createXmlPropertyCollection(newKeyPath, childXml, propertyCollection); } } } CAF_CM_EXIT; } void CConfigProvider::parseIniFileValuePath( const std::string& valuePath, std::string& valueName, std::string& valueValue) const { CAF_CM_FUNCNAME("parseIniFileValuePath"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(valuePath); const std::string::size_type delimPos = valuePath.find_first_of("/"); if (delimPos == std::string::npos) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Delim not found in valuePath - valuePath: %s", valuePath.c_str()); } valueName = valuePath.substr(0, delimPos); valueValue = valuePath.substr(delimPos + 1); CAF_CM_LOG_DEBUG_VA3("Parsed valuePath - valuePath: %s, valueName: %s, valueValue: %s", valuePath.c_str(), valueName.c_str(), valueValue.c_str()); } CAF_CM_EXIT; } void CConfigProvider::parseKeyPath( const std::string& keyPath, std::deque& keyPathCollection, std::string& keyName) const { CAF_CM_FUNCNAME_VALIDATE("parseKeyPath"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(keyPath); std::string token; std::stringstream stream(keyPath); while(std::getline(stream, token, _keyPathDelimChar)) { keyPathCollection.push_back(token); } keyName = keyPathCollection.back(); keyPathCollection.pop_back(); } CAF_CM_EXIT; } SmartPtrCXmlElement CConfigProvider::findXmlElement( const std::deque& keyPathCollection, const SmartPtrCXmlElement& rootXml) const { CAF_CM_FUNCNAME("findXmlElement"); SmartPtrCXmlElement xmlRc; CAF_CM_ENTER { CAF_CM_VALIDATE_STL(keyPathCollection); CAF_CM_VALIDATE_SMARTPTR(rootXml); xmlRc = rootXml; for (std::deque::const_iterator keyPathIter = keyPathCollection.begin(); keyPathIter != keyPathCollection.end(); keyPathIter++) { const std::string keyPath = *keyPathIter; if (keyPathIter == keyPathCollection.begin()) { if (xmlRc->getName().compare(keyPath) != 0) { CAF_CM_EXCEPTIONEX_VA2(NoSuchElementException, ERROR_NOT_FOUND, "Root element does not match - %s != %s", keyPath.c_str(), xmlRc->getName().c_str()); } } else { xmlRc = xmlRc->findRequiredChild(keyPath); } } } CAF_CM_EXIT; return xmlRc; } CConfigProvider.h000066400000000000000000000051411321503522500360420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CConfigProvider_h_ #define CConfigProvider_h_ #include "IInvokedProvider.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Xml/XmlUtils/CXmlElement.h" namespace Caf { /// Sends responses/errors back to the client. class CConfigProvider : public IInvokedProvider { public: CConfigProvider(); virtual ~CConfigProvider(); public: // IInvokedProvider const std::string getProviderNamespace() const { return "caf"; } const std::string getProviderName() const { return "ConfigProvider"; } const std::string getProviderVersion() const { return "1.0.0"; } const SmartPtrCSchemaDoc getSchema() const; void collect(const IProviderRequest& request, IProviderResponse& response) const; void invoke(const IProviderRequest& request, IProviderResponse& response) const; private: std::string _fileAliasPrefix; std::string _keyPathDelimStr; char _keyPathDelimChar; private: SmartPtrCDataClassInstanceDoc createDataClassInstance( const std::string& filePath, const std::string& encoding, const std::deque >& propertyCollection) const; void setValue( const std::string& filePath, const std::string& encoding, const std::string& valueName, const std::string& valueValue) const; void deleteValue( const std::string& filePath, const std::string& encoding, const std::string& valueName) const; std::deque > createIniFileWithoutSectionPropertyCollection( const std::string& filePath) const; std::deque > createIniFilePropertyCollection( const std::string& filePath) const; std::deque > createXmlFilePropertyCollection( const std::string& filePath) const; void createXmlPropertyCollection( const std::string& keyPath, const SmartPtrCXmlElement& thisXml, std::deque >& propertyCollection) const; void parseIniFileValuePath( const std::string& valuePath, std::string& valueName, std::string& valueValue) const; void parseKeyPath( const std::string& keyPath, std::deque& keyPathCollection, std::string& keyName) const; SmartPtrCXmlElement findXmlElement( const std::deque& keyPathCollection, const SmartPtrCXmlElement& rootXml) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CConfigProvider); }; } #endif // #ifndef CConfigProvider_h_ CIniFileWithoutSection.cpp000066400000000000000000000305341321503522500377110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_Provider/src/* * Author: bwilliams * Created: May 18, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/CCafRegex.h" #include "Common/CIniFile.h" #include "CIniFileWithoutSection.h" #include "Exception/CCafException.h" using namespace Caf; CIniFileWithoutSection::CIniFileWithoutSection() : _isInitialized(false), CAF_CM_INIT_LOG("CIniFileWithoutSection") { } CIniFileWithoutSection::~CIniFileWithoutSection() { } void CIniFileWithoutSection::initialize( const std::string& configFilePath) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(configFilePath); _configFilePath = configFilePath; _isInitialized = true; } CAF_CM_EXIT; } std::deque CIniFileWithoutSection::getEntryCollection() { CAF_CM_FUNCNAME_VALIDATE("getEntryCollection"); std::deque entryCollection; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (_entryCollection.empty()) { _entryCollection = parse(_configFilePath); } entryCollection = _entryCollection; } CAF_CM_EXIT; return entryCollection; } CIniFileWithoutSection::SmartPtrSIniEntry CIniFileWithoutSection::findOptionalEntry( const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findOptionalEntry"); CIniFileWithoutSection::SmartPtrSIniEntry iniEntry; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(keyName); if (_entryCollection.empty()) { _entryCollection = parse(_configFilePath); } for (TConstIterator > iniEntryIter(_entryCollection); iniEntryIter; iniEntryIter++) { const SmartPtrSIniEntry iniEntryTmp = *iniEntryIter; const std::string keyNameTmp = iniEntryTmp->_name; if (keyNameTmp.compare(keyName) == 0) { iniEntry = iniEntryTmp; break; } } } CAF_CM_EXIT; return iniEntry; } CIniFileWithoutSection::SmartPtrSIniEntry CIniFileWithoutSection::findRequiredEntry( const std::string& keyName) { CAF_CM_FUNCNAME("findRequiredEntry"); SmartPtrSIniEntry iniEntry; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(keyName); iniEntry = findOptionalEntry(keyName); if (iniEntry.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(NoSuchElementException, ERROR_NOT_FOUND, "Value not found - keyName: %s", keyName.c_str()); } } CAF_CM_EXIT; return iniEntry; } std::string CIniFileWithoutSection::findOptionalString( const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findOptionalString"); std::string value; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(keyName); const SmartPtrSIniEntry iniEntry = findOptionalEntry(keyName); if (! iniEntry.IsNull()) { value = iniEntry->_valueExpanded; } } CAF_CM_EXIT; return value; } std::string CIniFileWithoutSection::findRequiredString( const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findRequiredString"); std::string value; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(keyName); const SmartPtrSIniEntry iniEntry = findRequiredEntry(keyName); value = iniEntry->_valueExpanded; } CAF_CM_EXIT; return value; } std::string CIniFileWithoutSection::findOptionalRawString( const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findOptionalRawString"); std::string value; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(keyName); const SmartPtrSIniEntry iniEntry = findOptionalEntry(keyName); if (! iniEntry.IsNull()) { value = iniEntry->_valueRaw; } } CAF_CM_EXIT; return value; } std::string CIniFileWithoutSection::findRequiredRawString( const std::string& keyName) { CAF_CM_FUNCNAME_VALIDATE("findRequiredRawString"); std::string value; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(keyName); const SmartPtrSIniEntry iniEntry = findRequiredEntry(keyName); value = iniEntry->_valueRaw; } CAF_CM_EXIT; return value; } void CIniFileWithoutSection::log() { CAF_CM_FUNCNAME_VALIDATE("log"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (_entryCollection.empty()) { _entryCollection = parse(_configFilePath); } for (TConstIterator > iniEntryIter(_entryCollection); iniEntryIter; iniEntryIter++) { const SmartPtrSIniEntry iniEntry = *iniEntryIter; CAF_CM_LOG_DEBUG_VA3("Entry - %s=%s (%s)", iniEntry->_name.c_str(), iniEntry->_valueRaw.c_str(), iniEntry->_valueExpanded.c_str()); } } CAF_CM_EXIT; } void CIniFileWithoutSection::setValue( const std::string valueName, const std::string valueValue) { CAF_CM_FUNCNAME_VALIDATE("setValue"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(valueName); CAF_CM_VALIDATE_STRING(valueValue); const std::string srchValueName = valueName + "="; const std::string newFileLine = valueName + "=" + valueValue + "\n"; bool isValueNameFnd = false; std::deque newFileContents; const std::deque fileContents = loadTextFileIntoCollection(_configFilePath); for(TConstIterator > fileLineIter(fileContents); fileLineIter; fileLineIter++) { const std::string fileLine = *fileLineIter; if (fileLine.find(srchValueName) == 0) { CAF_CM_LOG_DEBUG_VA2("Matched line... changing - valueName: %s, valueValue: %s", valueName.c_str(), valueValue.c_str()); isValueNameFnd = true; newFileContents.push_back(newFileLine); } else { newFileContents.push_back(fileLine); } } if (! isValueNameFnd) { CAF_CM_LOG_WARN_VA1("Value name not found, adding... - %s", newFileLine.c_str()); newFileContents.push_back(newFileLine); } _entryCollection.clear(); saveTextFile(newFileContents, _configFilePath); } CAF_CM_EXIT; } void CIniFileWithoutSection::deleteValue( const std::string valueName) { CAF_CM_FUNCNAME_VALIDATE("deleteValue"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(valueName); const std::string srchValueName = valueName + "="; std::deque newFileContents; const std::deque FileContents = loadTextFileIntoCollection(_configFilePath); for(TConstIterator > fileLineIter(FileContents); fileLineIter; fileLineIter++) { const std::string fileLine = *fileLineIter; if (fileLine.find(srchValueName) == 0) { CAF_CM_LOG_DEBUG_VA2("Matched line... deleting - srchValueName: %s, line: %s", srchValueName.c_str(), fileLine.c_str()); } else { newFileContents.push_back(fileLine); } } _entryCollection.clear(); saveTextFile(newFileContents, _configFilePath); } CAF_CM_EXIT; } std::deque CIniFileWithoutSection::parse( const std::string& configFilePath) const { CAF_CM_FUNCNAME_VALIDATE("parse"); std::deque entryCollection; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(configFilePath); std::deque replacementCollection; SmartPtrCCafRegex goodLineRegex; goodLineRegex.CreateInstance(); goodLineRegex->initialize("^[A-Za-z0-9]"); SmartPtrCCafRegex newLineRegex; newLineRegex.CreateInstance(); newLineRegex->initialize("\n"); const std::deque fileContents = loadTextFileIntoCollection(configFilePath); for(TConstIterator > fileLineIter(fileContents); fileLineIter; fileLineIter++) { const std::string fileLine = *fileLineIter; const std::string newFileLine = newLineRegex->replaceLiteral(fileLine, " "); if (goodLineRegex->isMatched(newFileLine)) { const Cdeqstr fileLineTokens = CStringUtils::split(newFileLine, '='); if (fileLineTokens.size() == 2) { const std::string keyName = fileLineTokens[0]; const std::string valueRaw = fileLineTokens[1]; std::string valueExpanded = CStringUtils::expandEnv(valueRaw); for (TConstIterator > replacementIter(replacementCollection); replacementIter; replacementIter++ ) { const SmartPtrSReplacement replacement = *replacementIter; if (replacement->_regex->isMatched(valueExpanded)) { valueExpanded = replacement->_regex->replaceLiteral(valueExpanded, replacement->_value); break; } } const SmartPtrSReplacement replacement = createReplacement(keyName, valueExpanded); replacementCollection.push_back(replacement); const SmartPtrSIniEntry iniEntry = createIniEntry(keyName, valueRaw, valueExpanded); entryCollection.push_back(iniEntry); } else { CAF_CM_LOG_WARN_VA2("Invalid line - file: %s, line: %s", configFilePath.c_str(), newFileLine.c_str()); } } } } CAF_CM_EXIT; return entryCollection; } CIniFileWithoutSection::SmartPtrSReplacement CIniFileWithoutSection::createReplacement( const std::string& keyName, const std::string& value) const { CAF_CM_FUNCNAME_VALIDATE("createReplacement"); SmartPtrSReplacement replacement; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(keyName); std::string pattern("\\$\\{"); pattern += keyName; pattern += "\\}"; SmartPtrCCafRegex regex; regex.CreateInstance(); regex->initialize(pattern); replacement.CreateInstance(); replacement->_regex = regex; replacement->_value = value; } CAF_CM_EXIT; return replacement; } CIniFileWithoutSection::SmartPtrSIniEntry CIniFileWithoutSection::createIniEntry( const std::string& keyName, const std::string& valueRaw, const std::string& valueExpanded) const { CAF_CM_FUNCNAME_VALIDATE("createIniEntry"); SmartPtrSIniEntry iniEntry; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(keyName); CAF_CM_VALIDATE_STRING(valueRaw); CAF_CM_VALIDATE_STRING(valueExpanded); iniEntry.CreateInstance(); iniEntry->_name = keyName; iniEntry->_valueRaw = valueRaw; iniEntry->_valueExpanded = valueExpanded; } CAF_CM_EXIT; return iniEntry; } std::deque CIniFileWithoutSection::loadTextFileIntoCollection( const std::string& filePath) const { CAF_CM_FUNCNAME("loadTextFileIntoCollection"); std::deque rc; const uint32 maxLineLen = 512; FILE* fileHandle = NULL; try { CAF_CM_VALIDATE_STRING(filePath); if (! FileSystemUtils::doesFileExist(filePath)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "File not found - %s", filePath.c_str()); } #ifdef WIN32 const errno_t fopenRc = ::fopen_s(&fileHandle, filePath.c_str(), "r" ); if ((fopenRc != 0) || (fileHandle == NULL)) { CAF_CM_EXCEPTIONEX_VA1(InvalidHandleException, E_UNEXPECTED, "Failed to open file - %s", filePath.c_str()); } #else fileHandle = ::fopen(filePath.c_str(), "r" ); if (fileHandle == NULL) { CAF_CM_EXCEPTIONEX_VA1(InvalidHandleException, E_UNEXPECTED, "Failed to open file - %s", filePath.c_str()); } #endif char buffer[maxLineLen]; while(::fgets(buffer, maxLineLen, fileHandle) != NULL) { rc.push_back(buffer); } } CAF_CM_CATCH_ALL; try { if (fileHandle != NULL) { ::fclose(fileHandle); } } CAF_CM_CATCH_ALL; CAF_CM_THROWEXCEPTION; return rc; } void CIniFileWithoutSection::saveTextFile( const std::deque fileContents, const std::string filePath) const { CAF_CM_FUNCNAME("saveTextFile"); FILE* fileHandle = NULL; try { CAF_CM_VALIDATE_STL(fileContents); CAF_CM_VALIDATE_STRING(filePath); if (! FileSystemUtils::doesFileExist(filePath)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "File not found - %s", filePath.c_str()); } #ifdef WIN32 const errno_t fopenRc = ::fopen_s(&fileHandle, filePath.c_str(), "w" ); if ((fopenRc != 0) || (fileHandle == NULL)) { CAF_CM_EXCEPTIONEX_VA1(InvalidHandleException, E_UNEXPECTED, "Failed to open file - %s", filePath.c_str()); } #else fileHandle = ::fopen(filePath.c_str(), "w" ); if (fileHandle == NULL) { CAF_CM_EXCEPTIONEX_VA1(InvalidHandleException, E_UNEXPECTED, "Failed to open file - %s", filePath.c_str()); } #endif for(TConstIterator > fileLineIter(fileContents); fileLineIter; fileLineIter++) { const std::string fileLine = *fileLineIter; ::fputs(fileLine.c_str(), fileHandle); } } CAF_CM_CATCH_ALL; try { if (fileHandle != NULL) { ::fclose(fileHandle); } } CAF_CM_CATCH_ALL; CAF_CM_THROWEXCEPTION; } ConfigProvider.cpp000066400000000000000000000010321321503522500362650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" using namespace Caf; int main(int csz, char* asz[]) { CAF_CM_STATIC_FUNC_LOG("ConfigProvider", "main"); int rc = 0; try { CConfigProvider provider; rc = CProviderDriver::processProviderCommandline(provider, csz, asz); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; rc = CAF_CM_ISEXCEPTION ? 1 : rc; CAF_CM_CLEAREXCEPTION; return rc; } stdafx.h000066400000000000000000000005171321503522500343120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Config_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ //{{CAF_SUBSYSTEM}} #include #include #include #include "CConfigProvider.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/000077500000000000000000000000001321503522500323365ustar00rootroot00000000000000include/000077500000000000000000000000001321503522500337025ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_ProviderCPackageInstaller.h000066400000000000000000000072531321503522500373760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/include/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPackageInstaller_h_ #define CPackageInstaller_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CInstallPackageSpecDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" namespace Caf { /// Sends responses/errors back to the client. class CPackageInstaller { public: typedef std::deque CInstallPackageSpecCollection; CAF_DECLARE_SMART_POINTER(CInstallPackageSpecCollection); struct CInstallPackageMatch { CInstallUtils::MATCH_STATUS _matchStatus; SmartPtrCInstallPackageSpecDoc _matchedInstallPackageSpec; }; CAF_DECLARE_SMART_POINTER(CInstallPackageMatch); public: static void installPackages( const std::deque& fullPackageElemCollection, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const std::string& outputDir); static void uninstallPackages( const std::deque& minPackageElemCollection, const std::deque& installProviderSpecCollection, const std::string& outputDir); private: static void installPackage( const SmartPtrCInstallPackageSpecDoc& installPackageSpec, const SmartPtrCInstallPackageSpecDoc& uninstallPackageSpec, const std::string& outputDir); static void executePackage( const SmartPtrCInstallPackageSpecDoc& installPackageSpec, const std::string& startupArgument, const std::string& outputDir); static SmartPtrCInstallPackageSpecDoc resolveAndCopyAttachments( const SmartPtrCInstallPackageSpecDoc& installPackageSpec); static void saveInstallPackageSpec( const SmartPtrCInstallPackageSpecDoc& installPackageSpec); static std::map orderFullPackageElems( const std::deque& fullPackageElemCollection); static std::map orderMinPackageElems( const std::deque& minPackageElemCollection); static SmartPtrCAttachmentCollectionDoc resolveAttachments( const SmartPtrCAttachmentNameCollectionDoc& attachmentNameCollection, const SmartPtrCAttachmentCollectionDoc& attachmentCollection); static SmartPtrCAttachmentCollectionDoc copyAttachments( const SmartPtrCAttachmentDoc& startupAttachment, const SmartPtrCAttachmentDoc& packageAttachment, const SmartPtrCAttachmentCollectionDoc& supportingAttachmentCollection, const std::string& outputDir); static SmartPtrCInstallPackageMatch matchInstallPackageSpec( const SmartPtrCInstallPackageSpecDoc& installPackageSpec); static SmartPtrCInstallPackageSpecCollection readInstallPackageSpecs(); static uint32 countPackageReferences( const SmartPtrCInstallPackageSpecDoc& installPackageSpec, const std::deque& installProviderSpecCollection); static void logDebug( const std::string& message, const SmartPtrCInstallPackageSpecDoc& installPackageSpec1, const SmartPtrCInstallPackageSpecDoc& installPackageSpec2); static void logWarn( const std::string& message, const SmartPtrCInstallPackageSpecDoc& installPackageSpec1, const SmartPtrCInstallPackageSpecDoc& installPackageSpec2); static void cleanupPackage( const SmartPtrCInstallPackageMatch& installPackageMatch); private: CAF_CM_DECLARE_NOCREATE(CPackageInstaller); }; } #endif // #ifndef CPackageInstaller_h_ CProviderInstaller.h000066400000000000000000000052071321503522500376320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/include/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderInstaller_h_ #define CProviderInstaller_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" namespace Caf { class CProviderInstaller { public: typedef std::deque CInstallProviderSpecCollection; CAF_DECLARE_SMART_POINTER(CInstallProviderSpecCollection); struct CInstallProviderMatch { CInstallUtils::MATCH_STATUS _matchStatus; SmartPtrCInstallProviderSpecDoc _matchedInstallProviderSpec; }; CAF_DECLARE_SMART_POINTER(CInstallProviderMatch); public: static void installProvider( const SmartPtrCInstallProviderJobDoc& installProviderJob, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const std::string& outputDir); static void uninstallProvider( const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob, const std::string& outputDir); static SmartPtrCInstallProviderSpecCollection readInstallProviderSpecs(); private: static void installProviderLow( const SmartPtrCInstallProviderJobDoc& installProviderJob, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const std::string& outputDir); static void uninstallProviderLow( const SmartPtrCInstallProviderSpecDoc& installProviderSpec, const std::string& outputDir); static void storeInstallProviderSpec( const SmartPtrCInstallProviderSpecDoc& installProviderSpec); static SmartPtrCInstallProviderMatch matchInstallProviderSpec( const SmartPtrCInstallProviderSpecDoc& installProviderSpec); static SmartPtrCInstallProviderSpecDoc createInstallProviderSpec( const SmartPtrCInstallProviderJobDoc& installProviderJob); static void logDebug( const std::string& message, const SmartPtrCInstallProviderSpecDoc& installProviderSpec1, const SmartPtrCInstallProviderSpecDoc& installProviderSpec2); static void logWarn( const std::string& message, const SmartPtrCInstallProviderSpecDoc& installProviderSpec1, const SmartPtrCInstallProviderSpecDoc& installProviderSpec2); static void cleanupProvider( const SmartPtrCInstallProviderSpecDoc& installProviderSpec); static std::string calcProviderFqn( const SmartPtrCInstallProviderSpecDoc& installProviderSpec); static std::string calcProviderFqn( const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob); private: CAF_CM_DECLARE_NOCREATE(CProviderInstaller); }; } #endif // #ifndef CProviderInstaller_h_ IPackage.h000066400000000000000000000017741321503522500355300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/include/* * Author: bwilliams * Created: July 25, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _InstallProvider_IPackage_h_ #define _InstallProvider_IPackage_h_ #include "ICafObject.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IPackage : public ICafObject { CAF_DECL_UUID("e372d4bc-2384-4fcc-8042-f916f2d11bd2") virtual void fullPackageElem( const SmartPtrCAttachmentDoc packageAttachment, const std::string arguments, const SmartPtrCAttachmentCollectionDoc supportingAttachmentCollection, const std::string outputDir) = 0; virtual void unfullPackageElem( const SmartPtrCAttachmentDoc packageAttachment, const std::string arguments, const SmartPtrCAttachmentCollectionDoc supportingAttachmentCollection, const std::string outputDir) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IPackage); } #endif open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/000077500000000000000000000000001321503522500331255ustar00rootroot00000000000000CInstallProvider.cpp000066400000000000000000000260721321503522500370050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" #include "CProviderInstaller.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Exception/CCafException.h" #include "CInstallProvider.h" #include "IProviderResponse.h" #include "IProviderRequest.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Caf/CCafMessagePayload.h" using namespace Caf; CInstallProvider::CInstallProvider() : CAF_CM_INIT_LOG("CInstallProvider") { } CInstallProvider::~CInstallProvider() { } const SmartPtrCSchemaDoc CInstallProvider::getSchema() const { std::deque dc1Props; dc1Props.push_back(CProviderDocHelper::createClassProperty("index", PROPERTY_UINT32, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("packageNamespace", PROPERTY_STRING, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("packageName", PROPERTY_STRING, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("packageVersion", PROPERTY_STRING, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("startupAttachmentName", PROPERTY_STRING, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("packageAttachmentName", PROPERTY_STRING, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("arguments", PROPERTY_STRING, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("supportingAttachmentName", PROPERTY_STRING, false, false, true)); std::deque dc2Props; dc2Props.push_back(CProviderDocHelper::createClassProperty("clientId", PROPERTY_STRING, true)); dc2Props.push_back(CProviderDocHelper::createClassProperty("providerNamespace", PROPERTY_STRING, true)); dc2Props.push_back(CProviderDocHelper::createClassProperty("providerName", PROPERTY_STRING, true)); dc2Props.push_back(CProviderDocHelper::createClassProperty("providerVersion", PROPERTY_STRING, true)); dc2Props.push_back(CProviderDocHelper::createClassProperty("packageOSType", PROPERTY_STRING, true)); std::deque instanceProperties; instanceProperties.push_back(CProviderDocHelper::createClassInstanceProperty( "fullPackageElem", CProviderDocHelper::createClassIdentifier("caf", "FullPackageElem", "1.0.0"), true, false, true)); instanceProperties.push_back(CProviderDocHelper::createClassInstanceProperty( "unfullPackageElem", CProviderDocHelper::createClassIdentifier("caf", "FullPackageElem", "1.0.0"), true, false, true)); std::deque dc3Props; dc3Props.push_back(CProviderDocHelper::createClassProperty("packageOSType", PROPERTY_STRING, true)); dc3Props.push_back(CProviderDocHelper::createClassProperty("clientId", PROPERTY_STRING, true)); dc3Props.push_back(CProviderDocHelper::createClassProperty("providerNamespace", PROPERTY_STRING, true)); dc3Props.push_back(CProviderDocHelper::createClassProperty("providerName", PROPERTY_STRING, true)); dc3Props.push_back(CProviderDocHelper::createClassProperty("providerVersion", PROPERTY_STRING, true)); dc3Props.push_back(CProviderDocHelper::createClassProperty("packageOSType", PROPERTY_STRING, true)); std::deque dataClasses; dataClasses.push_back(CProviderDocHelper::createDataClass("caf", "FullPackageElem", "1.0.0", dc1Props)); dataClasses.push_back(CProviderDocHelper::createDataClass("caf", "InstallProviderJob", "1.0.0", dc2Props, instanceProperties)); dataClasses.push_back(CProviderDocHelper::createDataClass("caf", "UninstallProviderJob", "1.0.0", dc3Props)); std::deque m1InstanceParams; m1InstanceParams.push_back(CProviderDocHelper::createInstanceParameter( "installProviderJob", "caf", "InstallProviderJob", "1.0.0", false)); std::deque m2InstanceParams; m2InstanceParams.push_back(CProviderDocHelper::createInstanceParameter( "uninstallProviderJob", "caf", "UninstallProviderJob", "1.0.0", false)); std::deque emptyParams; std::deque methods; methods.push_back(CProviderDocHelper::createMethod("installProviderJob", emptyParams, m1InstanceParams)); methods.push_back(CProviderDocHelper::createMethod("uninstallProviderJob", emptyParams, m2InstanceParams)); std::deque actionClasses; actionClasses.push_back( CProviderDocHelper::createActionClass( "caf", "InstallActions", "1.0.0", CProviderDocHelper::createCollectMethod("collectInstances"), methods)); return CProviderDocHelper::createSchema(dataClasses, actionClasses); } void CInstallProvider::collect(const IProviderRequest& request, IProviderResponse& response) const { const CProviderInstaller::SmartPtrCInstallProviderSpecCollection installProviderSpecCollection = CProviderInstaller::readInstallProviderSpecs(); if (!installProviderSpecCollection.IsNull()) { for (TConstIterator > installProviderSpecIter(*installProviderSpecCollection); installProviderSpecIter; installProviderSpecIter++) { const SmartPtrCInstallProviderSpecDoc installProviderSpec = *installProviderSpecIter; const SmartPtrCDataClassInstanceDoc dataClassInstance = createDataClassInstance( installProviderSpec); response.addInstance(dataClassInstance); } } } void CInstallProvider::invoke(const IProviderRequest& request, IProviderResponse& response) const { CAF_CM_FUNCNAME("invoke"); SmartPtrCProviderInvokeOperationDoc doc = request.getInvokeOperations(); CAF_CM_VALIDATE_SMARTPTR(doc); const SmartPtrCOperationDoc operation = doc->getOperation(); const std::string operationName = operation->getName(); const SmartPtrCParameterCollectionDoc parameterCollection = operation->getParameterCollection(); const std::string outputDir = doc->getOutputDir(); if (operationName.compare("installProviderJob") == 0) { const std::string installProviderJobStr = ParameterUtils::findRequiredInstanceParameterAsString("installProviderJob", parameterCollection); CAF_CM_VALIDATE_STRING(installProviderJobStr); const SmartPtrCDynamicByteArray payload = CCafMessagePayload::createBufferFromStr(installProviderJobStr); const SmartPtrCInstallProviderJobDoc installProviderJob = CCafMessagePayloadParser::getInstallProviderJob(payload); if (isCurrentOS(installProviderJob->getPackageOSType())) { CProviderInstaller::installProvider(installProviderJob, request.getAttachments(), outputDir); } } else if (operationName.compare("uninstallProviderJob") == 0) { const std::string uninstallProviderJobStr = ParameterUtils::findRequiredInstanceParameterAsString("uninstallProviderJob", parameterCollection); const SmartPtrCDynamicByteArray payload = CCafMessagePayload::createBufferFromStr(uninstallProviderJobStr); const SmartPtrCUninstallProviderJobDoc uninstallProviderJob = CCafMessagePayloadParser::getUninstallProviderJob(payload); if (isCurrentOS(uninstallProviderJob->getPackageOSType())) { CProviderInstaller::uninstallProvider(uninstallProviderJob, outputDir); } } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Invalid operation name (must be \'installProviderJob\' or \'uninstallProviderJob\') - %s", operationName.c_str()) } } SmartPtrCDataClassInstanceDoc CInstallProvider::createDataClassInstance( const SmartPtrCInstallProviderSpecDoc& installProviderSpec) const { CAF_CM_FUNCNAME_VALIDATE("createDataClassInstance"); CAF_CM_VALIDATE_SMARTPTR(installProviderSpec); const std::deque minPackageElemCollection = installProviderSpec->getPackageCollection(); std::deque subInstances; for (TConstIterator > minPackageElemIter( minPackageElemCollection); minPackageElemIter; minPackageElemIter++) { const SmartPtrCMinPackageElemDoc minPackageElem = *minPackageElemIter; const std::string packageNamespace = minPackageElem->getPackageNamespace(); const std::string packageName = minPackageElem->getPackageName(); const std::string packageVersion = minPackageElem->getPackageVersion(); std::deque siProperties; siProperties.push_back(CProviderDocHelper::createDataClassProperty("packageNamespace", packageNamespace)); siProperties.push_back(CProviderDocHelper::createDataClassProperty("packageName", packageName)); siProperties.push_back(CProviderDocHelper::createDataClassProperty("packageVersion", packageVersion)); subInstances.push_back(CProviderDocHelper::createDataClassSubInstance( "fullPackageElem", siProperties)); } const std::string clientId = BasePlatform::UuidToString(installProviderSpec->getClientId()); const std::string providerNamespace = installProviderSpec->getProviderNamespace(); const std::string providerName = installProviderSpec->getProviderName(); const std::string providerVersion = installProviderSpec->getProviderVersion(); std::deque dataClassProperties; dataClassProperties.push_back(CProviderDocHelper::createDataClassProperty("clientId", clientId)); dataClassProperties.push_back(CProviderDocHelper::createDataClassProperty("providerNamespace", providerNamespace)); dataClassProperties.push_back(CProviderDocHelper::createDataClassProperty("providerName", providerName)); dataClassProperties.push_back(CProviderDocHelper::createDataClassProperty("providerVersion", providerVersion)); return CProviderDocHelper::createDataClassInstance( "caf", "CafProviderInventory", "1.0.0", dataClassProperties, subInstances); } bool CInstallProvider::isCurrentOS(const PACKAGE_OS_TYPE& packageOSType) const { CAF_CM_FUNCNAME_VALIDATE("isCurrentOS"); #ifdef WIN32 const PACKAGE_OS_TYPE packageOSTypeLocal = PACKAGE_OS_WIN; #else const PACKAGE_OS_TYPE packageOSTypeLocal = PACKAGE_OS_NIX; #endif bool rc = false; if ((packageOSType == packageOSTypeLocal) || (packageOSType == PACKAGE_OS_ALL)) { rc = true; } else { CAF_CM_LOG_WARN_VA0("Wrong OS... Skipping package"); } return rc; } CInstallProvider.h000066400000000000000000000026161321503522500364500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CInstallProvider_h_ #define CInstallProvider_h_ #include "IInvokedProvider.h" #include "Doc/CafInstallRequestDoc/CafInstallRequestDocTypes.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" namespace Caf { /// Sends responses/errors back to the client. class CInstallProvider : public IInvokedProvider { public: CInstallProvider(); virtual ~CInstallProvider(); public: // IInvokedProvider const std::string getProviderNamespace() const { return "caf"; } const std::string getProviderName() const { return "InstallProvider"; } const std::string getProviderVersion() const { return "1.0.0"; } const SmartPtrCSchemaDoc getSchema() const; void collect(const IProviderRequest& request, IProviderResponse& response) const; void invoke(const IProviderRequest& request, IProviderResponse& response) const; private: SmartPtrCDataClassInstanceDoc createDataClassInstance( const SmartPtrCInstallProviderSpecDoc& installProviderSpec) const; bool isCurrentOS(const PACKAGE_OS_TYPE& packageOSType) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CInstallProvider); }; } #endif // #ifndef CInstallProvider_h_ CInstallUtils.cpp000066400000000000000000000033421321503522500363060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CInstallUtils.h" using namespace Caf; CInstallUtils::MATCH_STATUS CInstallUtils::compareVersions( const std::string& packageVersion1, const std::string& packageVersion2) { CAF_CM_STATIC_FUNC_LOG("CInstallUtils", "compareVersions"); MATCH_STATUS matchStatus = MATCH_NOTEQUAL; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(packageVersion1); CAF_CM_VALIDATE_STRING(packageVersion2); const Cdeqstr packageVersionTokens1 = CStringUtils::split(packageVersion1, '.'); if (packageVersionTokens1.size() != 3) { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Package version 1 has a bad format - %s", packageVersion1.c_str()); } const Cdeqstr packageVersionTokens2 = CStringUtils::split(packageVersion2, '.'); if (packageVersionTokens2.size() != 3) { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Package version 2 has a bad format - %s", packageVersion2.c_str()); } if ((packageVersionTokens1[0].compare(packageVersionTokens2[0]) == 0) && (packageVersionTokens1[1].compare(packageVersionTokens2[1]) == 0)) { const uint32 lastVersionPos1 = CStringConv::fromString( packageVersionTokens1[2]); const uint32 lastVersionPos2 = CStringConv::fromString( packageVersionTokens2[2]); if (lastVersionPos1 == lastVersionPos2) { matchStatus = MATCH_VERSION_EQUAL; } else if (lastVersionPos1 < lastVersionPos2) { matchStatus = MATCH_VERSION_LESS; } else { matchStatus = MATCH_VERSION_GREATER; } } } CAF_CM_EXIT; return matchStatus; } CInstallUtils.h000066400000000000000000000010701321503522500357470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CInstallUtils_h_ #define CInstallUtils_h_ namespace Caf { class CInstallUtils { public: typedef enum { MATCH_NOTEQUAL, MATCH_VERSION_EQUAL, MATCH_VERSION_LESS, MATCH_VERSION_GREATER } MATCH_STATUS; static MATCH_STATUS compareVersions( const std::string& packageVersion1, const std::string& packageVersion2); private: CAF_CM_DECLARE_NOCREATE(CInstallUtils); }; } #endif // #ifndef CInstallUtils_h_ CPackageExecutor.cpp000066400000000000000000000127221321503522500367330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Exception/CCafException.h" #include "CPackageExecutor.h" using namespace Caf; void CPackageExecutor::executePackage( const SmartPtrCAttachmentDoc& startupAttachment, const std::string& startupArgument, const SmartPtrCAttachmentDoc& packageAttachment, const std::string& packageArguments, const SmartPtrCAttachmentCollectionDoc& supportingAttachmentCollection, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageExecutor", "executePackage"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(startupAttachment); CAF_CM_VALIDATE_STRING(startupArgument); CAF_CM_VALIDATE_SMARTPTR(packageAttachment); // packageArguments is optional // supportingAttachmentCollection is optional CAF_CM_VALIDATE_STRING(outputDir); const std::string installInvoker = createInstallInvoker(startupAttachment, startupArgument, packageAttachment, packageArguments, supportingAttachmentCollection, outputDir); runInstallInvoker(installInvoker, outputDir); } CAF_CM_EXIT; } std::string CPackageExecutor::createInstallInvoker( const SmartPtrCAttachmentDoc& startupAttachment, const std::string& startupArgument, const SmartPtrCAttachmentDoc& packageAttachment, const std::string& packageArguments, const SmartPtrCAttachmentCollectionDoc& supportingAttachmentCollection, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageExecutor", "createInstallInvoker"); std::string installInvoker; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(startupAttachment); CAF_CM_VALIDATE_STRING(startupArgument); CAF_CM_VALIDATE_SMARTPTR(packageAttachment); // packageArguments is optional // supportingAttachmentCollection is optional CAF_CM_VALIDATE_STRING(outputDir); const std::string inputDir = CPathBuilder::getRootConfigDir(_sConfigInputDir); #ifdef WIN32 const std::string installProviderHeaderPath = FileSystemUtils::buildPath(inputDir, "installProviderHeader.bat"); #else const std::string installProviderHeaderPath = FileSystemUtils::buildPath(inputDir, "installProviderHeader.sh"); #endif const std::string installProviderHeader = FileSystemUtils::loadTextFile( installProviderHeaderPath); std::string attachmentUris = ""; if (!supportingAttachmentCollection.IsNull()) { const std::deque attachmentCollectionInner = supportingAttachmentCollection->getAttachment(); for (TConstIterator > attachmentIter( attachmentCollectionInner); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; attachmentUris += attachment->getUri() + ";"; } } const std::string startupAttachmentUri = startupAttachment->getUri(); std::string startupAttachmentFile = UriUtils::parseRequiredFilePath( startupAttachmentUri); const std::string packageAttachmentUri = packageAttachment->getUri(); std::string packageAttachmentFile = UriUtils::parseRequiredFilePath( packageAttachmentUri); const std::string packageArgumentsTmp = packageArguments.empty() ? "" : packageArguments; #ifdef WIN32 const std::string newLine = "\r\n"; const std::string fileContents = installProviderHeader + newLine + std::string("set CAF_PACKAGE_FILE=") + packageAttachmentFile + newLine + std::string("set CAF_PACKAGE_ARGS=") + packageArgumentsTmp + newLine + std::string("set CAF_ATTACHMENT_URIS=") + attachmentUris + newLine + startupAttachmentFile + " " + startupArgument + newLine; installInvoker = FileSystemUtils::buildPath(outputDir, "CafInstallInvoker.bat"); #else const std::string newLine = "\n"; const std::string fileContents = installProviderHeader + newLine + std::string("export CAF_PACKAGE_FILE=") + packageAttachmentFile + newLine + std::string("export CAF_PACKAGE_ARGS=") + packageArgumentsTmp + newLine + std::string("export CAF_ATTACHMENT_URIS=") + attachmentUris + newLine + startupAttachmentFile + " " + startupArgument + newLine; installInvoker = FileSystemUtils::buildPath(outputDir, "CafInstallInvoker"); #endif const uint32 exeByOwner = 0100; const uint32 writeByOwner = 0200; const uint32 readByOwner = 0400; const uint32 fileMode = exeByOwner | writeByOwner | readByOwner; FileSystemUtils::saveTextFile(installInvoker, fileContents); FileSystemUtils::chmod(installInvoker, fileMode); FileSystemUtils::chmod(startupAttachmentFile, fileMode); FileSystemUtils::chmod(packageAttachmentFile, fileMode); } CAF_CM_EXIT; return installInvoker; } void CPackageExecutor::runInstallInvoker( const std::string& installInvoker, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG("CPackageExecutor", "runInstallInvoker"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(installInvoker); CAF_CM_VALIDATE_STRING(outputDir); if (!FileSystemUtils::doesFileExist(installInvoker)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Install invoker not found - %s", installInvoker.c_str()); } const std::string stdoutPath = FileSystemUtils::buildPath(outputDir, _sStdoutFilename); const std::string stderrPath = FileSystemUtils::buildPath(outputDir, _sStderrFilename); Cdeqstr argv; argv.push_back(installInvoker); ProcessUtils::runSyncToFiles(argv, stdoutPath, stderrPath); } CAF_CM_EXIT; } CPackageExecutor.h000066400000000000000000000023461321503522500364010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPackageExecutor_h_ #define CPackageExecutor_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" namespace Caf { /// Utilities used in the install process. class CPackageExecutor { public: static void executePackage( const SmartPtrCAttachmentDoc& startupAttachment, const std::string& startupArgument, const SmartPtrCAttachmentDoc& packageAttachment, const std::string& packageArguments, const SmartPtrCAttachmentCollectionDoc& supportingAttachmentCollection, const std::string& outputDir); private: static std::string createInstallInvoker( const SmartPtrCAttachmentDoc& startupAttachment, const std::string& startupArgument, const SmartPtrCAttachmentDoc& packageAttachment, const std::string& packageArguments, const SmartPtrCAttachmentCollectionDoc& supportingAttachmentCollection, const std::string& outputDir); static void runInstallInvoker( const std::string& installInvoker, const std::string& outputDir); private: CAF_CM_DECLARE_NOCREATE(CPackageExecutor); }; } #endif // #ifndef CPackageExecutor_h_ CPackageInstaller.cpp000066400000000000000000000616101321503522500370720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlRoots.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CInstallPackageSpecDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CPackageDefnDoc.h" #include "CPackageInstaller.h" using namespace Caf; void CPackageInstaller::installPackages( const std::deque& fullPackageElemCollection, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "installPackages"); CAF_CM_ENTER { CAF_CM_VALIDATE_STL(fullPackageElemCollection); CAF_CM_VALIDATE_SMARTPTR(attachmentCollection); CAF_CM_VALIDATE_STRING(outputDir); const std::map orderedFullPackageElemCollection = orderFullPackageElems(fullPackageElemCollection); for (TConstMapIterator > fullPackageElemIter( orderedFullPackageElemCollection); fullPackageElemIter; fullPackageElemIter++) { const SmartPtrCFullPackageElemDoc fullPackageElem = *fullPackageElemIter; const SmartPtrCPackageDefnDoc installPackageDefn = fullPackageElem->getInstallPackage(); SmartPtrCInstallPackageSpecDoc installPackageSpec; installPackageSpec.CreateInstance(); installPackageSpec->initialize(fullPackageElem->getPackageNamespace(), fullPackageElem->getPackageName(), fullPackageElem->getPackageVersion(), installPackageDefn->getStartupAttachmentName(), installPackageDefn->getPackageAttachmentName(), installPackageDefn->getSupportingAttachmentNameCollection(), attachmentCollection, installPackageDefn->getArguments()); const SmartPtrCPackageDefnDoc uninstallPackageDefn = fullPackageElem->getUninstallPackage(); SmartPtrCInstallPackageSpecDoc uninstallPackageSpec; uninstallPackageSpec.CreateInstance(); uninstallPackageSpec->initialize(fullPackageElem->getPackageNamespace(), fullPackageElem->getPackageName(), fullPackageElem->getPackageVersion(), uninstallPackageDefn->getStartupAttachmentName(), uninstallPackageDefn->getPackageAttachmentName(), uninstallPackageDefn->getSupportingAttachmentNameCollection(), attachmentCollection, uninstallPackageDefn->getArguments()); installPackage(installPackageSpec, uninstallPackageSpec, outputDir); } } CAF_CM_EXIT; } void CPackageInstaller::uninstallPackages( const std::deque& minPackageElemCollection, const std::deque& installProviderSpecCollection, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "uninstallPackages"); CAF_CM_ENTER { CAF_CM_VALIDATE_STL(minPackageElemCollection); // installProviderSpecCollection is optional CAF_CM_VALIDATE_STRING(outputDir); const std::map orderedProviderPackageElemCollection = orderMinPackageElems( minPackageElemCollection); for (TConstMapIterator > minPackageElemIter(orderedProviderPackageElemCollection); minPackageElemIter; minPackageElemIter++) { const SmartPtrCMinPackageElemDoc minPackageElem = *minPackageElemIter; const std::string installPackageDir = CPathBuilder::calcInstallPackageDir( minPackageElem->getPackageNamespace(), minPackageElem->getPackageName(), minPackageElem->getPackageVersion()); const std::string installPackageSpecPath = FileSystemUtils::buildPath( installPackageDir, _sInstallPackageSpecFilename); const SmartPtrCInstallPackageSpecDoc installPackageSpec = XmlRoots::parseInstallPackageSpecFromFile(installPackageSpecPath); const uint32 packageRefCnt = countPackageReferences(installPackageSpec, installProviderSpecCollection); if (packageRefCnt == 1) { try { CPackageInstaller::executePackage(installPackageSpec, "-uninstall", outputDir); } catch (ProcessFailedException* ex) { CAF_CM_LOG_DEBUG_VA1("Removing package directory - %s", installPackageDir.c_str()); FileSystemUtils::recursiveRemoveDirectory(installPackageDir); ex->throwSelf(); } CAF_CM_LOG_DEBUG_VA1("Removing package directory - %s", installPackageDir.c_str()); FileSystemUtils::recursiveRemoveDirectory(installPackageDir); } else { CAF_CM_LOG_WARN_VA4("Package referenced from more than one provider... not uninstalling - %s::%s::%s = %d", minPackageElem->getPackageNamespace().c_str(), minPackageElem->getPackageName().c_str(), minPackageElem->getPackageVersion().c_str(), packageRefCnt); } } } CAF_CM_EXIT; } void CPackageInstaller::installPackage( const SmartPtrCInstallPackageSpecDoc& installPackageSpec, const SmartPtrCInstallPackageSpecDoc& uninstallPackageSpec, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "installPackage"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpec); CAF_CM_VALIDATE_SMARTPTR(uninstallPackageSpec); CAF_CM_VALIDATE_STRING(outputDir); const SmartPtrCInstallPackageMatch installPackageMatch = matchInstallPackageSpec( installPackageSpec); switch (installPackageMatch->_matchStatus) { case CInstallUtils::MATCH_NOTEQUAL: { const SmartPtrCInstallPackageSpecDoc resolvedInstallPackageSpec = resolveAndCopyAttachments(uninstallPackageSpec); executePackage(installPackageSpec, "-install", outputDir); saveInstallPackageSpec(resolvedInstallPackageSpec); } break; case CInstallUtils::MATCH_VERSION_EQUAL: { logWarn("Package already installed", installPackageSpec, installPackageMatch->_matchedInstallPackageSpec); } break; case CInstallUtils::MATCH_VERSION_LESS: { logWarn("More recent package already installed", installPackageSpec, installPackageMatch->_matchedInstallPackageSpec); } break; case CInstallUtils::MATCH_VERSION_GREATER: { logWarn("Upgrading installed version", installPackageSpec, installPackageMatch->_matchedInstallPackageSpec); try { executePackage(installPackageMatch->_matchedInstallPackageSpec, "-upgrade_uninstall", outputDir); } catch (ProcessFailedException* ex) { cleanupPackage(installPackageMatch); ex->throwSelf(); } cleanupPackage(installPackageMatch); const SmartPtrCInstallPackageSpecDoc resolvedInstallPackageSpec = resolveAndCopyAttachments(uninstallPackageSpec); executePackage(installPackageSpec, "-upgrade_install", outputDir); saveInstallPackageSpec(resolvedInstallPackageSpec); } break; } } CAF_CM_EXIT; } void CPackageInstaller::executePackage( const SmartPtrCInstallPackageSpecDoc& installPackageSpec, const std::string& startupArgument, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "executePackage"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpec); CAF_CM_VALIDATE_STRING(outputDir); const SmartPtrCAttachmentCollectionDoc attachmentCollection = installPackageSpec->getAttachmentCollection(); const SmartPtrCAttachmentDoc startupAttachment = AttachmentUtils::findRequiredAttachment( installPackageSpec->getStartupAttachmentName(), attachmentCollection); const SmartPtrCAttachmentDoc packageAttachment = AttachmentUtils::findRequiredAttachment( installPackageSpec->getPackageAttachmentName(), attachmentCollection); const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection = installPackageSpec->getSupportingAttachmentNameCollection(); const SmartPtrCAttachmentCollectionDoc supportingAttachmentCollection = resolveAttachments(attachmentNameCollection, attachmentCollection); const std::string packageDir = CPathBuilder::calcDir( installPackageSpec->getPackageNamespace(), installPackageSpec->getPackageName(), installPackageSpec->getPackageVersion(), outputDir); const std::string packageArguments = installPackageSpec->getArguments(); if (!FileSystemUtils::doesDirectoryExist(packageDir)) { FileSystemUtils::createDirectory(packageDir); } CPackageExecutor::executePackage(startupAttachment, startupArgument, packageAttachment, packageArguments, supportingAttachmentCollection, packageDir); } CAF_CM_EXIT; } SmartPtrCInstallPackageSpecDoc CPackageInstaller::resolveAndCopyAttachments( const SmartPtrCInstallPackageSpecDoc& installPackageSpec) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "resolveAndCopyAttachments"); SmartPtrCInstallPackageSpecDoc installPackageSpecRc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpec); const std::string installPackageDir = CPathBuilder::calcInstallPackageDir( installPackageSpec->getPackageNamespace(), installPackageSpec->getPackageName(), installPackageSpec->getPackageVersion()); const SmartPtrCAttachmentCollectionDoc attachmentCollection = installPackageSpec->getAttachmentCollection(); const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection = installPackageSpec->getSupportingAttachmentNameCollection(); const SmartPtrCAttachmentCollectionDoc resolvedAttachmentCollection = resolveAttachments( attachmentNameCollection, attachmentCollection); const SmartPtrCAttachmentDoc startupAttachment = AttachmentUtils::findRequiredAttachment( installPackageSpec->getStartupAttachmentName(), attachmentCollection); const SmartPtrCAttachmentDoc packageAttachment = AttachmentUtils::findRequiredAttachment( installPackageSpec->getPackageAttachmentName(), attachmentCollection); const SmartPtrCAttachmentCollectionDoc copiedAttachmentCollection = copyAttachments( startupAttachment, packageAttachment, resolvedAttachmentCollection, installPackageDir); installPackageSpecRc.CreateInstance(); installPackageSpecRc->initialize(installPackageSpec->getPackageNamespace(), installPackageSpec->getPackageName(), installPackageSpec->getPackageVersion(), installPackageSpec->getStartupAttachmentName(), installPackageSpec->getPackageAttachmentName(), attachmentNameCollection, copiedAttachmentCollection, installPackageSpec->getArguments()); } CAF_CM_EXIT; return installPackageSpecRc; } void CPackageInstaller::saveInstallPackageSpec( const SmartPtrCInstallPackageSpecDoc& installPackageSpec) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "saveInstallPackageSpec"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpec); const std::string installPackageDir = CPathBuilder::calcInstallPackageDir( installPackageSpec->getPackageNamespace(), installPackageSpec->getPackageName(), installPackageSpec->getPackageVersion()); const std::string installPackageSpecPath = FileSystemUtils::buildPath(installPackageDir, _sInstallPackageSpecFilename); XmlRoots::saveInstallPackageSpecToFile(installPackageSpec, installPackageSpecPath); } CAF_CM_EXIT; } std::map CPackageInstaller::orderFullPackageElems( const std::deque& fullPackageElemCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "orderFullPackageElems"); std::map orderedFullPackageElemCollection; CAF_CM_ENTER { CAF_CM_VALIDATE_STL(fullPackageElemCollection); for (TConstIterator > fullPackageElemIter( fullPackageElemCollection); fullPackageElemIter; fullPackageElemIter++) { const SmartPtrCFullPackageElemDoc fullPackageElem = *fullPackageElemIter; orderedFullPackageElemCollection.insert( std::make_pair(fullPackageElem->getIndex(), fullPackageElem)); } } CAF_CM_EXIT; return orderedFullPackageElemCollection; } std::map CPackageInstaller::orderMinPackageElems( const std::deque& minPackageElemCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "orderProviderPackageElems"); std::map orderedMinPackageElemCollection; CAF_CM_ENTER { CAF_CM_VALIDATE_STL(minPackageElemCollection); for (TConstIterator > minPackageElemIter( minPackageElemCollection); minPackageElemIter; minPackageElemIter++) { const SmartPtrCMinPackageElemDoc minPackageElem = *minPackageElemIter; orderedMinPackageElemCollection.insert( std::make_pair(minPackageElem->getIndex(), minPackageElem)); } } CAF_CM_EXIT; return orderedMinPackageElemCollection; } SmartPtrCAttachmentCollectionDoc CPackageInstaller::resolveAttachments( const SmartPtrCAttachmentNameCollectionDoc& attachmentNameCollection, const SmartPtrCAttachmentCollectionDoc& attachmentCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "resolveAttachments"); SmartPtrCAttachmentCollectionDoc rc; CAF_CM_ENTER { // attachmentNameCollection is optional CAF_CM_VALIDATE_SMARTPTR(attachmentCollection); if (!attachmentNameCollection.IsNull()) { const std::deque attachmentNameCollectionInner = attachmentNameCollection->getName(); std::deque attachmentCollectionInner; for (TConstIterator > attachmentNameIter( attachmentNameCollectionInner); attachmentNameIter; attachmentNameIter++) { const std::string attachmentName = *attachmentNameIter; const SmartPtrCAttachmentDoc attachment = AttachmentUtils::findRequiredAttachment( attachmentName, attachmentCollection); attachmentCollectionInner.push_back(attachment); } if (!attachmentCollectionInner.empty()) { rc.CreateInstance(); rc->initialize(attachmentCollectionInner, std::deque()); } } } CAF_CM_EXIT; return rc; } SmartPtrCAttachmentCollectionDoc CPackageInstaller::copyAttachments( const SmartPtrCAttachmentDoc& startupAttachment, const SmartPtrCAttachmentDoc& packageAttachment, const SmartPtrCAttachmentCollectionDoc& supportingAttachmentCollection, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "copyAttachments"); SmartPtrCAttachmentCollectionDoc attachmentCollectionRc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(startupAttachment); CAF_CM_VALIDATE_SMARTPTR(packageAttachment); // supportingAttachmentCollection is optional CAF_CM_VALIDATE_STRING(outputDir); std::deque attachmentCollectionInner; attachmentCollectionInner.push_back(startupAttachment); attachmentCollectionInner.push_back(packageAttachment); if (!supportingAttachmentCollection.IsNull()) { for (TConstIterator > supportingAttachmentIter( supportingAttachmentCollection->getAttachment()); supportingAttachmentIter; supportingAttachmentIter++) { attachmentCollectionInner.push_back(*supportingAttachmentIter); } } std::deque attachmentCollectionInnerRc; for (TConstIterator > attachmentIter( attachmentCollectionInner); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; const std::string attachmentUri = attachment->getUri(); const std::string attachmentFilePath = UriUtils::parseRequiredFilePath(attachmentUri); UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(attachmentUri, uriRecord); std::string dstAttachmentDir = outputDir; std::string relPath = FileSystemUtils::getBasename(attachmentFilePath); const std::map::const_iterator iterParam = uriRecord.parameters.find("relPath"); if (iterParam != uriRecord.parameters.end()) { relPath = iterParam->second; const std::string tmpPath = FileSystemUtils::buildPath(outputDir, relPath); dstAttachmentDir = FileSystemUtils::getDirname(tmpPath); } else { CAF_CM_LOG_DEBUG_VA1("Attachment URI does not contain relPath - %s", attachmentUri.c_str()); } if (!FileSystemUtils::doesDirectoryExist(dstAttachmentDir)) { FileSystemUtils::createDirectory(dstAttachmentDir); } const std::string dstAttachmentFilePath = FileSystemUtils::buildPath(outputDir, relPath); if (FileSystemUtils::doesFileExist(dstAttachmentFilePath)) { CAF_CM_LOG_WARN_VA2("Destination file already exists... not copying \"%s\" to \"%s\"", attachmentFilePath.c_str(), dstAttachmentFilePath.c_str()); } else { CAF_CM_LOG_DEBUG_VA2("Copying attachment from \"%s\" to \"%s\"", attachmentFilePath.c_str(), dstAttachmentFilePath.c_str()); FileSystemUtils::copyFile(attachmentFilePath, dstAttachmentFilePath); } std::string dstAttachmentUri = "file:///" + dstAttachmentFilePath; if (!relPath.empty()) { dstAttachmentUri += "?relPath=" + relPath; } SmartPtrCAttachmentDoc dstAttachment; dstAttachment.CreateInstance(); dstAttachment->initialize(attachment->getName(), attachment->getType(), dstAttachmentUri, false, attachment->getCmsPolicy()); attachmentCollectionInnerRc.push_back(dstAttachment); } attachmentCollectionRc.CreateInstance(); attachmentCollectionRc->initialize(attachmentCollectionInnerRc, std::deque()); } CAF_CM_EXIT; return attachmentCollectionRc; } CPackageInstaller::SmartPtrCInstallPackageMatch CPackageInstaller::matchInstallPackageSpec( const SmartPtrCInstallPackageSpecDoc& installPackageSpec) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "matchInstallPackageSpec"); SmartPtrCInstallPackageMatch installPackageMatch; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpec); installPackageMatch.CreateInstance(); installPackageMatch->_matchStatus = CInstallUtils::MATCH_NOTEQUAL; const SmartPtrCInstallPackageSpecCollection installPackageSpecCollection = readInstallPackageSpecs(); if (!installPackageSpecCollection.IsNull()) { const std::string packageNamespace = installPackageSpec->getPackageNamespace(); const std::string packageName = installPackageSpec->getPackageName(); const std::string packageVersion = installPackageSpec->getPackageVersion(); for (TConstIterator > installPackageSpecIter(*installPackageSpecCollection); installPackageSpecIter; installPackageSpecIter++) { const SmartPtrCInstallPackageSpecDoc installPackageSpecCur = *installPackageSpecIter; const std::string packageNamespaceCur = installPackageSpecCur->getPackageNamespace(); const std::string packageNameCur = installPackageSpecCur->getPackageName(); if ((packageNamespace.compare(packageNamespaceCur) == 0) && (packageName.compare( packageNameCur) == 0)) { const std::string packageVersionCur = installPackageSpecCur->getPackageVersion(); installPackageMatch->_matchStatus = CInstallUtils::compareVersions( packageVersion, packageVersionCur); if (installPackageMatch->_matchStatus != CInstallUtils::MATCH_NOTEQUAL) { installPackageMatch->_matchedInstallPackageSpec = installPackageSpecCur; break; } } else { logDebug("Package did not match", installPackageSpec, installPackageSpecCur); } } } } CAF_CM_EXIT; return installPackageMatch; } CPackageInstaller::SmartPtrCInstallPackageSpecCollection CPackageInstaller::readInstallPackageSpecs() { CAF_CM_STATIC_FUNC_LOG_ONLY("CPackageInstaller", "readInstallPackageSpecs"); SmartPtrCInstallPackageSpecCollection installPackageSpecCollection; CAF_CM_ENTER { const std::string installPackageDir = CPathBuilder::calcInstallPackageDir(); const std::deque installPackageSpecFiles = FileSystemUtils::findOptionalFiles(installPackageDir, _sInstallPackageSpecFilename); if (installPackageSpecFiles.empty()) { CAF_CM_LOG_WARN_VA2("No package install specs found - dir: %s, filename: %s", installPackageDir.c_str(), _sInstallPackageSpecFilename); } else { installPackageSpecCollection.CreateInstance(); for (TConstIterator > installPackageSpecFileIter( installPackageSpecFiles); installPackageSpecFileIter; installPackageSpecFileIter++) { const std::string installPackageSpecFilePath = *installPackageSpecFileIter; CAF_CM_LOG_DEBUG_VA1("Found package install spec - %s", installPackageSpecFilePath.c_str()); const SmartPtrCInstallPackageSpecDoc installPackageSpec = XmlRoots::parseInstallPackageSpecFromFile(installPackageSpecFilePath); installPackageSpecCollection->push_back(installPackageSpec); } } } CAF_CM_EXIT; return installPackageSpecCollection; } uint32 CPackageInstaller::countPackageReferences( const SmartPtrCInstallPackageSpecDoc& installPackageSpec, const std::deque& installProviderSpecCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "countPackageReferences"); uint32 refCnt = 0; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installPackageSpec); // installProviderSpecCollection is optional const std::string packageNamespace = installPackageSpec->getPackageNamespace(); const std::string packageName = installPackageSpec->getPackageName(); const std::string packageVersion = installPackageSpec->getPackageVersion(); for (TConstIterator > installProviderSpecIter( installProviderSpecCollection); installProviderSpecIter; installProviderSpecIter++) { const SmartPtrCInstallProviderSpecDoc installProviderSpec = *installProviderSpecIter; const std::deque minPackageElemCollection = installProviderSpec->getPackageCollection(); for (TConstIterator > minPackageElemIter(minPackageElemCollection); minPackageElemIter; minPackageElemIter++) { const SmartPtrCMinPackageElemDoc minPackageElem = *minPackageElemIter; const std::string packageNamespaceCur = minPackageElem->getPackageNamespace(); const std::string packageNameCur = minPackageElem->getPackageName(); if ((packageNamespace.compare(packageNamespaceCur) == 0) && (packageName.compare( packageNameCur) == 0)) { const std::string packageVersionCur = minPackageElem->getPackageVersion(); const CInstallUtils::MATCH_STATUS matchStatus = CInstallUtils::compareVersions(packageVersion, packageVersionCur); if (matchStatus != CInstallUtils::MATCH_NOTEQUAL) { refCnt++; } } } } CAF_CM_LOG_DEBUG_VA4("Package ref cnt - %s::%s::%s = %d", packageNamespace.c_str(), packageName.c_str(), packageVersion.c_str(), refCnt); } CAF_CM_EXIT; return refCnt; } void CPackageInstaller::logDebug( const std::string& message, const SmartPtrCInstallPackageSpecDoc& installPackageSpec1, const SmartPtrCInstallPackageSpecDoc& installPackageSpec2) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "logDebug"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(message); CAF_CM_VALIDATE_SMARTPTR(installPackageSpec1); CAF_CM_VALIDATE_SMARTPTR(installPackageSpec2); const std::string fullMessage = message + " - %s::%s::%s, %s::%s::%s"; CAF_CM_LOG_DEBUG_VA6(fullMessage.c_str(), installPackageSpec1->getPackageNamespace().c_str(), installPackageSpec1->getPackageName().c_str(), installPackageSpec1->getPackageVersion().c_str(), installPackageSpec2->getPackageNamespace().c_str(), installPackageSpec2->getPackageName().c_str(), installPackageSpec2->getPackageVersion().c_str()); } CAF_CM_EXIT; } void CPackageInstaller::logWarn( const std::string& message, const SmartPtrCInstallPackageSpecDoc& installPackageSpec1, const SmartPtrCInstallPackageSpecDoc& installPackageSpec2) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "logWarn"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(message); CAF_CM_VALIDATE_SMARTPTR(installPackageSpec1); CAF_CM_VALIDATE_SMARTPTR(installPackageSpec2); const std::string fullMessage = message + " - %s::%s::%s, %s::%s::%s"; CAF_CM_LOG_DEBUG_VA6(fullMessage.c_str(), installPackageSpec1->getPackageNamespace().c_str(), installPackageSpec1->getPackageName().c_str(), installPackageSpec1->getPackageVersion().c_str(), installPackageSpec2->getPackageNamespace().c_str(), installPackageSpec2->getPackageName().c_str(), installPackageSpec2->getPackageVersion().c_str()); } CAF_CM_EXIT; } void CPackageInstaller::cleanupPackage( const SmartPtrCInstallPackageMatch& installPackageMatch) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPackageInstaller", "cleanupPackage"); CAF_CM_VALIDATE_SMARTPTR(installPackageMatch); const std::string installPackageDir = CPathBuilder::calcInstallPackageDir( installPackageMatch->_matchedInstallPackageSpec->getPackageNamespace(), installPackageMatch->_matchedInstallPackageSpec->getPackageName(), installPackageMatch->_matchedInstallPackageSpec->getPackageVersion()); CAF_CM_LOG_DEBUG_VA1("Removing package directory - %s", installPackageDir.c_str()); FileSystemUtils::recursiveRemoveDirectory(installPackageDir); } CPathBuilder.cpp000066400000000000000000000126661321503522500360730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CPathBuilder.h" using namespace Caf; std::string CPathBuilder::calcInstallProviderDir() { std::string installProviderDir; CAF_CM_ENTER { const std::string installDir = getProviderHostConfigDir( _sConfigInstallDir); installProviderDir = FileSystemUtils::buildPath(installDir, "providers"); if (!FileSystemUtils::doesDirectoryExist(installProviderDir)) { FileSystemUtils::createDirectory(installProviderDir); } } CAF_CM_EXIT; return installProviderDir; } std::string CPathBuilder::calcInstallPackageDir() { std::string installPackageDir; CAF_CM_ENTER { const std::string installDir = getProviderHostConfigDir( _sConfigInstallDir); installPackageDir = FileSystemUtils::buildPath(installDir, "packages"); if (!FileSystemUtils::doesDirectoryExist(installPackageDir)) { FileSystemUtils::createDirectory(installPackageDir); } } CAF_CM_EXIT; return installPackageDir; } std::string CPathBuilder::calcInstallProviderDir( const std::string& providerNamespace, const std::string& providerName, const std::string& providerVersion) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPathBuilder", "calcInstallProviderDir"); std::string installProviderDir; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(providerNamespace); CAF_CM_VALIDATE_STRING(providerName); CAF_CM_VALIDATE_STRING(providerVersion); const std::string installDir = getProviderHostConfigDir( _sConfigInstallDir); const std::string providersDir = FileSystemUtils::buildPath(installDir, "providers"); installProviderDir = calcDir(providerNamespace, providerName, providerVersion, providersDir); if (!FileSystemUtils::doesDirectoryExist(installProviderDir)) { FileSystemUtils::createDirectory(installProviderDir); } } CAF_CM_EXIT; return installProviderDir; } std::string CPathBuilder::calcInstallPackageDir( const std::string& packageNamespace, const std::string& packageName, const std::string& packageVersion) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPathBuilder", "calcInstallPackageDir"); std::string installPackageDir; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(packageNamespace); CAF_CM_VALIDATE_STRING(packageName); CAF_CM_VALIDATE_STRING(packageVersion); const std::string installDir = getProviderHostConfigDir( _sConfigInstallDir); const std::string packagesDir = FileSystemUtils::buildPath(installDir, "packages"); installPackageDir = calcDir(packageNamespace, packageName, packageVersion, packagesDir); if (!FileSystemUtils::doesDirectoryExist(installPackageDir)) { FileSystemUtils::createDirectory(installPackageDir); } } CAF_CM_EXIT; return installPackageDir; } std::string CPathBuilder::calcProviderSchemaCacheDir( const std::string& providerNamespace, const std::string& providerName, const std::string& providerVersion) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPathBuilder", "calcProviderSchemaCacheDir"); std::string providerSchemaCacheDir; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(providerNamespace); CAF_CM_VALIDATE_STRING(providerName); CAF_CM_VALIDATE_STRING(providerVersion); const std::string schemaCacheDir = getProviderHostConfigDir( _sConfigSchemaCacheDir); providerSchemaCacheDir = calcDir(providerNamespace, providerName, providerVersion, schemaCacheDir); } CAF_CM_EXIT; return providerSchemaCacheDir; } std::string CPathBuilder::calcDir( const std::string& thisNamespace, const std::string& thisName, const std::string& thisVersion, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPathBuilder", "calcDir"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(thisNamespace); CAF_CM_VALIDATE_STRING(thisName); CAF_CM_VALIDATE_STRING(thisVersion); CAF_CM_VALIDATE_STRING(outputDir); const std::string dirName = thisNamespace + "_" + thisName + "_" + thisVersion; rc = FileSystemUtils::buildPath(outputDir, dirName); } CAF_CM_EXIT; return rc; } std::string CPathBuilder::getRootConfigDir(const std::string& configName) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPathBuilder", "getRootConfigDir"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(configName); const std::string configDir = AppConfigUtils::getRequiredString(configName); const std::string configDirExp = CStringUtils::expandEnv(configDir); if (!FileSystemUtils::doesDirectoryExist(configDirExp)) { CAF_CM_LOG_DEBUG_VA2( "AppConfig directory does not exist... Creating - name: %s, dir: %s", configName.c_str(), configDirExp.c_str()); FileSystemUtils::createDirectory(configDirExp); } rc = FileSystemUtils::normalizePathForPlatform(configDirExp); } CAF_CM_EXIT; return rc; } std::string CPathBuilder::getProviderHostConfigDir(const std::string& configName) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CPathBuilder", "getProviderHostConfigDir"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(configName); const std::string configDir = AppConfigUtils::getRequiredString(_sProviderHostArea, configName); const std::string configDirExp = CStringUtils::expandEnv(configDir); if (!FileSystemUtils::doesDirectoryExist(configDirExp)) { CAF_CM_LOG_DEBUG_VA2( "AppConfig directory does not exist... Creating - name: %s, dir: %s", configName.c_str(), configDirExp.c_str()); FileSystemUtils::createDirectory(configDirExp); } rc = FileSystemUtils::normalizePathForPlatform(configDirExp); } CAF_CM_EXIT; return rc; } CPathBuilder.h000066400000000000000000000022711321503522500355270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPathBuilder_h_ #define CPathBuilder_h_ namespace Caf { class CPathBuilder { public: static std::string calcInstallPackageDir(); static std::string calcInstallProviderDir(); static std::string calcInstallProviderDir( const std::string& providerNamespace, const std::string& providerName, const std::string& providerVersion); static std::string calcInstallPackageDir( const std::string& packageNamespace, const std::string& packageName, const std::string& packageVersion); static std::string calcProviderSchemaCacheDir( const std::string& providerNamespace, const std::string& providerName, const std::string& providerVersion); static std::string calcDir( const std::string& thisNamespace, const std::string& thisName, const std::string& thisVersion, const std::string& outputDir); static std::string getRootConfigDir(const std::string& configName); static std::string getProviderHostConfigDir(const std::string& configName); private: CAF_CM_DECLARE_NOCREATE( CPathBuilder); }; } #endif // #ifndef CPathBuilder_h_ CProviderInstaller.cpp000066400000000000000000000360011321503522500373250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/CafInstallRequestXml/CafInstallRequestXmlRoots.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafInstallRequestDoc/CFullPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderSpecDoc.h" #include "Doc/CafInstallRequestDoc/CMinPackageElemDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "CProviderInstaller.h" #include "CPackageInstaller.h" using namespace Caf; void CProviderInstaller::installProvider( const SmartPtrCInstallProviderJobDoc& installProviderJob, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "installProvider"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderJob); CAF_CM_VALIDATE_SMARTPTR(attachmentCollection); CAF_CM_VALIDATE_STRING(outputDir); const SmartPtrCInstallProviderSpecDoc installProviderSpec = createInstallProviderSpec( installProviderJob); const SmartPtrCInstallProviderMatch installProviderMatch = matchInstallProviderSpec( installProviderSpec); switch (installProviderMatch->_matchStatus) { case CInstallUtils::MATCH_NOTEQUAL: { installProviderLow(installProviderJob, attachmentCollection, outputDir); } break; case CInstallUtils::MATCH_VERSION_EQUAL: { logWarn("Provider already installed", installProviderSpec, installProviderMatch->_matchedInstallProviderSpec); } break; case CInstallUtils::MATCH_VERSION_LESS: { logWarn("More recent provider already installed", installProviderSpec, installProviderMatch->_matchedInstallProviderSpec); } break; case CInstallUtils::MATCH_VERSION_GREATER: { logWarn("Upgrading provider", installProviderSpec, installProviderMatch->_matchedInstallProviderSpec); uninstallProviderLow(installProviderMatch->_matchedInstallProviderSpec, outputDir); installProviderLow(installProviderJob, attachmentCollection, outputDir); } break; } } CAF_CM_EXIT; } void CProviderInstaller::uninstallProvider( const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "uninstallProvider"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(uninstallProviderJob); CAF_CM_VALIDATE_STRING(outputDir); const std::string installProviderDir = CPathBuilder::calcInstallProviderDir( uninstallProviderJob->getProviderNamespace(), uninstallProviderJob->getProviderName(), uninstallProviderJob->getProviderVersion()); const std::string installProviderSpecPath = FileSystemUtils::buildPath(installProviderDir, _sInstallProviderSpecFilename); if (FileSystemUtils::doesFileExist(installProviderSpecPath)) { const SmartPtrCInstallProviderSpecDoc installProviderSpec = XmlRoots::parseInstallProviderSpecFromFile(installProviderSpecPath); uninstallProviderLow(installProviderSpec, outputDir); } else { CAF_CM_LOG_INFO_VA1("Uninstall unnecessary... provider is not installed - %s", calcProviderFqn(uninstallProviderJob).c_str()); } } CAF_CM_EXIT; } CProviderInstaller::SmartPtrCInstallProviderSpecCollection CProviderInstaller::readInstallProviderSpecs() { CAF_CM_STATIC_FUNC_LOG_ONLY("CProviderInstaller", "readInstallProviderSpecs"); SmartPtrCInstallProviderSpecCollection installProviderSpecCollection; CAF_CM_ENTER { const std::string installProviderDir = CPathBuilder::calcInstallProviderDir(); const std::deque installProviderSpecFiles = FileSystemUtils::findOptionalFiles(installProviderDir, _sInstallProviderSpecFilename); if (installProviderSpecFiles.empty()) { CAF_CM_LOG_WARN_VA2("No provider install specs found - dir: %s, filename: %s", installProviderDir.c_str(), _sInstallProviderSpecFilename); } else { installProviderSpecCollection.CreateInstance(); for (TConstIterator > installProviderSpecFileIter( installProviderSpecFiles); installProviderSpecFileIter; installProviderSpecFileIter++) { const std::string installProviderSpecFilePath = *installProviderSpecFileIter; CAF_CM_LOG_DEBUG_VA1("Found provider install spec - %s", installProviderSpecFilePath.c_str()); const SmartPtrCInstallProviderSpecDoc installProviderSpec = XmlRoots::parseInstallProviderSpecFromFile(installProviderSpecFilePath); installProviderSpecCollection->push_back(installProviderSpec); } } } CAF_CM_EXIT; return installProviderSpecCollection; } void CProviderInstaller::installProviderLow( const SmartPtrCInstallProviderJobDoc& installProviderJob, const SmartPtrCAttachmentCollectionDoc& attachmentCollection, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "installProviderLow"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderJob); CAF_CM_VALIDATE_SMARTPTR(attachmentCollection); CAF_CM_VALIDATE_STRING(outputDir); const std::deque fullPackageElemCollection = installProviderJob->getPackageCollection(); CPackageInstaller::installPackages(fullPackageElemCollection, attachmentCollection, outputDir); const SmartPtrCInstallProviderSpecDoc uninstallProviderSpec = createInstallProviderSpec( installProviderJob); storeInstallProviderSpec(uninstallProviderSpec); } CAF_CM_EXIT; } void CProviderInstaller::uninstallProviderLow( const SmartPtrCInstallProviderSpecDoc& installProviderSpec, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "uninstallProviderLow"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderSpec); CAF_CM_VALIDATE_STRING(outputDir); const std::deque minPackageElemCollection = installProviderSpec->getPackageCollection(); const SmartPtrCInstallProviderSpecCollection installProviderSpecCollection = readInstallProviderSpecs(); std::deque installProviderSpecCollectionInner; if (!installProviderSpecCollection.IsNull()) { installProviderSpecCollectionInner = *installProviderSpecCollection; } try { CPackageInstaller::uninstallPackages(minPackageElemCollection, installProviderSpecCollectionInner, outputDir); } catch (ProcessFailedException* ex) { cleanupProvider(installProviderSpec); ex->throwSelf(); } cleanupProvider(installProviderSpec); } CAF_CM_EXIT; } void CProviderInstaller::storeInstallProviderSpec( const SmartPtrCInstallProviderSpecDoc& installProviderSpec) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "storeInstallProviderSpec"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderSpec); const std::string installProviderDir = CPathBuilder::calcInstallProviderDir( installProviderSpec->getProviderNamespace(), installProviderSpec->getProviderName(), installProviderSpec->getProviderVersion()); const std::string installProviderSpecPath = FileSystemUtils::buildPath(installProviderDir, _sInstallProviderSpecFilename); XmlRoots::saveInstallProviderSpecToFile(installProviderSpec, installProviderSpecPath); } CAF_CM_EXIT; } CProviderInstaller::SmartPtrCInstallProviderMatch CProviderInstaller::matchInstallProviderSpec( const SmartPtrCInstallProviderSpecDoc& installProviderSpec) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "matchInstallProviderSpec"); SmartPtrCInstallProviderMatch installProviderMatch; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderSpec); installProviderMatch.CreateInstance(); installProviderMatch->_matchStatus = CInstallUtils::MATCH_NOTEQUAL; const SmartPtrCInstallProviderSpecCollection installProviderSpecCollection = readInstallProviderSpecs(); if (!installProviderSpecCollection.IsNull()) { const std::string providerNamespace = installProviderSpec->getProviderNamespace(); const std::string providerName = installProviderSpec->getProviderName(); const std::string providerVersion = installProviderSpec->getProviderVersion(); for (TConstIterator > installProviderSpecIter(*installProviderSpecCollection); installProviderSpecIter; installProviderSpecIter++) { const SmartPtrCInstallProviderSpecDoc installProviderSpecCur = *installProviderSpecIter; const std::string providerNamespaceCur = installProviderSpecCur->getProviderNamespace(); const std::string providerNameCur = installProviderSpecCur->getProviderName(); if ((providerNamespace.compare(providerNamespaceCur) == 0) && (providerName.compare(providerNameCur) == 0)) { const std::string providerVersionCur = installProviderSpecCur->getProviderVersion(); installProviderMatch->_matchStatus = CInstallUtils::compareVersions( providerVersion, providerVersionCur); if (installProviderMatch->_matchStatus != CInstallUtils::MATCH_NOTEQUAL) { installProviderMatch->_matchedInstallProviderSpec = installProviderSpecCur; break; } } else { logDebug("Provider did not match", installProviderSpec, installProviderSpecCur); } } } } CAF_CM_EXIT; return installProviderMatch; } SmartPtrCInstallProviderSpecDoc CProviderInstaller::createInstallProviderSpec( const SmartPtrCInstallProviderJobDoc& installProviderJob) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "createInstallProviderSpec"); SmartPtrCInstallProviderSpecDoc installProviderSpec; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderJob); const std::deque fullPackageElemCollection = installProviderJob->getPackageCollection(); std::deque minPackageElemCollection; for (TConstIterator > fullPackageElemIter( fullPackageElemCollection); fullPackageElemIter; fullPackageElemIter++) { const SmartPtrCFullPackageElemDoc fullPackageElem = *fullPackageElemIter; SmartPtrCMinPackageElemDoc minPackageElem; minPackageElem.CreateInstance(); minPackageElem->initialize(fullPackageElem->getIndex(), fullPackageElem->getPackageNamespace(), fullPackageElem->getPackageName(), fullPackageElem->getPackageVersion()); minPackageElemCollection.push_back(minPackageElem); } installProviderSpec.CreateInstance(); installProviderSpec->initialize(installProviderJob->getClientId(), installProviderJob->getProviderNamespace(), installProviderJob->getProviderName(), installProviderJob->getProviderVersion(), minPackageElemCollection); } CAF_CM_EXIT; return installProviderSpec; } void CProviderInstaller::logDebug( const std::string& message, const SmartPtrCInstallProviderSpecDoc& installProviderSpec1, const SmartPtrCInstallProviderSpecDoc& installProviderSpec2) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "logDebug"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(message); CAF_CM_VALIDATE_SMARTPTR(installProviderSpec1); CAF_CM_VALIDATE_SMARTPTR(installProviderSpec2); const std::string fullMessage = message + " - %s::%s::%s, %s::%s::%s"; CAF_CM_LOG_DEBUG_VA6(fullMessage.c_str(), installProviderSpec1->getProviderNamespace().c_str(), installProviderSpec1->getProviderName().c_str(), installProviderSpec1->getProviderVersion().c_str(), installProviderSpec2->getProviderNamespace().c_str(), installProviderSpec2->getProviderName().c_str(), installProviderSpec2->getProviderVersion().c_str()); } CAF_CM_EXIT; } void CProviderInstaller::logWarn( const std::string& message, const SmartPtrCInstallProviderSpecDoc& installProviderSpec1, const SmartPtrCInstallProviderSpecDoc& installProviderSpec2) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "logWarn"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(message); CAF_CM_VALIDATE_SMARTPTR(installProviderSpec1); CAF_CM_VALIDATE_SMARTPTR(installProviderSpec2); const std::string fullMessage = message + " - %s::%s::%s, %s::%s::%s"; CAF_CM_LOG_DEBUG_VA6(fullMessage.c_str(), installProviderSpec1->getProviderNamespace().c_str(), installProviderSpec1->getProviderName().c_str(), installProviderSpec1->getProviderVersion().c_str(), installProviderSpec2->getProviderNamespace().c_str(), installProviderSpec2->getProviderName().c_str(), installProviderSpec2->getProviderVersion().c_str()); } CAF_CM_EXIT; } void CProviderInstaller::cleanupProvider( const SmartPtrCInstallProviderSpecDoc& installProviderSpec) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "cleanupProvider"); CAF_CM_VALIDATE_SMARTPTR(installProviderSpec); const std::string providerNamespace = installProviderSpec->getProviderNamespace(); const std::string providerName = installProviderSpec->getProviderName(); const std::string providerVersion = installProviderSpec->getProviderVersion(); const std::string providerFqn = calcProviderFqn(installProviderSpec); const std::string installProviderDir = CPathBuilder::calcInstallProviderDir( providerNamespace, providerName, providerVersion); if (FileSystemUtils::doesDirectoryExist(installProviderDir)) { FileSystemUtils::recursiveRemoveDirectory(installProviderDir); } const std::string providerSchemaCacheDir = CPathBuilder::calcProviderSchemaCacheDir( providerNamespace, providerName, providerVersion); if (FileSystemUtils::doesDirectoryExist(providerSchemaCacheDir)) { FileSystemUtils::recursiveRemoveDirectory(providerSchemaCacheDir); } const std::string providerRegDir = AppConfigUtils::getRequiredString( _sProviderHostArea, _sConfigProviderRegDir); const std::string providerRegDirExp = CStringUtils::expandEnv(providerRegDir); const std::string providerRegFilename = providerFqn + ".xml"; const std::string providerRegPath = FileSystemUtils::buildPath(providerRegDirExp, providerRegFilename); if (FileSystemUtils::doesFileExist(providerRegPath)) { FileSystemUtils::removeFile(providerRegPath); } const std::string invokersDir = AppConfigUtils::getRequiredString( _sProviderHostArea, _sConfigInvokersDir); const std::string invokersDirExp = CStringUtils::expandEnv(invokersDir); const std::string invokersFilename = providerFqn; const std::string invokersPath = FileSystemUtils::buildPath(invokersDirExp, invokersFilename); if (FileSystemUtils::doesFileExist(invokersPath)) { FileSystemUtils::removeFile(invokersPath); } } std::string CProviderInstaller::calcProviderFqn( const SmartPtrCInstallProviderSpecDoc& installProviderSpec) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "calcProviderFqn"); CAF_CM_VALIDATE_SMARTPTR(installProviderSpec); return installProviderSpec->getProviderNamespace() + "_" + installProviderSpec->getProviderName() + "_" + installProviderSpec->getProviderVersion(); } std::string CProviderInstaller::calcProviderFqn( const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CProviderInstaller", "calcProviderFqn"); CAF_CM_VALIDATE_SMARTPTR(uninstallProviderJob); return uninstallProviderJob->getProviderNamespace() + "_" + uninstallProviderJob->getProviderName() + "_" + uninstallProviderJob->getProviderVersion(); } InstallProvider.cpp000066400000000000000000000012751321503522500367000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" using namespace Caf; namespace Caf { const char* _sInstallPackageSpecFilename = "installPackageSpec.xml"; const char* _sInstallProviderSpecFilename = "installProviderSpec.xml"; } int main(int csz, char* asz[]) { CAF_CM_STATIC_FUNC_LOG("InstallProvider", "main"); int rc = 0; try { CInstallProvider provider; rc = CProviderDriver::processProviderCommandline(provider, csz, asz); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; rc = CAF_CM_ISEXCEPTION ? 1 : rc; CAF_CM_CLEAREXCEPTION; return rc; } stdafx.h000066400000000000000000000010671321503522500345140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Install_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ //{{CAF_SUBSYSTEM}} #include #include #include #include namespace Caf { extern const char* _sInstallPackageSpecFilename; extern const char* _sInstallProviderSpecFilename; } #include "CInstallUtils.h" #include "CPathBuilder.h" #include "CPackageExecutor.h" #include "CInstallProvider.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/Makefile.am000066400000000000000000000117331321503522500311170ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ AUTOMAKE_OPTIONS = subdir-objects cafbindir = @CAF_PME_BIN_DIR@ cafbin_PROGRAMS = cafbin_PROGRAMS += ConfigProvider ConfigProvider_SOURCES= ConfigProvider_SOURCES += Config_Provider/src/CConfigProvider.cpp ConfigProvider_SOURCES += Config_Provider/src/CIniFileWithoutSection.cpp ConfigProvider_SOURCES += Config_Provider/src/ConfigProvider.cpp ConfigProvider_CPPFLAGS = ConfigProvider_CPPFLAGS += @GLIB2_CPPFLAGS@ ConfigProvider_CPPFLAGS += @LOG4CPP_CPPFLAGS@ ConfigProvider_CPPFLAGS += @SSL_CPPFLAGS@ ConfigProvider_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ ConfigProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include ConfigProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ProviderFx/ProviderFx/include ConfigProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/InternalProviders/Config_Provider/include ConfigProvider_LDADD = ConfigProvider_LDADD += @GLIB2_LIBS@ ConfigProvider_LDADD += @LOG4CPP_LIBS@ ConfigProvider_LDADD += -ldl ConfigProvider_LDADD += ../Framework/libFramework.la ConfigProvider_LDADD += ../ProviderFx/libProviderFx.la cafbin_PROGRAMS += InstallProvider InstallProvider_SOURCES= InstallProvider_SOURCES += Install_Provider/src/CInstallProvider.cpp InstallProvider_SOURCES += Install_Provider/src/CInstallUtils.cpp InstallProvider_SOURCES += Install_Provider/src/CPackageExecutor.cpp InstallProvider_SOURCES += Install_Provider/src/CPackageInstaller.cpp InstallProvider_SOURCES += Install_Provider/src/CPathBuilder.cpp InstallProvider_SOURCES += Install_Provider/src/CProviderInstaller.cpp InstallProvider_SOURCES += Install_Provider/src/InstallProvider.cpp InstallProvider_CPPFLAGS = InstallProvider_CPPFLAGS += @GLIB2_CPPFLAGS@ InstallProvider_CPPFLAGS += @LOG4CPP_CPPFLAGS@ InstallProvider_CPPFLAGS += @SSL_CPPFLAGS@ InstallProvider_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ InstallProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include InstallProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ProviderFx/ProviderFx/include InstallProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/InternalProviders/Install_Provider/include InstallProvider_LDADD = InstallProvider_LDADD += @GLIB2_LIBS@ InstallProvider_LDADD += @LOG4CPP_LIBS@ InstallProvider_LDADD += -ldl InstallProvider_LDADD += ../Framework/libFramework.la InstallProvider_LDADD += ../ProviderFx/libProviderFx.la cafbin_PROGRAMS += RemoteCommandProvider RemoteCommandProvider_SOURCES= RemoteCommandProvider_SOURCES += RemoteCommand_Provider/src/CRemoteCommandProvider.cpp RemoteCommandProvider_SOURCES += RemoteCommand_Provider/src/RemoteCommandProvider.cpp RemoteCommandProvider_CPPFLAGS = RemoteCommandProvider_CPPFLAGS += @GLIB2_CPPFLAGS@ RemoteCommandProvider_CPPFLAGS += @LOG4CPP_CPPFLAGS@ RemoteCommandProvider_CPPFLAGS += @SSL_CPPFLAGS@ RemoteCommandProvider_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ RemoteCommandProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include RemoteCommandProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ProviderFx/ProviderFx/include RemoteCommandProvider_LDADD = RemoteCommandProvider_LDADD += @GLIB2_LIBS@ RemoteCommandProvider_LDADD += @LOG4CPP_LIBS@ RemoteCommandProvider_LDADD += -ldl RemoteCommandProvider_LDADD += ../Framework/libFramework.la RemoteCommandProvider_LDADD += ../ProviderFx/libProviderFx.la cafbin_PROGRAMS += TestInfraProvider TestInfraProvider_SOURCES= TestInfraProvider_SOURCES += TestInfra_Provider/src/CTestInfraProvider.cpp TestInfraProvider_SOURCES += TestInfra_Provider/src/TestInfraProvider.cpp TestInfraProvider_CPPFLAGS = TestInfraProvider_CPPFLAGS += @GLIB2_CPPFLAGS@ TestInfraProvider_CPPFLAGS += @LOG4CPP_CPPFLAGS@ TestInfraProvider_CPPFLAGS += @SSL_CPPFLAGS@ TestInfraProvider_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ TestInfraProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include TestInfraProvider_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ProviderFx/ProviderFx/include TestInfraProvider_LDADD = TestInfraProvider_LDADD += @GLIB2_LIBS@ TestInfraProvider_LDADD += @LOG4CPP_LIBS@ TestInfraProvider_LDADD += -ldl TestInfraProvider_LDADD += ../Framework/libFramework.la TestInfraProvider_LDADD += ../ProviderFx/libProviderFx.la open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/RemoteCommand_Provider/000077500000000000000000000000001321503522500334625ustar00rootroot00000000000000src/000077500000000000000000000000001321503522500341725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/RemoteCommand_ProviderCRemoteCommandProvider.cpp000066400000000000000000000161051321503522500412510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/RemoteCommand_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Exception/CCafException.h" #include "CRemoteCommandProvider.h" #include "IProviderRequest.h" using namespace Caf; CRemoteCommandProvider::CRemoteCommandProvider() : CAF_CM_INIT_LOG("CRemoteCommandProvider") { } CRemoteCommandProvider::~CRemoteCommandProvider() { } const SmartPtrCSchemaDoc CRemoteCommandProvider::getSchema() const { std::deque m1Params; m1Params.push_back(CProviderDocHelper::createMethodParameter("scriptAttachmentName", PARAMETER_STRING, false)); m1Params.push_back(CProviderDocHelper::createMethodParameter("scriptParameters", PARAMETER_STRING, false)); m1Params.push_back(CProviderDocHelper::createMethodParameter("attachmentNames", PARAMETER_STRING, false)); std::deque m2Params; m2Params.push_back(CProviderDocHelper::createMethodParameter("inlineScript", PARAMETER_STRING, false)); m2Params.push_back(CProviderDocHelper::createMethodParameter("scriptParameters", PARAMETER_STRING, true, true)); m2Params.push_back(CProviderDocHelper::createMethodParameter("attachmentNames", PARAMETER_STRING, true, true)); std::deque methods; methods.push_back(CProviderDocHelper::createMethod("executeScript", m1Params)); methods.push_back(CProviderDocHelper::createMethod("executeInlineScript", m2Params)); std::deque actionClasses; actionClasses.push_back( CProviderDocHelper::createActionClass( "caf", "RemoteCommandActions", "1.0.0", SmartPtrCCollectMethodDoc(), methods)); return CProviderDocHelper::createSchema(std::deque(), actionClasses); } void CRemoteCommandProvider::collect(const IProviderRequest& request, IProviderResponse& response) const { CAF_CM_FUNCNAME("collect"); CAF_CM_EXCEPTIONEX_VA0(UnsupportedOperationException, E_NOTIMPL, "Collect not implemented for Remote Commands") } void CRemoteCommandProvider::invoke(const IProviderRequest& request, IProviderResponse& response) const { CAF_CM_FUNCNAME("invoke"); SmartPtrCProviderInvokeOperationDoc doc = request.getInvokeOperations(); CAF_CM_VALIDATE_SMARTPTR(doc); const SmartPtrCOperationDoc operation = doc->getOperation(); const std::string operationName = operation->getName(); const SmartPtrCParameterCollectionDoc parameterCollection = operation->getParameterCollection(); const std::string outputDir = doc->getOutputDir(); const std::string scriptResultsDir = FileSystemUtils::buildPath(outputDir, "scriptResults"); if (! FileSystemUtils::doesDirectoryExist(scriptResultsDir)) { FileSystemUtils::createDirectory(scriptResultsDir); } const std::deque scriptParameters = ParameterUtils::findOptionalParameterAsStringCollection("scriptParameters", parameterCollection); const std::deque attachmentNames = ParameterUtils::findOptionalParameterAsStringCollection("attachmentNames", parameterCollection); const std::string attachmentUris = createAttachmentUris( attachmentNames, request.getAttachments()); std::string scriptPath; if (operationName.compare("executeScript") == 0) { const std::string scriptAttachmentName = ParameterUtils::findRequiredParameterAsString("scriptAttachmentName", parameterCollection); SmartPtrCAttachmentDoc scriptAttachment = AttachmentUtils::findRequiredAttachment( scriptAttachmentName, request.getAttachments()); CAF_CM_VALIDATE_BOOL(scriptAttachment->getIsReference() == FALSE); const std::string attachmentUri = scriptAttachment->getUri(); UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(attachmentUri, uriRecord); CAF_CM_LOG_DEBUG_VA3("Parsed URI - Uri: %s, protocol: %s, address: %s", attachmentUri.c_str(), uriRecord.protocol.c_str(), uriRecord.address.c_str()); CAF_CM_VALIDATE_BOOL(uriRecord.protocol.compare("file") == 0); UriUtils::SFileUriRecord scriptFileUriRecord; UriUtils::parseFileAddress(uriRecord.address, scriptFileUriRecord); scriptPath = scriptFileUriRecord.path; } else if (operationName.compare("executeInlineScript") == 0) { const std::string inlineScript = ParameterUtils::findRequiredParameterAsString("inlineScript", parameterCollection); #ifdef WIN32 scriptPath = FileSystemUtils::buildPath(outputDir, "script.bat"); #else scriptPath = FileSystemUtils::buildPath(outputDir, "_script_"); #endif FileSystemUtils::saveTextFile(scriptPath, inlineScript); } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Invalid operation name (must be \'executeScript\' or \'executeInlineScript\') - %s", operationName.c_str()) } FileSystemUtils::chmod(scriptPath); executeScript(scriptPath, scriptResultsDir, scriptParameters, attachmentUris); } void CRemoteCommandProvider::executeScript( const std::string& scriptPath, const std::string& scriptResultsDir, const std::deque& scriptParameters, const std::string& attachmentUris) const { CAF_CM_FUNCNAME_VALIDATE("executeScript"); CAF_CM_VALIDATE_STRING(scriptPath); CAF_CM_VALIDATE_STRING(scriptResultsDir); // scriptParameters are optional // attachmentUris are optional Cdeqstr argv; argv.push_back(scriptPath); argv.push_back("-o"); argv.push_back(scriptResultsDir); if (! attachmentUris.empty()) { argv.push_back("-u"); argv.push_back(attachmentUris); } if (! scriptParameters.empty()) { for(TConstIterator scriptParameterIter(scriptParameters); scriptParameterIter; scriptParameterIter++) { argv.push_back(*scriptParameterIter); } } const std::string stdoutPath = FileSystemUtils::buildPath( scriptResultsDir, _sStdoutFilename); const std::string stderrPath = FileSystemUtils::buildPath( scriptResultsDir, _sStderrFilename); ProcessUtils::runSyncToFiles(argv, stdoutPath, stderrPath); } std::string CRemoteCommandProvider::createAttachmentUris( const std::deque& attachmentNames, const SmartPtrCAttachmentCollectionDoc& attachmentCollection) const { CAF_CM_FUNCNAME_VALIDATE("createAttachmentUris"); std::string rc; if (! attachmentNames.empty()) { CAF_CM_VALIDATE_SMARTPTR(attachmentCollection); rc += "\""; for(TConstIterator attachmentNameIter(attachmentNames); attachmentNameIter; attachmentNameIter++) { const std::string attachmentName = *attachmentNameIter; const SmartPtrCAttachmentDoc attachment = AttachmentUtils::findRequiredAttachment( attachmentName, attachmentCollection); rc += attachment->getName() + "^" + attachment->getUri() + "|"; } rc += "\""; } return rc; } CRemoteCommandProvider.h000066400000000000000000000027371321503522500407240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/RemoteCommand_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CRemoteCommandProvider_h_ #define CRemoteCommandProvider_h_ #include "IInvokedProvider.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" namespace Caf { /// Sends responses/errors back to the client. class CRemoteCommandProvider : public IInvokedProvider { public: CRemoteCommandProvider(); virtual ~CRemoteCommandProvider(); public: // IInvokedProvider const std::string getProviderNamespace() const { return "caf"; } const std::string getProviderName() const { return "RemoteCommandProvider"; } const std::string getProviderVersion() const { return "1.0.0"; } const SmartPtrCSchemaDoc getSchema() const; void collect(const IProviderRequest& request, IProviderResponse& response) const; void invoke(const IProviderRequest& request, IProviderResponse& response) const; private: void executeScript( const std::string& script, const std::string& scriptResultsDir, const std::deque& scriptParameters, const std::string& attachmentUris) const; std::string createAttachmentUris( const std::deque& attachmentNamesStr, const SmartPtrCAttachmentCollectionDoc& attachmentCollection) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CRemoteCommandProvider); }; } #endif // #ifndef CRemoteCommandProvider_h_ RemoteCommandProvider.cpp000066400000000000000000000010501321503522500411370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/RemoteCommand_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" using namespace Caf; int main(int csz, char* asz[]) { CAF_CM_STATIC_FUNC_LOG("RemoteCommandProvider", "main"); int rc = 0; try { CRemoteCommandProvider provider; rc = CProviderDriver::processProviderCommandline(provider, csz, asz); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; rc = CAF_CM_ISEXCEPTION ? 1 : rc; CAF_CM_CLEAREXCEPTION; return rc; } stdafx.h000066400000000000000000000005261321503522500356370ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/RemoteCommand_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ //{{CAF_SUBSYSTEM}} #include #include #include #include "CRemoteCommandProvider.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/TestInfra_Provider/000077500000000000000000000000001321503522500326275ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/TestInfra_Provider/src/000077500000000000000000000000001321503522500334165ustar00rootroot00000000000000CTestInfraProvider.cpp000066400000000000000000000132361321503522500375650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/TestInfra_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "Exception/CCafException.h" #include "CTestInfraProvider.h" #include "IProviderResponse.h" #include "IProviderRequest.h" using namespace Caf; CTestInfraProvider::CTestInfraProvider() : CAF_CM_INIT_LOG("CTestInfraProvider") { } CTestInfraProvider::~CTestInfraProvider() { } const SmartPtrCSchemaDoc CTestInfraProvider::getSchema() const { std::deque dc1Props; dc1Props.push_back(CProviderDocHelper::createClassProperty("name", PROPERTY_STRING, true)); dc1Props.push_back(CProviderDocHelper::createClassProperty("value", PROPERTY_STRING, true)); std::deque dataClasses; dataClasses.push_back(CProviderDocHelper::createDataClass("cafTestInfra", "TestDataClass", "1.0.0", dc1Props)); std::deque m1Params; m1Params.push_back(CProviderDocHelper::createMethodParameter("requestAttachmentName", PARAMETER_STRING, false)); std::deque m2Params; m2Params.push_back(CProviderDocHelper::createMethodParameter("param1", PARAMETER_STRING, false)); m2Params.push_back(CProviderDocHelper::createMethodParameter("param2", PARAMETER_STRING, false)); std::deque methods; methods.push_back(CProviderDocHelper::createMethod("echoRequest", m1Params)); methods.push_back(CProviderDocHelper::createMethod("testMethod", m2Params)); std::deque actionClasses; actionClasses.push_back( CProviderDocHelper::createActionClass( "cafTestInfra", "TestActionClass", "1.0.0", CProviderDocHelper::createCollectMethod("collectInstances"), methods)); return CProviderDocHelper::createSchema(dataClasses, actionClasses); } void CTestInfraProvider::collect(const IProviderRequest& request, IProviderResponse& response) const { CAF_CM_ENTER { const SmartPtrCDataClassInstanceDoc dataClassInstance = createDataClassInstance("testName", "testValue"); response.addInstance(dataClassInstance); } CAF_CM_EXIT; } void CTestInfraProvider::invoke(const IProviderRequest& request, IProviderResponse& response) const { CAF_CM_FUNCNAME("invoke"); CAF_CM_ENTER { SmartPtrCProviderInvokeOperationDoc doc = request.getInvokeOperations(); CAF_CM_VALIDATE_SMARTPTR(doc); const SmartPtrCOperationDoc operation = doc->getOperation(); const std::string operationName = operation->getName(); const SmartPtrCParameterCollectionDoc parameterCollection = operation->getParameterCollection(); if (operationName.compare("testMethod") == 0) { const std::string param1 = ParameterUtils::findRequiredParameterAsString( "param1", parameterCollection); const std::string param2Str = ParameterUtils::findRequiredParameterAsString( "param2", parameterCollection); const int32 param2 = CStringConv::fromString(param2Str); CAF_CM_LOG_DEBUG_VA2("testMethod() called - param1: %s, param2: %d", param1.c_str(), param2); } else if (operationName.compare("echoRequest") == 0) { const std::string requestAttachmentName = ParameterUtils::findRequiredParameterAsString( "requestAttachmentName", parameterCollection); SmartPtrCAttachmentCollectionDoc attachmentCollection = request.getAttachments(); if (attachmentCollection.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Attachment collection is empty - %s", requestAttachmentName.c_str()) } SmartPtrCAttachmentDoc attachmentFnd; const std::deque attachmentCollectionInner = attachmentCollection->getAttachment(); for (TConstIterator > attachmentIter(attachmentCollectionInner); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; const std::string attachmentName = attachment->getName(); if (attachmentName.compare(requestAttachmentName) == 0) { attachmentFnd = attachment; } } if (attachmentFnd.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Request Attachment not found - %s", requestAttachmentName.c_str()) } response.addAttachment(attachmentFnd); } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Invalid operation name (must be \'echoRequest\') - %s", operationName.c_str()) } } CAF_CM_EXIT; } SmartPtrCDataClassInstanceDoc CTestInfraProvider::createDataClassInstance( const std::string& name, const std::string& value) const { CAF_CM_FUNCNAME_VALIDATE("createDataClassInstance"); CAF_CM_VALIDATE_STRING(name); CAF_CM_VALIDATE_STRING(value); std::deque dataClassProperties; dataClassProperties.push_back(CProviderDocHelper::createDataClassProperty("name", name)); dataClassProperties.push_back(CProviderDocHelper::createDataClassProperty("value", value)); return CProviderDocHelper::createDataClassInstance( "cafTestInfra", "TestDataClass", "1.0.0", dataClassProperties); } CTestInfraProvider.h000066400000000000000000000023451321503522500372310ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/TestInfra_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CTestInfraProvider_h_ #define CTestInfraProvider_h_ #include "IInvokedProvider.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" namespace Caf { /// Sends responses/errors back to the client. class CTestInfraProvider : public IInvokedProvider { public: CTestInfraProvider(); virtual ~CTestInfraProvider(); public: // IInvokedProvider const std::string getProviderNamespace() const { return "cafTestInfra"; } const std::string getProviderName() const { return "CafTestInfraProvider"; } const std::string getProviderVersion() const { return "1.0.0"; } const SmartPtrCSchemaDoc getSchema() const; void collect(const IProviderRequest& request, IProviderResponse& response) const; void invoke(const IProviderRequest& request, IProviderResponse& response) const; private: SmartPtrCDataClassInstanceDoc createDataClassInstance( const std::string& name, const std::string& value) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CTestInfraProvider); }; } #endif // #ifndef CTestInfraProvider_h_ TestInfraProvider.cpp000066400000000000000000000010401321503522500374500ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/TestInfra_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" using namespace Caf; int main(int csz, char* asz[]) { CAF_CM_STATIC_FUNC_LOG("TestInfraProvider", "main"); int rc = 0; try { CTestInfraProvider provider; rc = CProviderDriver::processProviderCommandline(provider, csz, asz); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; rc = CAF_CM_ISEXCEPTION ? 1 : rc; CAF_CM_CLEAREXCEPTION; return rc; } stdafx.h000066400000000000000000000005571321503522500350100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/InternalProviders/TestInfra_Provider/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ //{{CAF_SUBSYSTEM}} #include #include #include #include "../../TestInfra_Provider/src/CTestInfraProvider.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/000077500000000000000000000000001321503522500264375ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Makefile.am000066400000000000000000000176401321503522500305030ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016-2017 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ AUTOMAKE_OPTIONS = subdir-objects subsysdir = @CAF_SUBSYS_DIR@ subsys_LTLIBRARIES = cafbindir = @CAF_PME_BIN_DIR@ cafbin_PROGRAMS = subsys_LTLIBRARIES += libMaIntegrationSubsys.la libMaIntegrationSubsys_la_LDFLAGS = @CAF_SUBSYS_LDFLAGS@ libMaIntegrationSubsys_la_SOURCES= libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CAttachmentRequestTransformer.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CAttachmentRequestTransformerInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CCollectSchemaExecutor.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CConfigEnv.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CConfigEnvInboundChannelAdapterInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CConfigEnvMerge.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CConfigEnvMessageHandler.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CConfigEnvOutboundChannelAdapterInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CConfigEnvReadingMessageSource.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CDiagToMgmtRequestTransformer.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CDiagToMgmtRequestTransformerInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CInstallToMgmtRequestTransformer.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CInstallToMgmtRequestTransformerInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CMonitorInboundChannelAdapterInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CMonitorListener.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CMonitorReadingMessageSource.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CPersistenceInboundChannelAdapterInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CPersistenceMerge.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CPersistenceMessageHandler.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CPersistenceNamespaceDb.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CPersistenceOutboundChannelAdapterInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CPersistenceReadingMessageSource.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CProviderCollectSchemaExecutor.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CProviderExecutor.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CProviderExecutorRequest.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CProviderExecutorRequestHandler.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CResponseFactory.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CSchemaCacheManager.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CSinglePmeRequestSplitter.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CSinglePmeRequestSplitterInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CVersionTransformer.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/CVersionTransformerInstance.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/IntegrationObjects.cpp libMaIntegrationSubsys_la_SOURCES += Subsystems/MaIntegration/src/MaIntegration.cpp libMaIntegrationSubsys_la_CPPFLAGS = libMaIntegrationSubsys_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libMaIntegrationSubsys_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libMaIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libMaIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Subsystems/CafIntegration/include libMaIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ManagementAgent/ManagementAgent/include libMaIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include libMaIntegrationSubsys_la_LIBADD = libMaIntegrationSubsys_la_LIBADD += @GLIB2_LIBS@ libMaIntegrationSubsys_la_LIBADD += @LOG4CPP_LIBS@ libMaIntegrationSubsys_la_LIBADD += -ldl libMaIntegrationSubsys_la_LIBADD += ../Framework/libFramework.la libMaIntegrationSubsys_la_LDFLAGS += -shared cafbin_PROGRAMS += ManagementAgentHost ManagementAgentHost_SOURCES= ManagementAgentHost_SOURCES += ManagementAgent/src/CManagementAgentHostWork.cpp ManagementAgentHost_SOURCES += ManagementAgent/src/ManagementAgentHost.cpp ManagementAgentHost_SOURCES += ManagementAgent/src/ManagementAgentHostMain.cpp ManagementAgentHost_CPPFLAGS = ManagementAgentHost_CPPFLAGS += @GLIB2_CPPFLAGS@ ManagementAgentHost_CPPFLAGS += @LOG4CPP_CPPFLAGS@ ManagementAgentHost_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include ManagementAgentHost_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ManagementAgent/ManagementAgent/include ManagementAgentHost_LDADD = ManagementAgentHost_LDADD += @GLIB2_LIBS@ ManagementAgentHost_LDADD += @LOG4CPP_LIBS@ ManagementAgentHost_LDADD += -ldl ManagementAgentHost_LDADD += ../Framework/libFramework.la ManagementAgentHost_LDADD += $(top_builddir)/vgauth/lib/libvgauth.la subsys_LTLIBRARIES += libVgAuthIntegrationSubsys.la libVgAuthIntegrationSubsys_la_LDFLAGS = @CAF_SUBSYS_LDFLAGS@ libVgAuthIntegrationSubsys_la_SOURCES= libVgAuthIntegrationSubsys_la_SOURCES += Subsystems/VgAuth/src/CGuestAuthenticator.cpp libVgAuthIntegrationSubsys_la_SOURCES += Subsystems/VgAuth/src/CGuestAuthenticatorInstance.cpp libVgAuthIntegrationSubsys_la_SOURCES += Subsystems/VgAuth/src/CVgAuthContext.cpp libVgAuthIntegrationSubsys_la_SOURCES += Subsystems/VgAuth/src/CVgAuthError.cpp libVgAuthIntegrationSubsys_la_SOURCES += Subsystems/VgAuth/src/CVgAuthImpersonation.cpp libVgAuthIntegrationSubsys_la_SOURCES += Subsystems/VgAuth/src/CVgAuthInitializer.cpp libVgAuthIntegrationSubsys_la_SOURCES += Subsystems/VgAuth/src/CVgAuthUserHandle.cpp libVgAuthIntegrationSubsys_la_SOURCES += Subsystems/VgAuth/src/VgAuthIntegration.cpp libVgAuthIntegrationSubsys_la_CPPFLAGS = libVgAuthIntegrationSubsys_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libVgAuthIntegrationSubsys_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libVgAuthIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/vgauth/public libVgAuthIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libVgAuthIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ManagementAgent/ManagementAgent/include libVgAuthIntegrationSubsys_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/include libVgAuthIntegrationSubsys_la_LIBADD = libVgAuthIntegrationSubsys_la_LIBADD += @GLIB2_LIBS@ libVgAuthIntegrationSubsys_la_LIBADD += @LOG4CPP_LIBS@ libVgAuthIntegrationSubsys_la_LIBADD += -ldl libVgAuthIntegrationSubsys_la_LIBADD += ../Framework/libFramework.la libVgAuthIntegrationSubsys_la_LIBADD += $(top_builddir)/vgauth/lib/libvgauth.la libVgAuthIntegrationSubsys_la_LDFLAGS += -shared open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/ManagementAgent/000077500000000000000000000000001321503522500314725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/ManagementAgent/include/000077500000000000000000000000001321503522500331155ustar00rootroot00000000000000CManagementAgentHostWork.h000066400000000000000000000013761321503522500400550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/ManagementAgent/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CManagementAgentHostWork_h_ #define CManagementAgentHostWork_h_ #include "Common/IWork.h" namespace Caf { /// Sends responses/errors back to the client. class CManagementAgentHostWork : public IWork { public: CManagementAgentHostWork(); virtual ~CManagementAgentHostWork(); public: void initialize(); public: // IWork void doWork(); void stopWork(); private: bool _isInitialized; bool _isWorking; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CManagementAgentHostWork); }; CAF_DECLARE_SMART_POINTER(CManagementAgentHostWork); } #endif // #ifndef CManagementAgentHostWork_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/ManagementAgent/src/000077500000000000000000000000001321503522500322615ustar00rootroot00000000000000CManagementAgentHostWork.cpp000066400000000000000000000037541321503522500375560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/ManagementAgent/src/* * Author: bwilliams * Created: June 29, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntegrationAppContext.h" #include "CManagementAgentHostWork.h" #include "Common/CLoggingUtils.h" using namespace Caf; CManagementAgentHostWork::CManagementAgentHostWork() : _isInitialized(false), _isWorking(false), CAF_CM_INIT_LOG("CManagementAgentHostWork") { } CManagementAgentHostWork::~CManagementAgentHostWork() { } void CManagementAgentHostWork::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } void CManagementAgentHostWork::doWork() { CAF_CM_FUNCNAME("doWork"); SmartPtrCIntegrationAppContext integrationAppContext; uint32 hostIntegrationTimeoutMs = 5000; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _isWorking = true; CLoggingUtils::setStartupConfigFile( AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile), AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogDir)); const uint32 hostDelaySec = AppConfigUtils::getRequiredUint32( _sManagementAgentArea, "host_delay_sec"); hostIntegrationTimeoutMs = AppConfigUtils::getRequiredUint32( _sManagementAgentArea, "host_integration_timeout_ms"); integrationAppContext.CreateInstance(); integrationAppContext->initialize(hostIntegrationTimeoutMs); while (_isWorking) { CThreadUtils::sleep(hostDelaySec * 1000); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; try { if (! integrationAppContext.IsNull()) { integrationAppContext->terminate(hostIntegrationTimeoutMs); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_THROWEXCEPTION; } void CManagementAgentHostWork::stopWork() { CAF_CM_FUNCNAME_VALIDATE("stopWork"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _isWorking = false; } CAF_CM_EXIT; } ManagementAgentHost.cpp000066400000000000000000000004231321503522500365760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/ManagementAgent/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" extern "C" { BOOL APIENTRY DllMain(HMODULE hModule, uint32 dwReason, LPVOID lpReserved) { return TRUE; } } ManagementAgentHostMain.cpp000066400000000000000000000106131321503522500374050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/ManagementAgent/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CManagementAgentHostWork.h" #include "Common/CLoggingUtils.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #ifndef WIN32 #include #endif bool _gDaemonized = true; bool _gSysLogInfos = false; SmartPtrCManagementAgentHostWork _gManagementAgentHostWork; using namespace Caf; #ifndef WIN32 extern "C" void TermHandler(int32 signum); #endif int32 main(int32 argc, char** argv) { HRESULT hr = CafInitialize::init(); if (hr != S_OK) { #ifndef WIN32 ::syslog(LOG_ERR, "ManagementAgentHost: CafInitialize::init() failed 0x%08X.", hr); #endif ::fprintf(stderr, "ManagementAgentHost: CafInitialize::init() failed 0x%08X\n", hr); return 1; } SmartPtrIAppConfig appConfig; try { CafInitialize::serviceConfig(); std::string appConfigEnv; CEnvironmentUtils::readEnvironmentVar("CAF_APPCONFIG", appConfigEnv); if (appConfigEnv.empty()) { Cdeqstr deqstr; deqstr.push_back("cafenv-appconfig"); deqstr.push_back("persistence-appconfig"); deqstr.push_back("ma-appconfig"); deqstr.push_back("custom-appconfig"); appConfig = getAppConfig(deqstr); } else { appConfig = getAppConfig(); } } catch(CCafException *ex) { #ifndef WIN32 ::syslog( LOG_ERR, "ManagementAgentHost: getAppConfig() failed . %s", ex->getFullMsg().c_str()); #endif ::fprintf( stderr, "ManagementAgentHost: getAppConfig() failed . %s\n", ex->getFullMsg().c_str()); ex->Release(); } catch (std::exception ex) { #ifndef WIN32 ::syslog( LOG_ERR, "ManagementAgentHost: getAppConfig() failed . %s", ex.what()); #endif ::fprintf( stderr, "ManagementAgentHost: getAppConfig() failed . %s\n", ex.what()); } catch (...) { #ifndef WIN32 ::syslog( LOG_ERR, "ManagementAgentHost: getAppConfig() failed . unknown exception"); #endif ::fprintf( stderr, "ManagementAgentHost: getAppConfig() failed . unknown exception\n"); } CAF_CM_STATIC_FUNC_LOG("ManagementAgentHostMain", "main"); int32 iRc = 0; try { if (!appConfig) { CafInitialize::term(); return 1; } const std::string cafBinDir = AppConfigUtils::getRequiredString("globals", "bin_dir"); g_setenv("CAF_BIN_DIR", cafBinDir.c_str(), TRUE); const std::string cafLibDir = AppConfigUtils::getRequiredString("globals", "lib_dir"); g_setenv("CAF_LIB_DIR", cafLibDir.c_str(), TRUE); _gManagementAgentHostWork.CreateInstance(); _gManagementAgentHostWork->initialize(); const uint32 maxStrLen = 4096; if ((argc < 1) || (NULL == argv) || (NULL == argv[0]) || (::strnlen(argv[0], maxStrLen) >= maxStrLen)) { CAF_CM_EXCEPTION_VA0(E_INVALIDARG, "argc/argv are invalid"); } #ifdef WIN32 CWinService::initialize(_gManagementAgentHostWork); CWinService::execute(argc, argv); #else if (S_OK != hr) { ::syslog(LOG_ERR, "CafInitialize::init() failed (0x%08X.", hr); return 1; } const std::string procPath(argv[0]); CDaemonUtils::MakeDaemon( argc, argv, procPath, "ManagementAgentHost", TermHandler, _gDaemonized, _gSysLogInfos); CLoggingUtils::setStartupConfigFile( AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogConfigFile), AppConfigUtils::getRequiredString(_sAppConfigGlobalParamLogDir)); _gManagementAgentHostWork->doWork(); #endif } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; if (CAF_CM_ISEXCEPTION) { const std::string msg = CAF_CM_EXCEPTION_GET_FULLMSG; #ifndef WIN32 ::syslog( LOG_ERR, "ManagementAgentHost: %s", msg.c_str()); #endif ::fprintf( stderr, "ManagementAgentHost: %s\n", msg.c_str()); iRc = 1; } CAF_CM_CLEAREXCEPTION; CafInitialize::term(); return iRc; } #ifndef WIN32 extern "C" void TermHandler(int32 signum) { CAF_CM_STATIC_FUNC_LOG_ONLY( "ManagementAgentHost", "TermHandler" ); CAF_CM_ENTER { switch (signum) { case SIGTERM: CAF_CM_LOG_INFO_VA0( "Received SIGTERM" ); if (! _gManagementAgentHostWork.IsNull()) { _gManagementAgentHostWork->stopWork(); } break; case SIGINT: CAF_CM_LOG_INFO_VA0( "Received SIGINT" ); if (! _gManagementAgentHostWork.IsNull()) { _gManagementAgentHostWork->stopWork(); } break; default: CAF_CM_LOG_ERROR_VA1( "Ignoring Unexpected signal %d", signum); break; } } CAF_CM_EXIT; } #endif stdafx.h000066400000000000000000000004651321503522500336510ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/ManagementAgent/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ #include #include #ifdef WIN32 #include "CWinService.h" #endif #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/000077500000000000000000000000001321503522500306205ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/000077500000000000000000000000001321503522500333615ustar00rootroot00000000000000include/000077500000000000000000000000001321503522500347255ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegrationCAttachmentRequestTransformerInstance.h000066400000000000000000000045411321503522500445560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAttachmentRequestTransformerInstance_h_ #define CAttachmentRequestTransformerInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CAttachmentRequestTransformerInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: struct SExpandedFileAlias { std::string _filePath; std::string _encoding; }; CAF_DECLARE_SMART_POINTER(SExpandedFileAlias); public: CAttachmentRequestTransformerInstance(); virtual ~CAttachmentRequestTransformerInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdAttachmentRequestTransformerInstance) CAF_BEGIN_INTERFACE_MAP(CAttachmentRequestTransformerInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: std::string calcOutputDirPath( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope) const; std::string calcFilePath( const UriUtils::SUriRecord& uriRecord) const; std::string calcRelPath( const std::string& filePath, const UriUtils::SUriRecord& uriRecord) const; void moveFile( const std::string& srcFilePath, const std::string& dstFilePath) const; private: bool _isInitialized; std::string _id; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CAttachmentRequestTransformerInstance); }; } #endif // #ifndef CAttachmentRequestTransformerInstance_h_ CConfigEnvReadingMessageSource.h000066400000000000000000000024141321503522500430400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CConfigEnvReadingMessageSource_h_ #define _MaIntegration_CConfigEnvReadingMessageSource_h_ #include "IConfigEnv.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/Core/CAbstractPollableChannel.h" namespace Caf { class CConfigEnvReadingMessageSource : public CAbstractPollableChannel { private: typedef std::map CFileCollection; CAF_DECLARE_SMART_POINTER(CFileCollection); public: CConfigEnvReadingMessageSource(); virtual ~CConfigEnvReadingMessageSource(); public: void initialize( const SmartPtrIDocument& configSection, const SmartPtrIConfigEnv& configEnv); protected: // CAbstractPollableChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); SmartPtrIIntMessage doReceive(const int32 timeout); private: bool _isInitialized; std::string _id; SmartPtrIConfigEnv _configEnv; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CConfigEnvReadingMessageSource); }; CAF_DECLARE_SMART_POINTER(CConfigEnvReadingMessageSource); } #endif // #ifndef _MaIntegration_CConfigEnvReadingMessageSource_h_ CDiagToMgmtRequestTransformerInstance.h000066400000000000000000000073261321503522500444660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CDiagToMgmtRequestTransformerInstance_h_ #define CDiagToMgmtRequestTransformerInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "CEnvelopeToPayloadTransformerInstance.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/DiagTypesDoc/CDiagCollectInstancesDoc.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CDiagToMgmtRequestTransformerInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: struct SExpandedFileAlias { std::string _filePath; std::string _encoding; }; CAF_DECLARE_SMART_POINTER(SExpandedFileAlias); public: CDiagToMgmtRequestTransformerInstance(); virtual ~CDiagToMgmtRequestTransformerInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdDiagToMgmtRequestTransformerInstance) CAF_BEGIN_INTERFACE_MAP(CDiagToMgmtRequestTransformerInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: SmartPtrCMgmtCollectInstancesCollectionDoc createMgmtCollectInstancesCollection( const SmartPtrCDiagCollectInstancesDoc& diagCollectInstances) const; SmartPtrCMgmtInvokeOperationCollectionDoc createMgmtInvokeOperationCollection( const SmartPtrCDiagSetValueCollectionDoc& diagSetValueCollection, const SmartPtrCDiagDeleteValueCollectionDoc& diagDeleteValueCollection) const; SmartPtrCMgmtCollectInstancesDoc createCollectInstances( const UUID& jobId, const SmartPtrSExpandedFileAlias& expandedFileAlias) const; SmartPtrCOperationDoc createSetValueOperation( const std::string& valueName, const std::deque& valueCollection, const SmartPtrSExpandedFileAlias& expandedFileAlias) const; SmartPtrCOperationDoc createDeleteValueOperation( const std::string& valueName, const SmartPtrSExpandedFileAlias& expandedFileAlias) const; SmartPtrCMgmtInvokeOperationDoc createInvokeOperation( const UUID& jobId, const SmartPtrCOperationDoc operation) const; std::deque expandFileAliases() const; SmartPtrSExpandedFileAlias expandFileAlias( const std::string& fileAlias) const; std::string findUriParameter( const std::string& parameterName, const UriUtils::SUriRecord& uri) const; private: bool _isInitialized; std::string _id; std::string _fileAliasPrefix; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CDiagToMgmtRequestTransformerInstance); }; } #endif // #ifndef CDiagToMgmtRequestTransformerInstance_h_ CMonitorReadingMessageSource.h000066400000000000000000000040241321503522500426100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CMonitorReadingMessageSource_h_ #define _MaIntegration_CMonitorReadingMessageSource_h_ #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/Core/CAbstractPollableChannel.h" namespace Caf { class CMonitorReadingMessageSource : public CAbstractPollableChannel { private: typedef std::map CFileCollection; CAF_DECLARE_SMART_POINTER(CFileCollection); public: CMonitorReadingMessageSource(); virtual ~CMonitorReadingMessageSource(); public: void initialize( const SmartPtrIDocument& configSection); protected: // CAbstractPollableChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); SmartPtrIIntMessage doReceive(const int32 timeout); private: bool isListenerRunning() const; void startListener( const std::string& reason) const; void stopListener( const std::string& reason) const; void restartListener( const std::string& reason) const; std::string executeScript( const std::string& scriptPath, const std::string& scriptResultsDir) const; bool areSystemResourcesLow() const; bool isTimeForListenerRestart() const; uint64 calcListenerRestartMs() const; private: bool _isInitialized; std::string _id; uint64 _listenerStartTimeMs; uint64 _listenerRestartMs; std::string _monitorDir; std::string _restartListenerPath; std::string _listenerConfiguredStage2Path; std::string _scriptOutputDir; std::string _stopListenerScript; std::string _startListenerScript; std::string _isListenerRunningScript; std::string _listenerStartupType; int32 _listenerRetryCnt; int32 _listenerRetryMax; SmartPtrCMonitorListener _monitorListener; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CMonitorReadingMessageSource); }; CAF_DECLARE_SMART_POINTER(CMonitorReadingMessageSource); } #endif // #ifndef _MaIntegration_CMonitorReadingMessageSource_h_ CPersistenceReadingMessageSource.h000066400000000000000000000024461321503522500434530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CPersistenceReadingMessageSource_h_ #define _MaIntegration_CPersistenceReadingMessageSource_h_ #include "IPersistence.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/Core/CAbstractPollableChannel.h" namespace Caf { class CPersistenceReadingMessageSource : public CAbstractPollableChannel { private: typedef std::map CFileCollection; CAF_DECLARE_SMART_POINTER(CFileCollection); public: CPersistenceReadingMessageSource(); virtual ~CPersistenceReadingMessageSource(); public: void initialize( const SmartPtrIDocument& configSection, const SmartPtrIPersistence& persistence); protected: // CAbstractPollableChannel bool doSend( const SmartPtrIIntMessage& message, int32 timeout); SmartPtrIIntMessage doReceive(const int32 timeout); private: bool _isInitialized; std::string _id; SmartPtrIPersistence _persistence; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CPersistenceReadingMessageSource); }; CAF_DECLARE_SMART_POINTER(CPersistenceReadingMessageSource); } #endif // #ifndef _MaIntegration_CPersistenceReadingMessageSource_h_ CProviderExecutorRequest.h000066400000000000000000000021021321503522500420560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: brets * Created: Nov 20, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderExecutorRequest_h_ #define CProviderExecutorRequest_h_ #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Integration/IIntMessage.h" namespace Caf { /// TODO - describe class class CProviderExecutorRequest { public: CProviderExecutorRequest(); virtual ~CProviderExecutorRequest(); public: void initialize(const SmartPtrIIntMessage& request); const SmartPtrIIntMessage getInternalRequest() const; const SmartPtrCProviderRequestDoc getRequest() const; const std::string& getOutputDirectory() const; const std::string& getProviderUri() const; private: bool _isInitialized; SmartPtrIIntMessage _internalRequest; SmartPtrCProviderRequestDoc _request; std::string _outputDir; std::string _providerUri; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CProviderExecutorRequest); }; CAF_DECLARE_SMART_POINTER(CProviderExecutorRequest); } #endif // #ifndef CProviderExecutorRequest_h_ CProviderExecutorRequestHandler.h000066400000000000000000000037051321503522500433660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: brets * Created: Nov 20, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderExecutorRequestHandler_h_ #define CProviderExecutorRequestHandler_h_ #include "Integration/IRunnable.h" #include "CProviderExecutorRequest.h" #include "Common/CAutoMutex.h" #include "Integration/IErrorHandler.h" #include "Integration/ITaskExecutor.h" #include "Integration/ITransformer.h" namespace Caf { /// TODO - describe class class CProviderExecutorRequestHandler : public IRunnable { public: CProviderExecutorRequestHandler(); virtual ~CProviderExecutorRequestHandler(); public: void initialize(const std::string& providerUri, const SmartPtrITransformer beginImpersonationTransformer, const SmartPtrITransformer endImpersonationTransformer, const SmartPtrIErrorHandler errorHandler); void handleRequest(const SmartPtrCProviderExecutorRequest request); public: // IRunnable void run(); void cancel(); private: SmartPtrCProviderExecutorRequest getNextPendingRequest(); void processRequest(const SmartPtrCProviderExecutorRequest& request) const; void executeRequestAsync( const SmartPtrCProviderExecutorRequest& request); std::deque removeFinishedTaskExecutors( const std::deque taskExecutors) const; private: bool _isInitialized; bool _isCancelled; std::string _providerPath; std::string _providerUri; std::deque _taskExecutors; SmartPtrCAutoMutex _mutex; std::deque _pendingRequests; SmartPtrITransformer _beginImpersonationTransformer; SmartPtrITransformer _endImpersonationTransformer; SmartPtrIErrorHandler _errorHandler; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CProviderExecutorRequestHandler); }; CAF_DECLARE_SMART_POINTER(CProviderExecutorRequestHandler); } #endif // #ifndef CProviderExecutorRequestHandler_h_ CResponseFactory.h000066400000000000000000000054311321503522500403320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CResponseFactory_h_ #define CResponseFactory_h_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ResponseDoc/CManifestCollectionDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" namespace Caf { /// Builds the response XML document. class CResponseFactory { public: static SmartPtrCResponseDoc createResponse( const SmartPtrCProviderCollectSchemaRequestDoc& providerCollectSchemaRequest, const std::string& outputDir, const std::string& schemaCacheDir); static SmartPtrCResponseDoc createResponse( const SmartPtrCProviderRequestDoc& providerRequest, const std::string& outputDir); private: static void findAndStoreGlobalAttachmentsAndProviderResponses( const std::string& outputDir, const std::string& schemaCacheDir, SmartPtrCManifestCollectionDoc& manifestCollection, SmartPtrCAttachmentCollectionDoc& attachmentCollection); static void findAndStoreProviderResponses( const std::string& outputDir, const std::string& schemaCacheDir, std::map& globalAttachmentCollection, std::deque& manifestCollection); static void findAndStoreGlobalAttachments( const std::string& outputDir, std::map& globalAttachmentCollection); static void resolveAndStoreGlobalAttachments( const std::deque attachmentCollectionInner, const std::string& outputDir, const std::string& schemaCacheDir, std::map& globalAttachmentCollection); static void storeGlobalAttachments( const std::string& attachmentName, const std::string& attachmentType, const std::deque& attachmentPathCollection, const std::string& baseDir, std::map& attachmentCollection); static void storeGlobalAttachment( const std::string& attachmentName, const std::string& attachmentType, const std::string& attachmentPath, const std::string& baseDir, std::map& attachmentCollection); static void resolveAttachmentPath( const std::string& attachmentPath, const std::string& baseDir, std::string& relPath, std::string& attachmentPathNew); static std::string removeLeadingChars( const std::string& sourceStr, const char leadingChar); private: CAF_CM_DECLARE_NOCREATE(CResponseFactory); }; CAF_DECLARE_SMART_POINTER(CResponseFactory); } #endif // #ifndef CResponseFactory_h_ CSchemaCacheManager.h000066400000000000000000000031531321503522500406220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CSchemaCacheManager_h_ #define CSchemaCacheManager_h_ #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" namespace Caf { /// Simple container class for identifying a class. class CClassId { public: SmartPtrCFullyQualifiedClassGroupDoc _fqc; std::string toString() const { return _fqc->getClassNamespace() + "::" + _fqc->getClassName() + "::" + _fqc->getClassVersion(); } }; bool operator< (const CClassId& lhs, const CClassId& rhs); /// Creates a provider request. class CSchemaCacheManager { private: typedef std::map CClassCollection; public: CSchemaCacheManager(); virtual ~CSchemaCacheManager(); public: void initialize(); std::string findProvider( const SmartPtrCFullyQualifiedClassGroupDoc& fqc); private: void processSchemaSummaries( const std::string& schemaCacheDirPath, CClassCollection& classCollection) const; void addNewClasses( const SmartPtrCSchemaSummaryDoc& schemaSummary, const std::string& schemaSummaryFilePath, CClassCollection& classCollection) const; void waitForSchemaCacheCreation( const std::string& schemaCacheDir, const uint16 maxWaitSecs) const; private: bool _isInitialized; std::string _schemaCacheDirPath; CClassCollection _classCollection; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CSchemaCacheManager); }; CAF_DECLARE_SMART_POINTER(CSchemaCacheManager); } #endif // #ifndef CSchemaCacheManager_h_ CSinglePmeRequestSplitterInstance.h000066400000000000000000000113341321503522500436530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CSinglePmeRequestSplitterInstance_h_ #define CSinglePmeRequestSplitterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "CSchemaCacheManager.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectSchemaDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageSplitter.h" namespace Caf { // Moved the following typedefs from the class because Windows produced // the warning "decorated name length exceeded, name was truncated" because // their name included CSinglePmeRequestSplitterInstance. struct CSplitterJob { SmartPtrCFullyQualifiedClassGroupDoc _fqc; SmartPtrCMgmtCollectInstancesDoc _mgmtCollectInstances; SmartPtrCMgmtInvokeOperationDoc _mgmtInvokeOperation; }; CAF_DECLARE_SMART_POINTER(CSplitterJob); typedef std::deque CSplitterJobsCollection; CAF_DECLARE_SMART_POINTER(CSplitterJobsCollection); typedef std::map CProviderJobsCollection; CAF_DECLARE_SMART_POINTER(CProviderJobsCollection); class CSinglePmeRequestSplitterInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public IMessageSplitter { private: typedef std::deque CClassCollection; CAF_DECLARE_SMART_POINTER(CClassCollection); public: CSinglePmeRequestSplitterInstance(); virtual ~CSinglePmeRequestSplitterInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdSinglePmeRequestSplitterInstance) CAF_BEGIN_INTERFACE_MAP(CSinglePmeRequestSplitterInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(IMessageSplitter) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // IMessageSplitter SmartPtrCMessageCollection splitMessage( const SmartPtrIIntMessage& message); private: SmartPtrCProviderCollectSchemaRequestDoc createCollectSchemaRequest( const SmartPtrCMgmtRequestDoc& mgmtRequest, const SmartPtrCMgmtCollectSchemaDoc& mgmtCollectSchema, const SmartPtrCProviderRequestHeaderDoc& providerRequestHeader, const std::string& outputDir) const; SmartPtrCProviderRequestDoc createProviderRequest( const SmartPtrCMgmtRequestDoc& mgmtRequest, const SmartPtrCSplitterJobsCollection& jobsCollection, const SmartPtrCProviderRequestHeaderDoc& providerRequestHeader, const std::string& outputDir) const; void addCollectInstancesJobs( const SmartPtrCMgmtCollectInstancesCollectionDoc& mgmtCollectInstancesCollection, SmartPtrCProviderJobsCollection& providerJobsCollection) const; void addInvokeOperationJobs( const SmartPtrCMgmtInvokeOperationCollectionDoc& mgmtInvokeOperationCollection, SmartPtrCProviderJobsCollection& providerJobsCollection) const; SmartPtrCClassCollection resolveClassSpecifier( const SmartPtrCClassSpecifierDoc& classSpecifier) const; std::string findProviderUri( const SmartPtrCFullyQualifiedClassGroupDoc& fqc) const; void createDirectory( const std::string& directory) const; void saveRequest( const std::string& outputDir, const SmartPtrCDynamicByteArray& payload) const; SmartPtrCProviderRequestHeaderDoc convertRequestHeader( const SmartPtrCRequestHeaderDoc& requestHeader) const; private: bool _isInitialized; std::string _id; SmartPtrCSchemaCacheManager _schemaCacheManager; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CSinglePmeRequestSplitterInstance); }; } #endif // #ifndef CSinglePmeRequestSplitterInstance_h_ IConfigEnv.h000066400000000000000000000014361321503522500370710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Nov 12, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaContracts_IConfigEnv_h_ #define _MaContracts_IConfigEnv_h_ #include "ICafObject.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "IPersistence.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IConfigEnv : public ICafObject { CAF_DECL_UUID("dea6cea4-9385-458e-b549-d05640382da6") virtual void initialize( const SmartPtrIPersistence& persistenceRemove = SmartPtrIPersistence()) = 0; virtual SmartPtrCPersistenceDoc getUpdated( const int32 timeout) = 0; virtual void update( const SmartPtrCPersistenceDoc& persistence) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IConfigEnv); } #endif IPersistence.h000066400000000000000000000014151321503522500374740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Author: bwilliams * Created: Nov 12, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaContracts_IPersistence_h_ #define _MaContracts_IPersistence_h_ #include "ICafObject.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" namespace Caf { /// TODO - describe interface struct __declspec(novtable) IPersistence : public ICafObject { CAF_DECL_UUID("5b48f8ef-7023-4583-9d2d-b15ae566b0cc") virtual void initialize() = 0; virtual SmartPtrCPersistenceDoc getUpdated( const int32 timeout) = 0; virtual void update( const SmartPtrCPersistenceDoc& persistence) = 0; virtual void remove( const SmartPtrCPersistenceDoc& persistence) = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IPersistence); } #endif MaIntegration.h000066400000000000000000000023001321503522500376320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/include/* * Created on: Nov 11, 2015 * Author: bwilliams * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_h_ #define _MaIntegration_h_ namespace Caf { /** @brief CAF AMQP Integration */ namespace MaIntegration { extern const char* _sObjIdIntegrationObjects; }} namespace Caf { extern const char* _sObjIdCollectSchemaExecutor; extern const char* _sObjIdProviderCollectSchemaExecutor; extern const char* _sObjIdProviderExecutor; extern const char* _sObjIdSinglePmeRequestSplitterInstance; extern const char* _sObjIdSinglePmeRequestSplitter; extern const char* _sObjIdDiagToMgmtRequestTransformerInstance; extern const char* _sObjIdDiagToMgmtRequestTransformer; extern const char* _sObjIdInstallToMgmtRequestTransformerInstance; extern const char* _sObjIdInstallToMgmtRequestTransformer; extern const char* _sObjIdAttachmentRequestTransformerInstance; extern const char* _sObjIdAttachmentRequestTransformer; extern const char* _sObjIdVersionTransformerInstance; extern const char* _sObjIdVersionTransformer; extern const char* _sObjIdPersistenceNamespaceDb; extern const char* _sObjIdConfigEnv; } #endif /* _MaIntegration_h_ */ src/000077500000000000000000000000001321503522500340715ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegrationCAttachmentRequestTransformer.cpp000066400000000000000000000036241321503522500425710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CAttachmentRequestTransformer.h" using namespace Caf; CAttachmentRequestTransformer::CAttachmentRequestTransformer() : _isInitialized(false), CAF_CM_INIT_LOG("CAttachmentRequestTransformer") { } CAttachmentRequestTransformer::~CAttachmentRequestTransformer() { } void CAttachmentRequestTransformer::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CAttachmentRequestTransformer::terminateBean() { } void CAttachmentRequestTransformer::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CAttachmentRequestTransformer::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CAttachmentRequestTransformer::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); rc.CreateInstance(_sObjIdAttachmentRequestTransformerInstance); rc->initialize(_ctorArgs, _properties, configSection); } CAF_CM_EXIT; return rc; } CAttachmentRequestTransformer.h000066400000000000000000000027561321503522500422430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CAttachmentRequestTransformer_h_ #define CAttachmentRequestTransformer_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CAttachmentRequestTransformer : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CAttachmentRequestTransformer(); virtual ~CAttachmentRequestTransformer(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdAttachmentRequestTransformer) CAF_BEGIN_INTERFACE_MAP(CAttachmentRequestTransformer) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CAttachmentRequestTransformer); }; } #endif // #ifndef CAttachmentRequestTransformer_h_ CAttachmentRequestTransformerInstance.cpp000066400000000000000000000164561321503522500442650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CAttachmentRequestTransformerInstance.h" #include "Exception/CCafException.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Caf/CCafMessageCreator.h" using namespace Caf; CAttachmentRequestTransformerInstance::CAttachmentRequestTransformerInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CAttachmentRequestTransformerInstance") { } CAttachmentRequestTransformerInstance::~CAttachmentRequestTransformerInstance() { } void CAttachmentRequestTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _isInitialized = true; } CAF_CM_EXIT; } std::string CAttachmentRequestTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CAttachmentRequestTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } CAF_CM_EXIT; } SmartPtrIIntMessage CAttachmentRequestTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); SmartPtrIIntMessage newMessage; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); newMessage = message; const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); // The standard is for an optional attachment collection at the root of all // documents. const std::deque attachmentCollection = payloadEnvelope->getAttachmentCollection()->getAttachment(); if (! attachmentCollection.empty()) { const std::string outputDirPath = calcOutputDirPath(payloadEnvelope); std::deque newAttachmentCollection; for (TConstIterator > attachmentIter(attachmentCollection); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; const std::string attachmentName = attachment->getName(); const std::string attachmentUri = attachment->getUri(); UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(attachmentUri, uriRecord); SmartPtrCAttachmentDoc newAttachment = attachment; if(uriRecord.protocol.compare("file") == 0) { const std::string origFilePath = calcFilePath(uriRecord); const std::string relPath = calcRelPath(origFilePath, uriRecord); const std::string newFilePath = FileSystemUtils::buildPath( outputDirPath, relPath); if (origFilePath.compare(newFilePath) == 0) { CAF_CM_LOG_DEBUG_VA1("File path unchanged... no-op - %s", newFilePath.c_str()); } else { moveFile(origFilePath, newFilePath); const std::string newUri = "file:///" + newFilePath + "?relPath=" + relPath; newAttachment.CreateInstance(); newAttachment->initialize(attachment->getName(), attachment->getType(), newUri, false, attachment->getCmsPolicy()); } } newAttachmentCollection.push_back(newAttachment); } newMessage = CCafMessageCreator::createPayloadEnvelope( payloadEnvelope, newAttachmentCollection, message->getHeaders()); } } CAF_CM_EXIT; return newMessage; } std::string CAttachmentRequestTransformerInstance::calcOutputDirPath( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope) const { CAF_CM_FUNCNAME_VALIDATE("calcOutputDirPath"); std::string outputDirPath; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelope); const std::string clientIdStr = BasePlatform::UuidToString(payloadEnvelope->getClientId()); const std::string requestIdStr = BasePlatform::UuidToString(payloadEnvelope->getRequestId()); const std::string pmeIdStr = payloadEnvelope->getPmeId(); const std::string outputDir = AppConfigUtils::getRequiredString(_sConfigOutputDir); outputDirPath = FileSystemUtils::buildPath( outputDir, "att", clientIdStr, requestIdStr, pmeIdStr); outputDirPath = CStringUtils::expandEnv(outputDirPath); if (! FileSystemUtils::doesDirectoryExist(outputDirPath)) { CAF_CM_LOG_DEBUG_VA1("Creating output directory - %s", outputDirPath.c_str()); FileSystemUtils::createDirectory(outputDirPath); } } CAF_CM_EXIT; return outputDirPath; } std::string CAttachmentRequestTransformerInstance::calcFilePath( const UriUtils::SUriRecord& uriRecord) const { CAF_CM_FUNCNAME("calcFilePath"); std::string filePath; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); UriUtils::SFileUriRecord fileUriRecord; UriUtils::parseFileAddress(uriRecord.address, fileUriRecord); filePath = CStringUtils::expandEnv(fileUriRecord.path); if(! FileSystemUtils::doesFileExist(filePath)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "URI file not found - %s", filePath.c_str()); } } CAF_CM_EXIT; return filePath; } std::string CAttachmentRequestTransformerInstance::calcRelPath( const std::string& filePath, const UriUtils::SUriRecord& uriRecord) const { CAF_CM_FUNCNAME_VALIDATE("calcRelPath"); std::string relPath; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const std::map::const_iterator iterParam = uriRecord.parameters.find("relPath"); if (iterParam != uriRecord.parameters.end()) { relPath = iterParam->second; } else { CAF_CM_LOG_DEBUG_VA1("Attachment URI does not contain relPath - %s", uriRecord.address.c_str()); CAF_CM_VALIDATE_STRING(filePath); relPath = FileSystemUtils::getBasename(filePath); } } CAF_CM_EXIT; return relPath; } void CAttachmentRequestTransformerInstance::moveFile( const std::string& srcFilePath, const std::string& dstFilePath) const { CAF_CM_FUNCNAME_VALIDATE("moveFile"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(srcFilePath); CAF_CM_VALIDATE_STRING(dstFilePath); if (FileSystemUtils::doesFileExist(dstFilePath)) { CAF_CM_LOG_WARN_VA1("File already exists - %s", dstFilePath.c_str()); } else { const std::string newDirPath = FileSystemUtils::getDirname(dstFilePath); if (! FileSystemUtils::doesDirectoryExist(newDirPath)) { CAF_CM_LOG_DEBUG_VA1("Creating input directory - %s", newDirPath.c_str()); FileSystemUtils::createDirectory(newDirPath); } CAF_CM_LOG_DEBUG_VA2("Moving file - \"%s\" to \"%s\"", srcFilePath.c_str(), dstFilePath.c_str()); FileSystemUtils::moveFile(srcFilePath, dstFilePath); } } CAF_CM_EXIT; } CCollectSchemaExecutor.cpp000066400000000000000000000065731321503522500411400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlRoots.h" #include "Integration/Caf/CCafMessageHeaders.h" #include "Common/CLoggingSetter.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" #include "Integration/IIntMessage.h" #include "CCollectSchemaExecutor.h" #include "CResponseFactory.h" #include "Integration/Caf/CCafMessageCreator.h" using namespace Caf; CCollectSchemaExecutor::CCollectSchemaExecutor() : _isInitialized(false), CAF_CM_INIT_LOG("CCollectSchemaExecutor") { } CCollectSchemaExecutor::~CCollectSchemaExecutor() { } void CCollectSchemaExecutor::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); const std::string schemaCacheDirPath = AppConfigUtils::getRequiredString(_sProviderHostArea, _sConfigSchemaCacheDir); const std::string schemaCacheDirPathExp = CStringUtils::expandEnv(schemaCacheDirPath); if (!FileSystemUtils::doesDirectoryExist(schemaCacheDirPathExp)) { CAF_CM_LOG_INFO_VA1( "Schema cache directory does not exist... creating - %s", schemaCacheDirPathExp.c_str()); FileSystemUtils::createDirectory(schemaCacheDirPathExp); } _schemaCacheDirPath = schemaCacheDirPathExp; _isInitialized = true; } CAF_CM_EXIT; } void CCollectSchemaExecutor::terminateBean() { } SmartPtrIIntMessage CCollectSchemaExecutor::processMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("processMessage"); SmartPtrIIntMessage newMessage; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); CAF_CM_LOG_DEBUG_VA1("Called - schemaCacheDirPath: %s", _schemaCacheDirPath.c_str()); const SmartPtrCCafMessageHeaders cafMessageHeaders = CCafMessageHeaders::create(message->getHeaders()); const std::string configOutputDir = AppConfigUtils::getRequiredString(_sConfigOutputDir); const std::string relDirectory = cafMessageHeaders->getRelDirectory(); const std::string outputDir = FileSystemUtils::buildPath( configOutputDir, _sProviderHostArea, relDirectory); SmartPtrCLoggingSetter loggingSetter; loggingSetter.CreateInstance(); loggingSetter->initialize(outputDir); const std::string providerCollectSchemaMem = message->getPayloadStr(); const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequest = XmlRoots::parseProviderCollectSchemaRequestFromString(providerCollectSchemaMem); CAF_CM_LOG_DEBUG_VA2("Copying directory from \"%s\" to \"%s\"", _schemaCacheDirPath.c_str(), outputDir.c_str()); FileSystemUtils::recursiveCopyDirectory(_schemaCacheDirPath, outputDir); const SmartPtrCResponseDoc response = CResponseFactory::createResponse(providerCollectSchemaRequest, outputDir, _schemaCacheDirPath); const std::string randomUuidStr = CStringUtils::createRandomUuid(); const std::string relFilename = randomUuidStr + "_" + _sResponseFilename; newMessage = CCafMessageCreator::createPayloadEnvelope( response, relFilename, message->getHeaders()); } CAF_CM_EXIT; return newMessage; } CCollectSchemaExecutor.h000066400000000000000000000023241321503522500405730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CCollectSchemaExecutor_h_ #define CCollectSchemaExecutor_h_ #include "IBean.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageProcessor.h" using namespace Caf; /// TODO - describe class class CCollectSchemaExecutor : public TCafSubSystemObjectRoot, public IBean, public IMessageProcessor { public: CCollectSchemaExecutor(); virtual ~CCollectSchemaExecutor(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdCollectSchemaExecutor) CAF_BEGIN_INTERFACE_MAP(CCollectSchemaExecutor) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IMessageProcessor) CAF_END_INTERFACE_MAP() public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IMessageProcessor SmartPtrIIntMessage processMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _schemaCacheDirPath; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CCollectSchemaExecutor); }; #endif // #ifndef CCollectSchemaExecutor_h_ CConfigEnv.cpp000066400000000000000000000176201321503522500365640ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "IPersistence.h" #include "Exception/CCafException.h" #include "CConfigEnv.h" using namespace Caf; CConfigEnv::CConfigEnv() : _isInitialized(false), CAF_CM_INIT_LOG("CConfigEnv") { CAF_CM_INIT_THREADSAFE; } CConfigEnv::~CConfigEnv() { } void CConfigEnv::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { } void CConfigEnv::terminateBean() { } void CConfigEnv::initialize( const SmartPtrIPersistence& persistenceRemove) { CAF_CM_LOCK_UNLOCK; if (_isInitialized) { if (! persistenceRemove.IsNull() && _persistenceRemove.IsNull()) { _persistenceRemove = persistenceRemove; } } else { _monitorListener.CreateInstance(); _monitorListener->initialize(); _persistenceRemove = persistenceRemove; _persistenceDir = AppConfigUtils::getRequiredString("persistence_dir"); _configDir = AppConfigUtils::getRequiredString("config_dir"); _persistenceAppconfigPath = FileSystemUtils::buildPath(_configDir, "persistence-appconfig"); _monitorDir = AppConfigUtils::getRequiredString("monitor_dir"); _restartListenerPath = FileSystemUtils::buildPath(_monitorDir, "restartListener.txt"); _listenerConfiguredStage1Path = FileSystemUtils::buildPath( _monitorDir, "listenerConfiguredStage1.txt"); _listenerConfiguredStage2Path = FileSystemUtils::buildPath( _monitorDir, "listenerConfiguredStage2.txt"); std::string guestProxyDir; #ifdef _WIN32 std::string programData; CEnvironmentUtils::readEnvironmentVar("ProgramData", programData); guestProxyDir = FileSystemUtils::buildPath(programData, "VMware", "VMware Tools", "GuestProxyData"); #else guestProxyDir = "/etc/vmware-tools/GuestProxyData"; #endif _vcidPath = FileSystemUtils::buildPath(guestProxyDir, "VmVcUuid", "vm.vc.uuid"); _cacertPath = FileSystemUtils::buildPath(guestProxyDir, "server", "cert.pem"); _isInitialized = true; } } SmartPtrCPersistenceDoc CConfigEnv::getUpdated( const int32 timeout) { CAF_CM_FUNCNAME_VALIDATE("getUpdated"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); bool preConfigDoneNow = _monitorListener->preConfigureListener(); if (FileSystemUtils::doesFileExist(_listenerConfiguredStage1Path)) { if (_persistence.IsNull() || preConfigDoneNow) { _persistence = CPersistenceUtils::loadPersistence(_persistenceDir); if (FileSystemUtils::doesFileExist(_listenerConfiguredStage2Path)) { _persistenceUpdated = _persistence; } } SmartPtrCPersistenceDoc persistenceTmp; if (preConfigDoneNow) { persistenceTmp = CConfigEnvMerge::mergePersistence( _persistence, _cacertPath, _vcidPath); } if (! persistenceTmp.IsNull()) { CPersistenceUtils::savePersistence(persistenceTmp, _persistenceDir); _persistence = CPersistenceUtils::loadPersistence(_persistenceDir); _persistenceUpdated = _persistence; savePersistenceAppconfig(_persistence, _configDir); const std::string reason = "Info changed in env"; listenerConfiguredStage2(reason); restartListener(reason); } } SmartPtrCPersistenceDoc rc; if (! _persistenceUpdated.IsNull()) { CAF_CM_LOG_DEBUG_VA1("Returning persistence info - %s", _persistenceDir.c_str()); rc = _persistenceUpdated; _persistenceUpdated = SmartPtrCPersistenceDoc(); } return rc; } void CConfigEnv::update( const SmartPtrCPersistenceDoc& persistence) { CAF_CM_FUNCNAME_VALIDATE("update"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); getUpdated(0); const SmartPtrCPersistenceDoc persistenceTmp1 = CPersistenceMerge::mergePersistence(_persistence, persistence); const SmartPtrCPersistenceDoc persistenceIn = persistenceTmp1.IsNull() ? _persistence : persistenceTmp1; const SmartPtrCPersistenceDoc persistenceTmp2 = CConfigEnvMerge::mergePersistence(persistenceIn, _cacertPath, _vcidPath); const SmartPtrCPersistenceDoc persistenceTmp = persistenceTmp2.IsNull() ? persistenceTmp1 : persistenceTmp2; if (! persistenceTmp.IsNull()) { CPersistenceUtils::savePersistence(persistenceTmp, _persistenceDir); _persistence = CPersistenceUtils::loadPersistence(_persistenceDir); _persistenceUpdated = _persistence; savePersistenceAppconfig(_persistence, _configDir); removePrivateKey(_persistence, _persistenceRemove); const std::string reason = "Info changed at source"; listenerConfiguredStage1(reason); listenerConfiguredStage2(reason); restartListener(reason); } } void CConfigEnv::savePersistenceAppconfig( const SmartPtrCPersistenceDoc& persistence, const std::string& configDir) const { CAF_CM_FUNCNAME_VALIDATE("savePersistenceAppconfig"); CAF_CM_VALIDATE_SMARTPTR(persistence); CAF_CM_VALIDATE_STRING(configDir); const SmartPtrCPersistenceProtocolDoc persistenceProtocol = CPersistenceUtils::loadPersistenceProtocol( persistence->getPersistenceProtocolCollection()); if (persistenceProtocol.IsNull() || persistenceProtocol->getUri().empty()) { CAF_CM_LOG_DEBUG_VA1( "Can't create persistence-appconfig until protocol is established - %s", configDir.c_str()); } else { #ifdef WIN32 const std::string newLine = "\r\n"; #else const std::string newLine = "\n"; #endif CAF_CM_LOG_DEBUG_VA1("Saving persistence-appconfig - %s", configDir.c_str()); UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(persistenceProtocol->getUri(), uriRecord); CAF_CM_VALIDATE_STRING(uriRecord.path); const std::string listenerContext = calcListenerContext(uriRecord.protocol, configDir); CAF_CM_LOG_DEBUG_VA2("Calculated listener context - uri: %s, protocol: %s", persistenceProtocol->getUri().c_str(), uriRecord.protocol.c_str()); std::string appconfigContents; appconfigContents = "[globals]" + newLine; appconfigContents += "reactive_request_amqp_queue_id=" + uriRecord.path + newLine; appconfigContents += "comm_amqp_listener_context=" + listenerContext + newLine; FileSystemUtils::saveTextFile(_persistenceAppconfigPath, appconfigContents); } } void CConfigEnv::removePrivateKey( const SmartPtrCPersistenceDoc& persistence, const SmartPtrIPersistence& persistenceRemove) const { CAF_CM_FUNCNAME_VALIDATE("removePrivateKey"); CAF_CM_VALIDATE_SMARTPTR(persistence); if (! persistenceRemove.IsNull() && ! persistence->getLocalSecurity()->getPrivateKey().empty()) { CAF_CM_LOG_DEBUG_VA0("Removing private key"); SmartPtrCLocalSecurityDoc localSecurity; localSecurity.CreateInstance(); localSecurity->initialize(std::string(), "removePrivateKey"); SmartPtrCPersistenceDoc persistenceRemoveTmp; persistenceRemoveTmp.CreateInstance(); persistenceRemoveTmp->initialize(localSecurity); persistenceRemove->remove(persistenceRemoveTmp); } } std::string CConfigEnv::calcListenerContext( const std::string& uriSchema, const std::string& configDir) const { CAF_CM_FUNCNAME("calcListenerContext"); CAF_CM_VALIDATE_STRING(uriSchema); CAF_CM_VALIDATE_STRING(configDir); std::string rc; if (uriSchema.compare("amqp") == 0) { rc = FileSystemUtils::buildPath(configDir, "CommAmqpListener-context-amqp.xml"); } else if (uriSchema.compare("tunnel") == 0) { rc = FileSystemUtils::buildPath(configDir, "CommAmqpListener-context-tunnel.xml"); } else { CAF_CM_EXCEPTION_VA1(E_INVALIDARG, "Unknown URI schema: %s", uriSchema.c_str()); } return FileSystemUtils::normalizePathWithForward(rc); } void CConfigEnv::restartListener( const std::string& reason) const { FileSystemUtils::saveTextFile(_restartListenerPath, reason); } void CConfigEnv::listenerConfiguredStage1( const std::string& reason) const { FileSystemUtils::saveTextFile(_listenerConfiguredStage1Path, reason); } void CConfigEnv::listenerConfiguredStage2( const std::string& reason) const { FileSystemUtils::saveTextFile(_listenerConfiguredStage2Path, reason); } CConfigEnv.h000066400000000000000000000045461321503522500362340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CConfigEnv_h_ #define _MaIntegration_CConfigEnv_h_ #include "IBean.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "IPersistence.h" #include "IConfigEnv.h" using namespace Caf; /// TODO - describe class class CConfigEnv : public TCafSubSystemObjectRoot, public IBean, public IConfigEnv { public: CConfigEnv(); virtual ~CConfigEnv(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdConfigEnv) CAF_BEGIN_INTERFACE_MAP(CConfigEnv) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IConfigEnv) CAF_END_INTERFACE_MAP() public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IConfigEnv void initialize( const SmartPtrIPersistence& persistenceRemove); SmartPtrCPersistenceDoc getUpdated( const int32 timeout); void update( const SmartPtrCPersistenceDoc& persistence); private: void savePersistenceAppconfig( const SmartPtrCPersistenceDoc& persistence, const std::string& configDir) const; void executeScript( const std::string& scriptPath, const std::string& scriptResultsDir) const; void removePrivateKey( const SmartPtrCPersistenceDoc& persistence, const SmartPtrIPersistence& persistenceRemove) const; std::string calcListenerContext( const std::string& uriSchema, const std::string& configDir) const; void restartListener( const std::string& reason) const; void listenerConfiguredStage1( const std::string& reason) const; void listenerConfiguredStage2( const std::string& reason) const; private: bool _isInitialized; std::string _persistenceDir; std::string _configDir; std::string _persistenceAppconfigPath; std::string _monitorDir; std::string _restartListenerPath; std::string _listenerConfiguredStage1Path; std::string _listenerConfiguredStage2Path; std::string _vcidPath; std::string _cacertPath; SmartPtrCPersistenceDoc _persistence; SmartPtrCPersistenceDoc _persistenceUpdated; SmartPtrIPersistence _persistenceRemove; SmartPtrCMonitorListener _monitorListener; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CConfigEnv); }; #endif // #ifndef _MaIntegration_CConfigEnv_h_ CConfigEnvInboundChannelAdapterInstance.cpp000066400000000000000000000107661321503522500443660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CConfigEnvReadingMessageSource.h" #include "Common/IAppContext.h" #include "IBean.h" #include "IConfigEnv.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CMessageHandler.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/Core/CSourcePollingChannelAdapter.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IMessageChannel.h" #include "CConfigEnvInboundChannelAdapterInstance.h" using namespace Caf; CConfigEnvInboundChannelAdapterInstance::CConfigEnvInboundChannelAdapterInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CConfigEnvInboundChannelAdapterInstance") { } CConfigEnvInboundChannelAdapterInstance::~CConfigEnvInboundChannelAdapterInstance() { } void CConfigEnvInboundChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CConfigEnvInboundChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CConfigEnvInboundChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const std::string outputChannelStr = _configSection->findRequiredAttribute("channel"); const SmartPtrIConfigEnv configEnv = createConfigEnv(appContext); SmartPtrCConfigEnvReadingMessageSource configEnvReadingMessageSource; configEnvReadingMessageSource.CreateInstance(); configEnvReadingMessageSource->initialize(_configSection, configEnv); const SmartPtrIMessageChannel outputMessageChannel = channelResolver->resolveChannelName(outputChannelStr); const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); SmartPtrCMessageHandler messageHandler; messageHandler.CreateInstance(); messageHandler->initialize( _id, outputMessageChannel, SmartPtrICafObject()); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, errorMessageChannel); SmartPtrCSourcePollingChannelAdapter sourcePollingChannelAdapter; sourcePollingChannelAdapter.CreateInstance(); sourcePollingChannelAdapter->initialize( messageHandler, configEnvReadingMessageSource, errorHandler); SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor; simpleAsyncTaskExecutor.CreateInstance(); simpleAsyncTaskExecutor->initialize(sourcePollingChannelAdapter, errorHandler); _taskExecutor = simpleAsyncTaskExecutor; } void CConfigEnvInboundChannelAdapterInstance::start( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Starting the executor"); _taskExecutor->execute(timeoutMs); } void CConfigEnvInboundChannelAdapterInstance::stop( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Stopping the executor"); _taskExecutor->cancel(timeoutMs); } bool CConfigEnvInboundChannelAdapterInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const bool rc = (_taskExecutor->getState() == ITaskExecutor::ETaskStateStarted); return rc; } bool CConfigEnvInboundChannelAdapterInstance::isMessageProducer() const { CAF_CM_FUNCNAME_VALIDATE("isMessageProducer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return true; } SmartPtrIConfigEnv CConfigEnvInboundChannelAdapterInstance::createConfigEnv( const SmartPtrIAppContext& appContext) const { CAF_CM_FUNCNAME_VALIDATE("createConfigEnv"); CAF_CM_VALIDATE_INTERFACE(appContext); SmartPtrIConfigEnv rc; const std::string refStr = _configSection->findRequiredAttribute("ref"); CAF_CM_LOG_DEBUG_VA1("Creating the configenv impl - %s", refStr.c_str()); const SmartPtrIBean bean = appContext->getBean(refStr); rc.QueryInterface(bean, false); CAF_CM_VALIDATE_INTERFACE(rc); rc->initialize(); return rc; } CConfigEnvInboundChannelAdapterInstance.h000066400000000000000000000040061321503522500440210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CConfigEnvInboundChannelAdapterInstance_h_ #define CConfigEnvInboundChannelAdapterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "IConfigEnv.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/ITaskExecutor.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" #include "Integration/IMessageProducer.h" namespace Caf { class CConfigEnvInboundChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle, public IMessageProducer { public: CConfigEnvInboundChannelAdapterInstance(); virtual ~CConfigEnvInboundChannelAdapterInstance(); public: CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(IMessageProducer) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // IMessageProducer bool isMessageProducer() const; private: SmartPtrIConfigEnv createConfigEnv( const SmartPtrIAppContext& appContext) const; private: bool _isInitialized; std::string _id; SmartPtrIDocument _configSection; SmartPtrITaskExecutor _taskExecutor; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CConfigEnvInboundChannelAdapterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CConfigEnvInboundChannelAdapterInstance); } #endif // #ifndef CConfigEnvInboundChannelAdapterInstance_h_ CConfigEnvMerge.cpp000066400000000000000000000234311321503522500375410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Exception/CCafException.h" #include "CConfigEnvMerge.h" #ifdef WIN32 #include #pragma comment (lib, "wsock32.lib") #else #include #include #include #endif using namespace Caf; SmartPtrCPersistenceDoc CConfigEnvMerge::mergePersistence( const SmartPtrCPersistenceDoc& persistence, const std::string& cacertPath, const std::string& vcidPath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "mergePersistence"); CAF_CM_VALIDATE_SMARTPTR(persistence); CAF_CM_VALIDATE_STRING(cacertPath); CAF_CM_VALIDATE_STRING(vcidPath); const std::string localId = mergeLocalId(persistence, vcidPath); std::string localIdDiff; if (persistence->getLocalSecurity()->getLocalId().compare(localId) != 0) { CAF_CM_LOG_DEBUG_VA2("LocalId changed - %s != %s", persistence->getLocalSecurity()->getLocalId().c_str(), localId.c_str()); localIdDiff = localId; } const std::string cacert = loadTextFile(cacertPath); const std::deque persistenceProtocolCollectionInnerDiff = mergePersistenceProtocolCollectionInner( persistence->getPersistenceProtocolCollection()->getPersistenceProtocol(), localId, cacert); SmartPtrCPersistenceDoc rc; if (! localIdDiff.empty() || ! persistenceProtocolCollectionInnerDiff.empty()) { SmartPtrCLocalSecurityDoc localSecurity = persistence->getLocalSecurity(); if (! localIdDiff.empty()) { CAF_CM_LOG_DEBUG_VA0("Creating local security diff"); localSecurity.CreateInstance(); localSecurity->initialize( localIdDiff, persistence->getLocalSecurity()->getPrivateKey(), persistence->getLocalSecurity()->getCert(), persistence->getLocalSecurity()->getPrivateKeyPath(), persistence->getLocalSecurity()->getCertPath()); } SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollection = persistence->getPersistenceProtocolCollection(); if (! persistenceProtocolCollectionInnerDiff.empty()) { CAF_CM_LOG_DEBUG_VA0("Creating persistence protocol diff"); persistenceProtocolCollection.CreateInstance(); persistenceProtocolCollection->initialize(persistenceProtocolCollectionInnerDiff); } rc.CreateInstance(); rc->initialize( localSecurity, persistence->getRemoteSecurityCollection(), persistenceProtocolCollection, persistence->getVersion()); } return rc; } std::string CConfigEnvMerge::mergeLocalId( const SmartPtrCPersistenceDoc& persistence, const std::string& vcidPath) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "mergeLocalId"); CAF_CM_VALIDATE_SMARTPTR(persistence); CAF_CM_VALIDATE_STRING(vcidPath); std::string rc = loadTextFile(vcidPath); if (rc.empty()) { if (persistence->getLocalSecurity()->getLocalId().empty()) { rc = CStringUtils::createRandomUuid(); } else { rc = persistence->getLocalSecurity()->getLocalId(); } } return rc; } std::deque CConfigEnvMerge::mergePersistenceProtocolCollectionInner( const std::deque& persistenceProtocolCollectionInner, const std::string& localId, const std::string& cacert) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "mergePersistenceProtocolCollectionInner"); CAF_CM_VALIDATE_BOOL(persistenceProtocolCollectionInner.size() == 1); CAF_CM_VALIDATE_STRING(localId); const bool isTunnelEnabled = isTunnelEnabledFunc(); std::deque rc; std::deque persistenceProtocolCollectionInnerDiff; std::deque persistenceProtocolCollectionInnerAll; for (TConstIterator > persistenceProtocolIter(persistenceProtocolCollectionInner); persistenceProtocolIter; persistenceProtocolIter++) { const SmartPtrCPersistenceProtocolDoc persistenceProtocol = *persistenceProtocolIter; const std::string uriDiff = mergeUri(persistenceProtocol, localId, isTunnelEnabled); const SmartPtrCCertCollectionDoc tlsCertCollectionDiff = mergeTlsCertCollection(persistenceProtocol->getTlsCertCollection(), cacert); SmartPtrCPersistenceProtocolDoc persistenceProtocolDiff; persistenceProtocolDiff.CreateInstance(); persistenceProtocolDiff->initialize( persistenceProtocol->getProtocolName(), ! uriDiff.empty() ? uriDiff : persistenceProtocol->getUri(), ! uriDiff.empty() && ! isTunnelEnabled ? uriDiff : persistenceProtocol->getUriAmqp(), ! uriDiff.empty() && isTunnelEnabled ? uriDiff : persistenceProtocol->getUriTunnel(), persistenceProtocol->getTlsCert(), persistenceProtocol->getTlsProtocol(), persistenceProtocol->getTlsCipherCollection(), tlsCertCollectionDiff.IsNull() ? persistenceProtocol->getTlsCertCollection() : tlsCertCollectionDiff, persistenceProtocol->getUriAmqpPath(), persistenceProtocol->getUriTunnelPath(), persistenceProtocol->getTlsCertPath(), persistenceProtocol->getTlsCertPathCollection()); persistenceProtocolCollectionInnerAll.push_back(persistenceProtocolDiff); CAF_CM_LOG_DEBUG_VA2("uriDiff=%s, isTunnelEnabled=%s", uriDiff.c_str(), isTunnelEnabled?"true":"false" ); if (! uriDiff.empty() || ! tlsCertCollectionDiff.IsNull()) { persistenceProtocolCollectionInnerDiff.push_back(persistenceProtocolDiff); } } if (! persistenceProtocolCollectionInnerDiff.empty()) { rc = persistenceProtocolCollectionInnerAll; } return rc; } std::string CConfigEnvMerge::mergeUri( const SmartPtrCPersistenceProtocolDoc& persistenceProtocol, const std::string& localId, const bool isTunnelEnabled) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "mergeUri"); CAF_CM_VALIDATE_SMARTPTR(persistenceProtocol); CAF_CM_VALIDATE_STRING(localId); const std::string uri = persistenceProtocol->getUri(); const std::string uriNew = isTunnelEnabled ? persistenceProtocol->getUriTunnel() : persistenceProtocol->getUriAmqp(); CAF_CM_VALIDATE_STRING(uriNew); CAF_CM_LOG_DEBUG_VA3("uri: %s, uriNew: %s, localId: %s", uri.c_str(), uriNew.c_str(), localId.c_str()); UriUtils::SUriRecord uriDataNew; UriUtils::parseUriString(uriNew, uriDataNew); std::string rc; std::string pathNew(localId); if (isTunnelEnabled) { pathNew += "-agentId1"; } if ((uri.compare(uriNew) != 0) || (uriDataNew.path.compare(pathNew) != 0)) { uriDataNew.path = pathNew; rc = UriUtils::buildUriString(uriDataNew); CAF_CM_LOG_DEBUG_VA4("uri changed - %s != %s || %s != %s", uri.c_str(), rc.c_str(), pathNew.c_str(), uriDataNew.path.c_str()); } CAF_CM_LOG_DEBUG_VA1("rc: %s", rc.c_str()); return rc; } SmartPtrCCertCollectionDoc CConfigEnvMerge::mergeTlsCertCollection( const SmartPtrCCertCollectionDoc& tlsCertCollection, const std::string& cacert) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "mergeTlsCertCollection"); CAF_CM_VALIDATE_SMARTPTR(tlsCertCollection); SmartPtrCCertCollectionDoc rc; if (! cacert.empty()) { const Cdeqstr tlsCertCollectionInner = tlsCertCollection->getCert(); if (tlsCertCollectionInner.size() == 1) { const std::string tlsCert = tlsCertCollectionInner.front(); if (tlsCert.compare(cacert) != 0) { CAF_CM_LOG_DEBUG_VA2("cacert changed - %s != %s", cacert.c_str(), tlsCert.c_str()); Cdeqstr tlsCertCollectionInnerTmp; tlsCertCollectionInnerTmp.push_back(cacert); rc.CreateInstance(); rc->initialize(tlsCertCollectionInnerTmp); } } } return rc; } bool CConfigEnvMerge::isTunnelEnabledFunc() { CAF_CM_STATIC_FUNC_LOG("CConfigEnvMerge", "isTunnelEnabledFunc"); bool rc = false; #ifdef WIN32 try { WSADATA wsaData; int result = ::WSAStartup(MAKEWORD(2, 2), &wsaData); if (result != NO_ERROR) { CAF_CM_EXCEPTION_VA0(E_UNEXPECTED, "WSAStartup() Failed"); } SOCKADDR_IN socketClient; memset(&socketClient, 0, sizeof(SOCKADDR_IN)); socketClient.sin_family = AF_INET; socketClient.sin_addr.s_addr = ::inet_addr("127.0.0.1"); socketClient.sin_port = ::htons(6672); SOCKET socketFd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (socketFd == INVALID_SOCKET) { CAF_CM_EXCEPTION_VA1(E_UNEXPECTED, "Failed to open socket - %s", WSAGetLastError()); } rc = (0 == ::connect(socketFd, (SOCKADDR*) &socketClient, sizeof(socketClient))); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; WSACleanup(); #else int socketFd = -1; try { socketFd = ::socket(AF_INET, SOCK_STREAM, 0); if (socketFd < 0) { CAF_CM_EXCEPTION_VA0(E_UNEXPECTED, "Failed to open socket"); } struct sockaddr_in socketClient; memset(&socketClient, 0, sizeof(sockaddr_in)); socketClient.sin_family = AF_INET; socketClient.sin_port = htons(6672); int result = ::inet_aton("127.0.0.1", &socketClient.sin_addr); if (0 == result) { CAF_CM_EXCEPTION_VA0(ERROR_PATH_NOT_FOUND, "Failed to get address of 127.0.0.1"); } rc = (0 == ::connect(socketFd, (struct sockaddr *) &socketClient, sizeof(socketClient))); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; if (socketFd >= 0) { ::close(socketFd); } #endif return rc; } std::string CConfigEnvMerge::loadTextFile( const std::string& path) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CConfigEnvMerge", "loadTextFile"); CAF_CM_VALIDATE_STRING(path); std::string rc; if (FileSystemUtils::doesFileExist(path)) { rc = FileSystemUtils::loadTextFile(path); rc = CStringUtils::trimRight(rc); } else { CAF_CM_LOG_DEBUG_VA1("File does not exist - %s", path.c_str()); } return rc; } CConfigEnvMerge.h000066400000000000000000000027631321503522500372130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CConfigEnvMerge_h_ #define _MaIntegration_CConfigEnvMerge_h_ #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" using namespace Caf; /// TODO - describe class class CConfigEnvMerge { public: static SmartPtrCPersistenceDoc mergePersistence( const SmartPtrCPersistenceDoc& persistence, const std::string& cacertPath, const std::string& vcidPath); static bool isTunnelEnabledFunc(); private: static std::deque mergePersistenceProtocolCollectionInner( const std::deque& persistenceProtocolCollectionInner, const std::string& localId, const std::string& cacert); static std::string mergeLocalId( const SmartPtrCPersistenceDoc& persistence, const std::string& vcidPath); static std::string mergeUri( const SmartPtrCPersistenceProtocolDoc& persistenceProtocol, const std::string& localId, const bool isTunnelEnabled); static SmartPtrCCertCollectionDoc mergeTlsCertCollection( const SmartPtrCCertCollectionDoc& tlsCertCollection, const std::string& cacert); private: static std::string loadTextFile( const std::string& path); private: CAF_CM_DECLARE_NOCREATE(CConfigEnvMerge); }; #endif // #ifndef _MaIntegration_CConfigEnvMerge_h_ CConfigEnvMessageHandler.cpp000066400000000000000000000043121321503522500413610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlRoots.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "IConfigEnv.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CConfigEnvMessageHandler.h" using namespace Caf; CConfigEnvMessageHandler::CConfigEnvMessageHandler() : _isInitialized(false), CAF_CM_INIT_LOG("CConfigEnvMessageHandler") { } CConfigEnvMessageHandler::~CConfigEnvMessageHandler() { } void CConfigEnvMessageHandler::initialize( const SmartPtrIDocument& configSection, const SmartPtrIConfigEnv& configEnv) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); CAF_CM_VALIDATE_SMARTPTR(configEnv); _id = configSection->findRequiredAttribute("id"); _configEnv = configEnv; _isInitialized = true; } void CConfigEnvMessageHandler::handleMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _savedMessage = message; SmartPtrCPersistenceDoc persistence; const std::string payloadStr = message->getPayloadStr(); if (! payloadStr.empty()) { persistence = XmlRoots::parsePersistenceFromString(payloadStr); } _configEnv->update(persistence); } SmartPtrIIntMessage CConfigEnvMessageHandler::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _savedMessage; } void CConfigEnvMessageHandler::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _savedMessage = NULL; } SmartPtrIIntMessage CConfigEnvMessageHandler::processErrorMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("processErrorMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _savedMessage = message; //TODO: Verify that I'm receiving the error message and decide what //to do with it. return SmartPtrIIntMessage(); } CConfigEnvMessageHandler.h000066400000000000000000000026251321503522500410330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CConfigEnvMessageHandler_h_ #define _MaIntegration_CConfigEnvMessageHandler_h_ #include "Integration/IErrorProcessor.h" #include "IConfigEnv.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" namespace Caf { class CConfigEnvMessageHandler : public IMessageHandler, public IErrorProcessor { public: CConfigEnvMessageHandler(); virtual ~CConfigEnvMessageHandler(); public: CAF_BEGIN_QI() CAF_QI_ENTRY(IMessageHandler) CAF_QI_ENTRY(IErrorProcessor) CAF_END_QI() public: void initialize( const SmartPtrIDocument& configSection, const SmartPtrIConfigEnv& configEnv); public: // IMessageHandler void handleMessage( const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); public: // IErrorProcessor SmartPtrIIntMessage processErrorMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; SmartPtrIConfigEnv _configEnv; SmartPtrIIntMessage _savedMessage; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CConfigEnvMessageHandler); }; CAF_DECLARE_SMART_QI_POINTER(CConfigEnvMessageHandler); } #endif // #ifndef _MaIntegration_CConfigEnvMessageHandler_h_ CConfigEnvOutboundChannelAdapterInstance.cpp000066400000000000000000000114401321503522500445550ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CConfigEnvMessageHandler.h" #include "Common/IAppContext.h" #include "IBean.h" #include "IConfigEnv.h" #include "IPersistence.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" #include "Integration/IMessageHandler.h" #include "CConfigEnvOutboundChannelAdapterInstance.h" using namespace Caf; CConfigEnvOutboundChannelAdapterInstance::CConfigEnvOutboundChannelAdapterInstance() : _isInitialized(false), _isRunning(false), CAF_CM_INIT_LOG("CConfigEnvOutboundChannelAdapterInstance") { } CConfigEnvOutboundChannelAdapterInstance::~CConfigEnvOutboundChannelAdapterInstance() { } void CConfigEnvOutboundChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _configSection = configSection; _isInitialized = true; } std::string CConfigEnvOutboundChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CConfigEnvOutboundChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); const std::string inputChannelStr = _configSection->findRequiredAttribute("channel"); SmartPtrIMessageChannel inputChannel = channelResolver->resolveChannelName(inputChannelStr); SmartPtrIIntegrationObject inputChannelObj; inputChannelObj.QueryInterface(inputChannel); const SmartPtrIConfigEnv configEnv = createConfigEnv(appContext); SmartPtrCConfigEnvMessageHandler configEnvMessageHandler; configEnvMessageHandler.CreateInstance(); configEnvMessageHandler->initialize(_configSection, configEnv); SmartPtrIMessageHandler messageHandler; messageHandler.QueryInterface(configEnvMessageHandler); _messagingTemplate.CreateInstance(); _messagingTemplate->initialize( channelResolver, inputChannelObj, errorMessageChannel, SmartPtrIMessageChannel(), messageHandler); } void CConfigEnvOutboundChannelAdapterInstance::start( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(!_isRunning); _isRunning = true; _messagingTemplate->start(0); } void CConfigEnvOutboundChannelAdapterInstance::stop( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(_isRunning); _isRunning = false; _messagingTemplate->stop(0); } bool CConfigEnvOutboundChannelAdapterInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _isRunning; } SmartPtrIConfigEnv CConfigEnvOutboundChannelAdapterInstance::createConfigEnv( const SmartPtrIAppContext& appContext) const { CAF_CM_FUNCNAME_VALIDATE("createConfigEnv"); CAF_CM_VALIDATE_INTERFACE(appContext); const SmartPtrIPersistence persistenceRemove = createOptPersistence(appContext); SmartPtrIConfigEnv rc; const std::string refStr = _configSection->findRequiredAttribute("ref"); CAF_CM_LOG_DEBUG_VA1("Creating the configenv impl - %s", refStr.c_str()); const SmartPtrIBean bean = appContext->getBean(refStr); rc.QueryInterface(bean, false); CAF_CM_VALIDATE_INTERFACE(rc); rc->initialize(persistenceRemove); return rc; } SmartPtrIPersistence CConfigEnvOutboundChannelAdapterInstance::createOptPersistence( const SmartPtrIAppContext& appContext) const { CAF_CM_FUNCNAME("createOptPersistence"); CAF_CM_VALIDATE_INTERFACE(appContext); SmartPtrIPersistence rc; const std::string removeRefStr = _configSection->findOptionalAttribute("remove-ref"); if (! removeRefStr.empty()) { CAF_CM_LOG_DEBUG_VA1("Creating the persistence impl - %s", removeRefStr.c_str()); const SmartPtrIBean bean = appContext->getBean(removeRefStr); rc.QueryInterface(bean, false); CAF_CM_VALIDATE_INTERFACE(rc); try { rc->initialize(); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_WARN_VA2("initialize failed - ref: %s, msg: %s", removeRefStr.c_str(), (CAF_CM_EXCEPTION_GET_FULLMSG).c_str()); rc = SmartPtrIPersistence(); CAF_CM_CLEAREXCEPTION; } } return rc; } CConfigEnvOutboundChannelAdapterInstance.h000066400000000000000000000040001321503522500442140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CConfigEnvOutboundChannelAdapterInstance_h_ #define CConfigEnvOutboundChannelAdapterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "IConfigEnv.h" #include "IPersistence.h" #include "Integration/Core/CMessagingTemplate.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" namespace Caf { class CConfigEnvOutboundChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle { public: CConfigEnvOutboundChannelAdapterInstance(); virtual ~CConfigEnvOutboundChannelAdapterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; private: SmartPtrIConfigEnv createConfigEnv( const SmartPtrIAppContext& appContext) const; SmartPtrIPersistence createOptPersistence( const SmartPtrIAppContext& appContext) const; private: bool _isInitialized; bool _isRunning; std::string _id; SmartPtrIDocument _configSection; SmartPtrCMessagingTemplate _messagingTemplate; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CConfigEnvOutboundChannelAdapterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CConfigEnvOutboundChannelAdapterInstance); } #endif // #ifndef CConfigEnvOutboundChannelAdapterInstance_h_ CConfigEnvReadingMessageSource.cpp000066400000000000000000000043241321503522500425410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "IConfigEnv.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CConfigEnvReadingMessageSource.h" #include "Exception/CCafException.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlRoots.h" using namespace Caf; CConfigEnvReadingMessageSource::CConfigEnvReadingMessageSource() : _isInitialized(false), CAF_CM_INIT_LOG("CConfigEnvReadingMessageSource") { } CConfigEnvReadingMessageSource::~CConfigEnvReadingMessageSource() { } void CConfigEnvReadingMessageSource::initialize( const SmartPtrIDocument& configSection, const SmartPtrIConfigEnv& configEnv) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); CAF_CM_VALIDATE_INTERFACE(configEnv); _id = configSection->findRequiredAttribute("id"); const SmartPtrIDocument pollerDoc = configSection->findOptionalChild("poller"); _configEnv = configEnv; setPollerMetadata(pollerDoc); _isInitialized = true; } bool CConfigEnvReadingMessageSource::doSend( const SmartPtrIIntMessage&, int32) { CAF_CM_FUNCNAME("doSend"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_EXCEPTIONEX_VA1( UnsupportedOperationException, E_NOTIMPL, "This is not a sending channel: %s", _id.c_str()); } SmartPtrIIntMessage CConfigEnvReadingMessageSource::doReceive( const int32 timeout) { CAF_CM_FUNCNAME("receive"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Timeout not currently supported: %s", _id.c_str()); } SmartPtrIIntMessage message; const SmartPtrCPersistenceDoc persistence = _configEnv->getUpdated(0); if (! persistence.IsNull()) { SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(XmlRoots::savePersistenceToString(persistence), IIntMessage::SmartPtrCHeaders(), IIntMessage::SmartPtrCHeaders()); message = messageImpl; } return message; } CDiagToMgmtRequestTransformer.cpp000066400000000000000000000036241321503522500424750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CDiagToMgmtRequestTransformer.h" using namespace Caf; CDiagToMgmtRequestTransformer::CDiagToMgmtRequestTransformer() : _isInitialized(false), CAF_CM_INIT_LOG("CDiagToMgmtRequestTransformer") { } CDiagToMgmtRequestTransformer::~CDiagToMgmtRequestTransformer() { } void CDiagToMgmtRequestTransformer::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CDiagToMgmtRequestTransformer::terminateBean() { } void CDiagToMgmtRequestTransformer::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CDiagToMgmtRequestTransformer::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CDiagToMgmtRequestTransformer::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); rc.CreateInstance(_sObjIdDiagToMgmtRequestTransformerInstance); rc->initialize(_ctorArgs, _properties, configSection); } CAF_CM_EXIT; return rc; } CDiagToMgmtRequestTransformer.h000066400000000000000000000027561321503522500421470ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CDiagToMgmtRequestTransformer_h_ #define CDiagToMgmtRequestTransformer_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CDiagToMgmtRequestTransformer : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CDiagToMgmtRequestTransformer(); virtual ~CDiagToMgmtRequestTransformer(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdDiagToMgmtRequestTransformer) CAF_BEGIN_INTERFACE_MAP(CDiagToMgmtRequestTransformer) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CDiagToMgmtRequestTransformer); }; } #endif // #ifndef CDiagToMgmtRequestTransformer_h_ CDiagToMgmtRequestTransformerInstance.cpp000066400000000000000000000422371321503522500441650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/DiagRequestXml/DiagRequestXmlRoots.h" #include "CEnvelopeToPayloadTransformerInstance.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" #include "Doc/DiagRequestDoc/CDiagRequestDoc.h" #include "Doc/DiagTypesDoc/CDiagCollectInstancesDoc.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagDeleteValueDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueCollectionDoc.h" #include "Doc/DiagTypesDoc/CDiagSetValueDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CDiagToMgmtRequestTransformerInstance.h" #include "Exception/CCafException.h" #include "Integration/Caf/CCafMessageCreator.h" using namespace Caf; CDiagToMgmtRequestTransformerInstance::CDiagToMgmtRequestTransformerInstance() : _isInitialized(false), _fileAliasPrefix("diagFileAlias_"), CAF_CM_INIT_LOG("CDiagToMgmtRequestTransformerInstance") { } CDiagToMgmtRequestTransformerInstance::~CDiagToMgmtRequestTransformerInstance() { } void CDiagToMgmtRequestTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _isInitialized = true; } CAF_CM_EXIT; } std::string CDiagToMgmtRequestTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CDiagToMgmtRequestTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } CAF_CM_EXIT; } SmartPtrIIntMessage CDiagToMgmtRequestTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); SmartPtrIIntMessage newMessage; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const std::string diagRequestXml = message->getPayloadStr(); CAF_CM_LOG_DEBUG_VA1("diagRequestXml - %s", diagRequestXml.c_str()); const SmartPtrCDiagRequestDoc diagRequestDoc = XmlRoots::parseDiagRequestFromString(diagRequestXml); const SmartPtrCMgmtCollectInstancesCollectionDoc mgmtCollectInstancesCollection = createMgmtCollectInstancesCollection( diagRequestDoc->getBatch()->getCollectInstances()); const SmartPtrCMgmtInvokeOperationCollectionDoc mgmtInvokeOperationCollection = createMgmtInvokeOperationCollection( diagRequestDoc->getBatch()->getSetValueCollection(), diagRequestDoc->getBatch()->getDeleteValueCollection()); SmartPtrCMgmtBatchDoc mgmtBatch; mgmtBatch.CreateInstance(); mgmtBatch->initialize( SmartPtrCMgmtCollectSchemaDoc(), mgmtCollectInstancesCollection, mgmtInvokeOperationCollection); SmartPtrCMgmtRequestDoc mgmtRequest; mgmtRequest.CreateInstance(); mgmtRequest->initialize( diagRequestDoc->getClientId(), diagRequestDoc->getRequestId(), diagRequestDoc->getPmeId(), diagRequestDoc->getRequestHeader(), mgmtBatch, SmartPtrCAttachmentCollectionDoc()); newMessage = CCafMessageCreator::create(mgmtRequest, message->getHeaders()); } CAF_CM_EXIT; return newMessage; } SmartPtrCMgmtCollectInstancesCollectionDoc CDiagToMgmtRequestTransformerInstance::createMgmtCollectInstancesCollection( const SmartPtrCDiagCollectInstancesDoc& diagCollectInstances) const { CAF_CM_FUNCNAME_VALIDATE("createMgmtCollectInstancesCollection"); SmartPtrCMgmtCollectInstancesCollectionDoc mgmtCollectInstancesCollection; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // diagCollectInstances is optional if (! diagCollectInstances.IsNull()) { std::deque mgmtCollectInstancesCollectionInner; UUID jobId = diagCollectInstances->getJobId(); const std::deque expandedFileAliasCollection = expandFileAliases(); for(TConstIterator > expandedFileAliasIter(expandedFileAliasCollection); expandedFileAliasIter; expandedFileAliasIter++) { const SmartPtrSExpandedFileAlias expandedFileAlias = *expandedFileAliasIter; const SmartPtrCMgmtCollectInstancesDoc mgmtCollectInstances = createCollectInstances(jobId, expandedFileAlias); mgmtCollectInstancesCollectionInner.push_back(mgmtCollectInstances); jobId = CStringUtils::createRandomUuidRaw(); } mgmtCollectInstancesCollection.CreateInstance(); mgmtCollectInstancesCollection->initialize( mgmtCollectInstancesCollectionInner); } } CAF_CM_EXIT; return mgmtCollectInstancesCollection; } SmartPtrCMgmtInvokeOperationCollectionDoc CDiagToMgmtRequestTransformerInstance::createMgmtInvokeOperationCollection( const SmartPtrCDiagSetValueCollectionDoc& diagSetValueCollection, const SmartPtrCDiagDeleteValueCollectionDoc& diagDeleteValueCollection) const { CAF_CM_FUNCNAME_VALIDATE("createMgmtInvokeOperationCollection"); SmartPtrCMgmtInvokeOperationCollectionDoc mgmtInvokeOperationCollection; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // diagSetValueCollection is optional // diagDeleteValueCollection is optional std::deque mgmtInvokeOperationCollectionInner; if (! diagSetValueCollection.IsNull()) { const std::deque diagSetValueCollectionInner = diagSetValueCollection->getSetValueCollection(); for(TConstIterator > diagSetValueIter(diagSetValueCollectionInner); diagSetValueIter; diagSetValueIter++) { const SmartPtrCDiagSetValueDoc diagSetValue = *diagSetValueIter; const std::string fileAlias = diagSetValue->getFileAlias(); const SmartPtrSExpandedFileAlias expandedFileAlias = expandFileAlias(fileAlias); const SmartPtrCPropertyDoc valueProperty = diagSetValue->getValue(); const SmartPtrCOperationDoc setValueOperation = createSetValueOperation( valueProperty->getName(), valueProperty->getValue(), expandedFileAlias); SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperation = createInvokeOperation( diagSetValue->getJobId(), setValueOperation); mgmtInvokeOperationCollectionInner.push_back(mgmtInvokeOperation); } } if (! diagDeleteValueCollection.IsNull()) { const std::deque diagDeleteValueCollectionInner = diagDeleteValueCollection->getDeleteValueCollection(); for(TConstIterator > diagDeleteValueIter(diagDeleteValueCollectionInner); diagDeleteValueIter; diagDeleteValueIter++) { const SmartPtrCDiagDeleteValueDoc diagDeleteValue = *diagDeleteValueIter; const std::string fileAlias = diagDeleteValue->getFileAlias(); const SmartPtrSExpandedFileAlias expandedFileAlias = expandFileAlias(fileAlias); const SmartPtrCOperationDoc setValueOperation = createDeleteValueOperation( diagDeleteValue->getValueName(), expandedFileAlias); SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperation = createInvokeOperation( diagDeleteValue->getJobId(), setValueOperation); mgmtInvokeOperationCollectionInner.push_back(mgmtInvokeOperation); } } if (! mgmtInvokeOperationCollectionInner.empty()) { mgmtInvokeOperationCollection.CreateInstance(); mgmtInvokeOperationCollection->initialize( mgmtInvokeOperationCollectionInner); } } CAF_CM_EXIT; return mgmtInvokeOperationCollection; } SmartPtrCMgmtCollectInstancesDoc CDiagToMgmtRequestTransformerInstance::createCollectInstances( const UUID& jobId, const SmartPtrSExpandedFileAlias& expandedFileAlias) const { CAF_CM_FUNCNAME_VALIDATE("createCollectInstances"); SmartPtrCMgmtCollectInstancesDoc mgmtCollectInstances; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_GUID(jobId); CAF_CM_VALIDATE_SMARTPTR(expandedFileAlias); SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClass; fullyQualifiedClass.CreateInstance(); fullyQualifiedClass->initialize("caf", "ConfigActions", "1.0.0"); SmartPtrCClassSpecifierDoc classSpecifier; classSpecifier.CreateInstance(); classSpecifier->initialize(fullyQualifiedClass, SmartPtrCClassFiltersDoc()); const SmartPtrCRequestParameterDoc filePathParameter = ParameterUtils::createParameter("filePath", expandedFileAlias->_filePath); const SmartPtrCRequestParameterDoc encodingParameter = ParameterUtils::createParameter("encoding", expandedFileAlias->_encoding); std::deque parameterCollectionInner; parameterCollectionInner.push_back(filePathParameter); parameterCollectionInner.push_back(encodingParameter); SmartPtrCParameterCollectionDoc parameterCollection; parameterCollection.CreateInstance(); parameterCollection->initialize( parameterCollectionInner, std::deque()); mgmtCollectInstances.CreateInstance(); mgmtCollectInstances->initialize(jobId, classSpecifier, parameterCollection); } CAF_CM_EXIT; return mgmtCollectInstances; } SmartPtrCOperationDoc CDiagToMgmtRequestTransformerInstance::createSetValueOperation( const std::string& valueName, const std::deque& valueCollection, const SmartPtrSExpandedFileAlias& expandedFileAlias) const { CAF_CM_FUNCNAME_VALIDATE("createSetValueOperation"); SmartPtrCOperationDoc operation; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(valueName); CAF_CM_VALIDATE_STL(valueCollection); CAF_CM_VALIDATE_SMARTPTR(expandedFileAlias); const SmartPtrCRequestParameterDoc filePathParameter = ParameterUtils::createParameter("filePath", expandedFileAlias->_filePath); const SmartPtrCRequestParameterDoc encodingParameter = ParameterUtils::createParameter("encoding", expandedFileAlias->_encoding); const SmartPtrCRequestParameterDoc valueNameParameter = ParameterUtils::createParameter("valueName", valueName); const SmartPtrCRequestParameterDoc valueDataParameter = ParameterUtils::createParameter("valueData", valueCollection); std::deque parameterCollectionInner; parameterCollectionInner.push_back(filePathParameter); parameterCollectionInner.push_back(encodingParameter); parameterCollectionInner.push_back(valueNameParameter); parameterCollectionInner.push_back(valueDataParameter); SmartPtrCParameterCollectionDoc parameterCollection; parameterCollection.CreateInstance(); parameterCollection->initialize( parameterCollectionInner, std::deque()); operation.CreateInstance(); operation->initialize("setValue", parameterCollection); } CAF_CM_EXIT; return operation; } SmartPtrCOperationDoc CDiagToMgmtRequestTransformerInstance::createDeleteValueOperation( const std::string& valueName, const SmartPtrSExpandedFileAlias& expandedFileAlias) const { CAF_CM_FUNCNAME_VALIDATE("createDeleteValueOperation"); SmartPtrCOperationDoc operation; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(valueName); CAF_CM_VALIDATE_SMARTPTR(expandedFileAlias); const SmartPtrCRequestParameterDoc filePathParameter = ParameterUtils::createParameter("filePath", expandedFileAlias->_filePath); const SmartPtrCRequestParameterDoc encodingParameter = ParameterUtils::createParameter("encoding", expandedFileAlias->_encoding); const SmartPtrCRequestParameterDoc valueNameParameter = ParameterUtils::createParameter("valueName", valueName); std::deque parameterCollectionInner; parameterCollectionInner.push_back(filePathParameter); parameterCollectionInner.push_back(encodingParameter); parameterCollectionInner.push_back(valueNameParameter); SmartPtrCParameterCollectionDoc parameterCollection; parameterCollection.CreateInstance(); parameterCollection->initialize( parameterCollectionInner, std::deque()); operation.CreateInstance(); operation->initialize("deleteValue", parameterCollection); } CAF_CM_EXIT; return operation; } SmartPtrCMgmtInvokeOperationDoc CDiagToMgmtRequestTransformerInstance::createInvokeOperation( const UUID& jobId, const SmartPtrCOperationDoc operation) const { CAF_CM_FUNCNAME_VALIDATE("createInvokeOperation"); SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperation; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_GUID(jobId); CAF_CM_VALIDATE_SMARTPTR(operation); SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClass; fullyQualifiedClass.CreateInstance(); fullyQualifiedClass->initialize("caf", "ConfigActions", "1.0.0"); SmartPtrCClassSpecifierDoc classSpecifier; classSpecifier.CreateInstance(); classSpecifier->initialize(fullyQualifiedClass, SmartPtrCClassFiltersDoc()); mgmtInvokeOperation.CreateInstance(); mgmtInvokeOperation->initialize(jobId, classSpecifier, operation); } CAF_CM_EXIT; return mgmtInvokeOperation; } std::deque CDiagToMgmtRequestTransformerInstance::expandFileAliases() const { CAF_CM_FUNCNAME_VALIDATE("expandFileAliases"); std::deque expandedFileAliasCollection; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const std::string diagFileAliases = AppConfigUtils::getRequiredString("provider", "diagFileAliases"); const Cdeqstr diagFileAliasCollection = CStringUtils::split(diagFileAliases, ':'); for(TConstIterator diagFileAliasIter(diagFileAliasCollection); diagFileAliasIter; diagFileAliasIter++) { const std::string fileAlias = *diagFileAliasIter; const SmartPtrSExpandedFileAlias expandedFileAlias = expandFileAlias(fileAlias); if (! expandedFileAlias.IsNull()) { expandedFileAliasCollection.push_back(expandedFileAlias); } } } CAF_CM_EXIT; return expandedFileAliasCollection; } CDiagToMgmtRequestTransformerInstance::SmartPtrSExpandedFileAlias CDiagToMgmtRequestTransformerInstance::expandFileAlias( const std::string& fileAlias) const { CAF_CM_FUNCNAME_VALIDATE("expandFileAlias"); SmartPtrSExpandedFileAlias expandedFileAlias; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const std::string fullFileAlias = _fileAliasPrefix + fileAlias; const std::string diagFileUriStr = AppConfigUtils::getOptionalString("provider", fullFileAlias); if (diagFileUriStr.empty()) { CAF_CM_LOG_WARN_VA1( "Diag file alias not found in appconfig file - alias: %s", fullFileAlias.c_str()); } else { UriUtils::SUriRecord diagFileUri; UriUtils::parseUriString(diagFileUriStr, diagFileUri); if (diagFileUri.protocol.compare("file") != 0) { CAF_CM_LOG_WARN_VA2( "Diag file alias URI must use \'file\' protocol - alias: %s, uri: %s", fullFileAlias.c_str(), diagFileUriStr.c_str()) } else { UriUtils::SFileUriRecord fileUriRecord; UriUtils::parseFileAddress(diagFileUri.address, fileUriRecord); const std::string diagFile = fileUriRecord.path; if (! FileSystemUtils::doesFileExist(diagFile)) { CAF_CM_LOG_WARN_VA2( "Diag file alias file not found - alias: %s, file: %s", fullFileAlias.c_str(), diagFile.c_str()); } else { expandedFileAlias.CreateInstance(); expandedFileAlias->_filePath = diagFile; expandedFileAlias->_encoding = findUriParameter("encoding", diagFileUri); } } } } CAF_CM_EXIT; return expandedFileAlias; } std::string CDiagToMgmtRequestTransformerInstance::findUriParameter( const std::string& parameterName, const UriUtils::SUriRecord& uri) const { CAF_CM_FUNCNAME("findUriParameter"); std::string parameterValue; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(parameterName); std::map parameters = uri.parameters; std::map::const_iterator iterParameter = parameters.find(parameterName); if (iterParameter == parameters.end()) { CAF_CM_EXCEPTIONEX_VA3(InvalidArgumentException, E_INVALIDARG, "URI does not contain required parameter - parameter: %s, protocol: %s, address: %s", parameterName.c_str(), uri.protocol.c_str(), uri.address.c_str()); } parameterValue = iterParameter->second; } CAF_CM_EXIT; return parameterValue; } CInstallToMgmtRequestTransformer.cpp000066400000000000000000000036701321503522500432400ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CInstallToMgmtRequestTransformer.h" using namespace Caf; CInstallToMgmtRequestTransformer::CInstallToMgmtRequestTransformer() : _isInitialized(false), CAF_CM_INIT_LOG("CInstallToMgmtRequestTransformer") { } CInstallToMgmtRequestTransformer::~CInstallToMgmtRequestTransformer() { } void CInstallToMgmtRequestTransformer::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CInstallToMgmtRequestTransformer::terminateBean() { } void CInstallToMgmtRequestTransformer::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CInstallToMgmtRequestTransformer::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CInstallToMgmtRequestTransformer::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); rc.CreateInstance(_sObjIdInstallToMgmtRequestTransformerInstance); rc->initialize(_ctorArgs, _properties, configSection); } CAF_CM_EXIT; return rc; } CInstallToMgmtRequestTransformer.h000066400000000000000000000030141321503522500426750ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CInstallToMgmtRequestTransformer_h_ #define CInstallToMgmtRequestTransformer_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CInstallToMgmtRequestTransformer : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CInstallToMgmtRequestTransformer(); virtual ~CInstallToMgmtRequestTransformer(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdInstallToMgmtRequestTransformer) CAF_BEGIN_INTERFACE_MAP(CInstallToMgmtRequestTransformer) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CInstallToMgmtRequestTransformer); }; } #endif // #ifndef CInstallToMgmtRequestTransformer_h_ CInstallToMgmtRequestTransformerInstance.cpp000066400000000000000000000310371321503522500447230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/CafInstallRequestXml/InstallProviderJobXml.h" #include "Doc/DocXml/CafInstallRequestXml/UninstallProviderJobXml.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/CafCoreTypesDoc/CParameterCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CRequestInstanceParameterDoc.h" #include "Doc/CafCoreTypesDoc/CRequestParameterDoc.h" #include "Doc/CafInstallRequestDoc/CGetInventoryJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallRequestDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Exception/CCafException.h" #include "CInstallToMgmtRequestTransformerInstance.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Caf/CCafMessageCreator.h" using namespace Caf; CInstallToMgmtRequestTransformerInstance::CInstallToMgmtRequestTransformerInstance() : _isInitialized(false), _fileAliasPrefix("installFileAlias_"), CAF_CM_INIT_LOG("CInstallToMgmtRequestTransformerInstance") { } CInstallToMgmtRequestTransformerInstance::~CInstallToMgmtRequestTransformerInstance() { } void CInstallToMgmtRequestTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _isInitialized = true; } CAF_CM_EXIT; } std::string CInstallToMgmtRequestTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CInstallToMgmtRequestTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } CAF_CM_EXIT; } SmartPtrIIntMessage CInstallToMgmtRequestTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); SmartPtrIIntMessage newMessage; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCInstallRequestDoc installRequestDoc = CCafMessagePayloadParser::getInstallRequest(message->getPayload()); const SmartPtrCMgmtCollectInstancesCollectionDoc mgmtCollectInstancesCollection = createMgmtCollectInstancesCollection( installRequestDoc->getBatch()->getGetInventory()); const SmartPtrCMgmtInvokeOperationCollectionDoc mgmtInvokeOperationCollection = createMgmtInvokeOperationCollection( installRequestDoc->getBatch()->getInstallProvider(), installRequestDoc->getBatch()->getUninstallProvider()); SmartPtrCMgmtBatchDoc mgmtBatch; mgmtBatch.CreateInstance(); mgmtBatch->initialize( SmartPtrCMgmtCollectSchemaDoc(), mgmtCollectInstancesCollection, mgmtInvokeOperationCollection); SmartPtrCMgmtRequestDoc mgmtRequest; mgmtRequest.CreateInstance(); mgmtRequest->initialize( installRequestDoc->getClientId(), installRequestDoc->getRequestId(), installRequestDoc->getPmeId(), installRequestDoc->getRequestHeader(), mgmtBatch, installRequestDoc->getAttachmentCollection()); newMessage = CCafMessageCreator::create(mgmtRequest, message->getHeaders()); } CAF_CM_EXIT; return newMessage; } SmartPtrCMgmtCollectInstancesCollectionDoc CInstallToMgmtRequestTransformerInstance::createMgmtCollectInstancesCollection( const SmartPtrCGetInventoryJobDoc& getInventoryJob) const { CAF_CM_FUNCNAME_VALIDATE("createMgmtCollectInstancesCollection"); SmartPtrCMgmtCollectInstancesCollectionDoc mgmtCollectInstancesCollection; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // getInventoryJob is optional if (! getInventoryJob.IsNull()) { UUID jobId = getInventoryJob->getJobId(); const SmartPtrCMgmtCollectInstancesDoc mgmtCollectInstances = createCollectInstances(jobId); std::deque mgmtCollectInstancesCollectionInner; mgmtCollectInstancesCollectionInner.push_back(mgmtCollectInstances); mgmtCollectInstancesCollection.CreateInstance(); mgmtCollectInstancesCollection->initialize( mgmtCollectInstancesCollectionInner); } } CAF_CM_EXIT; return mgmtCollectInstancesCollection; } SmartPtrCMgmtInvokeOperationCollectionDoc CInstallToMgmtRequestTransformerInstance::createMgmtInvokeOperationCollection( const SmartPtrCInstallProviderJobDoc& installProviderJob, const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob) const { CAF_CM_FUNCNAME_VALIDATE("createMgmtInvokeOperationCollection"); SmartPtrCMgmtInvokeOperationCollectionDoc mgmtInvokeOperationCollection; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // installSetValueCollection is optional // installDeleteValueCollection is optional std::deque mgmtInvokeOperationCollectionInner; if (! installProviderJob.IsNull()) { const SmartPtrCOperationDoc installProviderJobOperation = createInstallProviderOperation(installProviderJob); SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperation = createInvokeOperation(installProviderJobOperation); mgmtInvokeOperationCollectionInner.push_back(mgmtInvokeOperation); } if (! uninstallProviderJob.IsNull()) { const SmartPtrCOperationDoc uninstallProviderJobOperation = createUninstallProviderJobOperation(uninstallProviderJob); SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperation = createInvokeOperation(uninstallProviderJobOperation); mgmtInvokeOperationCollectionInner.push_back(mgmtInvokeOperation); } if (! mgmtInvokeOperationCollectionInner.empty()) { mgmtInvokeOperationCollection.CreateInstance(); mgmtInvokeOperationCollection->initialize( mgmtInvokeOperationCollectionInner); } } CAF_CM_EXIT; return mgmtInvokeOperationCollection; } SmartPtrCMgmtCollectInstancesDoc CInstallToMgmtRequestTransformerInstance::createCollectInstances( const UUID& jobId) const { CAF_CM_FUNCNAME_VALIDATE("createCollectInstances"); SmartPtrCMgmtCollectInstancesDoc mgmtCollectInstances; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_GUID(jobId); SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClass; fullyQualifiedClass.CreateInstance(); fullyQualifiedClass->initialize("caf", "InstallActions", "1.0.0"); SmartPtrCClassSpecifierDoc classSpecifier; classSpecifier.CreateInstance(); classSpecifier->initialize(fullyQualifiedClass, SmartPtrCClassFiltersDoc()); SmartPtrCParameterCollectionDoc parameterCollection; parameterCollection.CreateInstance(); parameterCollection->initialize( std::deque(), std::deque()); mgmtCollectInstances.CreateInstance(); mgmtCollectInstances->initialize(jobId, classSpecifier, parameterCollection); } CAF_CM_EXIT; return mgmtCollectInstances; } SmartPtrCOperationDoc CInstallToMgmtRequestTransformerInstance::createInstallProviderOperation( const SmartPtrCInstallProviderJobDoc& installProviderJob) const { CAF_CM_FUNCNAME_VALIDATE("createInstallProviderOperation"); SmartPtrCOperationDoc operation; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(installProviderJob); const std::string installProviderJobStr = saveInstallProviderJobToString(installProviderJob); std::deque valueCollection; valueCollection.push_back(installProviderJobStr); SmartPtrCRequestInstanceParameterDoc instanceParameter; instanceParameter.CreateInstance(); instanceParameter->initialize( "installProviderJob", "caf", "InstallProviderJob", "1.0.0", valueCollection); std::deque instanceParameterCollectionInner; instanceParameterCollectionInner.push_back(instanceParameter); SmartPtrCParameterCollectionDoc parameterCollection; parameterCollection.CreateInstance(); parameterCollection->initialize( std::deque(), instanceParameterCollectionInner); operation.CreateInstance(); operation->initialize("installProviderJob", parameterCollection); } CAF_CM_EXIT; return operation; } SmartPtrCOperationDoc CInstallToMgmtRequestTransformerInstance::createUninstallProviderJobOperation( const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob) const { CAF_CM_FUNCNAME_VALIDATE("createUninstallProviderJobOperation"); SmartPtrCOperationDoc operation; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(uninstallProviderJob); const std::string& uninstallProviderJobJobStr = saveUninstallProviderJobToString(uninstallProviderJob); std::deque valueCollection; valueCollection.push_back(uninstallProviderJobJobStr); SmartPtrCRequestInstanceParameterDoc instanceParameter; instanceParameter.CreateInstance(); instanceParameter->initialize( "uninstallProviderJob", "caf", "InstallProviderJob", "1.0.0", valueCollection); std::deque instanceParameterCollectionInner; instanceParameterCollectionInner.push_back(instanceParameter); SmartPtrCParameterCollectionDoc parameterCollection; parameterCollection.CreateInstance(); parameterCollection->initialize( std::deque(), instanceParameterCollectionInner); operation.CreateInstance(); operation->initialize("uninstallProviderJob", parameterCollection); } CAF_CM_EXIT; return operation; } SmartPtrCMgmtInvokeOperationDoc CInstallToMgmtRequestTransformerInstance::createInvokeOperation( const SmartPtrCOperationDoc& operation) const { CAF_CM_FUNCNAME("createInvokeOperation"); SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperation; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(operation); SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClass; fullyQualifiedClass.CreateInstance(); fullyQualifiedClass->initialize("caf", "InstallActions", "1.0.0"); SmartPtrCClassSpecifierDoc classSpecifier; classSpecifier.CreateInstance(); classSpecifier->initialize(fullyQualifiedClass, SmartPtrCClassFiltersDoc()); UUID jobId; if (S_OK != ::UuidCreate(&jobId)) { CAF_CM_EXCEPTIONEX_VA0(InvalidHandleException, E_UNEXPECTED, "Failed to create the UUID"); } mgmtInvokeOperation.CreateInstance(); mgmtInvokeOperation->initialize(jobId, classSpecifier, operation); } CAF_CM_EXIT; return mgmtInvokeOperation; } std::string CInstallToMgmtRequestTransformerInstance::saveInstallProviderJobToString( const SmartPtrCInstallProviderJobDoc& installProviderJob) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveInstallProviderJobToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(installProviderJob); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "cafInstallProviderJob", schemaNamespace); InstallProviderJobXml::add(installProviderJob, rootXml); rc = rootXml->saveToStringRaw(); } CAF_CM_EXIT; return rc; } std::string CInstallToMgmtRequestTransformerInstance::saveUninstallProviderJobToString( const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob) { CAF_CM_STATIC_FUNC_VALIDATE("XmlRoots", "saveUninstallProviderJobToString"); std::string rc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(uninstallProviderJob); const std::string schemaNamespace = DocXmlUtils::getSchemaNamespace("fx"); const SmartPtrCXmlElement rootXml = CXmlUtils::createRootElement( "cafUninstallProviderJob", schemaNamespace); UninstallProviderJobXml::add(uninstallProviderJob, rootXml); rc = rootXml->saveToStringRaw(); } CAF_CM_EXIT; return rc; } CInstallToMgmtRequestTransformerInstance.h000066400000000000000000000065011321503522500443660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CInstallToMgmtRequestTransformerInstance_h_ #define CInstallToMgmtRequestTransformerInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/COperationDoc.h" #include "Doc/CafInstallRequestDoc/CGetInventoryJobDoc.h" #include "Doc/CafInstallRequestDoc/CInstallProviderJobDoc.h" #include "Doc/CafInstallRequestDoc/CUninstallProviderJobDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CInstallToMgmtRequestTransformerInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CInstallToMgmtRequestTransformerInstance(); virtual ~CInstallToMgmtRequestTransformerInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdInstallToMgmtRequestTransformerInstance) CAF_BEGIN_INTERFACE_MAP(CInstallToMgmtRequestTransformerInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: SmartPtrCMgmtCollectInstancesCollectionDoc createMgmtCollectInstancesCollection( const SmartPtrCGetInventoryJobDoc& getInventoryJob) const; SmartPtrCMgmtInvokeOperationCollectionDoc createMgmtInvokeOperationCollection( const SmartPtrCInstallProviderJobDoc& installProviderJob, const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob) const; SmartPtrCMgmtCollectInstancesDoc createCollectInstances( const UUID& jobId) const; SmartPtrCMgmtInvokeOperationDoc createInvokeOperation( const SmartPtrCOperationDoc& operation) const; SmartPtrCOperationDoc createInstallProviderOperation( const SmartPtrCInstallProviderJobDoc& installProviderJob) const; SmartPtrCOperationDoc createUninstallProviderJobOperation( const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob) const; static std::string saveInstallProviderJobToString( const SmartPtrCInstallProviderJobDoc& installProviderJob); static std::string saveUninstallProviderJobToString( const SmartPtrCUninstallProviderJobDoc& uninstallProviderJob); private: bool _isInitialized; std::string _id; std::string _fileAliasPrefix; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CInstallToMgmtRequestTransformerInstance); }; } #endif // #ifndef CInstallToMgmtRequestTransformerInstance_h_ CMonitorInboundChannelAdapterInstance.cpp000066400000000000000000000074701321503522500441350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CMonitorReadingMessageSource.h" #include "Common/IAppContext.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CMessageHandler.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/Core/CSourcePollingChannelAdapter.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IMessageChannel.h" #include "CMonitorInboundChannelAdapterInstance.h" using namespace Caf; CMonitorInboundChannelAdapterInstance::CMonitorInboundChannelAdapterInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CMonitorInboundChannelAdapterInstance") { } CMonitorInboundChannelAdapterInstance::~CMonitorInboundChannelAdapterInstance() { } void CMonitorInboundChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CMonitorInboundChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CMonitorInboundChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const std::string outputChannelStr = _configSection->findRequiredAttribute("channel"); SmartPtrCMonitorReadingMessageSource monitorReadingMessageSource; monitorReadingMessageSource.CreateInstance(); monitorReadingMessageSource->initialize(_configSection); const SmartPtrIMessageChannel outputMessageChannel = channelResolver->resolveChannelName(outputChannelStr); const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); SmartPtrCMessageHandler messageHandler; messageHandler.CreateInstance(); messageHandler->initialize( _id, outputMessageChannel, SmartPtrICafObject()); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, errorMessageChannel); SmartPtrCSourcePollingChannelAdapter sourcePollingChannelAdapter; sourcePollingChannelAdapter.CreateInstance(); sourcePollingChannelAdapter->initialize( messageHandler, monitorReadingMessageSource, errorHandler); SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor; simpleAsyncTaskExecutor.CreateInstance(); simpleAsyncTaskExecutor->initialize(sourcePollingChannelAdapter, errorHandler); _taskExecutor = simpleAsyncTaskExecutor; } void CMonitorInboundChannelAdapterInstance::start( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Starting the executor"); _taskExecutor->execute(timeoutMs); } void CMonitorInboundChannelAdapterInstance::stop( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Stopping the executor"); _taskExecutor->cancel(timeoutMs); } bool CMonitorInboundChannelAdapterInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const bool rc = (_taskExecutor->getState() == ITaskExecutor::ETaskStateStarted); return rc; } bool CMonitorInboundChannelAdapterInstance::isMessageProducer() const { CAF_CM_FUNCNAME_VALIDATE("isMessageProducer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return true; } CMonitorInboundChannelAdapterInstance.h000066400000000000000000000035771321503522500436060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CMonitorInboundChannelAdapterInstance_h_ #define CMonitorInboundChannelAdapterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/ITaskExecutor.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" #include "Integration/IMessageProducer.h" namespace Caf { class CMonitorInboundChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle, public IMessageProducer { public: CMonitorInboundChannelAdapterInstance(); virtual ~CMonitorInboundChannelAdapterInstance(); public: CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(IMessageProducer) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // IMessageProducer bool isMessageProducer() const; private: bool _isInitialized; std::string _id; SmartPtrIDocument _configSection; SmartPtrITaskExecutor _taskExecutor; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CMonitorInboundChannelAdapterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CMonitorInboundChannelAdapterInstance); } #endif // #ifndef CMonitorInboundChannelAdapterInstance_h_ CMonitorListener.cpp000066400000000000000000000156301321503522500400420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CMonitorListener.h" using namespace Caf; CMonitorListener::CMonitorListener() : _isInitialized(false), CAF_CM_INIT_LOG("CMonitorListener") { CAF_CM_INIT_THREADSAFE; } CMonitorListener::~CMonitorListener() { } void CMonitorListener::initialize() { CAF_CM_LOCK_UNLOCK; if (!_isInitialized) { _monitorDir = AppConfigUtils::getRequiredString("monitor_dir"); _restartListenerPath = FileSystemUtils::buildPath(_monitorDir, "restartListener.txt"); _listenerConfiguredStage1Path = FileSystemUtils::buildPath( _monitorDir, "listenerConfiguredStage1.txt"); _listenerConfiguredStage2Path = FileSystemUtils::buildPath( _monitorDir, "listenerConfiguredStage2.txt"); _listenerPreConfiguredPath = FileSystemUtils::buildPath( _monitorDir, "listenerPreConfigured.txt"); _listenerCtrlPreConfigure = AppConfigUtils::getRequiredUint32("monitor", "listener_ctrl_preconfigure") ? true : false; _listenerCtrlFollowTunnel = AppConfigUtils::getRequiredUint32("monitor", "listener_ctrl_follow_tunnel") ? true : false; _listenerPreConfigured = FileSystemUtils::doesFileExist(_listenerPreConfiguredPath) ? true : false; _scriptOutputDir = AppConfigUtils::getRequiredString(_sConfigTmpDir); const std::string installDir = AppConfigUtils::getRequiredString("install_dir"); const std::string scriptsDir = AppConfigUtils::getRequiredString("scripts_dir"); #ifdef _WIN32 _stopListenerScript = FileSystemUtils::buildPath(scriptsDir, "stop-listener.bat"); _startListenerScript = FileSystemUtils::buildPath(scriptsDir, "start-listener.bat"); _preConfigureListenerScript = FileSystemUtils::buildPath(installDir, "preconfigure-listener.bat"); _isListenerRunningScript = FileSystemUtils::buildPath(scriptsDir, "is-listener-running.bat"); #else _stopListenerScript = FileSystemUtils::buildPath(scriptsDir, "stop-listener"); _startListenerScript = FileSystemUtils::buildPath(scriptsDir, "start-listener"); _preConfigureListenerScript = FileSystemUtils::buildPath(installDir, "preconfigure-listener.sh"); _isListenerRunningScript = FileSystemUtils::buildPath(scriptsDir, "is-listener-running"); #endif _isInitialized = true; } } bool CMonitorListener::preConfigureListener() { CAF_CM_FUNCNAME_VALIDATE("preConfigureListener"); bool rc = true; if (!_listenerCtrlPreConfigure) { rc = false; CAF_CM_LOG_DEBUG_VA0("monitor/listener_ctrl_preconfigure is not enabled."); } else if (!isListenerPreConfigured()) { CAF_CM_LOG_DEBUG_VA0("Pre-configuring the listener..."); const std::string stdoutStr = FileSystemUtils::executeScript( _preConfigureListenerScript, _scriptOutputDir); if (stdoutStr.compare("true") == 0) { CAF_CM_LOG_DEBUG_VA0("Pre-configured the listener."); std::string reason = "PreConfiguredByMA"; listenerConfiguredStage1("Automatic"); listenerConfiguredStage2(reason); listenerPreConfigured(reason); } else { rc = false; CAF_CM_LOG_ERROR_VA1("Failed to pre-configure the listener. errstr: %s", stdoutStr.c_str()); } } return rc; } /* * Returns * true if listener is stopped/started upon tunnel and sets listenerStartupType */ bool CMonitorListener::followTunnel(std::string& listenerStartupType) { CAF_CM_FUNCNAME_VALIDATE("followTunnel"); // true - followed the tunnel bool rc = false; std::string reason; if (!_listenerCtrlFollowTunnel) { // If Listener is pre-configured and Tunnel enabled, start listener if (isListenerPreConfigured()) { // 1. Start the listener if tunnel is enabled // 2. Stop the listener otherwise if (CConfigEnvMerge::isTunnelEnabledFunc()) { CAF_CM_LOG_DEBUG_VA1("Listener is pre-configured and tunnel is enabled. " "Starting the listener. PreConfiguredPath=%s", _listenerPreConfiguredPath.c_str()); listenerConfiguredStage1(LISTENER_STARTUP_TYPE_AUTOMATIC); listenerConfiguredStage2(LISTENER_STARTUP_TYPE_AUTOMATIC); listenerStartupType = LISTENER_STARTUP_TYPE_AUTOMATIC; } else { CAF_CM_LOG_DEBUG_VA1("Listener is pre-configured and tunnel is disabled. " "PreConfiguredPath=%s", _listenerPreConfiguredPath.c_str()); if (isListenerRunning()) { reason = "Listener pre-configured, tunnel disabled, and listener is running. Stopping it"; CAF_CM_LOG_DEBUG_VA0(reason.c_str()); stopListener(reason); } listenerUnConfiguredStage1(); listenerUnConfiguredStage2(); } rc = true; } } return rc; } bool CMonitorListener::canListenerBeStarted() { bool rc = false; if (CConfigEnvMerge::isTunnelEnabledFunc()) { if (_listenerCtrlFollowTunnel) { rc = true; } } else { //TODO: Implement non-tunnel case. Currently it is not a priority } return rc; } bool CMonitorListener::isListenerRunning() { const std::string stdoutStr = FileSystemUtils::executeScript( _isListenerRunningScript, _scriptOutputDir); return (stdoutStr.compare("true") == 0); } void CMonitorListener::stopListener( const std::string& reason) { CAF_CM_FUNCNAME_VALIDATE("stopListener"); CAF_CM_LOG_DEBUG_VA1( "Stopping the listener - reason: %s", reason.c_str()); FileSystemUtils::executeScript(_stopListenerScript, _scriptOutputDir); } void CMonitorListener::startListener( const std::string& reason) { CAF_CM_FUNCNAME_VALIDATE("startListener"); if (canListenerBeStarted()) { CAF_CM_LOG_DEBUG_VA1("Starting the listener - reason: %s", reason.c_str()); FileSystemUtils::executeScript(_startListenerScript, _scriptOutputDir); } else { CAF_CM_LOG_DEBUG_VA0("Listener is not allowed to start. Check setting..."); } } void CMonitorListener::restartListener( const std::string& reason) { FileSystemUtils::saveTextFile(_restartListenerPath, reason); } void CMonitorListener::listenerConfiguredStage1( const std::string& reason) const { FileSystemUtils::saveTextFile(_listenerConfiguredStage1Path, reason); } void CMonitorListener::listenerUnConfiguredStage1() { FileSystemUtils::removeFile(_listenerConfiguredStage1Path); } void CMonitorListener::listenerConfiguredStage2( const std::string& reason) const { FileSystemUtils::saveTextFile(_listenerConfiguredStage2Path, reason); } void CMonitorListener::listenerUnConfiguredStage2() { FileSystemUtils::removeFile(_listenerConfiguredStage2Path); } void CMonitorListener::listenerPreConfigured( const std::string& reason) const { FileSystemUtils::saveTextFile(_listenerPreConfiguredPath, reason); } CMonitorListener.h000066400000000000000000000035421321503522500375060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CMonitorListener_h_ #define _MaIntegration_CMonitorListener_h_ using namespace Caf; #define LISTENER_STARTUP_TYPE_AUTOMATIC "Automatic" #define LISTENER_STARTUP_TYPE_MANUAL "Manual" /* * Manages the listener LCM */ class CMonitorListener { public: CMonitorListener(); ~CMonitorListener(); void initialize(); bool preConfigureListener(); bool isListenerPreConfigured() { return _listenerPreConfigured; } bool followTunnel(std::string& listenerStartupType); void stopListener(const std::string& reason); bool isListenerRunning(); bool canListenerBeStarted(); void startListener(const std::string& reason); void restartListener(const std::string& reason); void listenerConfiguredStage1(const std::string& reason) const; void listenerUnConfiguredStage1(); void listenerConfiguredStage2(const std::string& reason) const; void listenerUnConfiguredStage2(); void listenerPreConfigured(const std::string& reason) const; private: bool _isInitialized; bool _listenerCtrlPreConfigure; bool _listenerCtrlFollowTunnel; bool _listenerPreConfigured; std::string _startListenerScript; std::string _restartListenerPath; std::string _listenerConfiguredStage1Path; std::string _listenerConfiguredStage2Path; std::string _listenerPreConfiguredPath; std::string _stopListenerScript; std::string _isListenerRunningScript; std::string _preConfigureListenerScript; std::string _monitorDir; std::string _scriptOutputDir; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CMonitorListener); }; CAF_DECLARE_SMART_POINTER(CMonitorListener); #endif // #ifndef _MaIntegration_CMonitorListener_h_ CMonitorReadingMessageSource.cpp000066400000000000000000000203311321503522500423060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CMonitorReadingMessageSource.h" #include "Exception/CCafException.h" using namespace Caf; #define LISTENER_STARTUP_TYPE_AUTOMATIC "Automatic" CMonitorReadingMessageSource::CMonitorReadingMessageSource() : _isInitialized(false), _listenerStartTimeMs(0), _listenerRestartMs(0), _listenerRetryCnt(0), _listenerRetryMax(0), CAF_CM_INIT_LOG("CMonitorReadingMessageSource") { } CMonitorReadingMessageSource::~CMonitorReadingMessageSource() { } void CMonitorReadingMessageSource::initialize( const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); const SmartPtrIDocument pollerDoc = configSection->findOptionalChild("poller"); setPollerMetadata(pollerDoc); _monitorListener.CreateInstance(); _monitorListener->initialize(); _monitorDir = AppConfigUtils::getRequiredString("monitor_dir"); _restartListenerPath = FileSystemUtils::buildPath(_monitorDir, "restartListener.txt"); _listenerConfiguredStage2Path = FileSystemUtils::buildPath(_monitorDir, "listenerConfiguredStage2.txt"); _scriptOutputDir = AppConfigUtils::getRequiredString(_sConfigTmpDir); _listenerStartupType = AppConfigUtils::getRequiredString("monitor", "listener_startup_type"); _listenerRetryMax = AppConfigUtils::getRequiredInt32("monitor", "listener_retry_max"); _listenerRestartMs = calcListenerRestartMs(); CAF_CM_LOG_DEBUG_VA1("_listenerRestartMs: %d", _listenerRestartMs); const std::string scriptsDir = AppConfigUtils::getRequiredString("scripts_dir"); #ifdef _WIN32 _stopListenerScript = FileSystemUtils::buildPath(scriptsDir, "stop-listener.bat"); _startListenerScript = FileSystemUtils::buildPath(scriptsDir, "start-listener.bat"); _isListenerRunningScript = FileSystemUtils::buildPath(scriptsDir, "is-listener-running.bat"); #else _stopListenerScript = FileSystemUtils::buildPath(scriptsDir, "stop-listener"); _startListenerScript = FileSystemUtils::buildPath(scriptsDir, "start-listener"); _isListenerRunningScript = FileSystemUtils::buildPath(scriptsDir, "is-listener-running"); #endif if (! FileSystemUtils::doesDirectoryExist(_monitorDir)) { FileSystemUtils::createDirectory(_monitorDir); } _isInitialized = true; } bool CMonitorReadingMessageSource::doSend( const SmartPtrIIntMessage&, int32) { CAF_CM_FUNCNAME("doSend"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_EXCEPTIONEX_VA1( UnsupportedOperationException, E_NOTIMPL, "This is not a sending channel: %s", _id.c_str()); } SmartPtrIIntMessage CMonitorReadingMessageSource::doReceive( const int32 timeout) { CAF_CM_FUNCNAME("doReceive"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Timeout not currently supported: %s", _id.c_str()); } std::string reason; // If Listener is pre-configured and Tunnel enabled, start listener // Sets startup type if it is following tunnel _monitorListener->followTunnel(_listenerStartupType); if (FileSystemUtils::doesFileExist(_listenerConfiguredStage2Path)) { if (FileSystemUtils::doesFileExist(_restartListenerPath)) { reason = FileSystemUtils::loadTextFile(_restartListenerPath); FileSystemUtils::removeFile(_restartListenerPath); _listenerRetryCnt = 0; _listenerStartTimeMs = CDateTimeUtils::getTimeMs(); restartListener(reason); } else { if (isListenerRunning()) { _listenerRetryCnt = 0; if (areSystemResourcesLow()) { reason = "Listener running... Stopping due to low system resources"; stopListener(reason); } else if (isTimeForListenerRestart()) { reason = "Listener running... Restarting due to expired timeout"; _listenerStartTimeMs = CDateTimeUtils::getTimeMs(); restartListener(reason); } } else { if (_listenerStartupType.compare("Automatic") == 0) { if ((_listenerRetryMax < 0) || (_listenerRetryCnt < _listenerRetryMax)) { reason = "Listener not running... Starting - " + CStringConv::toString(_listenerRetryCnt + 1) + " of " + CStringConv::toString(_listenerRetryMax); _listenerRetryCnt++; _listenerStartTimeMs = CDateTimeUtils::getTimeMs(); _monitorListener->startListener(reason); } else { reason = "Listener not running... Retries exhausted - " + CStringConv::toString(_listenerRetryCnt + 1) + " of " + CStringConv::toString(_listenerRetryMax); CAF_CM_LOG_WARN_VA0(reason.c_str()); } } else { reason = "Listener not running... Not Automatic startup - " + _listenerStartupType; CAF_CM_LOG_WARN_VA0(reason.c_str()); _listenerRetryCnt = 0; } } } } else { reason = "Listener not configured"; _listenerRetryCnt = 0; } SmartPtrCIntMessage messageImpl; if (! reason.empty()) { messageImpl.CreateInstance(); messageImpl->initializeStr(reason, IIntMessage::SmartPtrCHeaders(), IIntMessage::SmartPtrCHeaders()); } return messageImpl; } bool CMonitorReadingMessageSource::isListenerRunning() const { const std::string stdoutStr = executeScript(_isListenerRunningScript, _scriptOutputDir); return (stdoutStr.compare("true") == 0); } void CMonitorReadingMessageSource::startListener( const std::string& reason) const { CAF_CM_FUNCNAME_VALIDATE("startListener"); CAF_CM_LOG_DEBUG_VA1( "Starting the listener - reason: %s", reason.c_str()); executeScript(_startListenerScript, _scriptOutputDir); } void CMonitorReadingMessageSource::stopListener( const std::string& reason) const { CAF_CM_FUNCNAME_VALIDATE("stopListener"); CAF_CM_LOG_DEBUG_VA1( "Stopping the listener - reason: %s", reason.c_str()); executeScript(_stopListenerScript, _scriptOutputDir); } void CMonitorReadingMessageSource::restartListener( const std::string& reason) const { CAF_CM_FUNCNAME_VALIDATE("restartListener"); CAF_CM_LOG_DEBUG_VA1( "Restarting the listener - reason: %s", reason.c_str()); executeScript(_stopListenerScript, _scriptOutputDir); executeScript(_startListenerScript, _scriptOutputDir); } std::string CMonitorReadingMessageSource::executeScript( const std::string& scriptPath, const std::string& scriptResultsDir) const { CAF_CM_FUNCNAME_VALIDATE("executeScript"); CAF_CM_VALIDATE_STRING(scriptPath); CAF_CM_VALIDATE_STRING(scriptResultsDir); Cdeqstr argv; argv.push_back(scriptPath); const std::string stdoutPath = FileSystemUtils::buildPath( scriptResultsDir, "stdout"); const std::string stderrPath = FileSystemUtils::buildPath( scriptResultsDir, "stderr"); ProcessUtils::runSyncToFiles(argv, stdoutPath, stderrPath); std::string rc; if (FileSystemUtils::doesFileExist(stdoutPath)) { rc = FileSystemUtils::loadTextFile(stdoutPath); } return rc; } bool CMonitorReadingMessageSource::areSystemResourcesLow() const { // TODO: Implement return false; } bool CMonitorReadingMessageSource::isTimeForListenerRestart() const { return (_listenerRestartMs > 0) && (CDateTimeUtils::calcRemainingTime(_listenerStartTimeMs, _listenerRestartMs) == 0); } uint64 CMonitorReadingMessageSource::calcListenerRestartMs() const { const uint32 listenerRestartDays = AppConfigUtils::getOptionalUint32("monitor", "listener_restart_days"); const uint32 listenerRestartHours = AppConfigUtils::getOptionalUint32("monitor", "listener_restart_hours"); const uint32 listenerRestartMins = AppConfigUtils::getOptionalUint32("monitor", "listener_restart_mins"); const uint32 listenerRestartSecs = AppConfigUtils::getOptionalUint32("monitor", "listener_restart_secs"); uint64 rc = 0; rc = (rc == 0) && (listenerRestartDays > 0) ? CTimeUnit::DAYS::toMilliseconds(listenerRestartDays) : rc; rc = (rc == 0) && (listenerRestartHours > 0) ? CTimeUnit::HOURS::toMilliseconds(listenerRestartHours) : rc; rc = (rc == 0) && (listenerRestartMins > 0) ? CTimeUnit::MINUTES::toMilliseconds(listenerRestartMins) : rc; rc = (rc == 0) && (listenerRestartSecs > 0) ? CTimeUnit::SECONDS::toMilliseconds(listenerRestartSecs) : rc; return rc; } CPersistenceInboundChannelAdapterInstance.cpp000066400000000000000000000117561321503522500447740ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CPersistenceReadingMessageSource.h" #include "Common/IAppContext.h" #include "IBean.h" #include "IPersistence.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/Core/CMessageHandler.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/Core/CSourcePollingChannelAdapter.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IMessageChannel.h" #include "CPersistenceInboundChannelAdapterInstance.h" using namespace Caf; CPersistenceInboundChannelAdapterInstance::CPersistenceInboundChannelAdapterInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CPersistenceInboundChannelAdapterInstance") { } CPersistenceInboundChannelAdapterInstance::~CPersistenceInboundChannelAdapterInstance() { } void CPersistenceInboundChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _configSection = configSection; _id = _configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CPersistenceInboundChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CPersistenceInboundChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const SmartPtrIPersistence persistence = createPersistence(appContext); if (! persistence.IsNull()) { const std::string outputChannelStr = _configSection->findRequiredAttribute("channel"); SmartPtrCPersistenceReadingMessageSource persistenceReadingMessageSource; persistenceReadingMessageSource.CreateInstance(); persistenceReadingMessageSource->initialize(_configSection, persistence); const SmartPtrIMessageChannel outputMessageChannel = channelResolver->resolveChannelName(outputChannelStr); const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); SmartPtrCMessageHandler messageHandler; messageHandler.CreateInstance(); messageHandler->initialize( _id, outputMessageChannel, SmartPtrICafObject()); SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, errorMessageChannel); SmartPtrCSourcePollingChannelAdapter sourcePollingChannelAdapter; sourcePollingChannelAdapter.CreateInstance(); sourcePollingChannelAdapter->initialize( messageHandler, persistenceReadingMessageSource, errorHandler); SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor; simpleAsyncTaskExecutor.CreateInstance(); simpleAsyncTaskExecutor->initialize(sourcePollingChannelAdapter, errorHandler); _taskExecutor = simpleAsyncTaskExecutor; } } void CPersistenceInboundChannelAdapterInstance::start( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (! _taskExecutor.IsNull()) { CAF_CM_LOG_DEBUG_VA0("Starting the executor"); _taskExecutor->execute(timeoutMs); } } void CPersistenceInboundChannelAdapterInstance::stop( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (! _taskExecutor.IsNull()) { CAF_CM_LOG_DEBUG_VA0("Stopping the executor"); _taskExecutor->cancel(timeoutMs); } } bool CPersistenceInboundChannelAdapterInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const bool rc = ! _taskExecutor.IsNull() && (_taskExecutor->getState() == ITaskExecutor::ETaskStateStarted); return rc; } bool CPersistenceInboundChannelAdapterInstance::isMessageProducer() const { CAF_CM_FUNCNAME_VALIDATE("isMessageProducer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return true; } SmartPtrIPersistence CPersistenceInboundChannelAdapterInstance::createPersistence( const SmartPtrIAppContext& appContext) const { CAF_CM_FUNCNAME("createPersistence"); CAF_CM_VALIDATE_INTERFACE(appContext); SmartPtrIPersistence rc; const std::string removeRefStr = _configSection->findRequiredAttribute("ref"); CAF_CM_LOG_DEBUG_VA1("Creating the persistence impl - %s", removeRefStr.c_str()); const SmartPtrIBean bean = appContext->getBean(removeRefStr); rc.QueryInterface(bean, false); CAF_CM_VALIDATE_INTERFACE(rc); try { rc->initialize(); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_WARN_VA2("initialize failed - ref: %s, msg: %s", removeRefStr.c_str(), (CAF_CM_EXCEPTION_GET_FULLMSG).c_str()); rc = SmartPtrIPersistence(); CAF_CM_CLEAREXCEPTION; } return rc; } CPersistenceInboundChannelAdapterInstance.h000066400000000000000000000040341321503522500444300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPersistenceInboundChannelAdapterInstance_h_ #define CPersistenceInboundChannelAdapterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "IPersistence.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/ITaskExecutor.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" #include "Integration/IMessageProducer.h" namespace Caf { class CPersistenceInboundChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle, public IMessageProducer { public: CPersistenceInboundChannelAdapterInstance(); virtual ~CPersistenceInboundChannelAdapterInstance(); public: CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_QI_ENTRY(IMessageProducer) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; public: // IMessageProducer bool isMessageProducer() const; private: SmartPtrIPersistence createPersistence( const SmartPtrIAppContext& appContext) const; private: bool _isInitialized; std::string _id; SmartPtrIDocument _configSection; SmartPtrITaskExecutor _taskExecutor; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CPersistenceInboundChannelAdapterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CPersistenceInboundChannelAdapterInstance); } #endif // #ifndef CPersistenceInboundChannelAdapterInstance_h_ CPersistenceMerge.cpp000066400000000000000000000424731321503522500401560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" #include "CPersistenceMerge.h" using namespace Caf; SmartPtrCPersistenceDoc CPersistenceMerge::mergePersistence( const SmartPtrCPersistenceDoc& persistenceLoaded, const SmartPtrCPersistenceDoc& persistenceIn) { SmartPtrCPersistenceDoc rc; if (persistenceLoaded.IsNull()) { if (! persistenceIn.IsNull()) { rc = persistenceIn; } } else { if (persistenceIn.IsNull()) { rc = persistenceLoaded; } else { const SmartPtrCLocalSecurityDoc localSecurity = mergeLocalSecurity( persistenceLoaded->getLocalSecurity(), persistenceIn->getLocalSecurity()); const SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollection = mergePersistenceProtocolCollection( persistenceLoaded->getPersistenceProtocolCollection(), persistenceIn->getPersistenceProtocolCollection()); const SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollection = mergeRemoteSecurityCollection( persistenceLoaded->getRemoteSecurityCollection(), persistenceIn->getRemoteSecurityCollection()); if (! localSecurity.IsNull() || ! persistenceProtocolCollection.IsNull() || ! remoteSecurityCollection.IsNull()) { rc.CreateInstance(); rc->initialize( localSecurity.IsNull() ? persistenceIn->getLocalSecurity() : localSecurity, remoteSecurityCollection.IsNull() ? persistenceIn->getRemoteSecurityCollection() : remoteSecurityCollection, persistenceProtocolCollection.IsNull() ? persistenceIn->getPersistenceProtocolCollection() : persistenceProtocolCollection, persistenceIn->getVersion()); } } } return rc; } SmartPtrCLocalSecurityDoc CPersistenceMerge::mergeLocalSecurity( const SmartPtrCLocalSecurityDoc& localSecurityLoaded, const SmartPtrCLocalSecurityDoc& localSecurityIn) { SmartPtrCLocalSecurityDoc rc; if (localSecurityLoaded.IsNull()) { if (! localSecurityIn.IsNull()) { rc = localSecurityIn; } } else { if (localSecurityIn.IsNull()) { rc = localSecurityLoaded; } else { const std::string localId = mergeStrings( localSecurityLoaded->getLocalId(), localSecurityIn->getLocalId()); const std::string privateKey = mergeStrings( localSecurityIn->getPrivateKey(), localSecurityLoaded->getPrivateKey()); const std::string certPath = mergeStrings( localSecurityIn->getCert(), localSecurityLoaded->getCertPath()); if (! localId.empty() || ! privateKey.empty() || ! certPath.empty()) { rc.CreateInstance(); rc->initialize( localId.empty() ? localSecurityIn->getLocalId() : localId, privateKey.empty() ? localSecurityIn->getPrivateKey() : privateKey, certPath.empty() ? localSecurityIn->getCertPath() : certPath, localSecurityLoaded->getPrivateKeyPath(), localSecurityLoaded->getCertPath()); } } } return rc; } SmartPtrCPersistenceProtocolCollectionDoc CPersistenceMerge::mergePersistenceProtocolCollection( const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollectionLoaded, const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollectionIn) { SmartPtrCPersistenceProtocolCollectionDoc rc; if (persistenceProtocolCollectionLoaded.IsNull()) { if (! persistenceProtocolCollectionIn.IsNull()) { rc = persistenceProtocolCollectionIn; } } else { if (persistenceProtocolCollectionIn.IsNull()) { rc = persistenceProtocolCollectionLoaded; } else { const std::deque persistenceProtocolCollectionInner = mergePersistenceProtocolCollectionInner( persistenceProtocolCollectionLoaded->getPersistenceProtocol(), persistenceProtocolCollectionIn->getPersistenceProtocol()); if (! persistenceProtocolCollectionInner.empty()) { rc.CreateInstance(); rc->initialize(persistenceProtocolCollectionInner); } } } return rc; } std::deque CPersistenceMerge::mergePersistenceProtocolCollectionInner( const std::deque& persistenceProtocolCollectionInnerLoaded, const std::deque& persistenceProtocolCollectionInnerIn) { CAF_CM_STATIC_FUNC_VALIDATE("CConfigEnvMerge", "mergePersistenceProtocolCollectionInner"); std::deque rc; if (persistenceProtocolCollectionInnerLoaded.empty()) { if (! persistenceProtocolCollectionInnerIn.empty()) { rc = persistenceProtocolCollectionInnerIn; } } else { if (persistenceProtocolCollectionInnerIn.empty()) { rc = persistenceProtocolCollectionInnerLoaded; } else { CAF_CM_VALIDATE_BOOL(persistenceProtocolCollectionInnerLoaded.size() == 1); CAF_CM_VALIDATE_BOOL(persistenceProtocolCollectionInnerIn.size() == 1); typedef std::map > CPersistenceProtocolMap; CPersistenceProtocolMap persistenceProtocolMap; for (TConstIterator > persistenceProtocolLoadedIter(persistenceProtocolCollectionInnerLoaded); persistenceProtocolLoadedIter; persistenceProtocolLoadedIter++) { const SmartPtrCPersistenceProtocolDoc persistenceProtocolLoaded = *persistenceProtocolLoadedIter; persistenceProtocolMap.insert(std::make_pair( persistenceProtocolLoaded->getProtocolName(), std::make_pair(persistenceProtocolLoaded, SmartPtrCPersistenceProtocolDoc()))); } for (TConstIterator > persistenceProtocolInIter(persistenceProtocolCollectionInnerIn); persistenceProtocolInIter; persistenceProtocolInIter++) { const SmartPtrCPersistenceProtocolDoc persistenceProtocolIn = *persistenceProtocolInIter; if (persistenceProtocolMap.find(persistenceProtocolIn->getProtocolName()) == persistenceProtocolMap.end()) { CAF_CM_VALIDATE_BOOL(persistenceProtocolMap.empty()); persistenceProtocolMap.insert(std::make_pair( persistenceProtocolIn->getProtocolName(), std::make_pair(SmartPtrCPersistenceProtocolDoc(), persistenceProtocolIn))); } else { persistenceProtocolMap.find(persistenceProtocolIn->getProtocolName())->second.second = persistenceProtocolIn; } } CAF_CM_VALIDATE_BOOL(persistenceProtocolMap.size() == 1); for (TConstMapIterator persistenceProtocolMapIter(persistenceProtocolMap); persistenceProtocolMapIter; persistenceProtocolMapIter++) { const SmartPtrCPersistenceProtocolDoc persistenceProtocolLoaded = persistenceProtocolMapIter->first; const SmartPtrCPersistenceProtocolDoc persistenceProtocolIn = persistenceProtocolMapIter->second; const SmartPtrCPersistenceProtocolDoc persistenceProtocolTmp = mergePersistenceProtocol(persistenceProtocolLoaded, persistenceProtocolIn); if (! persistenceProtocolTmp.IsNull()) { rc.push_back(persistenceProtocolTmp); } } } } return rc; } SmartPtrCPersistenceProtocolDoc CPersistenceMerge::mergePersistenceProtocol( const SmartPtrCPersistenceProtocolDoc& persistenceProtocolLoaded, const SmartPtrCPersistenceProtocolDoc& persistenceProtocolIn) { SmartPtrCPersistenceProtocolDoc rc; if (persistenceProtocolLoaded.IsNull()) { if (! persistenceProtocolIn.IsNull()) { rc = persistenceProtocolIn; } } else { if (persistenceProtocolIn.IsNull()) { rc = persistenceProtocolLoaded; } else { const std::string protocolName = mergeStrings( persistenceProtocolLoaded->getProtocolName(), persistenceProtocolIn->getProtocolName()); const std::string uri = mergeUri( persistenceProtocolLoaded->getUri(), persistenceProtocolIn->getUri()); const std::string tlsCert = mergeStrings( persistenceProtocolIn->getTlsCert(), persistenceProtocolLoaded->getTlsCert()); const std::string tlsProtocol = mergeStrings( persistenceProtocolIn->getTlsProtocol(), persistenceProtocolLoaded->getTlsProtocol()); const Cdeqstr tlsCipherCollection = mergeDeqstr( persistenceProtocolIn->getTlsCipherCollection(), persistenceProtocolLoaded->getTlsCipherCollection()); const SmartPtrCCertCollectionDoc tlsCertCollection = mergeCertCollection( persistenceProtocolIn->getTlsCertCollection(), persistenceProtocolLoaded->getTlsCertCollection()); if (! protocolName.empty() || ! uri.empty() || ! tlsCert.empty() || ! tlsProtocol.empty() || ! tlsCipherCollection.empty() || ! tlsCertCollection.IsNull()) { rc.CreateInstance(); rc->initialize( protocolName.empty() ? persistenceProtocolIn->getProtocolName() : protocolName, uri.empty() ? persistenceProtocolIn->getUri() : uri, persistenceProtocolLoaded->getUriAmqp(), persistenceProtocolLoaded->getUriTunnel(), tlsCert.empty() ? persistenceProtocolIn->getTlsCert() : tlsCert, tlsProtocol.empty() ? persistenceProtocolIn->getTlsProtocol() : tlsProtocol, tlsCipherCollection.empty() ? persistenceProtocolIn->getTlsCipherCollection() : tlsCipherCollection, tlsCertCollection.IsNull() ? persistenceProtocolIn->getTlsCertCollection() : tlsCertCollection, persistenceProtocolLoaded->getUriAmqpPath(), persistenceProtocolLoaded->getUriTunnelPath(), persistenceProtocolLoaded->getTlsCertPath(), persistenceProtocolLoaded->getTlsCertPathCollection()); } } } return rc; } SmartPtrCRemoteSecurityCollectionDoc CPersistenceMerge::mergeRemoteSecurityCollection( const SmartPtrCRemoteSecurityCollectionDoc& remoteSecurityCollectionLoaded, const SmartPtrCRemoteSecurityCollectionDoc& remoteSecurityCollectionIn) { SmartPtrCRemoteSecurityCollectionDoc rc; if (remoteSecurityCollectionLoaded.IsNull()) { if (! remoteSecurityCollectionIn.IsNull()) { rc = remoteSecurityCollectionIn; } } else { if (remoteSecurityCollectionIn.IsNull()) { rc = remoteSecurityCollectionLoaded; } else { const std::deque remoteSecurityCollectionInner = mergeRemoteSecurityCollectionInner( remoteSecurityCollectionLoaded->getRemoteSecurity(), remoteSecurityCollectionIn->getRemoteSecurity()); if (! remoteSecurityCollectionInner.empty()) { rc.CreateInstance(); rc->initialize(remoteSecurityCollectionInner); } } } return rc; } std::deque CPersistenceMerge::mergeRemoteSecurityCollectionInner( const std::deque& remoteSecurityCollectionInnerLoaded, const std::deque& remoteSecurityCollectionInnerIn) { std::deque rc; if (remoteSecurityCollectionInnerLoaded.empty()) { if (! remoteSecurityCollectionInnerIn.empty()) { rc = remoteSecurityCollectionInnerIn; } } else { if (remoteSecurityCollectionInnerIn.empty()) { rc = remoteSecurityCollectionInnerLoaded; } else { typedef std::map > CRemoteSecurityMap; CRemoteSecurityMap remoteSecurityMap; for (TConstIterator > remoteSecurityLoadedIter(remoteSecurityCollectionInnerLoaded); remoteSecurityLoadedIter; remoteSecurityLoadedIter++) { const SmartPtrCRemoteSecurityDoc remoteSecurityLoaded = *remoteSecurityLoadedIter; remoteSecurityMap.insert(std::make_pair( remoteSecurityLoaded->getRemoteId(), std::make_pair(remoteSecurityLoaded, SmartPtrCRemoteSecurityDoc()))); } for (TConstIterator > remoteSecurityInIter(remoteSecurityCollectionInnerIn); remoteSecurityInIter; remoteSecurityInIter++) { const SmartPtrCRemoteSecurityDoc remoteSecurityIn = *remoteSecurityInIter; if (remoteSecurityMap.find(remoteSecurityIn->getRemoteId()) == remoteSecurityMap.end()) { remoteSecurityMap.insert(std::make_pair( remoteSecurityIn->getRemoteId(), std::make_pair(SmartPtrCRemoteSecurityDoc(), remoteSecurityIn))); } else { remoteSecurityMap.find(remoteSecurityIn->getRemoteId())->second.second = remoteSecurityIn; } } for (TConstMapIterator remoteSecurityMapIter(remoteSecurityMap); remoteSecurityMapIter; remoteSecurityMapIter++) { const SmartPtrCRemoteSecurityDoc remoteSecurityLoaded = (*remoteSecurityMapIter).first; const SmartPtrCRemoteSecurityDoc remoteSecurityIn = (*remoteSecurityMapIter).second; const SmartPtrCRemoteSecurityDoc remoteSecurityTmp = mergeRemoteSecurity(remoteSecurityLoaded, remoteSecurityIn); if (! remoteSecurityTmp.IsNull()) { rc.push_back(remoteSecurityTmp); } } } } return rc; } SmartPtrCRemoteSecurityDoc CPersistenceMerge::mergeRemoteSecurity( const SmartPtrCRemoteSecurityDoc& remoteSecurityLoaded, const SmartPtrCRemoteSecurityDoc& remoteSecurityIn) { SmartPtrCRemoteSecurityDoc rc; if (remoteSecurityLoaded.IsNull()) { if (! remoteSecurityIn.IsNull()) { rc = remoteSecurityIn; } } else { if (remoteSecurityIn.IsNull()) { rc = remoteSecurityLoaded; } else { const std::string remoteId = mergeStrings( remoteSecurityLoaded->getRemoteId(), remoteSecurityIn->getRemoteId()); const std::string protocolName = mergeStrings( remoteSecurityLoaded->getProtocolName(), remoteSecurityIn->getProtocolName()); const std::string cmsCert = mergeStrings( remoteSecurityIn->getCmsCert(), remoteSecurityLoaded->getCmsCert()); const std::string cmsCipherName = mergeStrings( remoteSecurityIn->getCmsCipherName(), remoteSecurityLoaded->getCmsCipherName()); const SmartPtrCCertCollectionDoc cmsCertCollection = mergeCertCollection( remoteSecurityIn->getCmsCertCollection(), remoteSecurityLoaded->getCmsCertCollection()); if (! remoteId.empty() || ! protocolName.empty() || ! cmsCert.empty() || ! cmsCipherName.empty() || ! cmsCertCollection.IsNull()) { rc.CreateInstance(); rc->initialize( remoteId.empty() ? remoteSecurityIn->getRemoteId() : remoteId, protocolName.empty() ? remoteSecurityIn->getProtocolName() : protocolName, cmsCert.empty() ? remoteSecurityIn->getCmsCert() : cmsCert, cmsCipherName.empty() ? remoteSecurityIn->getCmsCipherName() : cmsCipherName, cmsCertCollection.IsNull() ? remoteSecurityIn->getCmsCertCollection() : cmsCertCollection, remoteSecurityLoaded->getCmsCertPath(), remoteSecurityLoaded->getCmsCertPathCollection()); } } } return rc; } SmartPtrCCertCollectionDoc CPersistenceMerge::mergeCertCollection( const SmartPtrCCertCollectionDoc& certCollectionLoaded, const SmartPtrCCertCollectionDoc& certCollectionIn) { SmartPtrCCertCollectionDoc rc; if (certCollectionLoaded.IsNull()) { if (! certCollectionIn.IsNull()) { rc = certCollectionIn; } } else { if (certCollectionIn.IsNull()) { rc = certCollectionLoaded; } else { const std::deque certCollectionInner = mergeDeqstr( certCollectionLoaded->getCert(), certCollectionIn->getCert()); if (! certCollectionInner.empty()) { rc.CreateInstance(); rc->initialize(certCollectionInner); } } } return rc; } std::string CPersistenceMerge::mergeUri( const std::string& uriPreferred, const std::string& uriOther) { CAF_CM_STATIC_FUNC_LOG_ONLY("CPersistenceMerge", "mergeUri"); std::string rc; if (! uriPreferred.empty() && ! uriOther.empty()) { UriUtils::SUriRecord uriRecordPreferred; UriUtils::parseUriString(uriPreferred, uriRecordPreferred); UriUtils::SUriRecord uriRecordOther; UriUtils::parseUriString(uriOther, uriRecordOther); if (! uriRecordOther.host.empty() && (uriRecordPreferred.host.length() > 1) && ('#' == uriRecordPreferred.host[0]) && ('#' == uriRecordPreferred.host[uriRecordPreferred.host.length() - 1])) { CAF_CM_LOG_DEBUG_VA2("URI host changed - %s != %s", uriRecordPreferred.host.c_str(), uriRecordOther.host.c_str()); uriRecordPreferred.host = uriRecordOther.host; } if (! uriRecordOther.username.empty() && (uriRecordPreferred.username.length() > 1) && ('#' == uriRecordPreferred.username[0]) && ('#' == uriRecordPreferred.username[uriRecordPreferred.username.length() - 1])) { CAF_CM_LOG_DEBUG_VA2("URI username changed - %s != %s", uriRecordPreferred.username.c_str(), uriRecordOther.username.c_str()); uriRecordPreferred.username = uriRecordOther.username; } if (! uriRecordOther.username.empty() && (uriRecordPreferred.password.length() > 1) && ('#' == uriRecordPreferred.password[0]) && ('#' == uriRecordPreferred.password[uriRecordPreferred.password.length() - 1])) { CAF_CM_LOG_DEBUG_VA0("URI password changed"); uriRecordPreferred.password = uriRecordOther.password; } rc = UriUtils::buildUriString(uriRecordPreferred); } else { rc = mergeStrings(uriPreferred, uriOther); } return rc; } std::string CPersistenceMerge::mergeStrings( const std::string& strPreferred, const std::string& strOther) { return (strPreferred.compare(strOther) == 0) ? std::string() : strPreferred; } Cdeqstr CPersistenceMerge::mergeDeqstr( const Cdeqstr& deqstrPreferred, const Cdeqstr& deqstrOther) { Cdeqstr rc; if (deqstrPreferred.empty()) { if (! deqstrOther.empty()) { rc = deqstrOther; } } else { if (deqstrOther.empty()) { rc = deqstrPreferred; } } return rc; } CPersistenceMerge.h000066400000000000000000000056761321503522500376270ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CPersistenceMerge_h_ #define _MaIntegration_CPersistenceMerge_h_ #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" using namespace Caf; /// TODO - describe class class CPersistenceMerge { public: static SmartPtrCPersistenceDoc mergePersistence( const SmartPtrCPersistenceDoc& persistenceLoaded, const SmartPtrCPersistenceDoc& persistenceIn); private: static SmartPtrCLocalSecurityDoc mergeLocalSecurity( const SmartPtrCLocalSecurityDoc& localSecurityLoaded, const SmartPtrCLocalSecurityDoc& localSecurityIn); static SmartPtrCPersistenceProtocolCollectionDoc mergePersistenceProtocolCollection( const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollectionLoaded, const SmartPtrCPersistenceProtocolCollectionDoc& persistenceProtocolCollectionIn); static std::deque mergePersistenceProtocolCollectionInner( const std::deque& persistenceProtocolCollectionInnerLoaded, const std::deque& persistenceProtocolCollectionInnerIn); static SmartPtrCPersistenceProtocolDoc mergePersistenceProtocol( const SmartPtrCPersistenceProtocolDoc& persistenceProtocolLoaded, const SmartPtrCPersistenceProtocolDoc& persistenceProtocolIn); static SmartPtrCRemoteSecurityCollectionDoc mergeRemoteSecurityCollection( const SmartPtrCRemoteSecurityCollectionDoc& remoteSecurityCollectionLoaded, const SmartPtrCRemoteSecurityCollectionDoc& remoteSecurityCollectionIn); static std::deque mergeRemoteSecurityCollectionInner( const std::deque& remoteSecurityCollectionInnerLoaded, const std::deque& remoteSecurityCollectionInnerIn); static SmartPtrCRemoteSecurityDoc mergeRemoteSecurity( const SmartPtrCRemoteSecurityDoc& remoteSecurityLoaded, const SmartPtrCRemoteSecurityDoc& remoteSecurityIn); static SmartPtrCCertCollectionDoc mergeCertCollection( const SmartPtrCCertCollectionDoc& certCollectionLoaded, const SmartPtrCCertCollectionDoc& certCollectionIn); static std::string mergeStrings( const std::string& strLoaded, const std::string& strIn); static std::string mergeUri( const std::string& uriLoaded, const std::string& uriIn); static Cdeqstr mergeDeqstr( const Cdeqstr& deqstrPreferred, const Cdeqstr& deqstrOther); private: CAF_CM_DECLARE_NOCREATE(CPersistenceMerge); }; #endif // #ifndef _MaIntegration_CPersistenceMerge_h_ CPersistenceMessageHandler.cpp000066400000000000000000000043551321503522500417760ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlRoots.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "IPersistence.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CPersistenceMessageHandler.h" using namespace Caf; CPersistenceMessageHandler::CPersistenceMessageHandler() : _isInitialized(false), CAF_CM_INIT_LOG("CPersistenceMessageHandler") { } CPersistenceMessageHandler::~CPersistenceMessageHandler() { } void CPersistenceMessageHandler::initialize( const SmartPtrIDocument& configSection, const SmartPtrIPersistence& persistence) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); CAF_CM_VALIDATE_SMARTPTR(persistence); _id = configSection->findRequiredAttribute("id"); _persistence = persistence; _isInitialized = true; } void CPersistenceMessageHandler::handleMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _savedMessage = message; SmartPtrCPersistenceDoc persistence; const std::string payloadStr = message->getPayloadStr(); if (! payloadStr.empty()) { persistence = XmlRoots::parsePersistenceFromString(payloadStr); } _persistence->update(persistence); } SmartPtrIIntMessage CPersistenceMessageHandler::getSavedMessage() const { CAF_CM_FUNCNAME_VALIDATE("getSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _savedMessage; } void CPersistenceMessageHandler::clearSavedMessage() { CAF_CM_FUNCNAME_VALIDATE("clearSavedMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); _savedMessage = NULL; } SmartPtrIIntMessage CPersistenceMessageHandler::processErrorMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("processErrorMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); _savedMessage = message; //TODO: Verify that I'm receiving the error message and decide what //to do with it. return SmartPtrIIntMessage(); } CPersistenceMessageHandler.h000066400000000000000000000026571321503522500414460ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CPersistenceMessageHandler_h_ #define _MaIntegration_CPersistenceMessageHandler_h_ #include "Integration/IErrorProcessor.h" #include "IPersistence.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageHandler.h" namespace Caf { class CPersistenceMessageHandler : public IMessageHandler, public IErrorProcessor { public: CPersistenceMessageHandler(); virtual ~CPersistenceMessageHandler(); public: CAF_BEGIN_QI() CAF_QI_ENTRY(IMessageHandler) CAF_QI_ENTRY(IErrorProcessor) CAF_END_QI() public: void initialize( const SmartPtrIDocument& configSection, const SmartPtrIPersistence& persistence); public: // IMessageHandler void handleMessage( const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); public: // IErrorProcessor SmartPtrIIntMessage processErrorMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; SmartPtrIPersistence _persistence; SmartPtrIIntMessage _savedMessage; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CPersistenceMessageHandler); }; CAF_DECLARE_SMART_QI_POINTER(CPersistenceMessageHandler); } #endif // #ifndef _MaIntegration_CPersistenceMessageHandler_h_ CPersistenceNamespaceDb.cpp000066400000000000000000000510251321503522500412520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CCertCollectionDoc.h" #include "Doc/PersistenceDoc/CLocalSecurityDoc.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolCollectionDoc.h" #include "Doc/PersistenceDoc/CPersistenceProtocolDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" #include "Exception/CCafException.h" #include "CPersistenceNamespaceDb.h" #include using namespace Caf; CPersistenceNamespaceDb::CPersistenceNamespaceDb() : _isInitialized(false), _isReady(false), _dataReady2Read(false), _dataReady2Update(false), _dataReady2Remove(false), _polledDuringStart(false), _pollingIntervalSecs(86400), _pollingStartedTimeMs(0), CAF_CM_INIT_LOG("CPersistenceNamespaceDb") { CAF_CM_INIT_THREADSAFE; _nsdbNamespace = "com.vmware.caf.guest.rw"; } CPersistenceNamespaceDb::~CPersistenceNamespaceDb() { } void CPersistenceNamespaceDb::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { } void CPersistenceNamespaceDb::terminateBean() { } void CPersistenceNamespaceDb::initialize() { CAF_CM_LOCK_UNLOCK; if (! _isInitialized) { _polledDuringStart = false; _nsdbPollerSignalFile = AppConfigUtils::getRequiredString("monitor", "nsdb_poller_signal_file"); _pollingIntervalSecs = AppConfigUtils::getRequiredUint32("monitor", "nsdb_polling_interval_secs"); _pollingStartedTimeMs = CDateTimeUtils::getTimeMs(); setCmd(); _isInitialized = true; } } SmartPtrCPersistenceDoc CPersistenceNamespaceDb::getUpdated( const int32 timeout) { CAF_CM_FUNCNAME_VALIDATE("getUpdated"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("getUpdated"); SmartPtrCPersistenceDoc rc; if (isDataReady2Read() && isReady()) { const std::string updatesCur = getValue("updates"); if (_updates.compare(updatesCur) != 0) { _updates = updatesCur; const std::string version = getValue("version"); //EP Doc const std::string epLocalId = getValue("ep.local_id"); const std::string epPrivateKey = getValue("ep.private_key"); const std::string epCert = getValue("ep.cert"); SmartPtrCLocalSecurityDoc endpoint; endpoint.CreateInstance(); endpoint->initialize(epLocalId, epPrivateKey, epCert); //App collection std::deque applicationCollectionInner; const std::string applications = getValue("applications"); Cdeqstr appList = CStringUtils::split(applications, ','); for (Cdeqstr::iterator appIt = appList.begin(); appIt != appList.end(); appIt++) { const std::string appKey = "app." + *appIt; const std::string appId = getValue(appKey + ".remote_id"); const std::string appProtocolName = getValue(appKey + ".protocol_name"); const std::string appCmsCipher = getValue(appKey + ".cms.cipher"); std::deque cmsCertCollectionInner; const std::string appCmsCertChain = getValue(appKey + ".cms.cert_chain"); Cdeqstr appCertList = CStringUtils::split(appCmsCertChain, ','); for (Cdeqstr::iterator appCertIt = appCertList.begin(); appCertIt != appCertList.end(); appCertIt++) { cmsCertCollectionInner.push_back(*appCertIt); } SmartPtrCCertCollectionDoc cmsCertCollection; cmsCertCollection.CreateInstance(); cmsCertCollection->initialize(cmsCertCollectionInner); const std::string cmsCert = getValue(appKey + ".cms.cert"); SmartPtrCRemoteSecurityDoc application; application.CreateInstance(); application->initialize(appId, appProtocolName, cmsCert, appCmsCipher, cmsCertCollection); applicationCollectionInner.push_back(application); } SmartPtrCRemoteSecurityCollectionDoc applicationCollection; applicationCollection.CreateInstance(); applicationCollection->initialize(applicationCollectionInner); const std::string protocols = getValue("protocols"); Cdeqstr protocolList = CStringUtils::split(protocols, ','); std::deque persistenceProtocolCollectionInner; for (Cdeqstr::iterator protocolIt = protocolList.begin(); protocolIt != protocolList.end(); protocolIt++) { const std::string protocolKey = "protocol." + *protocolIt; //Protoccol Doc std::deque tlsCertCollectionInner; const std::string tlsCertChain = getValue(protocolKey + ".tls.cert.chain"); Cdeqstr tlsCertList = CStringUtils::split(tlsCertChain, ','); for (Cdeqstr::iterator tlsCertIt = tlsCertList.begin(); tlsCertIt != tlsCertList.end(); tlsCertIt++) { tlsCertCollectionInner.push_back(*tlsCertIt); } Cdeqstr tlsCipherCollection; const std::string tlsCiphers = getValue(protocolKey + ".tls.ciphers"); Cdeqstr tlsCipherList = CStringUtils::split(tlsCiphers, ','); for (Cdeqstr::iterator tlsCipherIt = tlsCipherList.begin(); tlsCipherIt != tlsCipherList.end(); tlsCipherIt++) { tlsCipherCollection.push_back(*tlsCipherIt); } SmartPtrCCertCollectionDoc tlsCertCollection; tlsCertCollection.CreateInstance(); tlsCertCollection->initialize(tlsCertCollectionInner); //For now, we only support one broker. const std::string protocolName = getValue(protocolKey + ".protocol_name"); const std::string tlsCert = getValue(protocolKey + ".tls.cert"); const std::string tlsProtocol = getValue(protocolKey + ".tls.protocol"); const std::string uri = getValue(protocolKey + ".uri"); const std::string uriAmqp = getValue(protocolKey + ".uri.amqp"); const std::string uriTunnel = getValue(protocolKey + ".uri.tunnel"); SmartPtrCPersistenceProtocolDoc persistenceProtocol; persistenceProtocol.CreateInstance(); persistenceProtocol->initialize( protocolName, uri, uriAmqp, uriTunnel, tlsCert, tlsProtocol, tlsCipherCollection, tlsCertCollection); persistenceProtocolCollectionInner.push_back(persistenceProtocol); } SmartPtrCPersistenceProtocolCollectionDoc persistenceProtocolCollection; persistenceProtocolCollection.CreateInstance(); persistenceProtocolCollection->initialize(persistenceProtocolCollectionInner); // Persist doc rc.CreateInstance(); rc->initialize(endpoint, applicationCollection, persistenceProtocolCollection, version); } } if (rc.IsNull()) { rc = _persistenceUpdate; } _dataReady2Read = false; return rc; } void CPersistenceNamespaceDb::update( const SmartPtrCPersistenceDoc& persistenceDoc) { CAF_CM_FUNCNAME("update"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("update"); if (isDataReady2Update() && isReady()) { const SmartPtrCPersistenceDoc persistenceCur = persistenceDoc.IsNull() ? _persistenceUpdate : persistenceDoc; if (! persistenceCur.IsNull()) { _persistenceUpdate = SmartPtrCPersistenceDoc(); setValue("version", persistenceCur->getVersion()); //Update LocalSecurity info if (!persistenceCur->getLocalSecurity().IsNull()){ setValue("ep.local_id", persistenceCur->getLocalSecurity()->getLocalId()); setValue("ep.private_key", persistenceCur->getLocalSecurity()->getPrivateKey()); setValue("ep.cert", persistenceCur->getLocalSecurity()->getCert()); } //Update RemoteSecurity info if (!persistenceCur->getRemoteSecurityCollection().IsNull()){ std::deque applications = persistenceCur->getRemoteSecurityCollection()->getRemoteSecurity(); for (std::deque::iterator appIt = applications.begin(); appIt != applications.end(); appIt++) { const std::string appKey = "app." + (*appIt)->getRemoteId(); setValue(appKey + ".remote_id", (*appIt)->getRemoteId()); setValue(appKey + ".cms.cert", (*appIt)->getCmsCert()); setValue(appKey + ".cms.cipher", (*appIt)->getCmsCipherName()); setValue(appKey + ".protocol_name", (*appIt)->getProtocolName()); std::string cmsCertChain; if (! (*appIt)->getCmsCertCollection().IsNull()) { Cdeqstr cmsCertList = (*appIt)->getCmsCertCollection()->getCert(); for (Cdeqstr::iterator cmsCertIt=cmsCertList.begin(); cmsCertIt != cmsCertList.end(); cmsCertIt++) { if (!cmsCertChain.empty()) { cmsCertChain += ","; } cmsCertChain += *cmsCertIt; } setValue(appKey + ".cms.cert_chain", cmsCertChain); } } } //Update PersistenceProtocol info if (!persistenceCur->getPersistenceProtocolCollection().IsNull()) { //For now, we only support one broker. CAF_CM_ASSERT(persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol().size() <= 1); std::deque brokerList = persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol(); for (std::deque::iterator protIt=brokerList.begin(); protIt != brokerList.end(); protIt++) { const std::string protocolKey = "protocol." + (*protIt)->getProtocolName(); setValue(protocolKey + ".protocol_name", (*protIt)->getProtocolName()); setValue(protocolKey + ".uri", (*protIt)->getUri()); setValue(protocolKey + ".uri.amqp", (*protIt)->getUriAmqp()); setValue(protocolKey + ".uri.tunnel", (*protIt)->getUriTunnel()); setValue(protocolKey + ".tls.cert", (*protIt)->getTlsCert()); setValue(protocolKey + ".tls.protocol", (*protIt)->getTlsProtocol()); Cdeqstr tlsCipherList = (*protIt)->getTlsCipherCollection(); std::string tlsCiphers; for (Cdeqstr::iterator tlsCipherIt=tlsCipherList.begin(); tlsCipherIt != tlsCipherList.end(); tlsCipherIt++) { if (!tlsCiphers.empty()) { tlsCiphers += ","; } tlsCiphers += *tlsCipherIt; } setValue(protocolKey + ".tls.ciphers", tlsCiphers); if (! (*protIt)->getTlsCertCollection().IsNull()) { Cdeqstr tlsCertList = (*protIt)->getTlsCertCollection()->getCert(); std::string tlsCerts; for (Cdeqstr::iterator tlsCertIt=tlsCertList.begin(); tlsCertIt != tlsCertList.end(); tlsCertIt++) { if (!tlsCerts.empty()) { tlsCerts += ","; } tlsCerts += *tlsCertIt; } setValue(protocolKey + ".tls.cert_chain", tlsCerts); } } } } } else { if (! persistenceDoc.IsNull()) { _persistenceUpdate = persistenceDoc; } } _dataReady2Update = false; } void CPersistenceNamespaceDb::remove( const SmartPtrCPersistenceDoc& persistenceDoc) { CAF_CM_FUNCNAME("remove"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("remove"); if (isDataReady2Remove() && isReady()) { const SmartPtrCPersistenceDoc persistenceCur = persistenceDoc.IsNull() ? _persistenceRemove : persistenceDoc; if (! persistenceCur.IsNull()) { _persistenceRemove = SmartPtrCPersistenceDoc(); if (!persistenceCur->getLocalSecurity().IsNull()){ if (!persistenceCur->getLocalSecurity()->getLocalId().empty()) { removeKey("ep.local_id"); } if (!persistenceCur->getLocalSecurity()->getPrivateKey().empty()) { removeKey("ep.private_key"); } if (!persistenceCur->getLocalSecurity()->getCert().empty()) { removeKey("ep.cert"); } } //Remove RemoteSecurity info if (!persistenceCur->getRemoteSecurityCollection().IsNull()){ std::deque applications = persistenceCur->getRemoteSecurityCollection()->getRemoteSecurity(); for (std::deque::iterator it=applications.begin(); it != applications.end(); it++) { std::string appKey = "app." + (*it)->getRemoteId(); if (!(*it)->getProtocolName().empty()) { removeKey(appKey + ".protocol_name"); } if (!(*it)->getCmsCert().empty()) { removeKey(appKey + ".cms.cert"); } if (!(*it)->getCmsCertCollection().IsNull() && !(*it)->getCmsCertCollection()->getCert().empty()) { removeKey(appKey + ".cms.cert_chain"); } if (!(*it)->getCmsCipherName().empty()) { removeKey(appKey + ".cms.cipher"); } } } //Remove PersistenceProtocol info if (!persistenceCur->getPersistenceProtocolCollection().IsNull()) { //For now, we only support one broker. CAF_CM_ASSERT(persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol().size() <= 1); std::deque brokerList = persistenceCur->getPersistenceProtocolCollection()->getPersistenceProtocol(); for (std::deque::iterator it=brokerList.begin(); it != brokerList.end(); it++) { std::string protocolKey = "protocol." + (*it)->getProtocolName(); if (!(*it)->getUri().empty()) { removeKey(protocolKey + "uri"); } if (!(*it)->getUriAmqp().empty()) { removeKey(protocolKey + "uri.amqp"); } if (!(*it)->getUriTunnel().empty()) { removeKey(protocolKey + "uri.tunnel"); } if (!(*it)->getTlsCert().empty()) { removeKey(protocolKey + "tls.cert"); } if (!(*it)->getTlsProtocol().empty()) { removeKey(protocolKey + "tls.protocol"); } if (!(*it)->getTlsCipherCollection().empty()) { removeKey(protocolKey + "tls.ciphers"); } if (!(*it)->getTlsCertCollection().IsNull() && !(*it)->getTlsCertCollection()->getCert().empty()) { removeKey(protocolKey + "tls.cert_chain"); } } } } } else { if (! persistenceDoc.IsNull()) { _persistenceRemove = persistenceDoc; } } _dataReady2Remove = false; } void CPersistenceNamespaceDb::setCmd() { CAF_CM_FUNCNAME("setCmd"); std::string nsdbCmdDir; std::string nsdbCmdFile; #ifdef WIN32 // "C:/Program Files/VMware/VMware Tools/VMwareNamespaceCmd.exe"; // bin_dir=C:/Program Files/VMware/VMware Tools/VMware CAF/pme//bin nsdbCmdDir = AppConfigUtils::getRequiredString("globals", "bin_dir"); //Back up two levels nsdbCmdDir = FileSystemUtils::getDirname(nsdbCmdDir); nsdbCmdDir = FileSystemUtils::getDirname(nsdbCmdDir); nsdbCmdFile = "VMwareNamespaceCmd.exe"; #else nsdbCmdDir = "/usr/sbin"; nsdbCmdFile = "vmware-namespace-cmd"; #endif _nsdbCmdPath = FileSystemUtils::buildPath(nsdbCmdDir, nsdbCmdFile); CAF_CM_LOG_DEBUG_VA1("_nsdbCmdPath: %s", _nsdbCmdPath.c_str()); if (!FileSystemUtils::doesFileExist(_nsdbCmdPath)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Namespace DB command not found - %s", _nsdbCmdPath.c_str()); } } std::string CPersistenceNamespaceDb::getValue(const std::string& key) { CAF_CM_FUNCNAME("getValue"); CAF_CM_VALIDATE_STRING(key); CAF_CM_LOG_DEBUG_VA0("getValue"); std::string value; std::string stdoutContent; std::string stderrContent; try { value = getValueRaw(key, stdoutContent, stderrContent); } catch(ProcessFailedException* ex){ CAF_CM_LOG_DEBUG_VA1("ProcessFailedException - %s", ex->getMsg().c_str()); CAF_CM_EXCEPTION_VA3(E_UNEXPECTED, "NamespaceDB command failed - %s: %s: %s", ex->getMsg().c_str(), stdoutContent.c_str(), stderrContent.c_str()); } return value; } void CPersistenceNamespaceDb::setValue( const std::string& key, const std::string& value) { CAF_CM_FUNCNAME("setValue"); CAF_CM_VALIDATE_STRING(key); CAF_CM_LOG_DEBUG_VA0("setValue"); if (_removedKeys.find(key) == _removedKeys.end()) { if (value.empty()) { CAF_CM_LOG_DEBUG_VA1("Cannot set empty value: %s", key.c_str()); return; } std::string stdoutContent; std::string stderrContent; Cdeqstr argv; std::string tmpFile; try { tmpFile = FileSystemUtils::saveTempTextFile("caf_nsdb_XXXXXX", value); CAF_CM_LOG_DEBUG_VA2("Setting %s to %s", key.c_str(), value.c_str()); argv.push_back(_nsdbCmdPath); argv.push_back("set-key"); argv.push_back(_nsdbNamespace); argv.push_back("-k"); argv.push_back(key); argv.push_back("-f"); argv.push_back(tmpFile); ProcessUtils::runSync(argv, stdoutContent, stderrContent); } catch(ProcessFailedException* ex){ CAF_CM_LOG_DEBUG_VA1("exception: %s", ex->getMsg().c_str()); CAF_CM_EXCEPTION_VA3(E_UNEXPECTED, "NamespaceDB command failed - %s: %s: %s", ex->getMsg().c_str(), stdoutContent.c_str(), stderrContent.c_str()); } if ( !tmpFile.empty() && FileSystemUtils::doesFileExist(tmpFile)) { FileSystemUtils::removeFile(tmpFile); } } else { CAF_CM_LOG_DEBUG_VA1("Cannot set a removed key: %s", key.c_str()); } } void CPersistenceNamespaceDb::removeKey(const std::string& key) { CAF_CM_FUNCNAME("removeKey"); CAF_CM_VALIDATE_STRING(key); CAF_CM_LOG_DEBUG_VA0("removeKey"); if (_removedKeys.find(key) == _removedKeys.end()) { std::string stdoutContent; std::string stderrContent; Cdeqstr argv; try { argv.push_back(_nsdbCmdPath); argv.push_back("delete-key"); argv.push_back(_nsdbNamespace); argv.push_back("-k"); argv.push_back(key); ProcessUtils::runSync(argv, stdoutContent, stderrContent); _removedKeys.insert(key); } catch(ProcessFailedException* ex){ CAF_CM_LOG_DEBUG_VA1("exception: %s", ex->getMsg().c_str()); CAF_CM_EXCEPTION_VA3(E_UNEXPECTED, "NamespaceDB command failed - %s: %s: %s", ex->getMsg().c_str(), stdoutContent.c_str(), stderrContent.c_str()); } } else { CAF_CM_LOG_DEBUG_VA1("Key already removed: %s", key.c_str()); } } bool CPersistenceNamespaceDb::isDataReady() { CAF_CM_FUNCNAME_VALIDATE("isDataReady"); CAF_CM_LOG_DEBUG_VA0("isDataReady method"); // Check if data is ready to read/modify bool rc = false; if (!_polledDuringStart) { rc = true; _polledDuringStart = true; CAF_CM_LOG_DEBUG_VA0("Set NSDB polling during service start"); } if (FileSystemUtils::doesFileExist(_nsdbPollerSignalFile)) { rc = true; CAF_CM_LOG_DEBUG_VA1("NSDB poller signal file %s exists.", _nsdbPollerSignalFile.c_str()); FileSystemUtils::removeFile(_nsdbPollerSignalFile); } CAF_CM_LOG_DEBUG_VA4("NSDB poller signal file %s, _pollingStartedTimeMs=%ld, _pollingIntervalSecs=%ld, rc=%s.", _nsdbPollerSignalFile.c_str(), long(_pollingStartedTimeMs), long(_pollingIntervalSecs), rc?"true":"false"); if (CDateTimeUtils::calcRemainingTime(_pollingStartedTimeMs, _pollingIntervalSecs * 1000) <= 0) { rc = true; CAF_CM_LOG_DEBUG_VA0("The next polling interval reached."); } if (rc) { _pollingStartedTimeMs = CDateTimeUtils::getTimeMs(); _dataReady2Read = _dataReady2Update = _dataReady2Remove = true; } return rc; } bool CPersistenceNamespaceDb::isDataReady2Read() { CAF_CM_FUNCNAME_VALIDATE("isDataReady2Read"); CAF_CM_LOG_DEBUG_VA1("_dataReady2Read = %s", _dataReady2Read?"true":"false"); return (isDataReady() || _dataReady2Read); } bool CPersistenceNamespaceDb::isDataReady2Update() { CAF_CM_FUNCNAME_VALIDATE("isDataReady2Update"); CAF_CM_LOG_DEBUG_VA1("_dataReady2Update = %s", _dataReady2Update?"true":"false"); return (isDataReady() || _dataReady2Update); } bool CPersistenceNamespaceDb::isDataReady2Remove() { CAF_CM_FUNCNAME_VALIDATE("isDataReady2Remove"); CAF_CM_LOG_DEBUG_VA1("_dataReady2Remove = %s", _dataReady2Remove?"true":"false"); return (isDataReady() || _dataReady2Remove); } bool CPersistenceNamespaceDb::isReady() { CAF_CM_FUNCNAME("isReady"); CAF_CM_LOG_DEBUG_VA0("isReady method"); bool rc = true; if (! _isReady) { std::string stdoutContent; std::string stderrContent; try { (void) getValueRaw("updates", stdoutContent, stderrContent); _isReady = true; } catch(ProcessFailedException* ex) { if ((stderrContent.find("There is no namespace database associated with this virtual machine") != std::string::npos) || (stderrContent.find("Permission denied") != std::string::npos)) { CAF_CM_LOG_DEBUG_VA1( "Received expected exception - msg: %s", ex->getMsg().c_str()); rc = false; } else { CAF_CM_LOG_DEBUG_VA3( "ProcessFailedException - msg: %s, stdout: %s, stderr: %s", ex->getMsg().c_str(), stdoutContent.c_str(), stderrContent.c_str()); CAF_CM_EXCEPTION_VA1(E_UNEXPECTED, "NamespaceDB command failed - msg: %s", ex->getMsg().c_str()); } } } return rc; } std::string CPersistenceNamespaceDb::getValueRaw( const std::string& key, std::string& stdoutContent, std::string& stderrContent) { CAF_CM_FUNCNAME_VALIDATE("getValueRaw"); CAF_CM_VALIDATE_STRING(key); CAF_CM_LOG_ERROR_VA0("getValueRaw"); Cdeqstr argv; argv.push_back(_nsdbCmdPath); argv.push_back("get-value"); argv.push_back(_nsdbNamespace); argv.push_back("-k"); argv.push_back(key); ProcessUtils::runSync(argv, stdoutContent, stderrContent); std::string value = stdoutContent; //strip spaces value = CStringUtils::trim(value); //strip quotes //TODO: make this less of a hack and add it to StringUtils if (value.length() > 1) { if (value[0] == '"') value.erase(0,1); if (value[value.length()-1] == '"') value.erase(value.length()-1,1); } return value; } CPersistenceNamespaceDb.h000066400000000000000000000043201321503522500407130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_CPersistenceNamespaceDb_h_ #define _MaIntegration_CPersistenceNamespaceDb_h_ #include "IBean.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "IPersistence.h" using namespace Caf; /// TODO - describe class class CPersistenceNamespaceDb : public TCafSubSystemObjectRoot, public IBean, public IPersistence { public: CPersistenceNamespaceDb(); virtual ~CPersistenceNamespaceDb(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdPersistenceNamespaceDb) CAF_BEGIN_INTERFACE_MAP(CPersistenceNamespaceDb) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IPersistence) CAF_END_INTERFACE_MAP() public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IPersistence void initialize(); SmartPtrCPersistenceDoc getUpdated( const int32 timeout); void update( const SmartPtrCPersistenceDoc& persistence); void remove( const SmartPtrCPersistenceDoc& persistence); private: void setCmd(); std::string getValue( const std::string& key); void setValue( const std::string& key, const std::string& value); void removeKey(const std::string& key); bool isReady(); bool isDataReady(); bool isDataReady2Read(); bool isDataReady2Update(); bool isDataReady2Remove(); std::string getValueRaw( const std::string& key, std::string& stdoutContent, std::string& stderrContent); private: bool _isInitialized; bool _isReady; bool _dataReady2Read; bool _dataReady2Update; bool _dataReady2Remove; bool _polledDuringStart; uint32 _pollingIntervalSecs; uint64 _pollingStartedTimeMs; std::string _nsdbCmdPath; std::string _nsdbNamespace; std::string _nsdbPollerSignalFile; Csetstr _removedKeys; std::string _updates; SmartPtrCPersistenceDoc _persistenceUpdate; SmartPtrCPersistenceDoc _persistenceRemove; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_CREATE_THREADSAFE; CAF_CM_DECLARE_NOCOPY(CPersistenceNamespaceDb); }; #endif // #ifndef _MaIntegration_CPersistenceNamespaceDb_h_ CPersistenceOutboundChannelAdapterInstance.cpp000066400000000000000000000103761321503522500451720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CPersistenceMessageHandler.h" #include "Common/IAppContext.h" #include "IBean.h" #include "IPersistence.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IMessageChannel.h" #include "Integration/IMessageHandler.h" #include "CPersistenceOutboundChannelAdapterInstance.h" using namespace Caf; CPersistenceOutboundChannelAdapterInstance::CPersistenceOutboundChannelAdapterInstance() : _isInitialized(false), _isRunning(false), CAF_CM_INIT_LOG("CPersistenceOutboundChannelAdapterInstance") { } CPersistenceOutboundChannelAdapterInstance::~CPersistenceOutboundChannelAdapterInstance() { } void CPersistenceOutboundChannelAdapterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _configSection = configSection; _isInitialized = true; } std::string CPersistenceOutboundChannelAdapterInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CPersistenceOutboundChannelAdapterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); const SmartPtrIPersistence persistence = createPersistence(appContext); if (! persistence.IsNull()) { const SmartPtrIMessageChannel errorMessageChannel = channelResolver->resolveChannelName("errorChannel"); const std::string inputChannelStr = _configSection->findRequiredAttribute("channel"); SmartPtrIMessageChannel inputChannel = channelResolver->resolveChannelName(inputChannelStr); SmartPtrIIntegrationObject inputChannelObj; inputChannelObj.QueryInterface(inputChannel); SmartPtrCPersistenceMessageHandler persistenceMessageHandler; persistenceMessageHandler.CreateInstance(); persistenceMessageHandler->initialize(_configSection, persistence); SmartPtrIMessageHandler messageHandler; messageHandler.QueryInterface(persistenceMessageHandler); _messagingTemplate.CreateInstance(); _messagingTemplate->initialize( channelResolver, inputChannelObj, errorMessageChannel, SmartPtrIMessageChannel(), messageHandler); } } void CPersistenceOutboundChannelAdapterInstance::start( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("start"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(!_isRunning); if (! _messagingTemplate.IsNull()) { _isRunning = true; _messagingTemplate->start(0); } } void CPersistenceOutboundChannelAdapterInstance::stop( const uint32 timeoutMs) { CAF_CM_FUNCNAME_VALIDATE("stop"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_BOOL(_isRunning); if (! _messagingTemplate.IsNull()) { _isRunning = false; _messagingTemplate->stop(0); } } bool CPersistenceOutboundChannelAdapterInstance::isRunning() const { CAF_CM_FUNCNAME_VALIDATE("isRunning"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _isRunning; } SmartPtrIPersistence CPersistenceOutboundChannelAdapterInstance::createPersistence( const SmartPtrIAppContext& appContext) const { CAF_CM_FUNCNAME("createPersistence"); CAF_CM_VALIDATE_INTERFACE(appContext); SmartPtrIPersistence rc; const std::string removeRefStr = _configSection->findRequiredAttribute("ref"); CAF_CM_LOG_DEBUG_VA1("Creating the persistence impl - %s", removeRefStr.c_str()); const SmartPtrIBean bean = appContext->getBean(removeRefStr); rc.QueryInterface(bean, false); CAF_CM_VALIDATE_INTERFACE(rc); try { rc->initialize(); } CAF_CM_CATCH_CAF CAF_CM_CATCH_DEFAULT; if (CAF_CM_ISEXCEPTION) { CAF_CM_LOG_WARN_VA2("initialize failed - ref: %s, msg: %s", removeRefStr.c_str(), (CAF_CM_EXCEPTION_GET_FULLMSG).c_str()); rc = SmartPtrIPersistence(); CAF_CM_CLEAREXCEPTION; } return rc; } CPersistenceOutboundChannelAdapterInstance.h000066400000000000000000000036371321503522500446410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CPersistenceOutboundChannelAdapterInstance_h_ #define CPersistenceOutboundChannelAdapterInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "IPersistence.h" #include "Integration/Core/CMessagingTemplate.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/ILifecycle.h" namespace Caf { class CPersistenceOutboundChannelAdapterInstance : public IIntegrationObject, public IIntegrationComponentInstance, public ILifecycle { public: CPersistenceOutboundChannelAdapterInstance(); virtual ~CPersistenceOutboundChannelAdapterInstance(); CAF_BEGIN_QI() CAF_QI_ENTRY(IIntegrationObject) CAF_QI_ENTRY(IIntegrationComponentInstance) CAF_QI_ENTRY(ILifecycle) CAF_END_QI() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ILifecycle void start(const uint32 timeoutMs); void stop(const uint32 timeoutMs); bool isRunning() const; private: SmartPtrIPersistence createPersistence( const SmartPtrIAppContext& appContext) const; private: bool _isInitialized; bool _isRunning; std::string _id; SmartPtrIDocument _configSection; SmartPtrCMessagingTemplate _messagingTemplate; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CPersistenceOutboundChannelAdapterInstance); }; CAF_DECLARE_SMART_QI_POINTER(CPersistenceOutboundChannelAdapterInstance); } #endif // #ifndef CPersistenceOutboundChannelAdapterInstance_h_ CPersistenceReadingMessageSource.cpp000066400000000000000000000043631321503522500431520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/PersistenceDoc/CPersistenceDoc.h" #include "IPersistence.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "CPersistenceReadingMessageSource.h" #include "Exception/CCafException.h" #include "Doc/DocXml/PersistenceXml/PersistenceXmlRoots.h" using namespace Caf; CPersistenceReadingMessageSource::CPersistenceReadingMessageSource() : _isInitialized(false), CAF_CM_INIT_LOG("CPersistenceReadingMessageSource") { } CPersistenceReadingMessageSource::~CPersistenceReadingMessageSource() { } void CPersistenceReadingMessageSource::initialize( const SmartPtrIDocument& configSection, const SmartPtrIPersistence& persistence) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); CAF_CM_VALIDATE_SMARTPTR(persistence); _id = configSection->findRequiredAttribute("id"); const SmartPtrIDocument pollerDoc = configSection->findOptionalChild("poller"); _persistence = persistence; setPollerMetadata(pollerDoc); _isInitialized = true; } bool CPersistenceReadingMessageSource::doSend( const SmartPtrIIntMessage&, int32) { CAF_CM_FUNCNAME("doSend"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_EXCEPTIONEX_VA1( UnsupportedOperationException, E_NOTIMPL, "This is not a sending channel: %s", _id.c_str()); } SmartPtrIIntMessage CPersistenceReadingMessageSource::doReceive( const int32 timeout) { CAF_CM_FUNCNAME("receive"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); if (timeout > 0) { CAF_CM_EXCEPTIONEX_VA1(UnsupportedOperationException, E_INVALIDARG, "Timeout not currently supported: %s", _id.c_str()); } SmartPtrIIntMessage message; const SmartPtrCPersistenceDoc persistence = _persistence->getUpdated(0); if (! persistence.IsNull()) { SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initializeStr(XmlRoots::savePersistenceToString(persistence), IIntMessage::SmartPtrCHeaders(), IIntMessage::SmartPtrCHeaders()); message = messageImpl; } return message; } CProviderCollectSchemaExecutor.cpp000066400000000000000000000323211321503522500426410ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlRoots.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlRoots.h" #include "Doc/DocXml/ResponseXml/ResponseXmlRoots.h" #include "Common/CLoggingSetter.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/ProviderInfraDoc/CClassCollectionDoc.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/ResponseDoc/CProviderResponseDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Exception/CCafException.h" #include "CProviderCollectSchemaExecutor.h" #include "Integration/Caf/CCafMessageCreator.h" #include "Integration/Caf/CCafMessagePayloadParser.h" using namespace Caf; CProviderCollectSchemaExecutor::CProviderCollectSchemaExecutor() : _isInitialized(false), CAF_CM_INIT_LOG("CProviderCollectSchemaExecutor") { } CProviderCollectSchemaExecutor::~CProviderCollectSchemaExecutor() { } void CProviderCollectSchemaExecutor::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); const std::string schemaCacheDirPath = AppConfigUtils::getRequiredString( _sProviderHostArea, _sConfigSchemaCacheDir); const std::string schemaCacheDirPathExp = CStringUtils::expandEnv(schemaCacheDirPath); if (!FileSystemUtils::doesDirectoryExist(schemaCacheDirPathExp)) { CAF_CM_LOG_INFO_VA1( "Schema cache directory does not exist... creating - %s", schemaCacheDirPathExp.c_str()); FileSystemUtils::createDirectory(schemaCacheDirPathExp); } const std::string invokersDir = AppConfigUtils::getRequiredString( _sProviderHostArea, _sConfigInvokersDir); const std::string invokersDirExp = CStringUtils::expandEnv(invokersDir); if (!FileSystemUtils::doesDirectoryExist(invokersDirExp)) { CAF_CM_LOG_INFO_VA1( "Invokers directory does not exist... creating - %s", invokersDirExp.c_str()); FileSystemUtils::createDirectory(invokersDirExp); } _schemaCacheDirPath = schemaCacheDirPathExp; _invokersDir = invokersDirExp; _isInitialized = true; } void CProviderCollectSchemaExecutor::terminateBean() { } SmartPtrIIntMessage CProviderCollectSchemaExecutor::processMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("processMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); CAF_CM_LOG_DEBUG_VA2("Called - schemaCacheDirPath: %s, invokersDir: %s", _schemaCacheDirPath.c_str(), _invokersDir.c_str()); SmartPtrCLoggingSetter loggingSetter; loggingSetter.CreateInstance(); const SmartPtrCProviderRegDoc providerReg = CCafMessagePayloadParser::getProviderReg(message->getPayload()); const std::string providerNamespace = providerReg->getProviderNamespace(); const std::string providerName = providerReg->getProviderName(); const std::string providerVersion = providerReg->getProviderVersion(); std::string providerVersionNew = providerVersion; std::replace(providerVersionNew.begin(), providerVersionNew.end(), '.', '_'); const std::string providerDirName = providerNamespace + "_" + providerName + "_" + providerVersionNew; const std::string providerSchemaCacheDir = FileSystemUtils::buildPath(_schemaCacheDirPath, providerDirName); const std::string providerResponsePath = FileSystemUtils::buildPath(providerSchemaCacheDir, _sProviderResponseFilename); executeProvider(providerReg, _invokersDir, providerSchemaCacheDir, providerResponsePath, loggingSetter); const std::string relFilename = FileSystemUtils::buildPath(providerDirName, _sProviderResponseFilename); const SmartPtrCDynamicByteArray providerResponse = FileSystemUtils::loadByteFile(providerResponsePath); return CCafMessageCreator::createFromProviderResponse( providerResponse, relFilename, message->getHeaders()); } void CProviderCollectSchemaExecutor::executeProvider( const SmartPtrCProviderRegDoc& providerReg, const std::string& invokersDir, const std::string& providerSchemaCacheDir, const std::string& providerResponsePath, SmartPtrCLoggingSetter& loggingSetter) const { CAF_CM_FUNCNAME("executeProvider"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(providerReg); CAF_CM_VALIDATE_STRING(invokersDir); CAF_CM_VALIDATE_STRING(providerSchemaCacheDir); CAF_CM_VALIDATE_STRING(providerResponsePath); CAF_CM_VALIDATE_SMARTPTR(loggingSetter); const std::string providerNamespace = providerReg->getProviderNamespace(); const std::string providerName = providerReg->getProviderName(); const std::string providerVersion = providerReg->getProviderVersion(); const std::string invokerRelPath = providerReg->getInvokerRelPath(); const std::string schemaSummaryPath = FileSystemUtils::buildPath(providerSchemaCacheDir, _sSchemaSummaryFilename); if (FileSystemUtils::doesFileExist(schemaSummaryPath)) { CAF_CM_LOG_INFO_VA1( "Schema summary file already exists - %s", schemaSummaryPath.c_str()); } else { std::string invokerPath; if (! invokerRelPath.empty()) { const std::string invokerRelPathExp = CStringUtils::expandEnv(invokerRelPath); invokerPath = FileSystemUtils::buildPath(invokersDir, invokerRelPathExp); if (!FileSystemUtils::doesFileExist(invokerPath)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Invoker does not exist - %s", invokerPath.c_str()); } setupSchemaCacheDir(providerSchemaCacheDir, loggingSetter); runProvider(invokerPath, providerSchemaCacheDir); } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Unrecognized provider URI protocol in Provider Registration file - %s", providerName.c_str()); } const std::string schemaPath = findSchemaPath(providerResponsePath); const SmartPtrCSchemaSummaryDoc schemaSummary = createSchemaSummary( schemaPath, invokerPath, providerNamespace, providerName, providerVersion); const std::string schemaSummaryMem = XmlRoots::saveSchemaSummaryToString(schemaSummary); FileSystemUtils::saveTextFile(schemaSummaryPath, schemaSummaryMem); } } void CProviderCollectSchemaExecutor::setupSchemaCacheDir( const std::string& providerSchemaCacheDir, const SmartPtrCLoggingSetter& loggingSetter) const { CAF_CM_FUNCNAME_VALIDATE("setupSchemaCacheDir"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(providerSchemaCacheDir); CAF_CM_VALIDATE_SMARTPTR(loggingSetter); if (FileSystemUtils::doesDirectoryExist(providerSchemaCacheDir)) { CAF_CM_LOG_INFO_VA1( "Removing the schema cache directory because it appears to be incomplete - %s", providerSchemaCacheDir.c_str()); FileSystemUtils::recursiveRemoveDirectory(providerSchemaCacheDir); } FileSystemUtils::createDirectory(providerSchemaCacheDir); loggingSetter->initialize(providerSchemaCacheDir); } void CProviderCollectSchemaExecutor::runProvider( const std::string& invokerPath, const std::string& providerSchemaCacheDir) const { CAF_CM_FUNCNAME_VALIDATE("runProvider"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(invokerPath); CAF_CM_VALIDATE_STRING(providerSchemaCacheDir); CAF_CM_LOG_DEBUG_VA2( "Executing the command - %s --schema -o %s", invokerPath.c_str(), providerSchemaCacheDir.c_str()); std::string newProviderSchemaCacheDir = FileSystemUtils::normalizePathWithForward( providerSchemaCacheDir); Cdeqstr argv; argv.push_back(invokerPath); argv.push_back("--schema"); argv.push_back("-o"); argv.push_back(newProviderSchemaCacheDir); const std::string stdoutPath = FileSystemUtils::buildPath( newProviderSchemaCacheDir, _sStdoutFilename); const std::string stderrPath = FileSystemUtils::buildPath( newProviderSchemaCacheDir, _sStderrFilename); ProcessUtils::runSyncToFiles(argv, stdoutPath, stderrPath); } SmartPtrCSchemaSummaryDoc CProviderCollectSchemaExecutor::createSchemaSummary( const std::string& schemaPath, const std::string& invokerPath, const std::string& providerNamespace, const std::string& providerName, const std::string& providerVersion) const { CAF_CM_FUNCNAME_VALIDATE("createSchemaSummary"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(schemaPath); CAF_CM_VALIDATE_STRING(invokerPath); CAF_CM_VALIDATE_STRING(providerNamespace); CAF_CM_VALIDATE_STRING(providerName); CAF_CM_VALIDATE_STRING(providerVersion); std::deque fqcCollection; const std::string schemaMem = FileSystemUtils::loadTextFile(schemaPath); const SmartPtrCSchemaDoc schema = XmlRoots::parseSchemaFromString(schemaMem); const std::deque dataClassCollection = schema->getDataClassCollection(); for (TConstIterator > dataClassIter(dataClassCollection); dataClassIter; dataClassIter++) { const SmartPtrCDataClassDoc dataClass = *dataClassIter; SmartPtrCFullyQualifiedClassGroupDoc fqc; fqc.CreateInstance(); fqc->initialize(dataClass->getNamespaceVal(), dataClass->getName(), dataClass->getVersion()); fqcCollection.push_back(fqc); } const std::deque actionClassCollection = schema->getActionClassCollection(); for (TConstIterator > actionClassIter(actionClassCollection); actionClassIter; actionClassIter++) { const SmartPtrCActionClassDoc actionClass = *actionClassIter; SmartPtrCFullyQualifiedClassGroupDoc fqc; fqc.CreateInstance(); fqc->initialize(actionClass->getNamespaceVal(), actionClass->getName(), actionClass->getVersion()); fqcCollection.push_back(fqc); } SmartPtrCClassCollectionDoc classCollection; classCollection.CreateInstance(); classCollection->initialize(fqcCollection); SmartPtrCSchemaSummaryDoc schemaSummary; schemaSummary.CreateInstance(); schemaSummary->initialize(providerNamespace, providerName, providerVersion, classCollection, invokerPath); return schemaSummary; } std::string CProviderCollectSchemaExecutor::findSchemaPath( const std::string& providerResponsePath) const { CAF_CM_FUNCNAME("findSchemaPath"); CAF_CM_VALIDATE_STRING(providerResponsePath); const std::string providerResponseMem = FileSystemUtils::loadTextFile(providerResponsePath); const SmartPtrCProviderResponseDoc providerResponse = XmlRoots::parseProviderResponseFromString(providerResponseMem); std::string schemaPath; const SmartPtrCAttachmentCollectionDoc attachmentCollection = providerResponse->getAttachmentCollection(); if (attachmentCollection.IsNull()) { CAF_CM_LOG_INFO_VA1( "Provider response doesn't contain an attachment collection - %s", providerResponsePath.c_str()); } else { const std::deque attachmentCollectionInner = attachmentCollection->getAttachment(); if (attachmentCollectionInner.empty()) { CAF_CM_LOG_INFO_VA1( "Provider response contains an empty attachment collection - %s", providerResponsePath.c_str()); } else { for(TConstIterator > attachmentIter(attachmentCollectionInner); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; const std::string attachmentName = attachment->getName(); const std::string attachmentType = attachment->getType(); if((attachmentType.compare("cdif") == 0) && (attachmentName.find("-collectSchema-") != std::string::npos)) { if(! schemaPath.empty()) { CAF_CM_EXCEPTIONEX_VA3(DuplicateElementException, ERROR_ALREADY_EXISTS, "Found multiple schema files - \"%s\" and \"%s\" in %s", attachmentName.c_str(), schemaPath.c_str(), providerResponsePath.c_str()); } const std::string attachmentUri = attachment->getUri(); UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(attachmentUri, uriRecord); if(uriRecord.protocol.compare("file") != 0) { CAF_CM_EXCEPTIONEX_VA3(InvalidArgumentException, ERROR_INVALID_DATA, "Unsupported protocol (%s != \"file\") - %s in %s", uriRecord.protocol.c_str(), attachmentUri.c_str(), providerResponsePath.c_str()); } UriUtils::SFileUriRecord fileUriRecord; UriUtils::parseFileAddress(uriRecord.address, fileUriRecord); schemaPath = CStringUtils::expandEnv(fileUriRecord.path); if(! FileSystemUtils::doesFileExist(schemaPath)) { CAF_CM_EXCEPTIONEX_VA2(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Schema file not found - %s in manifest %s", schemaPath.c_str(), providerResponsePath.c_str()); } } else { CAF_CM_LOG_DEBUG_VA3( "Provider response attachment is not a cdif collectSchema - type: %s, name: %s, path: %s", attachmentType.c_str(), attachmentName.c_str(), providerResponsePath.c_str()); } } } } if(schemaPath.empty()) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Schema not found in manifest - %s", providerResponsePath.c_str()); } return schemaPath; } CProviderCollectSchemaExecutor.h000066400000000000000000000043461321503522500423140ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderCollectSchemaExecutor_h_ #define CProviderCollectSchemaExecutor_h_ #include "IBean.h" #include "Common/CLoggingSetter.h" #include "Doc/ProviderInfraDoc/CProviderRegDoc.h" #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" #include "Integration/IIntMessage.h" #include "Integration/IMessageProcessor.h" using namespace Caf; /// TODO - describe class class CProviderCollectSchemaExecutor : public TCafSubSystemObjectRoot, public IBean, public IMessageProcessor { public: CProviderCollectSchemaExecutor(); virtual ~CProviderCollectSchemaExecutor(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdProviderCollectSchemaExecutor) CAF_BEGIN_INTERFACE_MAP(CProviderCollectSchemaExecutor) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IMessageProcessor) CAF_END_INTERFACE_MAP() public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IMessageProcessor SmartPtrIIntMessage processMessage( const SmartPtrIIntMessage& message); private: void executeProvider( const SmartPtrCProviderRegDoc& providerReg, const std::string& invokersDir, const std::string& providerSchemaCacheDir, const std::string& providerResponsePath, SmartPtrCLoggingSetter& loggingSetter) const; void setupSchemaCacheDir( const std::string& providerSchemaCacheDir, const SmartPtrCLoggingSetter& loggingSetter) const; void runProvider( const std::string& invokerPath, const std::string& providerSchemaCacheDir) const; SmartPtrCSchemaSummaryDoc createSchemaSummary( const std::string& schemaPath, const std::string& invokerPath, const std::string& providerNamespace, const std::string& providerName, const std::string& providerVersion) const; std::string findSchemaPath( const std::string& providerResponsePath) const; private: bool _isInitialized; std::string _schemaCacheDirPath; std::string _invokersDir; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CProviderCollectSchemaExecutor); }; #endif // #ifndef CProviderCollectSchemaExecutor_h_ CProviderExecutor.cpp000066400000000000000000000106101321503522500402070ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CProviderExecutorRequest.h" #include "Common/IAppContext.h" #include "IBean.h" #include "Integration/Core/CErrorHandler.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationComponent.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" #include "Exception/CCafException.h" #include "CProviderExecutor.h" using namespace Caf; CProviderExecutor::CProviderExecutor() : _isInitialized(false), CAF_CM_INIT_LOG("CProviderExecutor") { } CProviderExecutor::~CProviderExecutor() { } void CProviderExecutor::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); IBean::Cprops::const_iterator itr = properties.find("beginImpersonationBeanRef"); if (itr != properties.end()) { _beginImpersonationBeanId = itr->second; } itr = properties.find("endImpersonationBeanRef"); if (itr != properties.end()) { _endImpersonationBeanId = itr->second; } _isInitialized = true; } void CProviderExecutor::terminateBean() { } void CProviderExecutor::wire(const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); if (AppConfigUtils::getOptionalBoolean(_sManagementAgentArea, "use_impersonation")) { _beginImpersonationTransformer = loadTransformer(_beginImpersonationBeanId, appContext, channelResolver); _endImpersonationTransformer = loadTransformer(_endImpersonationBeanId, appContext, channelResolver); } SmartPtrCErrorHandler errorHandler; errorHandler.CreateInstance(); errorHandler->initialize(channelResolver, channelResolver->resolveChannelName("errorChannel")); _errorHandler = errorHandler; } SmartPtrITransformer CProviderExecutor::loadTransformer( const std::string& id, const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME("loadTransformer"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_STRING(id); SmartPtrITransformer transformer; if (!id.empty()) { const SmartPtrIBean bean = appContext->getBean(id); SmartPtrIIntegrationComponent integrationComponent; integrationComponent.QueryInterface(bean, false); if (!integrationComponent) { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, 0, "Bean is not an integration component - %s", id.c_str()); } SmartPtrIDocument configSection; SmartPtrIIntegrationObject integrationObject; integrationObject = integrationComponent->createObject(configSection); SmartPtrIIntegrationComponentInstance integrationComponentInstance; integrationComponentInstance.QueryInterface(integrationObject, false); if (!integrationComponentInstance.IsNull()) { integrationComponentInstance->wire(appContext, channelResolver); } transformer.QueryInterface(integrationObject, false); CAF_CM_VALIDATE_INTERFACE(transformer); } return transformer; } void CProviderExecutor::handleMessage(const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("handleMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(message); CAF_CM_LOG_DEBUG_VA0("Called"); SmartPtrCProviderExecutorRequest executorRequest; executorRequest.CreateInstance(); executorRequest->initialize(message); const std::string& providerUri = executorRequest->getProviderUri(); SmartPtrCProviderExecutorRequestHandler handler = _handlers[providerUri]; if (handler == NULL) { SmartPtrCProviderExecutorRequestHandler requestHandler; requestHandler.CreateInstance(); requestHandler->initialize(providerUri, _beginImpersonationTransformer, _endImpersonationTransformer, _errorHandler); _handlers[providerUri] = requestHandler; handler = requestHandler; } handler->handleRequest(executorRequest); } SmartPtrIIntMessage CProviderExecutor::getSavedMessage() const { return NULL; } void CProviderExecutor::clearSavedMessage() { } CProviderExecutor.h000066400000000000000000000042011321503522500376530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderExecutor_h_ #define CProviderExecutor_h_ #include "IBean.h" #include "CProviderExecutorRequestHandler.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IErrorHandler.h" #include "Integration/IIntMessage.h" #include "Integration/ITransformer.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IMessageHandler.h" using namespace Caf; /// TODO - describe class class CProviderExecutor : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponentInstance, public IMessageHandler { public: CProviderExecutor(); virtual ~CProviderExecutor(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdProviderExecutor) CAF_BEGIN_INTERFACE_MAP(CProviderExecutor) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(IMessageHandler) CAF_END_INTERFACE_MAP() public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponentInstance virtual void wire(const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // IMessageHandler virtual void handleMessage(const SmartPtrIIntMessage& message); SmartPtrIIntMessage getSavedMessage() const; void clearSavedMessage(); private: SmartPtrITransformer loadTransformer( const std::string& id, const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); private: bool _isInitialized; std::map _handlers; std::string _beginImpersonationBeanId; std::string _endImpersonationBeanId; SmartPtrITransformer _beginImpersonationTransformer; SmartPtrITransformer _endImpersonationTransformer; SmartPtrIErrorHandler _errorHandler; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CProviderExecutor); }; #endif // #ifndef CProviderExecutor_h_ CProviderExecutorRequest.cpp000066400000000000000000000052611321503522500415660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: brets * Created: Nov 20, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CPropertyDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Integration/IIntMessage.h" #include "CProviderExecutorRequest.h" #include "Exception/CCafException.h" #include "CProviderExecutor.h" #include "Integration/Caf/CCafMessagePayloadParser.h" using namespace Caf; CProviderExecutorRequest::CProviderExecutorRequest() : _isInitialized(false), CAF_CM_INIT_LOG("CProviderExecutorRequest") { } CProviderExecutorRequest::~CProviderExecutorRequest() { } void CProviderExecutorRequest::initialize(const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); CAF_CM_LOG_DEBUG_VA0("Called"); _internalRequest = message; _request = CCafMessagePayloadParser::getProviderRequest(message->getPayload()); std::deque properties = _request->getRequestHeader()->getEchoPropertyBag()->getProperty(); std::string relDirectory; for(std::deque::const_iterator itr = properties.begin(); itr != properties.end(); itr++) { if ((*itr)->getName().compare("relDirectory") == 0) { relDirectory = (*itr)->getValue().front(); } else if ((*itr)->getName().compare("providerUri") == 0) { _providerUri = (*itr)->getValue().front(); } } if (relDirectory.empty() || _providerUri.empty()) { CAF_CM_EXCEPTIONEX_VA2(Caf::NoSuchElementException, ERROR_NOT_FOUND, "Missing provider request information - relDirectory: [%s] providerUri: [%s]", relDirectory.c_str(), _providerUri.c_str()); } const std::string configOutputDir = AppConfigUtils::getRequiredString(_sConfigOutputDir); _outputDir = FileSystemUtils::buildPath(configOutputDir, _sProviderHostArea, relDirectory); _isInitialized = true; } const SmartPtrCProviderRequestDoc CProviderExecutorRequest::getRequest() const { CAF_CM_FUNCNAME_VALIDATE("getRequest"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _request; } const SmartPtrIIntMessage CProviderExecutorRequest::getInternalRequest() const { CAF_CM_FUNCNAME_VALIDATE("getRequest"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _internalRequest; } const std::string& CProviderExecutorRequest::getOutputDirectory() const { CAF_CM_FUNCNAME_VALIDATE("getOutputDirectory"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _outputDir; } const std::string& CProviderExecutorRequest::getProviderUri() const { CAF_CM_FUNCNAME_VALIDATE("getProviderUri"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _providerUri; } CProviderExecutorRequestHandler.cpp000066400000000000000000000215751321503522500430720ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: brets * Created: Nov 20, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CResponseFactory.h" #include "CProviderExecutorRequest.h" #include "Common/CLoggingSetter.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" #include "Integration/Core/CIntException.h" #include "Integration/Core/CSimpleAsyncTaskExecutor.h" #include "Integration/IErrorHandler.h" #include "Integration/IIntMessage.h" #include "Integration/ITaskExecutor.h" #include "Integration/ITransformer.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CProviderExecutorRequestHandler.h" #include "Exception/CCafException.h" #include "Integration/Caf/CCafMessageCreator.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Caf/CCafMessagePayload.h" #include "Integration/Core/FileHeaders.h" using namespace Caf; CProviderExecutorRequestHandler::CProviderExecutorRequestHandler() : _isInitialized(false), _isCancelled(false), CAF_CM_INIT_LOG("CProviderExecutorRequestHandler") { CAF_CM_INIT_THREADSAFE; } CProviderExecutorRequestHandler::~CProviderExecutorRequestHandler() { } void CProviderExecutorRequestHandler::initialize(const std::string& providerUri, const SmartPtrITransformer beginImpersonationTransformer, const SmartPtrITransformer endImpersonationTransformer, const SmartPtrIErrorHandler errorHandler) { CAF_CM_FUNCNAME("initialize"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(providerUri); _providerUri = providerUri; UriUtils::SUriRecord providerUriRecord; UriUtils::parseUriString(providerUri, providerUriRecord); if (providerUriRecord.protocol.compare("file") != 0) { CAF_CM_EXCEPTIONEX_VA2(Caf::NoSuchElementException, ERROR_NOT_FOUND, "Unrecognized provider URI protocol - %s, %s", providerUriRecord.protocol.c_str(), providerUri.c_str()); } UriUtils::SFileUriRecord fileUriRecord; UriUtils::parseFileAddress(providerUriRecord.address, fileUriRecord); _providerPath = fileUriRecord.path; if (!FileSystemUtils::doesFileExist(_providerPath)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Provider path not found - %s", _providerPath.c_str()); } _beginImpersonationTransformer = beginImpersonationTransformer; _endImpersonationTransformer = endImpersonationTransformer; _errorHandler = errorHandler; _isInitialized = true; } void CProviderExecutorRequestHandler::handleRequest( const SmartPtrCProviderExecutorRequest request) { CAF_CM_FUNCNAME("handleRequest"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(request); if (_providerUri.compare(request->getProviderUri()) != 0) { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, ERROR_INVALID_PARAMETER, "Provider request not for current provider - %s", _providerUri.c_str()); } executeRequestAsync(request); } void CProviderExecutorRequestHandler::run() { CAF_CM_FUNCNAME("run"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrIIntMessage message; const SmartPtrCProviderExecutorRequest request = getNextPendingRequest(); if (! request.IsNull()) { try { processRequest(request); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; if (CAF_CM_ISEXCEPTION) { SmartPtrCIntException intException; intException.CreateInstance(); intException->initialize(CAF_CM_GETEXCEPTION); _errorHandler->handleError(intException, request->getInternalRequest()); CAF_CM_CLEAREXCEPTION; } } CAF_CM_LOG_DEBUG_VA0("Finished"); } void CProviderExecutorRequestHandler::cancel() { CAF_CM_FUNCNAME_VALIDATE("cancel"); CAF_CM_LOCK_UNLOCK; CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_LOG_DEBUG_VA0("Canceling"); _isCancelled = true; } SmartPtrCProviderExecutorRequest CProviderExecutorRequestHandler::getNextPendingRequest() { SmartPtrCProviderExecutorRequest rc; if (! _isCancelled && ! _pendingRequests.empty()) { rc = _pendingRequests.front(); _pendingRequests.pop_front(); } return rc; } void CProviderExecutorRequestHandler::processRequest( const SmartPtrCProviderExecutorRequest& request) const { CAF_CM_FUNCNAME_VALIDATE("processRequest"); CAF_CM_VALIDATE_SMARTPTR(request); const std::string outputDir = request->getOutputDirectory(); SmartPtrCLoggingSetter loggingSetter; loggingSetter.CreateInstance(); loggingSetter->initialize(outputDir); SmartPtrIIntMessage message = request->getInternalRequest(); const std::string providerRequestPath = FileSystemUtils::buildPath(outputDir, _sProviderRequestFilename); const std::string stdoutPath = FileSystemUtils::buildPath(outputDir, _sStdoutFilename); const std::string stderrPath = FileSystemUtils::buildPath(outputDir, _sStderrFilename); std::string newProviderRequestPath = FileSystemUtils::normalizePathWithForward( providerRequestPath); // Create temporary request file for use by the provider CCafMessagePayload::saveToFile(message->getPayload(), newProviderRequestPath); Cdeqstr argv; argv.push_back(_providerPath); argv.push_back("-r"); argv.push_back(newProviderRequestPath); CAF_CM_LOG_INFO_VA2("Running command - %s -r %s", _providerPath.c_str(), newProviderRequestPath.c_str()); ProcessUtils::Priority priority = ProcessUtils::NORMAL; std::string appConfigPriority = AppConfigUtils::getOptionalString(_sManagementAgentArea, "provider_process_priority"); if (!appConfigPriority.empty()) { if (CStringUtils::isEqualIgnoreCase("LOW", appConfigPriority)) { priority = ProcessUtils::LOW; } else if (CStringUtils::isEqualIgnoreCase("IDLE", appConfigPriority)) { priority = ProcessUtils::IDLE; } } // Begin impersonation if (!_beginImpersonationTransformer.IsNull()) { message = _beginImpersonationTransformer->transformMessage(message); if (message.IsNull()) { CAF_CM_LOG_WARN_VA0("Begin impersonation transform did not return a message"); } } { CAF_CM_UNLOCK_LOCK; ProcessUtils::runSyncToFiles(argv, stdoutPath, stderrPath, priority); } // End impersonation if (!_endImpersonationTransformer.IsNull()) { message = _endImpersonationTransformer->transformMessage(message); if (message.IsNull()) { CAF_CM_LOG_WARN_VA0("End impersonation transform did not return a message"); } } // Delete temporary request file used by the provider if (FileSystemUtils::doesFileExist(newProviderRequestPath)) { CAF_CM_LOG_INFO_VA1("Removing handler produced request file - %s", newProviderRequestPath.c_str()); FileSystemUtils::removeFile(newProviderRequestPath); } // Delete original request const std::string originalFile = message->findOptionalHeaderAsString(FileHeaders::_sORIGINAL_FILE); if (!originalFile.empty()) { if (FileSystemUtils::doesFileExist(originalFile)) { CAF_CM_LOG_INFO_VA1("Removing original file - %s", originalFile.c_str()); FileSystemUtils::removeFile(originalFile); } } // Package response in envelope and write to global response location const SmartPtrCProviderRequestDoc providerRequest = CCafMessagePayloadParser::getProviderRequest(message->getPayload()); const SmartPtrCResponseDoc response = CResponseFactory::createResponse(providerRequest, outputDir); const std::string relFilename = CStringUtils::createRandomUuid() + "_" + _sResponseFilename; SmartPtrIIntMessage responseMessage = CCafMessageCreator::createPayloadEnvelope( response, relFilename, message->getHeaders()); const std::string directory = AppConfigUtils::getRequiredString("response_dir"); const std::string filePath = FileSystemUtils::buildPath(directory, relFilename); const SmartPtrCDynamicByteArray payload = responseMessage->getPayload(); FileSystemUtils::saveByteFile(filePath, payload->getPtr(), payload->getByteCount(), FileSystemUtils::FILE_MODE_REPLACE, ".writing"); } void CProviderExecutorRequestHandler::executeRequestAsync( const SmartPtrCProviderExecutorRequest& request) { CAF_CM_FUNCNAME_VALIDATE("executeRequestAsync"); CAF_CM_VALIDATE_SMARTPTR(request); _pendingRequests.push_back(request); _taskExecutors = removeFinishedTaskExecutors(_taskExecutors); SmartPtrCSimpleAsyncTaskExecutor simpleAsyncTaskExecutor; simpleAsyncTaskExecutor.CreateInstance(); simpleAsyncTaskExecutor->initialize(this, _errorHandler); _taskExecutors.push_back(simpleAsyncTaskExecutor); simpleAsyncTaskExecutor->execute(0); } std::deque CProviderExecutorRequestHandler::removeFinishedTaskExecutors( const std::deque taskExecutors) const { std::deque taskExecutorsTmp; for (TConstIterator > iter(taskExecutors); iter; iter++) { const SmartPtrITaskExecutor taskExecutorIter = *iter; if (! ((taskExecutorIter->getState() == ITaskExecutor::ETaskStateFinished) || (taskExecutorIter->getState() == ITaskExecutor::ETaskStateFailed))) { taskExecutorsTmp.push_back(taskExecutorIter); } } return taskExecutorsTmp; } CResponseFactory.cpp000066400000000000000000000341311321503522500400300ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/ResponseXml/ResponseXmlRoots.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ResponseDoc/CManifestCollectionDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Doc/ResponseDoc/CProviderResponseDoc.h" #include "Doc/ResponseDoc/CResponseDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "CResponseFactory.h" #include "Exception/CCafException.h" using namespace Caf; SmartPtrCResponseDoc CResponseFactory::createResponse( const SmartPtrCProviderCollectSchemaRequestDoc& providerCollectSchemaRequest, const std::string& outputDir, const std::string& schemaCacheDir) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CResponseFactory", "createResponse"); CAF_CM_VALIDATE_SMARTPTR(providerCollectSchemaRequest); CAF_CM_VALIDATE_STRING(outputDir); CAF_CM_VALIDATE_STRING(schemaCacheDir); SmartPtrCManifestCollectionDoc manifestCollection; SmartPtrCAttachmentCollectionDoc attachmentCollection; findAndStoreGlobalAttachmentsAndProviderResponses(outputDir, schemaCacheDir, manifestCollection, attachmentCollection); SmartPtrCResponseHeaderDoc responseHeader; responseHeader.CreateInstance(); responseHeader->initialize(); SmartPtrCResponseDoc response; response.CreateInstance(); response->initialize( providerCollectSchemaRequest->getClientId(), providerCollectSchemaRequest->getRequestId(), providerCollectSchemaRequest->getPmeId(), responseHeader, manifestCollection, attachmentCollection, SmartPtrCStatisticsDoc()); return response; } SmartPtrCResponseDoc CResponseFactory::createResponse( const SmartPtrCProviderRequestDoc& providerRequest, const std::string& outputDir) { CAF_CM_STATIC_FUNC_LOG("CResponseFactory", "createResponse"); CAF_CM_VALIDATE_SMARTPTR(providerRequest); CAF_CM_VALIDATE_STRING(outputDir); SmartPtrCManifestCollectionDoc manifestCollection; SmartPtrCAttachmentCollectionDoc attachmentCollection; findAndStoreGlobalAttachmentsAndProviderResponses(outputDir, std::string(), manifestCollection, attachmentCollection); if (manifestCollection.IsNull() && attachmentCollection.IsNull()) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Did not find any attachments - %s", outputDir.c_str()); } SmartPtrCResponseHeaderDoc responseHeader; responseHeader.CreateInstance(); responseHeader->initialize(); SmartPtrCResponseDoc response; response.CreateInstance(); response->initialize( providerRequest->getClientId(), providerRequest->getRequestId(), providerRequest->getPmeId(), responseHeader, manifestCollection, attachmentCollection, SmartPtrCStatisticsDoc()); return response; } void CResponseFactory::findAndStoreGlobalAttachmentsAndProviderResponses( const std::string& outputDir, const std::string& schemaCacheDir, SmartPtrCManifestCollectionDoc& manifestCollection, SmartPtrCAttachmentCollectionDoc& attachmentCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CResponseFactory", "findAndStoreGlobalAttachmentsAndProviderResponses"); CAF_CM_VALIDATE_STRING(outputDir); // schemaCacheDir is optional std::map globalAttachmentCollection; std::deque manifestCollectionInner; findAndStoreGlobalAttachments(outputDir, globalAttachmentCollection); findAndStoreProviderResponses(outputDir, schemaCacheDir, globalAttachmentCollection, manifestCollectionInner); if (!manifestCollectionInner.empty()) { manifestCollection.CreateInstance(); manifestCollection->initialize(manifestCollectionInner); } if (!globalAttachmentCollection.empty()) { std::deque globalAttachmentCollectionInner; for (TConstMapIterator > globalAttachmentIter(globalAttachmentCollection); globalAttachmentIter; globalAttachmentIter++) { const SmartPtrCAttachmentDoc attachment = *globalAttachmentIter; globalAttachmentCollectionInner.push_back(attachment); } attachmentCollection.CreateInstance(); attachmentCollection->initialize(globalAttachmentCollectionInner, std::deque()); } } void CResponseFactory::findAndStoreProviderResponses( const std::string& outputDir, const std::string& schemaCacheDir, std::map& globalAttachmentCollection, std::deque& manifestCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CResponseFactory", "findAndStoreProviderResponses"); CAF_CM_VALIDATE_STRING(outputDir); // schemaCacheDir is optional const std::deque providerResponsePathCollection = FileSystemUtils::findRequiredFiles(outputDir, _sProviderResponseFilename); for (TConstIterator > providerResponsePathIter( providerResponsePathCollection); providerResponsePathIter; providerResponsePathIter++) { const std::string providerResponsePath = *providerResponsePathIter; CAF_CM_LOG_DEBUG_VA1("Parsing provider response - %s", providerResponsePath.c_str()); const SmartPtrCProviderResponseDoc providerResponse = XmlRoots::parseProviderResponseFromFile(providerResponsePath); const SmartPtrCManifestDoc providerResponseManifest = providerResponse->getManifest(); if (!providerResponseManifest.IsNull()) { manifestCollection.push_back(providerResponseManifest); } const SmartPtrCAttachmentCollectionDoc providerResponseAttachmentCollection = providerResponse->getAttachmentCollection(); if (!providerResponseAttachmentCollection.IsNull()) { std::deque providerResponseAttachmentCollectionInner = providerResponseAttachmentCollection->getAttachment(); resolveAndStoreGlobalAttachments(providerResponseAttachmentCollectionInner, outputDir, schemaCacheDir, globalAttachmentCollection); } } } void CResponseFactory::findAndStoreGlobalAttachments( const std::string& outputDir, std::map& globalAttachmentCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CResponseFactory", "findAndStoreGlobalAttachments"); CAF_CM_VALIDATE_STRING(outputDir); const std::string parentOutputDir = FileSystemUtils::buildPath(outputDir, ".."); const std::string requestPath = FileSystemUtils::findOptionalFile(parentOutputDir, _sPayloadRequestFilename); const std::deque stdoutPathCollection = FileSystemUtils::findOptionalFiles(outputDir, _sStdoutFilename); const std::deque stderrPathCollection = FileSystemUtils::findOptionalFiles(outputDir, _sStderrFilename); const std::deque maDebugLogPathCollection = FileSystemUtils::findOptionalFiles(outputDir, "ma-log4cpp.log"); if (!requestPath.empty()) { std::deque requestPathCollection; requestPathCollection.push_back(requestPath); storeGlobalAttachments(std::string(), "request", requestPathCollection, outputDir, globalAttachmentCollection); } if (!stdoutPathCollection.empty()) { storeGlobalAttachments(std::string(), "stdout", stdoutPathCollection, outputDir, globalAttachmentCollection); } if (!stderrPathCollection.empty()) { storeGlobalAttachments(std::string(), "stderr", stderrPathCollection, outputDir, globalAttachmentCollection); } if (!maDebugLogPathCollection.empty()) { storeGlobalAttachments(std::string(), "log", maDebugLogPathCollection, outputDir, globalAttachmentCollection); } } void CResponseFactory::resolveAndStoreGlobalAttachments( const std::deque attachmentCollectionInner, const std::string& outputDir, const std::string& schemaCacheDir, std::map& globalAttachmentCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CResponseFactory", "resolveAndStoreGlobalAttachments"); CAF_CM_VALIDATE_STL(attachmentCollectionInner); CAF_CM_VALIDATE_STRING(outputDir); // schemaCacheDir is optional for (TConstIterator > attachmentIter( attachmentCollectionInner); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; UriUtils::SUriRecord uriRecord; UriUtils::parseUriString(attachment->getUri(), uriRecord); if (uriRecord.protocol.compare("file") == 0) { UriUtils::SFileUriRecord fileUriRecord; UriUtils::parseFileAddress(uriRecord.address, fileUriRecord); std::string attachmentPath = fileUriRecord.path; std::string attachmentPathNew = attachmentPath; if (!schemaCacheDir.empty()) { std::string relPath; resolveAttachmentPath(attachmentPath, outputDir, relPath, attachmentPathNew); } if (!attachmentPathNew.empty()) { storeGlobalAttachment(attachment->getName(), attachment->getType(), attachmentPathNew, outputDir, globalAttachmentCollection); } } else { globalAttachmentCollection.insert( std::make_pair(attachment->getUri(), attachment)); } } } void CResponseFactory::storeGlobalAttachments( const std::string& attachmentName, const std::string& attachmentType, const std::deque& attachmentPathCollection, const std::string& baseDir, std::map& attachmentCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CResponseFactory", "storeGlobalAttachments"); // attachmentName is optional CAF_CM_VALIDATE_STRING(attachmentType); CAF_CM_VALIDATE_STL(attachmentPathCollection); CAF_CM_VALIDATE_STRING(baseDir); for (TConstIterator > attachmentPathIter( attachmentPathCollection); attachmentPathIter; attachmentPathIter++) { const std::string attachmentPath = *attachmentPathIter; storeGlobalAttachment(attachmentName, attachmentType, attachmentPath, baseDir, attachmentCollection); } } void CResponseFactory::storeGlobalAttachment( const std::string& attachmentName, const std::string& attachmentType, const std::string& attachmentPath, const std::string& baseDir, std::map& attachmentCollection) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CResponseFactory", "storeGlobalAttachment"); // attachmentName is optional CAF_CM_VALIDATE_STRING(attachmentType); CAF_CM_VALIDATE_STRING(attachmentPath); CAF_CM_VALIDATE_STRING(baseDir); std::string relPath; std::string attachmentPathNew; resolveAttachmentPath(attachmentPath, baseDir, relPath, attachmentPathNew); if (!attachmentPathNew.empty()) { std::string attachmentNameNew = attachmentName; if (attachmentName.empty()) { attachmentNameNew = relPath; std::replace(attachmentNameNew.begin(), attachmentNameNew.end(), '/', '.'); } attachmentPathNew = FileSystemUtils::normalizePathWithForward(attachmentPathNew); const std::string attachmentUri = "file:///" + attachmentPathNew + "?relPath=" + relPath; CAF_CM_LOG_DEBUG_VA3("Creating attachment - name: %s, type: %s, uri: %s", attachmentNameNew.c_str(), attachmentType.c_str(), attachmentUri.c_str()); const std::string cmsPolicyStr = AppConfigUtils::getRequiredString( "security", "cms_policy"); SmartPtrCAttachmentDoc attachment; attachment.CreateInstance(); attachment->initialize(attachmentNameNew, attachmentType, attachmentUri, false, EnumConvertersXml::convertStringToCmsPolicy(cmsPolicyStr)); attachmentCollection.insert(std::make_pair(attachmentUri, attachment)); } } void CResponseFactory::resolveAttachmentPath( const std::string& attachmentPath, const std::string& baseDir, std::string& relPath, std::string& attachmentPathNew) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CResponseFactory", "resolveAttachmentPath"); CAF_CM_VALIDATE_STRING(attachmentPath); CAF_CM_VALIDATE_STRING(baseDir); // Initialize the input variables relPath = std::string(); attachmentPathNew = attachmentPath; std::string baseDirNew = baseDir; const std::string baseDirNewTmp = baseDirNew + '/'; const std::string::size_type fndPos = attachmentPathNew.find(baseDirNewTmp); if (fndPos != std::string::npos) { relPath = attachmentPathNew; relPath.replace(fndPos, baseDirNewTmp.length(), ""); relPath = removeLeadingChars(relPath, '.'); relPath = removeLeadingChars(relPath, '/'); } if (relPath.empty()) { relPath = FileSystemUtils::getBasename(attachmentPathNew); attachmentPathNew = FileSystemUtils::buildPath(baseDirNew, relPath); const std::string attachmentPathTmp = FileSystemUtils::normalizePathForPlatform(attachmentPath); if (attachmentPathTmp.compare(attachmentPathNew) != 0) { if (FileSystemUtils::doesFileExist(attachmentPathNew)) { bool isFileNameFound = false; const std::string origRelPath = relPath; for (uint32 index = 0; !isFileNameFound; index++) { relPath = CStringConv::toString(index) + "_" + origRelPath; attachmentPathNew = FileSystemUtils::buildPath(baseDirNew, relPath); if (! FileSystemUtils::doesFileExist(attachmentPathNew)) { CAF_CM_LOG_WARN_VA1("File already exists... calculated new name - %s", attachmentPathNew.c_str()); isFileNameFound = true; } } } if (FileSystemUtils::isRegularFile(attachmentPathTmp)) { CAF_CM_LOG_WARN_VA3("Attachment not in specified directory... Copying - attPath: \"%s\", goodDir: \"%s\", newPath: \"%s\"", attachmentPathTmp.c_str(), baseDirNew.c_str(), attachmentPathNew.c_str()); FileSystemUtils::copyFile(attachmentPathTmp, attachmentPathNew); } else { CAF_CM_LOG_ERROR_VA3("Attachment not in specified or calculated directory - attPath: \"%s\", goodDir: \"%s\", newPath: \"%s\"", attachmentPathTmp.c_str(), baseDirNew.c_str(), attachmentPathNew.c_str()); attachmentPathNew = std::string(); } } } } std::string CResponseFactory::removeLeadingChars( const std::string& sourceStr, const char leadingChar) { std::string rc; if (!sourceStr.empty()) { bool isCharFnd = false; for (size_t index = 0; index < sourceStr.length(); index++) { if (!isCharFnd && (sourceStr[index] != leadingChar)) { isCharFnd = true; } if (isCharFnd) { rc += sourceStr[index]; } } } return rc; } CSchemaCacheManager.cpp000066400000000000000000000170141321503522500403220ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/ProviderInfraXml/ProviderInfraXmlRoots.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/ProviderInfraDoc/CClassCollectionDoc.h" #include "Doc/ProviderInfraDoc/CSchemaSummaryDoc.h" #include "CSchemaCacheManager.h" #include "Exception/CCafException.h" using namespace Caf; bool Caf::operator<( const CClassId& lhs, const CClassId& rhs) { bool rc = false; if (lhs._fqc->getClassNamespace() < rhs._fqc->getClassNamespace()) { rc = true; } else if (lhs._fqc->getClassNamespace() == rhs._fqc->getClassNamespace()) { if (lhs._fqc->getClassName() < rhs._fqc->getClassName()) { rc = true; } else if (lhs._fqc->getClassName() == rhs._fqc->getClassName()) { if (lhs._fqc->getClassVersion() < rhs._fqc->getClassVersion()) { rc = true; } } } return rc; } CSchemaCacheManager::CSchemaCacheManager() : _isInitialized(false), CAF_CM_INIT_LOG("CSchemaCacheManager") { } CSchemaCacheManager::~CSchemaCacheManager() { } void CSchemaCacheManager::initialize() { CAF_CM_FUNCNAME("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); const std::string schemaCacheDirPath = AppConfigUtils::getRequiredString(_sProviderHostArea, _sConfigSchemaCacheDir); const std::string schemaCacheDirPathExp = CStringUtils::expandEnv(schemaCacheDirPath); if (!FileSystemUtils::doesDirectoryExist(schemaCacheDirPathExp)) { CAF_CM_EXCEPTIONEX_VA1(FileNotFoundException, ERROR_FILE_NOT_FOUND, "Schema cache directory does not exist: %s", schemaCacheDirPathExp.c_str()); } _schemaCacheDirPath = schemaCacheDirPathExp; _isInitialized = true; } CAF_CM_EXIT; } std::string CSchemaCacheManager::findProvider( const SmartPtrCFullyQualifiedClassGroupDoc& fqc) { CAF_CM_FUNCNAME_VALIDATE("findProvider"); std::string providerUri; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(fqc); CClassId classId; classId._fqc = fqc; CClassCollection::const_iterator iter = _classCollection.find(classId); if (iter == _classCollection.end()) { CAF_CM_LOG_INFO_VA1("Provider not found... refreshing cache - %s", classId.toString().c_str()); const uint16 maxWaitSecs = 10; waitForSchemaCacheCreation(_schemaCacheDirPath, maxWaitSecs); processSchemaSummaries(_schemaCacheDirPath, _classCollection); CClassCollection::const_iterator iter2 = _classCollection.find(classId); if (iter2 == _classCollection.end()) { CAF_CM_LOG_WARN_VA1("Provider not found even after refreshing the cache - %s", classId.toString().c_str()); } else { providerUri = iter2->second; } } else { providerUri = iter->second; } } CAF_CM_EXIT; return providerUri; } void CSchemaCacheManager::processSchemaSummaries( const std::string& schemaCacheDirPath, CClassCollection& classCollection) const { CAF_CM_FUNCNAME_VALIDATE("processSchemaSummaries"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(schemaCacheDirPath); const FileSystemUtils::DirectoryItems schemaCacheDirItems = FileSystemUtils::itemsInDirectory(schemaCacheDirPath, FileSystemUtils::REGEX_MATCH_ALL); if (schemaCacheDirItems.directories.empty()) { CAF_CM_LOG_WARN_VA1( "Schema cache is empty - %s", schemaCacheDirPath.c_str()); } for (TConstIterator schemaCacheDirIter( schemaCacheDirItems.directories); schemaCacheDirIter; schemaCacheDirIter++) { const std::string providerSchemaCacheDir = *schemaCacheDirIter; const std::string providerSchemaCacheDirPath = FileSystemUtils::buildPath( schemaCacheDirPath, providerSchemaCacheDir); const std::string schemaSummaryFilePath = FileSystemUtils::findOptionalFile( providerSchemaCacheDirPath, _sSchemaSummaryFilename); if (schemaSummaryFilePath.empty()) { CAF_CM_LOG_WARN_VA1( "Schema cache directory found without schema summary file... might be a timing issue - %s", providerSchemaCacheDirPath.c_str()); } else { CAF_CM_LOG_DEBUG_VA1("Found schema cache summary file - %s", schemaSummaryFilePath.c_str()); const SmartPtrCSchemaSummaryDoc schemaSummary = XmlRoots::parseSchemaSummaryFromFile(schemaSummaryFilePath); addNewClasses(schemaSummary, schemaSummaryFilePath, classCollection); } } } CAF_CM_EXIT; } void CSchemaCacheManager::addNewClasses( const SmartPtrCSchemaSummaryDoc& schemaSummary, const std::string& schemaSummaryFilePath, CClassCollection& classCollection) const { CAF_CM_FUNCNAME("addNewClasses"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(schemaSummary); CAF_CM_VALIDATE_STRING(schemaSummaryFilePath); const std::string invokerPath = schemaSummary->getInvokerPath(); std::string providerUri; if (! invokerPath.empty()) { const std::string invokerPathExp = CStringUtils::expandEnv(invokerPath); if (FileSystemUtils::doesFileExist(invokerPathExp)) { const std::string invokerPathExpTmp = FileSystemUtils::normalizePathWithForward(invokerPathExp); providerUri = "file:///" + invokerPathExpTmp; } else { CAF_CM_LOG_ERROR_VA2( "Invoker path does not exist - invokerPath: %s, filePath: %s", invokerPathExp.c_str(), schemaSummaryFilePath.c_str()); } } else { CAF_CM_EXCEPTIONEX_VA1(InvalidArgumentException, E_INVALIDARG, "Schema Summary file missing invokerRelPath - %s", schemaSummaryFilePath.c_str()); } if (! providerUri.empty()) { const SmartPtrCClassCollectionDoc classCollectionDoc = schemaSummary->getClassCollection(); const std::deque fqcCollection = classCollectionDoc->getFullyQualifiedClass(); for (TConstIterator > fqcIter(fqcCollection); fqcIter; fqcIter++) { CClassId classId; classId._fqc = *fqcIter; if (classCollection.find(classId) == classCollection.end()) { CAF_CM_LOG_DEBUG_VA1("Adding class %s", classId.toString().c_str()); classCollection.insert(std::make_pair(classId, providerUri)); } } } } CAF_CM_EXIT; } void CSchemaCacheManager::waitForSchemaCacheCreation( const std::string& schemaCacheDir, const uint16 maxWaitSecs) const { CAF_CM_FUNCNAME_VALIDATE("waitForSchemaCacheCreation"); CAF_CM_VALIDATE_STRING(schemaCacheDir); const std::string providerRegDir = AppConfigUtils::getRequiredString( _sProviderHostArea, _sConfigProviderRegDir); const std::string providerRegDirExp = CStringUtils::expandEnv(providerRegDir); if (FileSystemUtils::doesDirectoryExist(providerRegDirExp)) { size_t numSchemaCacheItems = 0; size_t numProviderRegItems = 0; for (uint16 retry = 0; retry < maxWaitSecs; retry++) { numSchemaCacheItems = FileSystemUtils::itemsInDirectory(schemaCacheDir, FileSystemUtils::REGEX_MATCH_ALL).directories.size(); numProviderRegItems = FileSystemUtils::itemsInDirectory(providerRegDir, FileSystemUtils::REGEX_MATCH_ALL).files.size(); if (numSchemaCacheItems >= numProviderRegItems) { break; } CThreadUtils::sleep(1000); } if (numSchemaCacheItems < numProviderRegItems) { CAF_CM_LOG_WARN_VA5( "Schema cache initialization not complete - schemaCache: %s::%d, providerReg: %s::%d, maxWaitSecs: %d", schemaCacheDir.c_str(), numSchemaCacheItems, providerRegDir.c_str(), numProviderRegItems, maxWaitSecs); } } else { CAF_CM_LOG_WARN_VA1("Provider Reg directory does not exist - %s", providerRegDirExp.c_str()); } } CSinglePmeRequestSplitter.cpp000066400000000000000000000035441321503522500416710ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CSinglePmeRequestSplitter.h" using namespace Caf; CSinglePmeRequestSplitter::CSinglePmeRequestSplitter() : _isInitialized(false), CAF_CM_INIT_LOG("CSinglePmeRequestSplitter") { } CSinglePmeRequestSplitter::~CSinglePmeRequestSplitter() { } void CSinglePmeRequestSplitter::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CSinglePmeRequestSplitter::terminateBean() { } void CSinglePmeRequestSplitter::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CSinglePmeRequestSplitter::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CSinglePmeRequestSplitter::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); rc.CreateInstance(_sObjIdSinglePmeRequestSplitterInstance); rc->initialize(_ctorArgs, _properties, configSection); } CAF_CM_EXIT; return rc; } CSinglePmeRequestSplitter.h000066400000000000000000000027151321503522500413350ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CSinglePmeRequestSplitter_h_ #define CSinglePmeRequestSplitter_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CSinglePmeRequestSplitter : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CSinglePmeRequestSplitter(); virtual ~CSinglePmeRequestSplitter(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdSinglePmeRequestSplitter) CAF_BEGIN_INTERFACE_MAP(CSinglePmeRequestSplitter) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CSinglePmeRequestSplitter); }; } #endif // #ifndef CSinglePmeRequestSplitter_h_ CSinglePmeRequestSplitterInstance.cpp000066400000000000000000000431731321503522500433600ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CClassSpecifierDoc.h" #include "Doc/CafCoreTypesDoc/CFullyQualifiedClassGroupDoc.h" #include "Doc/CafCoreTypesDoc/CRequestConfigDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "Doc/MgmtRequestDoc/CMgmtRequestDoc.h" #include "Doc/MgmtTypesDoc/CMgmtBatchDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectInstancesDoc.h" #include "Doc/MgmtTypesDoc/CMgmtCollectSchemaDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationCollectionDoc.h" #include "Doc/MgmtTypesDoc/CMgmtInvokeOperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderBatchDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectSchemaRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestConfigDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestHeaderDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "CSinglePmeRequestSplitterInstance.h" #include "Exception/CCafException.h" #include "Integration/Caf/CCafMessageCreator.h" #include "Integration/Caf/CCafMessagePayloadParser.h" #include "Integration/Caf/CCafMessagePayload.h" using namespace Caf; CSinglePmeRequestSplitterInstance::CSinglePmeRequestSplitterInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CSinglePmeRequestSplitterInstance") { } CSinglePmeRequestSplitterInstance::~CSinglePmeRequestSplitterInstance() { } void CSinglePmeRequestSplitterInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _schemaCacheManager.CreateInstance(); _schemaCacheManager->initialize(); _isInitialized = true; } std::string CSinglePmeRequestSplitterInstance::getId() const { return _id; } void CSinglePmeRequestSplitterInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } IMessageSplitter::SmartPtrCMessageCollection CSinglePmeRequestSplitterInstance::splitMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("splitMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(message); CAF_CM_LOG_DEBUG_VA1("Called - %s", _id.c_str()); SmartPtrCMessageCollection messageCollection; messageCollection.CreateInstance(); const SmartPtrCMgmtRequestDoc mgmtRequest = CCafMessagePayloadParser::getMgmtRequest(message->getPayload()); const SmartPtrCMgmtBatchDoc mgmtBatch = mgmtRequest->getBatch(); const SmartPtrCProviderRequestHeaderDoc providerRequestHeader = convertRequestHeader(mgmtRequest->getRequestHeader()); const std::string configOutputDir = AppConfigUtils::getRequiredString( _sConfigOutputDir); const std::string randomUuidStr = CStringUtils::createRandomUuid(); const std::string absRandomUuidDir = FileSystemUtils::buildPath(configOutputDir, _sProviderHostArea, randomUuidStr); createDirectory(absRandomUuidDir); saveRequest(absRandomUuidDir, message->getPayload()); // Process the collect schema job first since it follows a // completely different line of execution. const SmartPtrCMgmtCollectSchemaDoc mgmtCollectSchema = mgmtBatch->getCollectSchema(); if (!mgmtCollectSchema.IsNull()) { const std::string relProviderNumDir = FileSystemUtils::buildPath(randomUuidStr, CStringConv::toString(0)); const std::string absProviderNumDir = FileSystemUtils::buildPath( absRandomUuidDir, CStringConv::toString(0)); const SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequest = createCollectSchemaRequest(mgmtRequest, mgmtCollectSchema, providerRequestHeader, absProviderNumDir); const std::string relFilename = FileSystemUtils::buildPath(relProviderNumDir, _sProviderRequestFilename); const SmartPtrIIntMessage messageNew = CCafMessageCreator::create( providerCollectSchemaRequest, relFilename, relProviderNumDir, message->getHeaders()); messageCollection->push_back(messageNew); } SmartPtrCProviderJobsCollection providerJobsCollection; providerJobsCollection.CreateInstance(); addCollectInstancesJobs(mgmtBatch->getCollectInstancesCollection(), providerJobsCollection); addInvokeOperationJobs(mgmtBatch->getInvokeOperationCollection(), providerJobsCollection); uint32 providerCnt = 1; for (TConstIterator providerJobsIter( *providerJobsCollection); providerJobsIter; providerJobsIter++) { const std::string providerUri = providerJobsIter->first; const SmartPtrCSplitterJobsCollection jobsCollection = providerJobsIter->second; const std::string provderCntStr = CStringConv::toString(providerCnt); const std::string absProviderNumDir = FileSystemUtils::buildPath(absRandomUuidDir, provderCntStr); const SmartPtrCProviderRequestDoc providerRequest = createProviderRequest( mgmtRequest, jobsCollection, providerRequestHeader, absProviderNumDir); const std::string relProviderNumDir = FileSystemUtils::buildPath(randomUuidStr, provderCntStr); // const std::string relFilename = FileSystemUtils::buildPath(relProviderNumDir, // _sProviderRequestFilename); // const std::string relProviderNumDir = ""; const std::string relFilename = randomUuidStr + "_" + provderCntStr + "_" + _sProviderRequestFilename; const SmartPtrIIntMessage messageNew = CCafMessageCreator::create(providerRequest, relFilename, relProviderNumDir, providerUri, message->getHeaders()); messageCollection->push_back(messageNew); providerCnt++; } return messageCollection; } SmartPtrCProviderCollectSchemaRequestDoc CSinglePmeRequestSplitterInstance::createCollectSchemaRequest( const SmartPtrCMgmtRequestDoc& mgmtRequest, const SmartPtrCMgmtCollectSchemaDoc& mgmtCollectSchema, const SmartPtrCProviderRequestHeaderDoc& providerRequestHeader, const std::string& outputDir) const { CAF_CM_FUNCNAME_VALIDATE("createCollectSchemaRequest"); CAF_CM_VALIDATE_SMARTPTR(mgmtRequest); CAF_CM_VALIDATE_SMARTPTR(mgmtCollectSchema); CAF_CM_VALIDATE_SMARTPTR(providerRequestHeader); CAF_CM_VALIDATE_STRING(outputDir); SmartPtrCProviderCollectSchemaRequestDoc providerCollectSchemaRequest; providerCollectSchemaRequest.CreateInstance(); providerCollectSchemaRequest->initialize(mgmtRequest->getClientId(), mgmtRequest->getRequestId(), mgmtRequest->getPmeId(), mgmtCollectSchema->getJobId(), outputDir, providerRequestHeader); return providerCollectSchemaRequest; } SmartPtrCProviderRequestDoc CSinglePmeRequestSplitterInstance::createProviderRequest( const SmartPtrCMgmtRequestDoc& mgmtRequest, const SmartPtrCSplitterJobsCollection& jobsCollection, const SmartPtrCProviderRequestHeaderDoc& providerRequestHeader, const std::string& outputDir) const { CAF_CM_FUNCNAME_VALIDATE("createProviderRequest"); CAF_CM_VALIDATE_SMARTPTR(mgmtRequest); CAF_CM_VALIDATE_SMARTPTR(jobsCollection); CAF_CM_VALIDATE_SMARTPTR(providerRequestHeader); CAF_CM_VALIDATE_STRING(outputDir); std::deque collectInstancesCollectionInner; std::deque invokeOperationCollectionInner; for (TConstIterator > jobIter(*jobsCollection); jobIter; jobIter++) { const SmartPtrCSplitterJob job = *jobIter; if (!job->_mgmtCollectInstances.IsNull()) { const UUID jobId = job->_mgmtCollectInstances->getJobId(); const std::string jobIdStr = BasePlatform::UuidToString(jobId); const std::string jobOutputDir = FileSystemUtils::buildPath(outputDir, jobIdStr); if (FileSystemUtils::doesDirectoryExist(jobOutputDir)) { FileSystemUtils::recursiveRemoveDirectory(jobOutputDir); } FileSystemUtils::createDirectory(jobOutputDir); SmartPtrCProviderCollectInstancesDoc providerCollectInstances; providerCollectInstances.CreateInstance(); providerCollectInstances->initialize(job->_fqc->getClassNamespace(), job->_fqc->getClassName(), job->_fqc->getClassVersion(), job->_mgmtCollectInstances->getJobId(), jobOutputDir, job->_mgmtCollectInstances->getParameterCollection()); collectInstancesCollectionInner.push_back(providerCollectInstances); } if (!job->_mgmtInvokeOperation.IsNull()) { const UUID jobId = job->_mgmtInvokeOperation->getJobId(); const std::string jobIdStr = BasePlatform::UuidToString(jobId); const std::string jobOutputDir = FileSystemUtils::buildPath(outputDir, jobIdStr); if (FileSystemUtils::doesDirectoryExist(jobOutputDir)) { FileSystemUtils::recursiveRemoveDirectory(jobOutputDir); } FileSystemUtils::createDirectory(jobOutputDir); SmartPtrCProviderInvokeOperationDoc providerInvokeOperation; providerInvokeOperation.CreateInstance(); providerInvokeOperation->initialize(job->_fqc->getClassNamespace(), job->_fqc->getClassName(), job->_fqc->getClassVersion(), job->_mgmtInvokeOperation->getJobId(), jobOutputDir, job->_mgmtInvokeOperation->getOperation()); invokeOperationCollectionInner.push_back(providerInvokeOperation); } } SmartPtrCProviderCollectInstancesCollectionDoc collectInstancesCollection; if (!collectInstancesCollectionInner.empty()) { collectInstancesCollection.CreateInstance(); collectInstancesCollection->initialize(collectInstancesCollectionInner); } SmartPtrCProviderInvokeOperationCollectionDoc invokeOperationCollection; if (!invokeOperationCollectionInner.empty()) { invokeOperationCollection.CreateInstance(); invokeOperationCollection->initialize(invokeOperationCollectionInner); } SmartPtrCProviderBatchDoc providerBatch; providerBatch.CreateInstance(); providerBatch->initialize(outputDir, collectInstancesCollection, invokeOperationCollection); SmartPtrCProviderRequestDoc providerRequest; providerRequest.CreateInstance(); providerRequest->initialize(mgmtRequest->getClientId(), mgmtRequest->getRequestId(), mgmtRequest->getPmeId(), providerRequestHeader, providerBatch, mgmtRequest->getAttachmentCollection()); return providerRequest; } void CSinglePmeRequestSplitterInstance::addCollectInstancesJobs( const SmartPtrCMgmtCollectInstancesCollectionDoc& mgmtCollectInstancesCollection, SmartPtrCProviderJobsCollection& providerJobsCollection) const { CAF_CM_FUNCNAME_VALIDATE("addCollectInstancesJobs"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // mgmtCollectInstancesCollection is optional CAF_CM_VALIDATE_SMARTPTR(providerJobsCollection); if (!mgmtCollectInstancesCollection.IsNull()) { const std::deque mgmtCollectInstancesCollectionInner = mgmtCollectInstancesCollection->getCollectInstancesCollection(); for (TConstIterator > mgmtCollectInstancesIter( mgmtCollectInstancesCollectionInner); mgmtCollectInstancesIter; mgmtCollectInstancesIter++) { const SmartPtrCMgmtCollectInstancesDoc mgmtCollectInstances = *mgmtCollectInstancesIter; const SmartPtrCClassSpecifierDoc classSpecifier = mgmtCollectInstances->getClassSpecifier(); const SmartPtrCClassCollection fqcCollection = resolveClassSpecifier( classSpecifier); for (TConstIterator > fqcIter( *fqcCollection); fqcIter; fqcIter++) { const SmartPtrCFullyQualifiedClassGroupDoc fqc = *fqcIter; const std::string providerUri = findProviderUri(fqc); SmartPtrCSplitterJob job; job.CreateInstance(); job->_fqc = fqc; job->_mgmtCollectInstances = mgmtCollectInstances; CProviderJobsCollection::const_iterator fndIter = providerJobsCollection->find(providerUri); if (fndIter == providerJobsCollection->end()) { SmartPtrCSplitterJobsCollection jobsCollection; jobsCollection.CreateInstance(); jobsCollection->push_back(job); providerJobsCollection->insert( std::make_pair(providerUri, jobsCollection)); } else { fndIter->second->push_back(job); } } } } } void CSinglePmeRequestSplitterInstance::addInvokeOperationJobs( const SmartPtrCMgmtInvokeOperationCollectionDoc& mgmtInvokeOperationCollection, SmartPtrCProviderJobsCollection& providerJobsCollection) const { CAF_CM_FUNCNAME_VALIDATE("addInvokeOperationJobs"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); // mgmtInvokeOperationCollection is optional CAF_CM_VALIDATE_SMARTPTR(providerJobsCollection); if (!mgmtInvokeOperationCollection.IsNull()) { const std::deque mgmtInvokeOperationCollectionInner = mgmtInvokeOperationCollection->getInvokeOperationCollection(); for (TConstIterator > mgmtInvokeOperationIter( mgmtInvokeOperationCollectionInner); mgmtInvokeOperationIter; mgmtInvokeOperationIter++) { const SmartPtrCMgmtInvokeOperationDoc mgmtInvokeOperation = *mgmtInvokeOperationIter; const SmartPtrCClassSpecifierDoc classSpecifier = mgmtInvokeOperation->getClassSpecifier(); const SmartPtrCClassCollection fqcCollection = resolveClassSpecifier( classSpecifier); for (TConstIterator > fqcIter( *fqcCollection); fqcIter; fqcIter++) { const SmartPtrCFullyQualifiedClassGroupDoc fqc = *fqcIter; const std::string providerUri = findProviderUri(fqc); SmartPtrCSplitterJob job; job.CreateInstance(); job->_fqc = fqc; job->_mgmtInvokeOperation = mgmtInvokeOperation; CProviderJobsCollection::const_iterator fndIter = providerJobsCollection->find(providerUri); if (fndIter == providerJobsCollection->end()) { SmartPtrCSplitterJobsCollection jobsCollection; jobsCollection.CreateInstance(); jobsCollection->push_back(job); providerJobsCollection->insert( std::make_pair(providerUri, jobsCollection)); } else { fndIter->second->push_back(job); } } } } } CSinglePmeRequestSplitterInstance::SmartPtrCClassCollection CSinglePmeRequestSplitterInstance::resolveClassSpecifier( const SmartPtrCClassSpecifierDoc& classSpecifier) const { CAF_CM_FUNCNAME("resolveClassSpecifier"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(classSpecifier); SmartPtrCClassCollection classCollection; classCollection.CreateInstance(); const SmartPtrCFullyQualifiedClassGroupDoc fullyQualifiedClass = classSpecifier->getFullyQualifiedClass(); if (!fullyQualifiedClass.IsNull()) { classCollection->push_back(fullyQualifiedClass); } if (classCollection->empty()) { CAF_CM_EXCEPTION_VA0(ERROR_INVALID_DATA, "Failed to resolve to any fully-qualified classes"); } return classCollection; } std::string CSinglePmeRequestSplitterInstance::findProviderUri( const SmartPtrCFullyQualifiedClassGroupDoc& fqc) const { CAF_CM_FUNCNAME("findProviderUri"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(fqc); const std::string providerUri = _schemaCacheManager->findProvider(fqc); if (providerUri.empty()) { CAF_CM_EXCEPTIONEX_VA3(NoSuchElementException, ERROR_NOT_FOUND, "Provider not found for %s::%s::%s with status %d", fqc->getClassNamespace().c_str(), fqc->getClassName().c_str(), fqc->getClassVersion().c_str()); } return providerUri; } void CSinglePmeRequestSplitterInstance::createDirectory( const std::string& directory) const { CAF_CM_FUNCNAME_VALIDATE("createDirectory"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(directory); if (FileSystemUtils::doesDirectoryExist(directory)) { CAF_CM_LOG_WARN_VA1( "Directory already exists (perhaps from a previous failed run)... removing - %s", directory.c_str()); FileSystemUtils::recursiveRemoveDirectory(directory); } CAF_CM_LOG_DEBUG_VA1("Creating directory - %s", directory.c_str()); FileSystemUtils::createDirectory(directory); } void CSinglePmeRequestSplitterInstance::saveRequest( const std::string& outputDir, const SmartPtrCDynamicByteArray& payload) const { CAF_CM_FUNCNAME_VALIDATE("saveRequest"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(outputDir); CAF_CM_VALIDATE_SMARTPTR(payload); const std::string singlePmeRequestPath = FileSystemUtils::buildPath(outputDir, _sPayloadRequestFilename); CCafMessagePayload::saveToFile(payload, singlePmeRequestPath); } SmartPtrCProviderRequestHeaderDoc CSinglePmeRequestSplitterInstance::convertRequestHeader( const SmartPtrCRequestHeaderDoc& requestHeader) const { CAF_CM_FUNCNAME_VALIDATE("convertRequestHeader"); CAF_CM_VALIDATE_SMARTPTR(requestHeader); const SmartPtrCRequestConfigDoc requestConfig = requestHeader->getRequestConfig(); SmartPtrCProviderRequestConfigDoc providerRequestConfig; providerRequestConfig.CreateInstance(); providerRequestConfig->initialize(requestConfig->getResponseFormatType(), requestConfig->getLoggingLevelCollection()); SmartPtrCProviderRequestHeaderDoc providerRequestHeader; providerRequestHeader.CreateInstance(); providerRequestHeader->initialize(providerRequestConfig, requestHeader->getEchoPropertyBag()); return providerRequestHeader; } CVersionTransformer.cpp000066400000000000000000000034341321503522500405540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CVersionTransformer.h" using namespace Caf; CVersionTransformer::CVersionTransformer() : _isInitialized(false), CAF_CM_INIT_LOG("CVersionTransformer") { } CVersionTransformer::~CVersionTransformer() { } void CVersionTransformer::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); } CAF_CM_EXIT; } void CVersionTransformer::terminateBean() { } void CVersionTransformer::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CVersionTransformer::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CVersionTransformer::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); rc.CreateInstance(_sObjIdVersionTransformerInstance); rc->initialize(_ctorArgs, _properties, configSection); } CAF_CM_EXIT; return rc; } CVersionTransformer.h000066400000000000000000000026121321503522500402160ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVersionTransformer_h_ #define CVersionTransformer_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CVersionTransformer : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CVersionTransformer(); virtual ~CVersionTransformer(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdVersionTransformer) CAF_BEGIN_INTERFACE_MAP(CVersionTransformer) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean(const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CVersionTransformer); }; } #endif // #ifndef CVersionTransformer_h_ CVersionTransformerInstance.cpp000066400000000000000000000153271321503522500422450ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* G * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Common/IAppContext.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Exception/CCafException.h" #include "CVersionTransformerInstance.h" #include "Integration/Caf/CCafMessagePayloadParser.h" using namespace Caf; CVersionTransformerInstance::CVersionTransformerInstance() : _isInitialized(false), CAF_CM_INIT_LOG("CVersionTransformerInstance") { } CVersionTransformerInstance::~CVersionTransformerInstance() { } void CVersionTransformerInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); _isInitialized = true; } std::string CVersionTransformerInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _id; } void CVersionTransformerInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } SmartPtrIIntMessage CVersionTransformerInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(message); const SmartPtrCPayloadEnvelopeDoc payloadEnvelope = CCafMessagePayloadParser::getPayloadEnvelope(message->getPayload()); SmartPtrIIntMessage rc = message; rc = transformEnvelope(payloadEnvelope, rc); rc = transformPayload(payloadEnvelope, rc); return rc; } SmartPtrIIntMessage CVersionTransformerInstance::transformEnvelope( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const SmartPtrIIntMessage& message) const { CAF_CM_FUNCNAME("transformEnvelope"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelope); CAF_CM_VALIDATE_SMARTPTR(message); const std::string payloadType = payloadEnvelope->getPayloadType(); const std::string envelopeVersion = payloadEnvelope->getVersion(); std::string receivedMajorVersion; std::string receivedMinorVersion; parseVersion(payloadType, envelopeVersion, receivedMajorVersion, receivedMinorVersion); // Throwing an unsupported version exception is the last resort. // If at all possible, transform the old version document into the // new version. For example, if this is a v1.0 envelope, transform // it into v1.1 and return it, otherwise throw an unsupported version // exception. const std::string expectedMajorVersion = "1"; const std::string expectedMinorVersion = "0"; if (receivedMajorVersion.compare(expectedMajorVersion) != 0) { // Major version incompatibilities are not supported CAF_CM_EXCEPTIONEX_VA5(UnsupportedVersionException, ERROR_NOT_SUPPORTED, "Unsupported envelope major version - payloadType: %s, received: %s.%s, expected: %s.%s", payloadType.c_str(), receivedMajorVersion.c_str(), receivedMinorVersion.c_str(), expectedMajorVersion.c_str(), expectedMinorVersion.c_str()); } if (receivedMinorVersion.compare(expectedMinorVersion) != 0) { // Minor version incompatibilities are not supported CAF_CM_EXCEPTIONEX_VA5(UnsupportedVersionException, ERROR_NOT_SUPPORTED, "Unsupported envelope minor version - payloadType: %s, received: %s.%s, expected: %s.%s", payloadType.c_str(), receivedMajorVersion.c_str(), receivedMinorVersion.c_str(), expectedMajorVersion.c_str(), expectedMinorVersion.c_str()); } return message; } SmartPtrIIntMessage CVersionTransformerInstance::transformPayload( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const SmartPtrIIntMessage& message) const { CAF_CM_FUNCNAME("transformPayload"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(payloadEnvelope); CAF_CM_VALIDATE_SMARTPTR(message); const std::string payloadType = payloadEnvelope->getPayloadType(); const std::string payloadVersion = payloadEnvelope->getPayloadVersion(); std::string receivedMajorVersion; std::string receivedMinorVersion; parseVersion(payloadType, payloadVersion, receivedMajorVersion, receivedMinorVersion); // Throwing an unsupported version exception is the last resort. // If at all possible, transform the old version document into the // new version. For example, if this is a v1.0 mgmtRequest, transform // it into v1.1 and return it, otherwise throw an unsupported version // exception. The problem is that the payload is probably in an attachment // that's been signed and encrypted, so it isn't available to be transformed. // To handle this case, we'll probably do the enforcement here and the // actual transformation later in the process when the payload has been // verified and decrypted. const std::string expectedMajorVersion = "1"; const std::string expectedMinorVersion = "0"; if (receivedMajorVersion.compare(expectedMajorVersion) != 0) { // Major version incompatibilities are not supported CAF_CM_EXCEPTIONEX_VA5(UnsupportedVersionException, ERROR_NOT_SUPPORTED, "Unsupported payload major version - payloadType: %s, received: %s.%s, expected: %s.%s", payloadType.c_str(), receivedMajorVersion.c_str(), receivedMinorVersion.c_str(), expectedMajorVersion.c_str(), expectedMinorVersion.c_str()); } if (receivedMinorVersion.compare(expectedMinorVersion) != 0) { // Minor version incompatibilities are not supported CAF_CM_EXCEPTIONEX_VA5(UnsupportedVersionException, ERROR_NOT_SUPPORTED, "Unsupported payload minor version - payloadType: %s, received: %s.%s, expected: %s.%s", payloadType.c_str(), receivedMajorVersion.c_str(), receivedMinorVersion.c_str(), expectedMajorVersion.c_str(), expectedMinorVersion.c_str()); } return message; } void CVersionTransformerInstance::parseVersion( const std::string& messageType, const std::string& version, std::string& majorVersion, std::string& minorVersion) const { CAF_CM_FUNCNAME("parseVersion"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(messageType); CAF_CM_VALIDATE_STRING(version); const Cdeqstr versionDeq = CStringUtils::split(version, '.'); if (versionDeq.size() < 2) { CAF_CM_EXCEPTION_VA2(ERROR_INVALID_DATA, "Invalid version format - messageType: %s, version: %s", messageType.c_str(), version.c_str()); } majorVersion = versionDeq[0]; minorVersion = versionDeq[1]; } CVersionTransformerInstance.h000066400000000000000000000042521321503522500417050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVersionTransformerInstance_h_ #define CVersionTransformerInstance_h_ #include "Integration/IIntegrationComponentInstance.h" #include "Common/IAppContext.h" #include "Doc/PayloadEnvelopeDoc/CPayloadEnvelopeDoc.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CVersionTransformerInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer { public: CVersionTransformerInstance(); virtual ~CVersionTransformerInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdVersionTransformerInstance) CAF_BEGIN_INTERFACE_MAP(CVersionTransformerInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); private: SmartPtrIIntMessage transformEnvelope( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const SmartPtrIIntMessage& message) const; SmartPtrIIntMessage transformPayload( const SmartPtrCPayloadEnvelopeDoc& payloadEnvelope, const SmartPtrIIntMessage& message) const; void parseVersion( const std::string& payloadType, const std::string& version, std::string& majorVersion, std::string& minorVersion) const; private: bool _isInitialized; std::string _id; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CVersionTransformerInstance); }; } #endif // #ifndef CVersionTransformerInstance_h_ IntegrationObjects.cpp000066400000000000000000000055561321503522500404050ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Created on: Nov 13, 2015 * Author: bwilliams * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CConfigEnvInboundChannelAdapterInstance.h" #include "CConfigEnvOutboundChannelAdapterInstance.h" #include "CMonitorInboundChannelAdapterInstance.h" #include "CPersistenceOutboundChannelAdapterInstance.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Exception/CCafException.h" #include "IntegrationObjects.h" #include "CPersistenceInboundChannelAdapterInstance.h" using namespace Caf::MaIntegration; IntegrationObjects::IntegrationObjects() : CAF_CM_INIT("IntegrationObjects") { } IntegrationObjects::~IntegrationObjects() { } void IntegrationObjects::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL_EMPTY(properties); _ctorArgs = ctorArgs; _properties = properties; } void IntegrationObjects::terminateBean() { } bool IntegrationObjects::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_VALIDATE_INTERFACE(configSection); const std::string name = configSection->getName(); return (name.compare("persistence-inbound-channel-adapter") == 0) || (name.compare("persistence-outbound-channel-adapter") == 0) || (name.compare("configenv-inbound-channel-adapter") == 0) || (name.compare("configenv-outbound-channel-adapter") == 0) || (name.compare("monitor-inbound-channel-adapter") == 0); } SmartPtrIIntegrationObject IntegrationObjects::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME("createObject"); CAF_CM_VALIDATE_INTERFACE(configSection); SmartPtrIIntegrationObject rc; const std::string name = configSection->getName(); if (name.compare("persistence-inbound-channel-adapter") == 0) { SmartPtrCPersistenceInboundChannelAdapterInstance object; object.CreateInstance(); rc = object; } else if (name.compare("persistence-outbound-channel-adapter") == 0) { SmartPtrCPersistenceOutboundChannelAdapterInstance object; object.CreateInstance(); rc = object; } else if (name.compare("configenv-inbound-channel-adapter") == 0) { SmartPtrCConfigEnvInboundChannelAdapterInstance object; object.CreateInstance(); rc = object; } else if (name.compare("configenv-outbound-channel-adapter") == 0) { SmartPtrCConfigEnvOutboundChannelAdapterInstance object; object.CreateInstance(); rc = object; } else if (name.compare("monitor-inbound-channel-adapter") == 0) { SmartPtrCMonitorInboundChannelAdapterInstance object; object.CreateInstance(); rc = object; } else { CAF_CM_EXCEPTION_VA1(E_INVALIDARG, "Unknown name - %s", name.c_str()); } rc->initialize(_ctorArgs, _properties, configSection); return rc; } IntegrationObjects.h000066400000000000000000000025151321503522500400420ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Created on: Nov 13, 2015 * Author: bwilliams * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _MaIntegration_IntegrationObjects_h_ #define _MaIntegration_IntegrationObjects_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { namespace MaIntegration { class IntegrationObjects : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: IntegrationObjects(); virtual ~IntegrationObjects(); public: CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdIntegrationObjects) CAF_BEGIN_INTERFACE_MAP(IntegrationObjects) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: // IBean void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_DECLARE_NOCOPY(IntegrationObjects); }; }} #endif /* _MaIntegration_IntegrationObjects_h_ */ MaContracts.h000066400000000000000000000003571321503522500364650ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: 1/20/2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef MaContracts_h_ #define MaContracts_h_ //#include // Interfaces #endif MaIntegration.cpp000066400000000000000000000070261321503522500373430ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "MaIntegration.h" #include "IntegrationObjects.h" #include "CAttachmentRequestTransformerInstance.h" #include "CDiagToMgmtRequestTransformerInstance.h" #include "CSinglePmeRequestSplitterInstance.h" namespace Caf { namespace MaIntegration { const char* _sObjIdIntegrationObjects = "com.vmware.commonagent.maintegration.integrationobjects"; }} namespace Caf { const char* _sObjIdCollectSchemaExecutor = "com.vmware.commonagent.maintegration.collectschemaexecutor"; const char* _sObjIdProviderCollectSchemaExecutor = "com.vmware.commonagent.maintegration.providercollectschemaexecutor"; const char* _sObjIdProviderExecutor = "com.vmware.commonagent.maintegration.providerexecutor"; const char* _sObjIdSinglePmeRequestSplitterInstance = "com.vmware.commonagent.maintegration.singlepmerequestsplitterinstance"; const char* _sObjIdSinglePmeRequestSplitter = "com.vmware.commonagent.maintegration.singlepmerequestsplitter"; const char* _sObjIdDiagToMgmtRequestTransformerInstance = "com.vmware.commonagent.maintegration.diagtomgmtrequesttransformerinstance"; const char* _sObjIdDiagToMgmtRequestTransformer = "com.vmware.commonagent.maintegration.diagtomgmtrequesttransformer"; const char* _sObjIdInstallToMgmtRequestTransformerInstance = "com.vmware.commonagent.maintegration.installtomgmtrequesttransformerinstance"; const char* _sObjIdInstallToMgmtRequestTransformer = "com.vmware.commonagent.maintegration.installtomgmtrequesttransformer"; const char* _sObjIdPersistenceNamespaceDb = "com.vmware.commonagent.maintegration.persistencenamespacedb"; const char* _sObjIdConfigEnv = "com.vmware.commonagent.maintegration.configenv"; const char* _sObjIdAttachmentRequestTransformerInstance = "com.vmware.commonagent.maintegration.attachmentrequesttransformerinstance"; const char* _sObjIdAttachmentRequestTransformer = "com.vmware.commonagent.maintegration.attachmentrequesttransformer"; const char* _sObjIdVersionTransformerInstance = "com.vmware.commonagent.maintegration.versiontransformerinstance"; const char* _sObjIdVersionTransformer = "com.vmware.commonagent.maintegration.versiontransformer"; } CEcmSubSystemModule _Module; using namespace Caf::MaIntegration; CAF_BEGIN_OBJECT_MAP(ObjectMap) CAF_OBJECT_ENTRY(CAttachmentRequestTransformer) CAF_OBJECT_ENTRY(CAttachmentRequestTransformerInstance) CAF_OBJECT_ENTRY(CCollectSchemaExecutor) CAF_OBJECT_ENTRY(CConfigEnv) CAF_OBJECT_ENTRY(CDiagToMgmtRequestTransformer) CAF_OBJECT_ENTRY(CDiagToMgmtRequestTransformerInstance) CAF_OBJECT_ENTRY(CInstallToMgmtRequestTransformer) CAF_OBJECT_ENTRY(CInstallToMgmtRequestTransformerInstance) CAF_OBJECT_ENTRY(CPersistenceNamespaceDb) CAF_OBJECT_ENTRY(CProviderCollectSchemaExecutor) CAF_OBJECT_ENTRY(CProviderExecutor) CAF_OBJECT_ENTRY(CSinglePmeRequestSplitter) CAF_OBJECT_ENTRY(CSinglePmeRequestSplitterInstance) CAF_OBJECT_ENTRY(CVersionTransformer) CAF_OBJECT_ENTRY(CVersionTransformerInstance) CAF_OBJECT_ENTRY(IntegrationObjects) CAF_END_OBJECT_MAP() CAF_DECLARE_SUBSYSTEM_EXPORTS() extern "C" BOOL APIENTRY DllMain(HINSTANCE hModule, uint32 dwReason, LPVOID) { try { if (DLL_PROCESS_ATTACH == dwReason) { // initialize the sub-system module _Module.Init(ObjectMap, hModule); } else if (DLL_PROCESS_DETACH == dwReason) { // Terminate the sub-system module _Module.Term(); } } catch (std::runtime_error) { ::exit(2); } catch (...) { ::exit(2); } return TRUE; } stdafx.h000066400000000000000000000024341321503522500355360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/MaIntegration/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ //{{CAF_SUBSYSTEM}} #include #include #include #include "MaContracts.h" #include "MaIntegration.h" #include "IntegrationObjects.h" #include "CAttachmentRequestTransformer.h" #include "CDiagToMgmtRequestTransformer.h" #include "CInstallToMgmtRequestTransformerInstance.h" #include "CInstallToMgmtRequestTransformer.h" #include "CPersistenceNamespaceDb.h" #include "CPersistenceMessageHandler.h" #include "CPersistenceInboundChannelAdapterInstance.h" #include "CPersistenceOutboundChannelAdapterInstance.h" #include "CMonitorListener.h" #include "CPersistenceMerge.h" #include "CConfigEnvMerge.h" #include "CConfigEnv.h" #include "CConfigEnvMessageHandler.h" #include "CConfigEnvInboundChannelAdapterInstance.h" #include "CConfigEnvOutboundChannelAdapterInstance.h" #include "CCollectSchemaExecutor.h" #include "CProviderCollectSchemaExecutor.h" #include "CProviderExecutor.h" #include "CSinglePmeRequestSplitter.h" #include "CMonitorInboundChannelAdapterInstance.h" #include "CVersionTransformer.h" #include "CVersionTransformerInstance.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/000077500000000000000000000000001321503522500320165ustar00rootroot00000000000000include/000077500000000000000000000000001321503522500333625ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuthCVgAuthContext.h000066400000000000000000000012701321503522500364010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/include/* * Author: bwilliams * Created: Aug 16, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVgAuthContext_H_ #define CVgAuthContext_H_ namespace Caf { class CVgAuthContext { public: CVgAuthContext(); virtual ~CVgAuthContext(); public: void initialize( const std::string& applicationName); VGAuthContext* getPtr() const; std::string getApplicationName() const; private: bool _isInitialized; VGAuthContext* _vgAuthContext; std::string _applicationName; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CVgAuthContext); }; CAF_DECLARE_SMART_POINTER(CVgAuthContext); } #endif /* CVgAuthContext_H_ */ CVgAuthImpersonation.h000066400000000000000000000021671321503522500376120ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/include/* * Author: bwilliams * Created: Aug 16, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVgAuthImpersonation_H_ #define CVgAuthImpersonation_H_ #include "CVgAuthContext.h" #include "CVgAuthUserHandle.h" namespace Caf { class CVgAuthImpersonation { public: CVgAuthImpersonation(); virtual ~CVgAuthImpersonation(); public: void impersonateAndManage( const SmartPtrCVgAuthContext& vgAuthContext, const SmartPtrCVgAuthUserHandle& vgAuthUserHandle); public: static void beginImpersonation( const SmartPtrCVgAuthContext& vgAuthContext, const SmartPtrCVgAuthUserHandle& vgAuthUserHandle); static void endImpersonation( const SmartPtrCVgAuthContext& vgAuthContext); private: void impersonateLocal( const SmartPtrCVgAuthContext& vgAuthContext, const SmartPtrCVgAuthUserHandle& vgAuthUserHandle) const; private: bool _isInitialized; SmartPtrCVgAuthContext _vgAuthContext; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CVgAuthImpersonation); }; CAF_DECLARE_SMART_POINTER(CVgAuthImpersonation); } #endif /* CVgAuthImpersonation_H_ */ CVgAuthUserHandle.h000066400000000000000000000016761321503522500370210ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/include/* * Author: bwilliams * Created: Aug 16, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVgAuthUserHandle_H_ #define CVgAuthUserHandle_H_ #include "CVgAuthContext.h" namespace Caf { class CVgAuthUserHandle { public: CVgAuthUserHandle(); virtual ~CVgAuthUserHandle(); public: void initialize( const SmartPtrCVgAuthContext& vgAuthContext, const std::string& signedSamlToken); void initialize( const SmartPtrCVgAuthContext& vgAuthContext, const std::string& signedSamlToken, const std::string& userName); public: std::string getUserName( const SmartPtrCVgAuthContext& vgAuthContext) const; VGAuthUserHandle* getPtr() const; private: bool _isInitialized; VGAuthUserHandle* _vgAuthUserHandle; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CVgAuthUserHandle); }; CAF_DECLARE_SMART_POINTER(CVgAuthUserHandle); } #endif /* CVgAuthUserHandle_H_ */ IVgAuthImpersonation.h000066400000000000000000000007721321503522500376200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/include/* * Created on: Jan 25, 2012 * Author: mdonahue * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _IVgAuthImpersonation_H_ #define _IVgAuthImpersonation_H_ namespace Caf { struct __declspec(novtable) IVgAuthImpersonation : public ICafObject { CAF_DECL_UUID("63cfac22-e1b8-4977-8907-9582657b7420") virtual void endImpersonation() = 0; }; CAF_DECLARE_SMART_INTERFACE_POINTER(IVgAuthImpersonation); } #endif /* _IVgAuthImpersonation_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/000077500000000000000000000000001321503522500326055ustar00rootroot00000000000000CGuestAuthenticator.cpp000066400000000000000000000035311321503522500371610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "CGuestAuthenticator.h" using namespace Caf; CGuestAuthenticator::CGuestAuthenticator() : _isInitialized(false), CAF_CM_INIT_LOG("CGuestAuthenticator") { } CGuestAuthenticator::~CGuestAuthenticator() { } void CGuestAuthenticator::initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties) { CAF_CM_FUNCNAME_VALIDATE("initializeBean"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL(properties); _ctorArgs = ctorArgs; _properties = properties; initialize(); CAF_CM_LOG_DEBUG_VA1("num properties - %d", properties.size()); } CAF_CM_EXIT; } void CGuestAuthenticator::terminateBean() { } void CGuestAuthenticator::initialize() { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); _isInitialized = true; } CAF_CM_EXIT; } bool CGuestAuthenticator::isResponsible( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("isResponsible"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); } CAF_CM_EXIT; return false; } SmartPtrIIntegrationObject CGuestAuthenticator::createObject( const SmartPtrIDocument& configSection) const { CAF_CM_FUNCNAME_VALIDATE("createObject"); SmartPtrIIntegrationObject rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(configSection); rc.CreateInstance(_sObjIdGuestAuthenticatorInstance); rc->initialize(_ctorArgs, _properties, configSection); } CAF_CM_EXIT; return rc; } CGuestAuthenticator.h000066400000000000000000000026211321503522500366250ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CGuestAuthenticator_h_ #define CGuestAuthenticator_h_ #include "IBean.h" #include "Integration/IDocument.h" #include "Integration/IIntegrationObject.h" #include "Integration/IIntegrationComponent.h" namespace Caf { /// Sends responses/errors back to the client. class CGuestAuthenticator : public TCafSubSystemObjectRoot, public IBean, public IIntegrationComponent { public: CGuestAuthenticator(); virtual ~CGuestAuthenticator(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdGuestAuthenticator) CAF_BEGIN_INTERFACE_MAP(CGuestAuthenticator) CAF_INTERFACE_ENTRY(IBean) CAF_INTERFACE_ENTRY(IIntegrationComponent) CAF_END_INTERFACE_MAP() public: virtual void initialize(); public: // IBean virtual void initializeBean( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties); virtual void terminateBean(); public: // IIntegrationComponent bool isResponsible( const SmartPtrIDocument& configSection) const; SmartPtrIIntegrationObject createObject( const SmartPtrIDocument& configSection) const; private: bool _isInitialized; IBean::Cargs _ctorArgs; IBean::Cprops _properties; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CGuestAuthenticator); }; } #endif // #ifndef CGuestAuthenticator_h_ CGuestAuthenticatorInstance.cpp000066400000000000000000000176041321503522500406540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Integration/Caf/CCafMessagePayload.h" #include "CVgAuthImpersonation.h" #include "CVgAuthInitializer.h" #include "CVgAuthContext.h" #include "CVgAuthUserHandle.h" #include "Common/IAppContext.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAuthnAuthzDoc.h" #include "Doc/CafCoreTypesDoc/CRequestHeaderDoc.h" #include "ICafObject.h" #include "IVgAuthImpersonation.h" #include "Integration/Core/CIntMessage.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Integration/Core/CIntMessageHeaders.h" #include "CGuestAuthenticatorInstance.h" using namespace Caf; CGuestAuthenticatorInstance::CGuestAuthenticatorInstance() : _isInitialized(false), _beginImpersonation(false), _endImpersonation(false), CAF_CM_INIT_LOG("CGuestAuthenticatorInstance") { } CGuestAuthenticatorInstance::~CGuestAuthenticatorInstance() { } void CGuestAuthenticatorInstance::initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STL_EMPTY(ctorArgs); CAF_CM_VALIDATE_STL(properties); CAF_CM_VALIDATE_INTERFACE(configSection); _id = configSection->findRequiredAttribute("id"); const std::string beginImpersonationStr = findOptionalProperty("beginImpersonation", properties); const std::string endImpersonationStr = findOptionalProperty("endImpersonation", properties); _beginImpersonation = (beginImpersonationStr.empty() || beginImpersonationStr.compare("false") == 0) ? false : true; _endImpersonation = (endImpersonationStr.empty() || endImpersonationStr.compare("false") == 0) ? false : true; _isInitialized = true; } CAF_CM_EXIT; } std::string CGuestAuthenticatorInstance::getId() const { CAF_CM_FUNCNAME_VALIDATE("getId"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); rc = _id; } CAF_CM_EXIT; return rc; } void CGuestAuthenticatorInstance::wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver) { CAF_CM_FUNCNAME_VALIDATE("wire"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_INTERFACE(appContext); CAF_CM_VALIDATE_INTERFACE(channelResolver); } CAF_CM_EXIT; } SmartPtrIIntMessage CGuestAuthenticatorInstance::transformMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME_VALIDATE("transformMessage"); SmartPtrIIntMessage newMessage; CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(message); CAF_CM_LOG_DEBUG_VA1("Called - id: \"%s\"", _id.c_str()); CIntMessageHeaders messageHeaders; const std::string vgAuthImpersonationStr = "vgAuthImpersonation"; const SmartPtrICafObject cafObject = message->findOptionalObjectHeader(vgAuthImpersonationStr); if (cafObject.IsNull()) { if (_endImpersonation) { CAF_CM_LOG_ERROR_VA1("Cannot end impersonation without proper header - %s", vgAuthImpersonationStr.c_str()); } else { SmartPtrCVgAuthInitializer vgAuthInitializer; vgAuthInitializer.CreateInstance(); vgAuthInitializer->initialize("CAF"); const SmartPtrCVgAuthContext vgAuthContext = vgAuthInitializer->getContext(); const std::string signedSamlToken = getSignedSamlToken(message->getPayload()); SmartPtrCVgAuthUserHandle vgAuthUserHandle; vgAuthUserHandle.CreateInstance(); vgAuthUserHandle->initialize( vgAuthContext, signedSamlToken); if (_beginImpersonation) { logUserInfo("Before beginning impersonation"); CVgAuthImpersonation::beginImpersonation(vgAuthContext, vgAuthUserHandle); const std::string userName = vgAuthUserHandle->getUserName(vgAuthContext); logUserInfo("After beginning impersonation"); messageHeaders.insertObject(vgAuthImpersonationStr, vgAuthInitializer); messageHeaders.insertString("AUTHORITY", "IS_AUTHENTICATED_FULLY"); messageHeaders.insertString("AUTHORITY_USERNAME", userName); } } } else { if (_endImpersonation) { SmartPtrIVgAuthImpersonation vgAuthImpersonation; vgAuthImpersonation.QueryInterface(cafObject, true); CAF_CM_VALIDATE_SMARTPTR(vgAuthImpersonation); logUserInfo("Before ending impersonation"); vgAuthImpersonation->endImpersonation(); logUserInfo("After ending impersonation"); messageHeaders.insertString("AUTHORITY", "IS_AUTHENTICATED_ANONYMOUSLY"); messageHeaders.insertString("AUTHORITY_USERNAME", "ANONYMOUS"); } else { CAF_CM_LOG_WARN_VA1("Headers contain impersonation interface, but the ending of impersonation was not requested - %s", vgAuthImpersonationStr.c_str()); } //messageHeaders.insertObject(vgAuthImpersonationStr, SmartPtrICafObject()); } SmartPtrCIntMessage messageImpl; messageImpl.CreateInstance(); messageImpl->initialize(message->getPayload(), messageHeaders.getHeaders(), message->getHeaders()); newMessage = messageImpl; } CAF_CM_EXIT; return newMessage; } SmartPtrIIntMessage CGuestAuthenticatorInstance::processErrorMessage( const SmartPtrIIntMessage& message) { CAF_CM_FUNCNAME("processErrorMessage"); SmartPtrIIntMessage newMessage; try { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(message); CAF_CM_LOG_DEBUG_VA1("Called - %s", _id.c_str()); newMessage = transformMessage(message); } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; return newMessage; } std::string CGuestAuthenticatorInstance::getSignedSamlToken( const SmartPtrCDynamicByteArray& payload) const { CAF_CM_FUNCNAME_VALIDATE("getSignedSamlToken"); std::string signedSamlToken; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(payload); const SmartPtrCCafMessagePayload cafMessagePayload = CCafMessagePayload::create(payload); const SmartPtrCRequestHeaderDoc requestHeader = cafMessagePayload->getRequestHeader(); const SmartPtrCAuthnAuthzCollectionDoc authnAuthzCollection = requestHeader->getAuthnAuthzCollection(); CAF_CM_VALIDATE_SMARTPTR(authnAuthzCollection); CAF_CM_VALIDATE_STL(authnAuthzCollection->getAuthnAuthz()); //TODO: Pass the other types (e.g. username / password) to VgAuth. //TODO: Use the sequence number to prioritize the types. //TODO: Consider creating a type for the string "SAML" for (std::deque::const_iterator authnAuthzIter = authnAuthzCollection->getAuthnAuthz().begin(); authnAuthzIter != authnAuthzCollection->getAuthnAuthz().end(); authnAuthzIter++) { const SmartPtrCAuthnAuthzDoc authnAuthz = *authnAuthzIter; if (authnAuthz->getType().compare("SAML") == 0) { signedSamlToken = authnAuthz->getValue(); } } CAF_CM_VALIDATE_STRING(signedSamlToken); } CAF_CM_EXIT; return signedSamlToken; } std::string CGuestAuthenticatorInstance::findOptionalProperty( const std::string& propertyName, const IBean::Cprops& properties) const { CAF_CM_FUNCNAME_VALIDATE("findOptionalProperty"); std::string rc; CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(propertyName); CAF_CM_VALIDATE_STL(properties); IBean::Cprops::const_iterator propertiesIter = properties.find(propertyName); if (propertiesIter != properties.end()) { rc = propertiesIter->second; } } CAF_CM_EXIT; return rc; } void CGuestAuthenticatorInstance::logUserInfo( const std::string& msg) const { CAF_CM_FUNCNAME_VALIDATE("logUserInfo"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(msg); #ifndef WIN32 CAF_CM_LOG_DEBUG_VA3("%s - UID: %d, GID: %d", msg.c_str(), ::geteuid(), ::getegid()); #endif } CAF_CM_EXIT; } CGuestAuthenticatorInstance.h000066400000000000000000000043761321503522500403230ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CGuestAuthenticatorInstance_h_ #define CGuestAuthenticatorInstance_h_ #include "Integration/IErrorProcessor.h" #include "Common/IAppContext.h" #include "Integration/IChannelResolver.h" #include "Integration/IDocument.h" #include "Integration/IIntMessage.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Integration/IIntegrationComponentInstance.h" #include "Integration/IIntegrationObject.h" #include "Integration/ITransformer.h" namespace Caf { class CGuestAuthenticatorInstance : public TCafSubSystemObjectRoot, public IIntegrationObject, public IIntegrationComponentInstance, public ITransformer, public IErrorProcessor { public: CGuestAuthenticatorInstance(); virtual ~CGuestAuthenticatorInstance(); CAF_DECLARE_OBJECT_IDENTIFIER(_sObjIdGuestAuthenticatorInstance) CAF_BEGIN_INTERFACE_MAP(CGuestAuthenticatorInstance) CAF_INTERFACE_ENTRY(IIntegrationObject) CAF_INTERFACE_ENTRY(IIntegrationComponentInstance) CAF_INTERFACE_ENTRY(ITransformer) CAF_INTERFACE_ENTRY(IErrorProcessor) CAF_END_INTERFACE_MAP() public: // IIntegrationObject void initialize( const IBean::Cargs& ctorArgs, const IBean::Cprops& properties, const SmartPtrIDocument& configSection); std::string getId() const; public: // IIntegrationComponentInstance void wire( const SmartPtrIAppContext& appContext, const SmartPtrIChannelResolver& channelResolver); public: // ITransformer SmartPtrIIntMessage transformMessage( const SmartPtrIIntMessage& message); public: // IErrorProcessor SmartPtrIIntMessage processErrorMessage( const SmartPtrIIntMessage& message); private: bool _isInitialized; std::string _id; bool _beginImpersonation; bool _endImpersonation; private: std::string getSignedSamlToken( const SmartPtrCDynamicByteArray& payload) const; std::string findOptionalProperty( const std::string& propertyName, const IBean::Cprops& properties) const; void logUserInfo( const std::string& msg) const; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CGuestAuthenticatorInstance); }; } #endif // #ifndef CGuestAuthenticatorInstance_h_ CVgAuthContext.cpp000066400000000000000000000027521321503522500361060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Aug 16, 2012 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CVgAuthContext.h" CVgAuthContext::CVgAuthContext() : _isInitialized(false), _vgAuthContext(NULL), CAF_CM_INIT_LOG("CVgAuthContext") { } CVgAuthContext::~CVgAuthContext() { CAF_CM_FUNCNAME("~CVgAuthContext"); try { if (_isInitialized) { const VGAuthError vgAuthError = VGAuth_Shutdown(_vgAuthContext); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_Shutdown Failed"); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } void CVgAuthContext::initialize( const std::string& applicationName) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(applicationName); const VGAuthError vgAuthError = VGAuth_Init(applicationName.c_str(), 0, NULL, &_vgAuthContext); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_Init Failed", applicationName); CAF_CM_VALIDATE_PTR(_vgAuthContext); _applicationName = applicationName; _isInitialized = true; } CAF_CM_EXIT; } VGAuthContext* CVgAuthContext::getPtr() const { CAF_CM_FUNCNAME_VALIDATE("getPtr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _vgAuthContext; } std::string CVgAuthContext::getApplicationName() const { CAF_CM_FUNCNAME_VALIDATE("getApplicationName"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _applicationName; } CVgAuthError.cpp000066400000000000000000000133171321503522500355520ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Exception/CCafException.h" #include "CVgAuthError.h" using namespace Caf; void CVgAuthError::checkErrorExc( const VGAuthError& vgAuthError, const std::string& msg) { CAF_CM_STATIC_FUNC("CVgAuthError", "checkErrorExc"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(msg); if (VGAUTH_FAILED(vgAuthError)) { CAF_CM_EXCEPTIONEX_VA2(UnsupportedOperationException, getErrorCode(vgAuthError), "%s (%s)", msg.c_str(), getErrorMsg(vgAuthError).c_str()); } } CAF_CM_EXIT; } void CVgAuthError::checkErrorExc( const VGAuthError& vgAuthError, const std::string& msg, const std::string& addtlInfo) { CAF_CM_STATIC_FUNC("CVgAuthError", "checkErrorExc"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(msg); CAF_CM_VALIDATE_STRING(addtlInfo); if (VGAUTH_FAILED(vgAuthError)) { CAF_CM_EXCEPTIONEX_VA3(UnsupportedOperationException, getErrorCode(vgAuthError), "%s (%s) - %s", msg.c_str(), getErrorMsg(vgAuthError).c_str(), addtlInfo.c_str()); } } CAF_CM_EXIT; } void CVgAuthError::checkErrorErr( const VGAuthError& vgAuthError, const std::string& msg) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CVgAuthError", "checkErrorErr"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(msg); if (VGAUTH_FAILED(vgAuthError)) { CAF_CM_LOG_ERROR_VA2("%s (%s)", msg.c_str(), getErrorMsg(vgAuthError).c_str()); } } CAF_CM_EXIT; } void CVgAuthError::checkErrorErr( const VGAuthError& vgAuthError, const std::string& msg, const std::string& addtlInfo) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CVgAuthError", "checkErrorErr"); CAF_CM_ENTER { CAF_CM_VALIDATE_STRING(msg); CAF_CM_VALIDATE_STRING(addtlInfo); if (VGAUTH_FAILED(vgAuthError)) { CAF_CM_LOG_ERROR_VA3("%s (%s) - %s", msg.c_str(), getErrorMsg(vgAuthError).c_str(), addtlInfo.c_str()); } } CAF_CM_EXIT; } std::string CVgAuthError::getErrorMsg( const VGAuthError& vgAuthError) { std::string vgAuthErrorMsg; CAF_CM_ENTER { switch(vgAuthError) { case VGAUTH_E_OK: vgAuthErrorMsg = "VGAUTH_E_OK"; break; case VGAUTH_E_FAIL: vgAuthErrorMsg = "VGAUTH_E_FAIL"; break; case VGAUTH_E_INVALID_ARGUMENT: vgAuthErrorMsg = "VGAUTH_E_INVALID_ARGUMENT"; break; case VGAUTH_E_INVALID_CERTIFICATE: vgAuthErrorMsg = "VGAUTH_E_INVALID_CERTIFICATE"; break; case VGAUTH_E_PERMISSION_DENIED: vgAuthErrorMsg = "VGAUTH_E_PERMISSION_DENIED"; break; case VGAUTH_E_OUT_OF_MEMORY: vgAuthErrorMsg = "VGAUTH_E_OUT_OF_MEMORY"; break; case VGAUTH_E_COMM: vgAuthErrorMsg = "VGAUTH_E_COMM"; break; case VGAUTH_E_NOTIMPLEMENTED: vgAuthErrorMsg = "VGAUTH_E_NOTIMPLEMENTED"; break; case VGAUTH_E_NOT_CONNECTED: vgAuthErrorMsg = "VGAUTH_E_NOT_CONNECTED"; break; case VGAUTH_E_VERSION_MISMATCH: vgAuthErrorMsg = "VGAUTH_E_VERSION_MISMATCH"; break; case VGAUTH_E_SECURITY_VIOLATION: vgAuthErrorMsg = "VGAUTH_E_SECURITY_VIOLATION"; break; case VGAUTH_E_CERT_ALREADY_EXISTS: vgAuthErrorMsg = "VGAUTH_E_CERT_ALREADY_EXISTS"; break; case VGAUTH_E_AUTHENTICATION_DENIED: vgAuthErrorMsg = "VGAUTH_E_AUTHENTICATION_DENIED"; break; case VGAUTH_E_INVALID_TICKET: vgAuthErrorMsg = "VGAUTH_E_INVALID_TICKET"; break; case VGAUTH_E_MULTIPLE_MAPPINGS: vgAuthErrorMsg = "VGAUTH_E_MULTIPLE_MAPPINGS"; break; case VGAUTH_E_ALREADY_IMPERSONATING: vgAuthErrorMsg = "VGAUTH_E_ALREADY_IMPERSONATING"; break; case VGAUTH_E_NO_SUCH_USER: vgAuthErrorMsg = "VGAUTH_E_NO_SUCH_USER"; break; case VGAUTH_E_SERVICE_NOT_RUNNING: vgAuthErrorMsg = "VGAUTH_E_SERVICE_NOT_RUNNING"; break; case VGAUTH_E_SYSTEM_ERRNO: { const uint32 vgAuthErrorCode = VGAUTH_ERROR_EXTRA_ERROR(vgAuthError); const std::string errorMsg = CStringConv::toString(vgAuthErrorCode); vgAuthErrorMsg = std::string("VGAUTH_E_SYSTEM_ERRNO, msg: " + errorMsg); } break; case VGAUTH_E_SYSTEM_WINDOWS: { const uint32 vgAuthErrorCode = VGAUTH_ERROR_EXTRA_ERROR(vgAuthError); #ifdef WIN32 const std::string errorMsg = BasePlatform::PlatformApi::GetApiErrorMessage(vgAuthErrorCode); #else const std::string errorMsg = CStringConv::toString(vgAuthErrorCode); #endif vgAuthErrorMsg = std::string("VGAUTH_E_SYSTEM_WINDOWS, msg: " + errorMsg); } break; case VGAUTH_E_TOO_MANY_CONNECTIONS: vgAuthErrorMsg = "VGAUTH_E_TOO_MANY_CONNECTIONS"; break; case VGAUTH_E_UNSUPPORTED: vgAuthErrorMsg = "VGAUTH_E_UNSUPPORTED"; break; default: vgAuthErrorMsg = "Unknown"; } } CAF_CM_EXIT; return vgAuthErrorMsg; } uint32 CVgAuthError::getErrorCode( const VGAuthError& vgAuthError) { uint32 vgAuthErrorCode; CAF_CM_ENTER { switch(vgAuthError) { case VGAUTH_E_OK: case VGAUTH_E_FAIL: case VGAUTH_E_INVALID_ARGUMENT: case VGAUTH_E_INVALID_CERTIFICATE: case VGAUTH_E_PERMISSION_DENIED: case VGAUTH_E_OUT_OF_MEMORY: case VGAUTH_E_COMM: case VGAUTH_E_NOTIMPLEMENTED: case VGAUTH_E_NOT_CONNECTED: case VGAUTH_E_VERSION_MISMATCH: case VGAUTH_E_SECURITY_VIOLATION: case VGAUTH_E_CERT_ALREADY_EXISTS: case VGAUTH_E_AUTHENTICATION_DENIED: case VGAUTH_E_INVALID_TICKET: case VGAUTH_E_MULTIPLE_MAPPINGS: case VGAUTH_E_ALREADY_IMPERSONATING: case VGAUTH_E_NO_SUCH_USER: case VGAUTH_E_SERVICE_NOT_RUNNING: case VGAUTH_E_TOO_MANY_CONNECTIONS: case VGAUTH_E_UNSUPPORTED: vgAuthErrorCode = VGAUTH_ERROR_CODE(vgAuthError); break; case VGAUTH_E_SYSTEM_ERRNO: case VGAUTH_E_SYSTEM_WINDOWS: vgAuthErrorCode = VGAUTH_ERROR_EXTRA_ERROR(vgAuthError); break; default: vgAuthErrorCode = E_UNEXPECTED; } } CAF_CM_EXIT; return vgAuthErrorCode; } CVgAuthError.h000066400000000000000000000016041321503522500352130ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Jan 21, 2011 * * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVgAuthError_H_ #define CVgAuthError_H_ namespace Caf { class CVgAuthError { public: static void checkErrorExc( const VGAuthError& vgAuthError, const std::string& msg); static void checkErrorExc( const VGAuthError& vgAuthError, const std::string& msg, const std::string& addtlInfo); static void checkErrorErr( const VGAuthError& vgAuthError, const std::string& msg); static void checkErrorErr( const VGAuthError& vgAuthError, const std::string& msg, const std::string& addtlInfo); static std::string getErrorMsg( const VGAuthError& vgAuthError); static uint32 getErrorCode( const VGAuthError& vgAuthError); private: CAF_CM_DECLARE_NOCREATE(CVgAuthError); }; } #endif /* CVgAuthError_H_ */ CVgAuthImpersonation.cpp000066400000000000000000000043421321503522500373060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Aug 16, 2012 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CVgAuthContext.h" #include "CVgAuthUserHandle.h" #include "CVgAuthImpersonation.h" CVgAuthImpersonation::CVgAuthImpersonation() : _isInitialized(false), CAF_CM_INIT_LOG("CVgAuthImpersonation") { } CVgAuthImpersonation::~CVgAuthImpersonation() { CAF_CM_FUNCNAME("~CVgAuthImpersonation"); try { if (_isInitialized) { endImpersonation(_vgAuthContext); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } void CVgAuthImpersonation::impersonateAndManage( const SmartPtrCVgAuthContext& vgAuthContext, const SmartPtrCVgAuthUserHandle& vgAuthUserHandle) { CAF_CM_FUNCNAME_VALIDATE("impersonateAndManage"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(vgAuthContext); CAF_CM_VALIDATE_SMARTPTR(vgAuthUserHandle); beginImpersonation(vgAuthContext, vgAuthUserHandle); _vgAuthContext = vgAuthContext; _isInitialized = true; } CAF_CM_EXIT; } void CVgAuthImpersonation::beginImpersonation( const SmartPtrCVgAuthContext& vgAuthContext, const SmartPtrCVgAuthUserHandle& vgAuthUserHandle) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CVgAuthImpersonation", "beginImpersonation"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(vgAuthContext); CAF_CM_VALIDATE_SMARTPTR(vgAuthUserHandle); const std::string userName = vgAuthUserHandle->getUserName(vgAuthContext); CAF_CM_LOG_DEBUG_VA1("Beginning impersonation - %s", userName.c_str()); const VGAuthError vgAuthError = VGAuth_Impersonate( vgAuthContext->getPtr(), vgAuthUserHandle->getPtr(), 0, NULL); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_Impersonate Failed"); } CAF_CM_EXIT; } void CVgAuthImpersonation::endImpersonation( const SmartPtrCVgAuthContext& vgAuthContext) { CAF_CM_STATIC_FUNC_LOG_VALIDATE("CVgAuthImpersonation", "endImpersonation"); CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(vgAuthContext); CAF_CM_LOG_DEBUG_VA0("Ending impersonation"); const VGAuthError vgAuthError = VGAuth_EndImpersonation(vgAuthContext->getPtr()); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_EndImpersonation Failed"); } CAF_CM_EXIT; } CVgAuthInitializer.cpp000066400000000000000000000060211321503522500367360ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Aug 16, 2012 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CVgAuthContext.h" #include "CVgAuthInitializer.h" #include "CVgAuthImpersonation.h" CVgAuthInitializer::CVgAuthInitializer() : _isInitialized(false), CAF_CM_INIT_LOG("CVgAuthInitializer") { } CVgAuthInitializer::~CVgAuthInitializer() { } void CVgAuthInitializer::initialize( const std::string& applicationName) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_STRING(applicationName); VGAuth_SetLogHandler(logHandler, NULL, 0, NULL); _vgAuthContext.CreateInstance(); _vgAuthContext->initialize(applicationName); _isInitialized = true; } CAF_CM_EXIT; } SmartPtrCVgAuthContext CVgAuthInitializer::getContext() const { CAF_CM_FUNCNAME_VALIDATE("initializeThirdParty"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _vgAuthContext; } void CVgAuthInitializer::installClient() const { CAF_CM_FUNCNAME_VALIDATE("installClient"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const VGAuthError vgAuthError = VGAuth_InstallClient(_vgAuthContext->getPtr(), 0, NULL); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_InstallClient Failed", _vgAuthContext->getApplicationName()); } CAF_CM_EXIT; } void CVgAuthInitializer::uninstallClient() const { CAF_CM_FUNCNAME_VALIDATE("uninstallClient"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const VGAuthError vgAuthError = VGAuth_UninstallClient(_vgAuthContext->getPtr(), 0, NULL); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_UninstallClient Failed", _vgAuthContext->getApplicationName()); } CAF_CM_EXIT; } void CVgAuthInitializer::endImpersonation() { CAF_CM_FUNCNAME_VALIDATE("endImpersonation"); CAF_CM_ENTER { CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CVgAuthImpersonation::endImpersonation(_vgAuthContext); } CAF_CM_EXIT; } void CVgAuthInitializer::logHandler( const char *logDomain, int32 logLevel, const char *msg, void *userData) { CAF_CM_STATIC_FUNC_LOG_ONLY("CVgAuthInitializer", "logHandler"); CAF_CM_ENTER { switch (logLevel & G_LOG_LEVEL_MASK) { case G_LOG_LEVEL_ERROR: CAF_CM_LOG_ERROR_VA2("[ERROR][%s] %s", logDomain ? logDomain : "", msg); break; case G_LOG_LEVEL_CRITICAL: CAF_CM_LOG_ERROR_VA2("[CRITICAL][%s] %s", logDomain ? logDomain : "", msg); break; case G_LOG_LEVEL_WARNING: CAF_CM_LOG_WARN_VA2("[WARNING][%s] %s", logDomain ? logDomain : "", msg); break; case G_LOG_LEVEL_INFO: CAF_CM_LOG_INFO_VA2("[INFO][%s] %s", logDomain ? logDomain : "", msg); break; case G_LOG_LEVEL_MESSAGE: CAF_CM_LOG_DEBUG_VA2("[MESSAGE][%s] %s", logDomain ? logDomain : "", msg); break; case G_LOG_LEVEL_DEBUG: CAF_CM_LOG_DEBUG_VA2("[DEBUG][%s] %s", logDomain ? logDomain : "", msg); break; default: CAF_CM_LOG_WARN_VA2("[default][%s] %s", logDomain ? logDomain : "", msg); } } CAF_CM_EXIT; } CVgAuthInitializer.h000066400000000000000000000021401321503522500364010ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Aug 16, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CVGAUTHINITIALIZER_H_ #define CVGAUTHINITIALIZER_H_ #include "IVgAuthImpersonation.h" #include "CVgAuthContext.h" namespace Caf { class CVgAuthInitializer : public IVgAuthImpersonation { public: CVgAuthInitializer(); virtual ~CVgAuthInitializer(); CAF_BEGIN_QI() CAF_QI_ENTRY(ICafObject) CAF_QI_ENTRY(IVgAuthImpersonation) CAF_END_QI() public: void initialize( const std::string& applicationName); public: SmartPtrCVgAuthContext getContext() const; void installClient() const; void uninstallClient() const; public: // IVgAuthImpersonation void endImpersonation(); private: static void logHandler( const char *logDomain, int32 logLevel, const char *msg, void *userData); private: bool _isInitialized; SmartPtrCVgAuthContext _vgAuthContext; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CVgAuthInitializer); }; CAF_DECLARE_SMART_QI_POINTER(CVgAuthInitializer); } #endif /* CVGAUTHINITIALIZER_H_ */ CVgAuthUserHandle.cpp000066400000000000000000000052121321503522500365060ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Aug 16, 2012 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "CVgAuthContext.h" #include "CVgAuthUserHandle.h" CVgAuthUserHandle::CVgAuthUserHandle() : _isInitialized(false), _vgAuthUserHandle(NULL), CAF_CM_INIT_LOG("CVgAuthUserHandle") { } CVgAuthUserHandle::~CVgAuthUserHandle() { CAF_CM_FUNCNAME("~CVgAuthUserHandle"); try { if (_isInitialized) { VGAuth_UserHandleFree(_vgAuthUserHandle); } } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; CAF_CM_CLEAREXCEPTION; } void CVgAuthUserHandle::initialize( const SmartPtrCVgAuthContext& vgAuthContext, const std::string& signedSamlToken) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(vgAuthContext); CAF_CM_VALIDATE_STRING(signedSamlToken); const VGAuthError vgAuthError = VGAuth_ValidateSamlBearerToken(vgAuthContext->getPtr(), signedSamlToken.c_str(), NULL, 0, NULL, &_vgAuthUserHandle); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_ValidateSamlBearerToken Failed"); _isInitialized = true; } CAF_CM_EXIT; } void CVgAuthUserHandle::initialize( const SmartPtrCVgAuthContext& vgAuthContext, const std::string& signedSamlToken, const std::string& userName) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_ENTER { CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(vgAuthContext); CAF_CM_VALIDATE_STRING(signedSamlToken); CAF_CM_VALIDATE_STRING(userName); const VGAuthError vgAuthError = VGAuth_ValidateSamlBearerToken(vgAuthContext->getPtr(), signedSamlToken.c_str(), userName.c_str(), 0, NULL, &_vgAuthUserHandle); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_ValidateSamlBearerToken Failed", userName); _isInitialized = true; } CAF_CM_EXIT; } std::string CVgAuthUserHandle::getUserName( const SmartPtrCVgAuthContext& vgAuthContext) const { CAF_CM_FUNCNAME_VALIDATE("getUserName"); std::string userNameRc; CAF_CM_ENTER { CAF_CM_VALIDATE_SMARTPTR(vgAuthContext); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); char* userName = NULL; const VGAuthError vgAuthError = VGAuth_UserHandleUsername(vgAuthContext->getPtr(), _vgAuthUserHandle, &userName); CVgAuthError::checkErrorExc(vgAuthError, "VGAuth_UserHandleUsername Failed"); CAF_CM_VALIDATE_PTR(userName); userNameRc = userName; VGAuth_FreeBuffer(userName); } CAF_CM_EXIT; return userNameRc; } VGAuthUserHandle* CVgAuthUserHandle::getPtr() const { CAF_CM_FUNCNAME_VALIDATE("getPtr"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _vgAuthUserHandle; } VgAuthIntegration.cpp000066400000000000000000000020701321503522500366330ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" namespace Caf { const char* _sObjIdGuestAuthenticatorInstance = "com.vmware.commonagent.maintegration.guestauthenticatorinstance"; const char* _sObjIdGuestAuthenticator = "com.vmware.commonagent.maintegration.guestauthenticator"; } using namespace Caf; CEcmSubSystemModule _Module; CAF_BEGIN_OBJECT_MAP(ObjectMap) #ifndef __APPLE__ CAF_OBJECT_ENTRY(CGuestAuthenticator) CAF_OBJECT_ENTRY(CGuestAuthenticatorInstance) #endif CAF_END_OBJECT_MAP() CAF_DECLARE_SUBSYSTEM_EXPORTS() extern "C" BOOL APIENTRY DllMain(HINSTANCE hModule, uint32 dwReason, LPVOID) { try { if (DLL_PROCESS_ATTACH == dwReason) { // initialize the sub-system module _Module.Init(ObjectMap, hModule); } else if (DLL_PROCESS_DETACH == dwReason) { // Terminate the sub-system module _Module.Term(); } } catch (std::runtime_error) { ::exit(2); } catch (...) { ::exit(2); } return TRUE; } stdafx.h000066400000000000000000000011261321503522500341700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ManagementAgent/Subsystems/VgAuth/src/* * Author: bwilliams * Created: Oct 22, 2010 * * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ namespace Caf { extern const char* _sObjIdGuestAuthenticatorInstance; extern const char* _sObjIdGuestAuthenticator; } #include #include #include #ifndef __APPLE__ #include #include "CVgAuthError.h" #include "CVgAuthInitializer.h" #include "CGuestAuthenticatorInstance.h" #include "CGuestAuthenticator.h" #endif #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/000077500000000000000000000000001321503522500254745ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/Makefile.am000066400000000000000000000036141321503522500275340ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ AUTOMAKE_OPTIONS = subdir-objects caflibdir = @CAF_PME_LIB_DIR@ caflib_LTLIBRARIES = caflib_LTLIBRARIES += libProviderFx.la libProviderFx_la_SOURCES= libProviderFx_la_SOURCES += ProviderFx/src/CProviderCdifFormatter.cpp libProviderFx_la_SOURCES += ProviderFx/src/CProviderDocHelper.cpp libProviderFx_la_SOURCES += ProviderFx/src/CProviderDriver.cpp libProviderFx_la_SOURCES += ProviderFx/src/ProviderFx.cpp libProviderFx_la_CPPFLAGS = libProviderFx_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libProviderFx_la_CPPFLAGS += @LOG4CPP_CPPFLAGS@ libProviderFx_la_CPPFLAGS += @SSL_CPPFLAGS@ libProviderFx_la_CPPFLAGS += @LIBRABBITMQ_CPPFLAGS@ libProviderFx_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/Framework/Framework/include libProviderFx_la_CPPFLAGS += -I$(top_srcdir)/common-agent/Cpp/ProviderFx/ProviderFx/include libProviderFx_la_LIBADD = libProviderFx_la_LIBADD += @GLIB2_LIBS@ libProviderFx_la_LIBADD += @LOG4CPP_LIBS@ libProviderFx_la_LIBADD += -ldl libProviderFx_la_LIBADD += ../Framework/libFramework.la libProviderFx_la_LDFLAGS = -shared open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/000077500000000000000000000000001321503522500275645ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/include/000077500000000000000000000000001321503522500312075ustar00rootroot00000000000000CProviderDocHelper.h000066400000000000000000000101071321503522500347630ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/include/* * Author: brets * Created: Dec 3, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderDocHelper_H_ #define CProviderDocHelper_H_ #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" namespace Caf { class PROVIDERFX_LINKAGE CProviderDocHelper { public: static SmartPtrCClassPropertyDoc createClassProperty( const std::string name, const PROPERTY_TYPE type, const bool required = false, const bool key = false, const bool list = false); static SmartPtrCClassIdentifierDoc createClassIdentifier( const std::string namespaceVal, const std::string name, const std::string version); static SmartPtrCClassInstancePropertyDoc createClassInstanceProperty( const std::string name, const SmartPtrCClassIdentifierDoc type, const bool required = false, const bool transientVal = false, const bool list = false); static SmartPtrCDataClassDoc createDataClass( const std::string namespaceVal, const std::string name, const std::string version, const std::deque properties, const std::deque instanceProperties = std::deque()); static SmartPtrCMethodParameterDoc createMethodParameter( const std::string name, const PARAMETER_TYPE type, const bool isOptional = false, const bool isList = false); static SmartPtrCInstanceParameterDoc createInstanceParameter( const std::string name, const std::string instanceNamespace, const std::string instanceName, const std::string instanceVersion, const bool isOptional = false, const bool isList = false); static SmartPtrCCollectMethodDoc createCollectMethod( const std::string name, const std::deque parameters = std::deque(), const std::deque instanceParameters = std::deque()); static SmartPtrCMethodDoc createMethod( const std::string name, const std::deque parameters = std::deque(), const std::deque instanceParameters = std::deque()); static SmartPtrCActionClassDoc createActionClass( const std::string namespaceVal, const std::string name, const std::string version, const SmartPtrCCollectMethodDoc collectMethod, const std::deque methodCollection); static SmartPtrCSchemaDoc createSchema( const std::deque dataClasses, const std::deque actionClasses); static SmartPtrCDataClassPropertyDoc createDataClassProperty( const std::string name, const std::string value); static SmartPtrCDataClassSubInstanceDoc createDataClassSubInstance( const std::string name, const std::deque properties); static SmartPtrCDataClassInstanceDoc createDataClassInstance( const std::string namespaceVal, const std::string name, const std::string version, const std::deque properties, const std::deque instanceProperties = std::deque()); private: CProviderDocHelper(); CAF_CM_DECLARE_NOCOPY(CProviderDocHelper); }; } #endif /* CProviderDocHelper_H_ */ CProviderDriver.h000066400000000000000000000041251321503522500343540ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/include/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderDriver_h_ #define CProviderDriver_h_ #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" namespace Caf { struct IInvokedProvider; // Forward declaration /// Sends responses/errors back to the client. class PROVIDERFX_LINKAGE CProviderDriver { private: CProviderDriver(IInvokedProvider& provider); virtual ~CProviderDriver(); public: static int processProviderCommandline(IInvokedProvider& provider, int argc, char* argv[]); private: int processProviderCommandline(int argc, char* argv[]); void collectSchema(const std::string& outputDir) const; void executeRequest(const std::string& requestPath) const; void executeCollectInstances( const SmartPtrCProviderRequestDoc request, const SmartPtrCProviderCollectInstancesDoc doc) const; void executeInvokeOperation( const SmartPtrCProviderRequestDoc request, const SmartPtrCProviderInvokeOperationDoc doc) const; SmartPtrCRequestIdentifierDoc createRequestId( const SmartPtrCProviderRequestDoc request, const SmartPtrCActionClassDoc actionClass, const UUID jobId) const; SmartPtrCActionClassDoc findActionClass( const std::string srchClassNamespace, const std::string srchClassName, const std::string srchClassVersion, const std::string srchOperationName) const; void saveProviderResponse( const std::string attachmentFilePath) const; private: IInvokedProvider& _provider; const SmartPtrCSchemaDoc _schema; const std::string _providerNamespace; const std::string _providerName; const std::string _providerVersion; std::vector _commandLineArgs; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CProviderDriver); }; } #endif // #ifndef CProviderDriver_h_ IInvokedProvider.h000066400000000000000000000017441321503522500345320ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/include/* * Author: brets * Created: October 28, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _ProviderContracts_IInvokedProvider_H_ #define _ProviderContracts_IInvokedProvider_H_ #include "Doc/ProviderResultsDoc/CSchemaDoc.h" namespace Caf { struct IProviderRequest; // Forward declaration struct IProviderResponse; // Forward declaration struct __declspec(novtable) IInvokedProvider { virtual const std::string getProviderNamespace() const = 0; virtual const std::string getProviderName() const = 0; virtual const std::string getProviderVersion() const = 0; virtual const SmartPtrCSchemaDoc getSchema() const = 0; virtual void collect(const IProviderRequest& request, IProviderResponse& response) const = 0; virtual void invoke(const IProviderRequest& request, IProviderResponse& response) const = 0; }; //CAF_DECLARE_SMART_INTERFACE_POINTER(IInvokedProvider); } #endif // #ifndef _ProviderContracts_IInvokedProvider_H_ IProviderRequest.h000066400000000000000000000020601321503522500345530ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/include/* * Author: brets * Created: October 28, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _ProviderContracts_IProviderRequest_H_ #define _ProviderContracts_IProviderRequest_H_ #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" namespace Caf { struct __declspec(novtable) IProviderRequest { virtual const UUID getClientId() const = 0; virtual const UUID getRequestId() const = 0; virtual const std::string getPmeId() const = 0; virtual const std::vector getCommandLine() const = 0; virtual const SmartPtrCAttachmentCollectionDoc getAttachments() const = 0; virtual const SmartPtrCProviderCollectInstancesDoc getCollectInstances() const = 0; virtual const SmartPtrCProviderInvokeOperationDoc getInvokeOperations() const = 0; }; //CAF_DECLARE_SMART_INTERFACE_POINTER(IProviderRequest); } #endif // #ifndef _ProviderContracts_IProviderRequest_H_ IProviderResponse.h000066400000000000000000000012551321503522500347260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/include/* * Author: brets * Created: October 28, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef _ProviderContracts_IProviderResponse_H_ #define _ProviderContracts_IProviderResponse_H_ #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" namespace Caf { struct __declspec(novtable) IProviderResponse { virtual void addInstance(const SmartPtrCDataClassInstanceDoc instance) = 0; virtual void addAttachment(const SmartPtrCAttachmentDoc attachment) = 0; }; //CAF_DECLARE_SMART_INTERFACE_POINTER(IProviderResponse); } #endif // #ifndef _ProviderContracts_IProviderResponse_H_ ProviderFxLink.h000066400000000000000000000011101321503522500342000ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/include/* * Author: brets * Created: October 28, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef PROVIDERFXLINK_H_ #define PROVIDERFXLINK_H_ #ifndef PROVIDERFX_LINKAGE #ifdef WIN32 #ifdef PROVIDERFX_BUILD #define PROVIDERFX_LINKAGE __declspec(dllexport) #else #define PROVIDERFX_LINKAGE __declspec(dllimport) #endif #else #define PROVIDERFX_LINKAGE #endif #endif #include "CProviderDriver.h" #include "CProviderDocHelper.h" #endif // #ifndef PROVIDERFXLINK_H_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/src/000077500000000000000000000000001321503522500303535ustar00rootroot00000000000000CProviderCdifFormatter.cpp000066400000000000000000000175531321503522500353620ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlRoots.h" #include "Doc/DocXml/ResponseXml/ResponseXmlRoots.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" #include "Doc/ProviderResultsDoc/CCdifDoc.h" #include "Doc/ProviderResultsDoc/CDefinitionObjectCollectionDoc.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/ResponseDoc/CManifestDoc.h" #include "Doc/ResponseDoc/CProviderResponseDoc.h" #include "Doc/ResponseDoc/CResponseHeaderDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "CProviderCdifFormatter.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlLink.h" #include "Doc/DocXml/ResponseXml/ResponseXmlLink.h" #include "../../Framework/src/Doc/DocUtils/DocUtilsLink.h" using namespace Caf; CProviderCdifFormatter::CProviderCdifFormatter() : _isInitialized(false), CAF_CM_INIT_LOG("CProviderCdifFormatter") { } CProviderCdifFormatter::~CProviderCdifFormatter() { } void CProviderCdifFormatter::initialize( const SmartPtrCRequestIdentifierDoc requestIdentifier, const SmartPtrCSchemaDoc schema, const std::string outputFilePath) { CAF_CM_FUNCNAME_VALIDATE("initialize"); CAF_CM_PRECOND_ISNOTINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(requestIdentifier); CAF_CM_VALIDATE_SMARTPTR(schema); CAF_CM_VALIDATE_STRING(outputFilePath); _requestIdentifier = requestIdentifier; _schema = schema; _outputFilePath = outputFilePath; _isInitialized = true; } void CProviderCdifFormatter::finished() { CAF_CM_FUNCNAME_VALIDATE("finished"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrCDefinitionObjectCollectionDoc definitionObjectCollection; if (!_defnObjCollection.empty()) { definitionObjectCollection.CreateInstance(); definitionObjectCollection->initialize(_defnObjCollection); } SmartPtrCCdifDoc cdifDoc; cdifDoc.CreateInstance(); cdifDoc->initialize(_requestIdentifier, definitionObjectCollection, _schema); const std::string cdifXml = XmlRoots::saveCdifToString(cdifDoc); CAF_CM_LOG_DEBUG_VA1("Writing CDIF to file - %s", _outputFilePath.c_str()); FileSystemUtils::saveTextFile(_outputFilePath, cdifXml); saveProviderResponse(); } void CProviderCdifFormatter::addInstance( const SmartPtrCDataClassInstanceDoc dataClassInstance) { CAF_CM_FUNCNAME_VALIDATE("format"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(dataClassInstance); const std::string defnObjXml = DefnObjectConverter::toString(dataClassInstance); _defnObjCollection.push_back(defnObjXml); } std::string CProviderCdifFormatter::getOutputFilePath() const { CAF_CM_FUNCNAME_VALIDATE("getOutputFilePath"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); return _outputFilePath; } void CProviderCdifFormatter::addAttachment(const SmartPtrCAttachmentDoc attachment) { CAF_CM_FUNCNAME_VALIDATE("addAttachment"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); CAF_CM_VALIDATE_SMARTPTR(attachment); _attachmentCollectionInner.push_back(attachment); } void CProviderCdifFormatter::saveProviderResponse() { CAF_CM_FUNCNAME_VALIDATE("saveProviderResponse"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const SmartPtrCAttachmentDoc attachment = createAttachment(); _attachmentCollectionInner.push_back(attachment); const SmartPtrCAttachmentCollectionDoc attachmentCollection = createAttachmentCollection(); const SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection = createAttachmentNameCollection(); std::string classNamespace; std::string className; std::string classVersion; std::string operationName; const SmartPtrCActionClassDoc actionClass = _requestIdentifier->getActionClass(); if (!actionClass.IsNull()) { classNamespace = actionClass->getNamespaceVal(); className = actionClass->getName(); classVersion = actionClass->getVersion(); const SmartPtrCCollectMethodDoc collectMethod = actionClass->getCollectMethod(); const std::deque methodCollection = actionClass->getMethodCollection(); if (!collectMethod.IsNull()) { operationName = collectMethod->getName(); } else if (!methodCollection.empty()) { const SmartPtrCMethodDoc method = methodCollection.front(); operationName = method->getName(); } } SmartPtrCManifestDoc manifest; manifest.CreateInstance(); manifest->initialize(classNamespace, className, classVersion, _requestIdentifier->getJobId(), operationName, attachmentNameCollection); SmartPtrCResponseHeaderDoc responseHeader; responseHeader.CreateInstance(); responseHeader->initialize( "1.0", CDateTimeUtils::getCurrentDateTime(), 0, true, _requestIdentifier->getSessionId()); SmartPtrCProviderResponseDoc providerResponse; providerResponse.CreateInstance(); providerResponse->initialize(_requestIdentifier->getClientId(), _requestIdentifier->getRequestId(), _requestIdentifier->getPmeId(), responseHeader, manifest, attachmentCollection, SmartPtrCStatisticsDoc()); const std::string attachmentDirPath = FileSystemUtils::getDirname(_outputFilePath); const std::string providerResponseStr = XmlRoots::saveProviderResponseToString(providerResponse); const std::string providerResponsePath = FileSystemUtils::buildPath( attachmentDirPath, _sProviderResponseFilename); FileSystemUtils::saveTextFile(providerResponsePath, providerResponseStr); CAF_CM_LOG_DEBUG_VA1("Saved provider response file - %s", providerResponsePath.c_str()); } SmartPtrCAttachmentDoc CProviderCdifFormatter::createAttachment() const { CAF_CM_FUNCNAME_VALIDATE("createAttachment"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); const std::string attachmentFileName = FileSystemUtils::getBasename(_outputFilePath); const std::string jobIdStr = BasePlatform::UuidToString(_requestIdentifier->getJobId()); const std::string attachmentName = jobIdStr + "." + attachmentFileName; const std::string cdifAttachmentFilePathTmp = FileSystemUtils::normalizePathWithForward(_outputFilePath); const std::string cmsPolicyStr = AppConfigUtils::getRequiredString( "security", "cms_policy");; SmartPtrCAttachmentDoc attachment; attachment.CreateInstance(); attachment->initialize(attachmentName, "cdif", "file:///" + cdifAttachmentFilePathTmp, false, EnumConvertersXml::convertStringToCmsPolicy(cmsPolicyStr)); return attachment; } SmartPtrCAttachmentCollectionDoc CProviderCdifFormatter::createAttachmentCollection() const { CAF_CM_FUNCNAME_VALIDATE("createAttachmentCollection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); SmartPtrCAttachmentCollectionDoc attachmentCollection; attachmentCollection.CreateInstance(); attachmentCollection->initialize(_attachmentCollectionInner, std::deque()); return attachmentCollection; } SmartPtrCAttachmentNameCollectionDoc CProviderCdifFormatter::createAttachmentNameCollection() const { CAF_CM_FUNCNAME_VALIDATE("createAttachmentNameCollection"); CAF_CM_PRECOND_ISINITIALIZED(_isInitialized); std::deque attachmentNameCollectionInner; for (TConstIterator > attachmentIter( _attachmentCollectionInner); attachmentIter; attachmentIter++) { const SmartPtrCAttachmentDoc attachment = *attachmentIter; attachmentNameCollectionInner.push_back(attachment->getName()); } SmartPtrCAttachmentNameCollectionDoc attachmentNameCollection; attachmentNameCollection.CreateInstance(); attachmentNameCollection->initialize(attachmentNameCollectionInner); return attachmentNameCollection; } CProviderCdifFormatter.h000066400000000000000000000033571321503522500350240ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderCdifFormatter_h_ #define CProviderCdifFormatter_h_ #include "IProviderResponse.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentNameCollectionDoc.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" namespace Caf { /// Sends responses/errors back to the client. class CProviderCdifFormatter : public IProviderResponse { public: CProviderCdifFormatter(); virtual ~CProviderCdifFormatter(); public: void initialize( const SmartPtrCRequestIdentifierDoc requestIdentifier, const SmartPtrCSchemaDoc schema, const std::string outputFilePath); void finished(); std::string getOutputFilePath() const; public: // IProviderResponse void addInstance(const SmartPtrCDataClassInstanceDoc instance); void addAttachment(const SmartPtrCAttachmentDoc attachment); private: void saveProviderResponse(); SmartPtrCAttachmentDoc createAttachment() const; SmartPtrCAttachmentCollectionDoc createAttachmentCollection() const; SmartPtrCAttachmentNameCollectionDoc createAttachmentNameCollection() const; private: bool _isInitialized; SmartPtrCRequestIdentifierDoc _requestIdentifier; SmartPtrCSchemaDoc _schema; std::string _outputFilePath; std::deque _defnObjCollection; std::deque _attachmentCollectionInner; private: CAF_CM_CREATE; CAF_CM_CREATE_LOG; CAF_CM_DECLARE_NOCOPY(CProviderCdifFormatter); }; } #endif // #ifndef CProviderCdifFormatter_h_ CProviderDocHelper.cpp000066400000000000000000000133431321503522500344670ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/src/* * Author: brets * Created: Dec 3, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/CafCoreTypesDoc/CafCoreTypesDocTypes.h" #include "Doc/ProviderResultsDoc/CSchemaDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CClassIdentifierDoc.h" #include "Doc/SchemaTypesDoc/CClassInstancePropertyDoc.h" #include "Doc/SchemaTypesDoc/CClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CCmdlMetadataDoc.h" #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/SchemaTypesDoc/CDataClassDoc.h" #include "Doc/SchemaTypesDoc/CDataClassInstanceDoc.h" #include "Doc/SchemaTypesDoc/CDataClassPropertyDoc.h" #include "Doc/SchemaTypesDoc/CDataClassSubInstanceDoc.h" #include "Doc/SchemaTypesDoc/CInstanceParameterDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodParameterDoc.h" #include "../include/CProviderDocHelper.h" using namespace Caf; SmartPtrCClassPropertyDoc CProviderDocHelper::createClassProperty( const std::string name, const PROPERTY_TYPE type, const bool required, const bool key, const bool list) { SmartPtrCClassPropertyDoc doc; doc.CreateInstance(); doc->initialize(name, type, std::deque(), required, key, list); return doc; } SmartPtrCClassIdentifierDoc CProviderDocHelper::createClassIdentifier( const std::string namespaceVal, const std::string name, const std::string version) { SmartPtrCClassIdentifierDoc doc; doc.CreateInstance(); doc->initialize(namespaceVal, name, version); return doc; } SmartPtrCClassInstancePropertyDoc CProviderDocHelper::createClassInstanceProperty( const std::string name, const SmartPtrCClassIdentifierDoc type, const bool required, const bool transientVal, const bool list) { std::deque types; types.push_back(type); SmartPtrCClassInstancePropertyDoc doc; doc.CreateInstance(); doc->initialize(name, types, required, transientVal, list); return doc; } SmartPtrCDataClassDoc CProviderDocHelper::createDataClass( const std::string namespaceVal, const std::string name, const std::string version, const std::deque properties, const std::deque instanceProperties) { SmartPtrCDataClassDoc doc; doc.CreateInstance(); doc->initialize(namespaceVal, name, version, properties, instanceProperties); return doc; } SmartPtrCMethodParameterDoc CProviderDocHelper::createMethodParameter( const std::string name, const PARAMETER_TYPE type, const bool isOptional, const bool isList) { SmartPtrCMethodParameterDoc doc; doc.CreateInstance(); doc->initialize(name, type, isOptional, isList); return doc; } SmartPtrCCollectMethodDoc CProviderDocHelper::createCollectMethod( const std::string name, const std::deque parameters, const std::deque instanceParameters) { SmartPtrCCollectMethodDoc doc; doc.CreateInstance(); doc->initialize(name, parameters, instanceParameters); return doc; } SmartPtrCInstanceParameterDoc CProviderDocHelper::createInstanceParameter( const std::string name, const std::string instanceNamespace, const std::string instanceName, const std::string instanceVersion, const bool isOptional, const bool isList) { SmartPtrCInstanceParameterDoc doc; doc.CreateInstance(); doc->initialize(name, instanceNamespace, instanceName, instanceVersion, isOptional, isList); return doc; } SmartPtrCMethodDoc CProviderDocHelper::createMethod( const std::string name, const std::deque parameters, const std::deque instanceParameters) { SmartPtrCMethodDoc doc; doc.CreateInstance(); doc->initialize(name, parameters, instanceParameters); return doc; } SmartPtrCActionClassDoc CProviderDocHelper::createActionClass( const std::string namespaceVal, const std::string name, const std::string version, const SmartPtrCCollectMethodDoc collectMethod, const std::deque methodCollection) { SmartPtrCActionClassDoc doc; doc.CreateInstance(); doc->initialize(namespaceVal, name, version, collectMethod, methodCollection); return doc; } SmartPtrCSchemaDoc CProviderDocHelper::createSchema( const std::deque dataClasses, const std::deque actionClasses) { SmartPtrCSchemaDoc doc; doc.CreateInstance(); doc->initialize(dataClasses, actionClasses); return doc; } SmartPtrCDataClassPropertyDoc CProviderDocHelper::createDataClassProperty( const std::string name, const std::string value) { SmartPtrCDataClassPropertyDoc doc; doc.CreateInstance(); doc->initialize(name, std::deque(), value); return doc; } SmartPtrCDataClassSubInstanceDoc CProviderDocHelper::createDataClassSubInstance( const std::string name, const std::deque properties) { SmartPtrCDataClassSubInstanceDoc doc; doc.CreateInstance(); doc->initialize( name, std::deque(), properties, std::deque(), SmartPtrCCmdlUnionDoc()); return doc; } SmartPtrCDataClassInstanceDoc CProviderDocHelper::createDataClassInstance( const std::string namespaceVal, const std::string name, const std::string version, const std::deque properties, const std::deque instanceProperties) { SmartPtrCDataClassInstanceDoc doc; doc.CreateInstance(); doc->initialize( namespaceVal, name, version, std::deque(), properties, instanceProperties, SmartPtrCCmdlUnionDoc()); return doc; } CProviderDriver.cpp000066400000000000000000000344161321503522500340610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/src/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" #include "Doc/DocXml/ProviderRequestXml/ProviderRequestXmlRoots.h" #include "Doc/DocXml/ProviderResultsXml/ProviderResultsXmlRoots.h" #include "Doc/DocXml/ResponseXml/ResponseXmlRoots.h" #include "Doc/DocUtils/EnumConvertersXml.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/CafCoreTypesDoc/CAttachmentDoc.h" #include "Doc/CafCoreTypesDoc/CInlineAttachmentDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" #include "Doc/ProviderResultsDoc/CRequestIdentifierDoc.h" #include "Doc/ResponseDoc/CProviderResponseDoc.h" #include "Doc/SchemaTypesDoc/CActionClassDoc.h" #include "Doc/SchemaTypesDoc/CCollectMethodDoc.h" #include "Doc/SchemaTypesDoc/CMethodDoc.h" #include "Memory/DynamicArray/DynamicArrayInc.h" #include "Exception/CCafException.h" #include "Common/IAppConfig.h" #include "CProviderDriver.h" #include "CProviderCdifFormatter.h" #include "CProviderRequest.h" #include "IInvokedProvider.h" #include "Integration/Caf/CCafMessagePayload.h" using namespace Caf; CProviderDriver::CProviderDriver(IInvokedProvider& provider) : _provider(provider), _schema(provider.getSchema()), _providerNamespace(provider.getProviderNamespace()), _providerName(provider.getProviderName()), _providerVersion(provider.getProviderVersion()), CAF_CM_INIT_LOG("CProviderDriver") { } CProviderDriver::~CProviderDriver() { } int CProviderDriver::processProviderCommandline(IInvokedProvider& provider, int argc, char* argv[]) { SmartPtrIAppConfig appConfig; try { if (g_getenv("CAF_APPCONFIG") == NULL) { Cdeqstr deqstr; deqstr.push_back("cafenv-appconfig"); deqstr.push_back("persistence-appconfig"); deqstr.push_back("providerFx-appconfig"); deqstr.push_back("custom-appconfig"); appConfig = getAppConfig(deqstr); } else { appConfig = getAppConfig(); } } catch(CCafException *ex) { std::cerr << "CProviderDriver::processProviderCommandline() failed to initialize AppConfig: " << ex->getFullMsg().c_str(); ex->Release(); return 1; } catch (std::exception ex) { std::cerr << "CProviderDriver::getAppConfig() failed to initialize AppConfig: " << ex.what(); return 1; } catch (...) { std::cerr << "CProviderDriver::getAppConfig() failed to initialize AppConfig: unknown exception"; return 1; } // NOTE: Want to define parameters as constants if (argc == 0) { // Error std::cerr << "Invalid command line: no options provided"; return 1; } CProviderDriver driver(provider); return driver.processProviderCommandline(argc, argv); } int CProviderDriver::processProviderCommandline(int argc, char* argv[]) { CAF_CM_FUNCNAME("processProviderCommandline"); _commandLineArgs.clear(); _commandLineArgs.reserve(argc); for (int32 i = 0; i < argc; i++) { _commandLineArgs.push_back(argv[i]); } for (std::vector::const_iterator itr = _commandLineArgs.begin(); itr != _commandLineArgs.end(); itr++) { if ((*itr).compare("--schema") == 0) { itr++; if (itr == _commandLineArgs.end()) { std::cerr << "Invalid command line: no schema output directory provided"; return 1; } else if ((*itr).compare("-o") != 0) { std::cerr << "Invalid command line: unexpected option: " << (*itr).c_str(); return 1; } itr++; if (itr == _commandLineArgs.end()) { std::cerr << "Invalid command line: no schema output directory provided"; return 1; } std::string outputDir = *itr; while (++itr != _commandLineArgs.end()) { outputDir += " " + *itr; } collectSchema(outputDir); return 0; } else if ((*itr).compare("-r") == 0) { itr++; if (itr == _commandLineArgs.end()) { std::cerr << "Invalid command line: no request location provided"; return 1; } std::string requestPath = *itr; while (++itr != _commandLineArgs.end()) { requestPath += " " + *itr; } try { executeRequest(requestPath); return 0; } CAF_CM_CATCH_ALL; CAF_CM_LOG_CRIT_CAFEXCEPTION; std::cerr << "Error executing request: " << _cm_exception_->getFullMsg().c_str() << std::endl; CAF_CM_CLEAREXCEPTION return 1; } } std::cerr << "Invalid command line: unknown options"; return 1; } void CProviderDriver::collectSchema(const std::string& outputDir) const { CAF_CM_FUNCNAME_VALIDATE("collectSchema"); CAF_CM_VALIDATE_STRING(outputDir); const std::string schemaStr = XmlRoots::saveSchemaToString(_schema); const std::string schemaFilename = _providerName + "-collectSchema-Rnd.provider-data.xml"; const std::string schemaPath = FileSystemUtils::buildPath(outputDir, schemaFilename); FileSystemUtils::saveTextFile(schemaPath, schemaStr); CAF_CM_LOG_DEBUG_VA1("Saved schema file - %s", schemaPath.c_str()); saveProviderResponse(schemaPath); } void CProviderDriver::executeRequest(const std::string& requestPath) const { CAF_CM_FUNCNAME("executeRequest"); CAF_CM_VALIDATE_STRING(requestPath); // TODO: Verify file exists SmartPtrCDynamicByteArray fileContents = CCafMessagePayload::createBufferFromFile(requestPath); std::string providerRequestXml(reinterpret_cast(fileContents->getPtr())); const SmartPtrCProviderRequestDoc request = XmlRoots::parseProviderRequestFromString(providerRequestXml); bool isProviderCalled = false; const SmartPtrCProviderCollectInstancesCollectionDoc collectInstancesCollection = request->getBatch()->getCollectInstancesCollection(); if (! collectInstancesCollection.IsNull()) { const std::deque instances = collectInstancesCollection->getCollectInstances(); for(TConstIterator > iter(instances); iter; iter++) { isProviderCalled = true; executeCollectInstances(request, *iter); } } const SmartPtrCProviderInvokeOperationCollectionDoc invokeOperationCollection = request->getBatch()->getInvokeOperationCollection(); if (! invokeOperationCollection.IsNull()) { const std::deque operations = invokeOperationCollection->getInvokeOperation(); for(TConstIterator > iter(operations); iter; iter++) { isProviderCalled = true; executeInvokeOperation(request, *iter); } } if (! isProviderCalled) { CAF_CM_EXCEPTIONEX_VA3(NoSuchElementException, ERROR_NOT_FOUND, "Did not call anything on the provider - %s::%s::%s", _providerNamespace.c_str(), _providerName.c_str(), _providerVersion.c_str()); } } void CProviderDriver::executeCollectInstances( const SmartPtrCProviderRequestDoc request, const SmartPtrCProviderCollectInstancesDoc doc) const { CAF_CM_FUNCNAME_VALIDATE("executeCollectInstances"); CAF_CM_VALIDATE_SMARTPTR(request); CAF_CM_VALIDATE_SMARTPTR(doc); const SmartPtrCActionClassDoc actionClass = findActionClass(doc->getClassNamespace(), doc->getClassName(), doc->getClassVersion(), "collectInstances"); const SmartPtrCRequestIdentifierDoc requestId = createRequestId(request, actionClass, doc->getJobId()); const std::string outputFilename = _providerName + std::string("-collectInstances.provider-data.xml"); const std::string outputFilePath = FileSystemUtils::buildPath(doc->getOutputDir(), outputFilename); CProviderCdifFormatter formatter; CAF_CM_LOG_DEBUG_VA1("Initializing formatter with path - %s", outputFilePath.c_str()); formatter.initialize(requestId, _schema, outputFilePath); CAF_CM_LOG_DEBUG_VA1("Calling collect on the provider - %s", _providerName.c_str()); CProviderRequest providerRequest(request, _commandLineArgs); providerRequest.setCollectInstances(doc); _provider.collect(providerRequest, formatter); formatter.finished(); } void CProviderDriver::executeInvokeOperation( const SmartPtrCProviderRequestDoc request, const SmartPtrCProviderInvokeOperationDoc doc) const { CAF_CM_FUNCNAME_VALIDATE("executeInvokeOperation"); CAF_CM_VALIDATE_SMARTPTR(request); CAF_CM_VALIDATE_SMARTPTR(doc); const SmartPtrCActionClassDoc actionClass = findActionClass(doc->getClassNamespace(), doc->getClassName(), doc->getClassVersion(), doc->getOperation()->getName()); const SmartPtrCRequestIdentifierDoc requestId = createRequestId(request, actionClass, doc->getJobId()); const std::string outputFilename = _providerName + std::string("-invokeOperation.provider-data.xml"); const std::string outputFilePath = FileSystemUtils::buildPath(doc->getOutputDir(), outputFilename); CProviderCdifFormatter formatter; CAF_CM_LOG_DEBUG_VA1("Initializing formatter with path - %s", outputFilePath.c_str()); formatter.initialize(requestId, _schema, outputFilePath); CAF_CM_LOG_DEBUG_VA1("Calling invoke on the provider - %s", _providerName.c_str()); CProviderRequest providerRequest(request, _commandLineArgs); providerRequest.setInvokeOperations(doc); _provider.invoke(providerRequest, formatter); formatter.finished(); } SmartPtrCRequestIdentifierDoc CProviderDriver::createRequestId( const SmartPtrCProviderRequestDoc request, const SmartPtrCActionClassDoc actionClass, const UUID jobId) const { CAF_CM_FUNCNAME_VALIDATE("createRequestId"); CAF_CM_VALIDATE_SMARTPTR(request); CAF_CM_VALIDATE_SMARTPTR(actionClass); CAF_CM_VALIDATE_GUID(jobId); SmartPtrCRequestIdentifierDoc requestIdentifier; requestIdentifier.CreateInstance(); requestIdentifier->initialize( request->getClientId(), request->getRequestId(), request->getPmeId(), jobId, actionClass, CAFCOMMON_GUID_NULL); return requestIdentifier; } SmartPtrCActionClassDoc CProviderDriver::findActionClass( const std::string srchClassNamespace, const std::string srchClassName, const std::string srchClassVersion, const std::string srchOperationName) const { CAF_CM_FUNCNAME("findActionClass"); CAF_CM_VALIDATE_STRING(srchClassNamespace); CAF_CM_VALIDATE_STRING(srchClassName); CAF_CM_VALIDATE_STRING(srchClassVersion); CAF_CM_VALIDATE_STRING(srchOperationName); const std::deque actionClassCollection = _schema->getActionClassCollection(); CAF_CM_VALIDATE_STL(actionClassCollection); SmartPtrCActionClassDoc actionClassRc; for(TConstIterator > actionClassIter(actionClassCollection); actionClassIter; actionClassIter++) { const SmartPtrCActionClassDoc actionClass = *actionClassIter; const std::string actionClassNamespace = actionClass->getNamespaceVal(); const std::string actionClassName = actionClass->getName(); const std::string actionClassVersion = actionClass->getVersion(); if ((srchClassNamespace.compare(actionClassNamespace) == 0) && (srchClassName.compare(actionClassName) == 0) && (srchClassVersion.compare(actionClassVersion) == 0)) { const SmartPtrCCollectMethodDoc actionCollectMethod = actionClass->getCollectMethod(); if (! actionCollectMethod.IsNull() && (srchOperationName.compare(actionCollectMethod->getName()) == 0)) { actionClassRc.CreateInstance(); actionClassRc->initialize( actionClassNamespace, actionClassName, actionClassVersion, actionCollectMethod, std::deque(), actionClass->getDisplayName(), actionClass->getDescription()); break; } else { const std::deque actionMethodCollection = actionClass->getMethodCollection(); for(TConstIterator > actionMethodIter(actionMethodCollection); actionMethodIter; actionMethodIter++) { const SmartPtrCMethodDoc actionMethod = *actionMethodIter; if (srchOperationName.compare(actionMethod->getName()) == 0) { std::deque actionMethodCollection; actionMethodCollection.push_back(actionMethod); actionClassRc.CreateInstance(); actionClassRc->initialize( actionClassNamespace, actionClassName, actionClassVersion, SmartPtrCCollectMethodDoc(), actionMethodCollection, actionClass->getDisplayName(), actionClass->getDescription()); break; } } } } } if (actionClassRc.IsNull()) { CAF_CM_EXCEPTIONEX_VA4(NoSuchElementException, ERROR_NOT_FOUND, "Action Class not found - %s::%s::%s::%s", srchClassNamespace.c_str(), srchClassName.c_str(), srchClassVersion.c_str(), srchOperationName.c_str()); } return actionClassRc; } void CProviderDriver::saveProviderResponse(const std::string attachmentFilePath) const { CAF_CM_FUNCNAME_VALIDATE("saveProviderResponse"); CAF_CM_VALIDATE_STRING(attachmentFilePath); const std::string attachmentName = FileSystemUtils::getBasename(attachmentFilePath); const std::string attachmentDirPath = FileSystemUtils::getDirname(attachmentFilePath); const std::string attachmentFilePathTmp = FileSystemUtils::normalizePathWithForward(attachmentFilePath); const std::string cmsPolicyStr = AppConfigUtils::getRequiredString( "security", "cms_policy");; SmartPtrCAttachmentDoc attachment; attachment.CreateInstance(); attachment->initialize(attachmentName, "cdif", "file:///" + attachmentFilePathTmp, false, EnumConvertersXml::convertStringToCmsPolicy(cmsPolicyStr)); std::deque attachmentCollectionInner; attachmentCollectionInner.push_back(attachment); SmartPtrCAttachmentCollectionDoc attachmentCollection; attachmentCollection.CreateInstance(); attachmentCollection->initialize(attachmentCollectionInner, std::deque()); const UUID clientId = CAFCOMMON_GUID_NULL; const UUID requestId = CAFCOMMON_GUID_NULL; const std::string pmeId = BasePlatform::UuidToString(CAFCOMMON_GUID_NULL); SmartPtrCProviderResponseDoc providerResponse; providerResponse.CreateInstance(); providerResponse->initialize( clientId, requestId, pmeId, SmartPtrCResponseHeaderDoc(), SmartPtrCManifestDoc(), attachmentCollection, SmartPtrCStatisticsDoc()); const std::string providerResponseStr = XmlRoots::saveProviderResponseToString(providerResponse); const std::string providerResponsePath = FileSystemUtils::buildPath(attachmentDirPath, _sProviderResponseFilename); FileSystemUtils::saveTextFile(providerResponsePath, providerResponseStr); CAF_CM_LOG_DEBUG_VA1("Saved provider response file - %s", providerResponsePath.c_str()); } CProviderRequest.h000066400000000000000000000036751321503522500337260ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/src/* * Author: brets * Created: November 5, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef CProviderRequest_h_ #define CProviderRequest_h_ #include "IProviderRequest.h" #include "Doc/CafCoreTypesDoc/CAttachmentCollectionDoc.h" #include "Doc/ProviderRequestDoc/CProviderCollectInstancesDoc.h" #include "Doc/ProviderRequestDoc/CProviderInvokeOperationDoc.h" #include "Doc/ProviderRequestDoc/CProviderRequestDoc.h" namespace Caf { // Request information forwarded to the provider class CProviderRequest : public IProviderRequest { public: CProviderRequest(const SmartPtrCProviderRequestDoc request, const std::vector commandLine) : _request(request), _commandLine(commandLine) { } virtual ~CProviderRequest() {}; public: // IProviderRequest const UUID getClientId() const { return _request->getClientId(); } const UUID getRequestId() const { return _request->getRequestId(); } const std::string getPmeId() const { return _request->getPmeId(); } const std::vector getCommandLine() const { return _commandLine; } const SmartPtrCAttachmentCollectionDoc getAttachments() const { return _request->getAttachmentCollection(); } const SmartPtrCProviderCollectInstancesDoc getCollectInstances() const { return _collectInstances; } const SmartPtrCProviderInvokeOperationDoc getInvokeOperations() const { return _invokeOperations; } public: void setCollectInstances(SmartPtrCProviderCollectInstancesDoc doc) { _collectInstances = doc; _invokeOperations = NULL; } void setInvokeOperations(SmartPtrCProviderInvokeOperationDoc doc) { _collectInstances = NULL; _invokeOperations = doc; } private: const SmartPtrCProviderRequestDoc _request; const std::vector _commandLine; SmartPtrCProviderCollectInstancesDoc _collectInstances; SmartPtrCProviderInvokeOperationDoc _invokeOperations; }; } #endif // #ifndef CProviderRequest_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/src/ProviderFx.cpp000066400000000000000000000004011321503522500331420ustar00rootroot00000000000000/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #include "stdafx.h" extern "C" BOOL APIENTRY DllMain(HINSTANCE hModule, uint32 dwReason, LPVOID) { return TRUE; } open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Cpp/ProviderFx/ProviderFx/src/stdafx.h000066400000000000000000000006301321503522500320140ustar00rootroot00000000000000/* * Author: bwilliams * Created: May 3, 2012 * * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. -- VMware Confidential */ #ifndef stdafx_h_ #define stdafx_h_ //{{CAF_SUBSYSTEM}} #include #include #include #include "../include/ProviderFxLink.h" #include "CProviderCdifFormatter.h" #include "CProviderRequest.h" #endif // #ifndef stdafx_h_ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Install/000077500000000000000000000000001321503522500242705ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Install/packages/000077500000000000000000000000001321503522500260465ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Install/packages/pme/000077500000000000000000000000001321503522500266275ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Install/packages/pme/files/000077500000000000000000000000001321503522500277315ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Install/packages/pme/files/common/000077500000000000000000000000001321503522500312215ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Install/packages/pme/files/common/Linux/000077500000000000000000000000001321503522500323205ustar00rootroot00000000000000install/000077500000000000000000000000001321503522500337075ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Install/packages/pme/files/common/Linuxpreconfigure-listener.sh000066400000000000000000000050441321503522500405610ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/Install/packages/pme/files/common/Linux/install#!/bin/sh #Standard env SCRIPT=`basename "$0"` installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts configDir=$installDir/../config set_caf_pme_paths() { PATH=$PATH:$installDir:$scriptsDir PERSISTENCE_DIR=${CAF_INPUT_DIR}/persistence CERTS_DIR=${CERTS_DIR:-'/etc/vmware-tools/GuestProxyData/server'} } configure_caf_common() { mkdir -p ${PERSISTENCE_DIR}/local mkdir -p ${PERSISTENCE_DIR}/remote/remote_default/cmsCertCollection mkdir -p ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCertCollection mkdir -p ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCipherCollection/ echo "amqpBroker_default" > ${PERSISTENCE_DIR}/remote/remote_default/protocolName.txt echo "remote_default" > ${PERSISTENCE_DIR}/remote/remote_default/remoteId.txt echo "des-ede3-cbc" > ${PERSISTENCE_DIR}/remote/remote_default/cmsCipherName.txt echo "SRP-RSA-AES-128-CBC-SHA" > ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCipherCollection/tlsCipher0.txt echo "amqpBroker_default" > ${PERSISTENCE_DIR}/protocol/amqpBroker_default/protocolName.txt echo "TLSv1" > ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsProtocol.txt cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/local/cert.pem cp -rf ${CERTS_DIR}/key.pem ${PERSISTENCE_DIR}/local/privateKey.pem cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCert.pem cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/remote/remote_default/cmsCertCollection/cmsCert0.pem cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/remote/remote_default/cmsCert.pem /usr/bin/vmware-guestproxycerttool -a ${PERSISTENCE_DIR}/local/cert.pem /usr/bin/vmware-guestproxycerttool -a ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCert.pem /usr/bin/vmware-guestproxycerttool -a ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem } ##============================================================================= ## Main ##============================================================================= . $scriptsDir/caf-common sourceCafenv "$configDir" set_caf_pme_paths configure_caf_common #echo QUIT | openssl s_client -connect localhost:6672 -cert ${CERTS_DIR}/cert.pem -key ${CERTS_DIR}/key.pem -CAfile ${CERTS_DIR}/cert.pem -tls1_2 #echo QUIT | openssl s_client -connect localhost:6672 -cert ${CERTS_DIR}/cert.pem -key ${CERTS_DIR}/key.pem -CAfile ${CERTS_DIR}/cert.pem -tls1_2 echo -n true open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/000077500000000000000000000000001321503522500234355ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/Makefile.am000066400000000000000000000021141321503522500254670ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ SUBDIRS = install config scripts uninstall-hook: rm -rf $(DESTDIR)/etc/vmware-caf rm -rf $(DESTDIR)/var/lib/vmware-caf rm -rf $(DESTDIR)/var/vmware-caf rm -rf $(DESTDIR)/$(libdir)/open-vm-tools/vmware-caf/ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/000077500000000000000000000000001321503522500247025ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/CommAmqpListener-appconfig000066400000000000000000000061531321503522500320160ustar00rootroot00000000000000# Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential [globals] response_dir=${output_dir}/responses event_dir=${output_dir}/events request_dir=${output_dir}/requests tmp_dir=${output_dir}/tmp persistence_dir=${input_dir}/persistence monitor_dir=${input_dir}/monitor log_config_file=${config_dir}/CommAmqpListener-log4cpp_config thread_stack_size_kb=0 schema_namespace_root=http://schemas.vmware.com/caf/schema schema_location_root=${input_dir}/schemas/caf remap_logging_location=false [communication_amqp] working_dir=${output_dir}/comm-wrk context_file=${comm_amqp_listener_context} resolver_cache_file=${output_dir}/cache/commAmqpResolver-cache reactive_request_queue_id=${reactive_request_amqp_queue_id} startup_timeout=5000 shutdown_timeout=5000 connection_retry_interval=5000 # Temporarily set to 60MB for Hyperic Agent POC # 1024 Bytes/KB * 1024 KB/MB * 60 max_part_size=62976000 vhost=caf # Wait for (connection_retries * connection_seconds_to_wait) in milli-seconds connection_timeout=150000 connection_retries=10 connection_seconds_to_wait=15 channel_cache_size=4 reply_timeout=5000 [security] cms_policy=None is_signing_enforced=false is_encryption_enforced=false tls_protocol=TLSv1_2 tls_ciphers=SRP-RSA-AES-128-CBC-SHA cms_cipher=des-ede3-cbc [subsystems] # Integration System Beans com.vmware.commonagent.integration.objectfactory=IntegrationSubsys com.vmware.commonagent.integration.channels.errorchannel=IntegrationSubsys com.vmware.commonagent.integration.channels.nullchannel=IntegrationSubsys com.vmware.commonagent.integration.headerexpressioninvoker=IntegrationSubsys # Communication Integration Beans com.vmware.caf.comm.integration.cmsmessagetransformer=CommIntegrationSubsys com.vmware.caf.comm.integration.cmsmessagetransformerinstance=CommIntegrationSubsys com.vmware.caf.comm.integration.eventtopiccalculator=CommIntegrationSubsys com.vmware.caf.comm.integration.incomingmessagehandler=CommIntegrationSubsys com.vmware.caf.comm.integration.incomingmessagehandlerinstance=CommIntegrationSubsys com.vmware.caf.comm.integration.outgoingmessagehandler=CommIntegrationSubsys com.vmware.caf.comm.integration.protocolheaderenricher=CommIntegrationSubsys com.vmware.caf.comm.integration.protocolheaderenricherinstance=CommIntegrationSubsys com.vmware.caf.comm.integration.replytocacher=CommIntegrationSubsys com.vmware.caf.comm.integration.replytocacherinstance=CommIntegrationSubsys com.vmware.caf.comm.integration.replytoresolver=CommIntegrationSubsys com.vmware.caf.comm.integration.objects=CommAmqpIntegrationSubsys # Amqp Listener Context Beans com.vmware.caf.comm.integration.amqp.caching.connection.factory=CommAmqpIntegrationSubsys com.vmware.caf.comm.integration.amqp.secure.caching.connection.factory=CommAmqpIntegrationSubsys # CAF Integration System Beans com.vmware.commonagent.cafintegration.errortoresponsetransformerinstance=CafIntegrationSubsys com.vmware.commonagent.cafintegration.errortoresponsetransformer=CafIntegrationSubsys com.vmware.commonagent.cafintegration.payloadheaderenricherinstance=CafIntegrationSubsys com.vmware.commonagent.cafintegration.payloadheaderenricher=CafIntegrationSubsys open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/CommAmqpListener-context-amqp.xml000066400000000000000000000041311321503522500332610ustar00rootroot00000000000000 CommAmqpListener-context-common.xml000066400000000000000000000141211321503522500335340ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config
CommAmqpListener-context-tunnel.xml000066400000000000000000000030471321503522500335560ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/CommAmqpListener-log4cpp_config000066400000000000000000000015321321503522500327410ustar00rootroot00000000000000#log4j.rootCategory=DEBUG, console log4j.rootCategory=ERROR, rolling log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.fileName=CommAmqpListener-log4cpp.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.rolling=org.apache.log4j.RollingFileAppender log4j.appender.rolling.fileName=CommAmqpListener-log4cpp_rolling.log log4j.appender.rolling.layout=org.apache.log4j.PatternLayout log4j.appender.rolling.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.rolling.MaxFileSize=1024KB log4j.appender.rolling.MaxBackupIndex=5 open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/IntBeanConfigFile.xml000066400000000000000000000011331321503522500306700ustar00rootroot00000000000000 open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/Makefile.am000066400000000000000000000026551321503522500267460ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ confdir=/etc/vmware-caf/pme/config conf_DATA = \ cafenv-appconfig \ CommAmqpListener-appconfig \ CommAmqpListener-context-amqp.xml \ CommAmqpListener-context-common.xml \ CommAmqpListener-context-tunnel.xml \ CommAmqpListener-log4cpp_config \ IntBeanConfigFile.xml \ ma-appconfig \ ma-context.xml \ ma-log4cpp_config \ providerFx-appconfig \ providerFx-log4cpp_config \ vgauth.conf install-data-local: D=$(DESTDIR) /bin/bash $(top_srcdir)/common-agent/etc/install/install.sh -L -l $(libdir)/open-vm-tools -B $(libdir)/open-vm-tools -i /var -o /var open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/cafenv-appconfig000066400000000000000000000031111321503522500300270ustar00rootroot00000000000000# Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential [globals] # Specifies where python is located. python_dir=/opt/vmware/caf/python # Substitute @binDir@ for the value passed in during install # Maps to 'bin' in the build output bin_dir=@binDir@ # Substitute @libDir@ for the value passed in during install # Maps to 'lib' in the build output lib_dir=@libDir@ # Substitute @configDir@ for the value passed in during install # Maps to 'config' in the build output config_dir=@configDir@ # Substitute @inputDir@ for the value passed in during install # Maps to 'data/input' in the build output input_dir=@inputDir@ # Substitute @outputDir@ for the value passed in during install # No mapping in the build output since the output files are created at run-time output_dir=@outputDir@ # Substitute @logDir@ for the value passed in during install # No mapping in the build output since the log files are created at run-time log_dir=@logDir@ # Substitute @invokersDir@ for the value passed in during install # Maps to 'invokers' in the build output - Used by the internal providers invokers_dir=@invokersDir@ # Substitute @providersDir@ for the value passed in during install # Maps to 'providers' in the build output - Used by the internal providers providers_dir=@providersDir@ # Substitute @toolsLibDir@ for the value passed in during install # Maps to 'lib' in the build output tools_lib_dir=@toolsLibDir@ # Substitute @cafInstallMode@ for the value passed in during install # No mapping in the build output since it is just a reference value install_mode=@cafInstallMode@ open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/ma-appconfig000066400000000000000000000111111321503522500271610ustar00rootroot00000000000000# Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential [globals] persistence_dir=${input_dir}/persistence monitor_dir=${input_dir}/monitor response_dir=${output_dir}/responses request_dir=${output_dir}/requests split_request_dir=${output_dir}/split-requests tmp_dir=${output_dir}/tmp bean_config_file=${config_dir}/ma-context.xml log_config_file=${config_dir}/ma-log4cpp_config scripts_dir=${config_dir}/../scripts install_dir=${config_dir}/../install thread_stack_size_kb=0 schema_namespace_root=http://schemas.vmware.com/caf/schema schema_location_root=${input_dir}/schemas/caf remap_logging_location=false [security] cms_policy=None [managementAgent] host_delay_sec=5 host_integration_timeout_ms=5000 use_impersonation=false # Value used to specify the priority that provider sub-process are created at. # Valid values are: NORMAL, LOW, IDLE. Default value is NORMAL. provider_process_priority=NORMAL [providerHost] install_dir=${config_dir}/../install invokers_dir=${invokers_dir} providers_dir=${providers_dir} schema_cache_dir=${output_dir}/schemaCache provider_reg_dir=${input_dir}/providerReg common_packages_dir=${input_dir}/commonPackages [provider] diagFileAliases=ma-appconfig:ma-log4cpp_config:ma-context:CommAmqpListener-appconfig:CommAmqpListener-log4cpp_config:CommAmqpListener-context:IntBeanConfigFile diagFileAlias_ma-appconfig=file://${root_dir}/config/ma-appconfig?encoding=iniFile diagFileAlias_ma-log4cpp_config=file://${root_dir}/config/ma-log4cpp_config?encoding=iniFileWithoutSection diagFileAlias_ma-context=file://${root_dir}/config/ma-context.xml?encoding=xmlFile diagFileAlias_CommAmqpListener-appconfig=file://${root_dir}/config/CommAmqpListener-appconfig?encoding=iniFile diagFileAlias_CommAmqpListener-log4cpp_config=file://${root_dir}/config/CommAmqpListener-log4cpp_config?encoding=iniFileWithoutSection diagFileAlias_CommAmqpListener-context=file://${root_dir}/config/CommAmqpListener-context.xml?encoding=xmlFile diagFileAlias_IntBeanConfigFile=file://${root_dir}/config/IntBeanConfigFile.xml?encoding=xmlFile [monitor] listener_retry_max=-1 listener_startup_type=Automatic listener_restart_hours=48 listener_ctrl_preconfigure=1 listener_ctrl_follow_tunnel=1 nsdb_poller_signal_file=${monitor_dir}/nsdbPollerSignal.txt nsdb_polling_interval_secs=86400 [subsystems] # Integration System Beans com.vmware.commonagent.integration.objectfactory=IntegrationSubsys com.vmware.commonagent.integration.channels.errorchannel=IntegrationSubsys com.vmware.commonagent.integration.channels.nullchannel=IntegrationSubsys # CAF Integration com.vmware.commonagent.cafintegration.errortoresponsetransformerinstance=CafIntegrationSubsys com.vmware.commonagent.cafintegration.errortoresponsetransformer=CafIntegrationSubsys com.vmware.commonagent.cafintegration.payloadheaderenricherinstance=CafIntegrationSubsys com.vmware.commonagent.cafintegration.payloadheaderenricher=CafIntegrationSubsys com.vmware.commonagent.cafintegration.envelopetopayloadtransformerinstance=CafIntegrationSubsys com.vmware.commonagent.cafintegration.envelopetopayloadtransformer=CafIntegrationSubsys # Management Agent # MA Integration com.vmware.commonagent.maintegration.collectschemaexecutor=MaIntegrationSubsys com.vmware.commonagent.maintegration.providercollectschemaexecutor=MaIntegrationSubsys com.vmware.commonagent.maintegration.providerexecutor=MaIntegrationSubsys com.vmware.commonagent.maintegration.singlepmerequestsplitterinstance=MaIntegrationSubsys com.vmware.commonagent.maintegration.singlepmerequestsplitter=MaIntegrationSubsys com.vmware.commonagent.maintegration.diagtomgmtrequesttransformerinstance=MaIntegrationSubsys com.vmware.commonagent.maintegration.diagtomgmtrequesttransformer=MaIntegrationSubsys com.vmware.commonagent.maintegration.installtomgmtrequesttransformerinstance=MaIntegrationSubsys com.vmware.commonagent.maintegration.installtomgmtrequesttransformer=MaIntegrationSubsys com.vmware.commonagent.maintegration.versiontransformerinstance=MaIntegrationSubsys com.vmware.commonagent.maintegration.versiontransformer=MaIntegrationSubsys com.vmware.commonagent.maintegration.attachmentrequesttransformerinstance=MaIntegrationSubsys com.vmware.commonagent.maintegration.attachmentrequesttransformer=MaIntegrationSubsys com.vmware.commonagent.maintegration.integrationobjects=MaIntegrationSubsys com.vmware.commonagent.maintegration.guestauthenticatorinstance=VgAuthIntegrationSubsys com.vmware.commonagent.maintegration.guestauthenticator=VgAuthIntegrationSubsys com.vmware.commonagent.maintegration.configenv=MaIntegrationSubsys com.vmware.commonagent.maintegration.persistencenamespacedb=MaIntegrationSubsys open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/ma-context.xml000066400000000000000000000275751321503522500275230ustar00rootroot00000000000000
open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/ma-log4cpp_config000066400000000000000000000014761321503522500301250ustar00rootroot00000000000000#log4j.rootCategory=DEBUG, console log4j.rootCategory=ERROR, rolling log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.fileName=ma-log4cpp.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.rolling=org.apache.log4j.RollingFileAppender log4j.appender.rolling.fileName=ma-log4cpp_rolling.log log4j.appender.rolling.layout=org.apache.log4j.PatternLayout log4j.appender.rolling.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.rolling.MaxFileSize=1024KB log4j.appender.rolling.MaxBackupIndex=5 open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/providerFx-appconfig000066400000000000000000000013301321503522500307160ustar00rootroot00000000000000# Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential [globals] #response_dir=${output_dir}/responses #request_dir=${output_dir}/requests #tmp_dir=${output_dir}/tmp #bean_config_file=${config_dir}/ma-context.xml log_config_file=${config_dir}/providerFx-log4cpp_config thread_stack_size_kb=0 schema_namespace_root=http://schemas.vmware.com/caf/schema schema_location_root=${input_dir}/schemas/caf remap_logging_location=false [providerHost] install_dir=${config_dir}/../install invokers_dir=${invokers_dir} providers_dir=${providers_dir} schema_cache_dir=${output_dir}/schemaCache provider_reg_dir=${input_dir}/providerReg common_packages_dir=${input_dir}/commonPackages [security] cms_policy=None open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/providerFx-log4cpp_config000066400000000000000000000015161321503522500316530ustar00rootroot00000000000000#log4j.rootCategory=DEBUG, console log4j.rootCategory=ERROR, rolling log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.fileName=providerFx-log4cpp.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.rolling=org.apache.log4j.RollingFileAppender log4j.appender.rolling.fileName=providerFx-log4cpp_rolling.log log4j.appender.rolling.layout=org.apache.log4j.PatternLayout log4j.appender.rolling.layout.ConversionPattern=%p|%d{ISO8601}|%t|%c|%m%n log4j.appender.rolling.MaxFileSize=1024KB log4j.appender.rolling.MaxBackupIndex=5 open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/config/vgauth.conf000066400000000000000000000002531321503522500270470ustar00rootroot00000000000000[service] logfile=@logDir@/vgauth.log loglevel=verbose enableLogging=true enableCoreDumps=true samlSchemaDir=${input_dir}/schemas/saml [auditing] auditSuccessEvents=true open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/000077500000000000000000000000001321503522500251035ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/Makefile.am000066400000000000000000000023521321503522500271410ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ confdir = /etc/vmware-caf/pme/install conf_SCRIPTS = \ caf-c-communication-service \ caf-c-management-agent \ caf-dbg.sh \ caf-vgauth \ commonenv.sh \ install.sh \ postinstallInstall.sh \ postinstallUpgrade.sh \ preinstallUpgrade.sh \ preremoveUninstall.sh \ preuninstall.sh \ preupgrade.sh \ restartServices.sh \ stopAndRemoveServices.sh \ upgrade.sh open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/caf-c-communication-service000066400000000000000000000030641321503522500323030ustar00rootroot00000000000000#!/bin/bash # # Init file for the VMware CAF Communication Service # # chkconfig: 35 95 20 # description: VMware Common Agent Framework Communication Service daemon # # processname: CommAmqpListener if [ -f /etc/rc.d/init.d/functions ]; then . /etc/rc.d/init.d/functions elif [ -f /lib/lsb/init-functions ]; then . /lib/lsb/init-functions type success >/dev/null 2>/dev/null if [ $? -ne 0 ]; then success() { echo -en "$@" echo -e "$rc_done" } failure() { echo -en "$@" echo -e "$rc_failed" } fi fi progName="VMware CAF Communication Service (C Version)" listenerName=CommAmqpListener prog="@binDir@/$listenerName" startScript="@scriptDir@/start-listener" stopScript="@scriptDir@/stop-listener" lockFile=/var/lock/subsys/caf-communication-service start() { [ -x $startScript ] || exit 0 echo -n $"Starting $progName:" msg="$progBase daemon startup" "$startScript" && success "$msg" || failure "$msg" rc=$? [ $rc -eq 0 ] && touch $lockFile echo return $rc } stop() { echo -n $"Stoppping $progName:" killproc $prog -TERM rc=$? [ -x $stopScript ] && $stopScript && [ $rc -ne 0 ] && [ -z "`pidof -x $prog`" ] && rc=0 [ $rc -eq 0 ] && rm -f $lockFile echo return $rc } restart() { stop sleep 2 start } condrestart() { [ -e $lockFile ] && restart || : } case "$1" in start) start ;; stop) stop ;; status) status $prog ;; restart) restart ;; condrestart) condrestart ;; *) echo $"Usage: $0 {start|stop|status|condrestart|restart}" exit 1 esac exit $? open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/caf-c-management-agent000066400000000000000000000030221321503522500312020ustar00rootroot00000000000000#!/bin/bash # # Init file for the VMware CAF Management Agent # # chkconfig: 35 95 20 # description: VMware Common Agent Framework Management Agent daemon # # processname: ManagementAgentHost if [ -f /etc/rc.d/init.d/functions ]; then . /etc/rc.d/init.d/functions elif [ -f /lib/lsb/init-functions ]; then . /lib/lsb/init-functions type success >/dev/null 2>/dev/null if [ $? -ne 0 ]; then success() { echo -en "$@" echo -e "$rc_done" } failure() { echo -en "$@" echo -e "$rc_failed" } fi fi progName="VMware CAF Management Agent (C Version)" progBase=ManagementAgentHost prog="@binDir@/$progBase" startScript="@scriptDir@/start-ma" stopScript="@scriptDir@/stop-ma" lockFile=/var/lock/subsys/caf-management-agent start() { [ -x $startScript ] || exit 0 echo -n $"Starting $progName:" msg="$progBase daemon startup" "$startScript" && success "$msg" || failure "$msg" rc=$? [ $rc -eq 0 ] && touch $lockFile echo return $rc } stop() { echo -n $"Stoppping $progName:" killproc $prog -TERM rc=$? [ -x $stopScript ] && $stopScript && [ $rc -ne 0 ] && [ -z "`pidof -x $prog`" ] && rc=0 [ $rc -eq 0 ] && rm -f $lockFile echo return $rc } restart() { stop sleep 2 start } condrestart() { [ -e $lockFile ] && restart || : } case "$1" in start) start ;; stop) stop ;; status) status $prog ;; restart) restart ;; condrestart) condrestart ;; *) echo $"Usage: $0 {start|stop|status|condrestart|restart}" exit 1 esac exit $? open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/caf-dbg.sh000066400000000000000000000500541321503522500267260ustar00rootroot00000000000000#!/bin/bash # Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential function prtHeader() { local header=$1 echo "*************************" echo "***" echo "*** $header" echo "***" echo "*************************" } function validateNotEmpty() { local value=$1 local name=$2 if [ "$value" = "" ]; then echo "Value cannot be empty - $name" exit 1 fi } function configAmqp() { local username="$1" local password="$2" local brokerAddr="$3" validateNotEmpty "$username" "username" validateNotEmpty "$password" "password" validateNotEmpty "$brokerAddr" "brokerAddr" local uriAmqpFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/uri_amqp.txt" sed -i -e "s/#amqpUsername#/${username}/g" -e "s/#amqpPassword#/${password}/g" -e "s/#brokerAddr#/$brokerAddr/g" "$uriAmqpFile" } function enableCaf() { local username="$1" local password="$2" validateNotEmpty "$username" "username" validateNotEmpty "$password" "password" local uriAmqpFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/uri_amqp.txt" sed -i -e "s/#amqpUsername#/${username}/g" -e "s/#amqpPassword#/${password}/g" "$uriAmqpFile" } function setBroker() { local brokerAddr="$1" validateNotEmpty "$brokerAddr" "brokerAddr" local uriAmqpFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/uri_amqp.txt" sed -i "s/#brokerAddr#/$brokerAddr/g" "$uriAmqpFile" } function setListenerConfigured() { mkdir -p "$CAF_INPUT_DIR/monitor" echo "Manual" > "$CAF_INPUT_DIR/monitor/listenerConfiguredStage1.txt" } function setListenerStartupType() { local startupType="$1" validateNotEmpty "$startupType" "startupType" local appconfigFile="$CAF_CONFIG_DIR/ma-appconfig" sed -i "s/listener_startup_type=.*/listener_startup_type=$startupType/g" "$appconfigFile" } function prtHelp() { echo "*** $(basename $0) cmd - Runs commands that help with debugging CAF" echo " * configAmqp brokerUsername brokerPassword brokerAddress Configures AMQP" echo " * enableCaf brokerUsername brokerPassword Enables CAF" echo " * setBroker brokerAddress Sets the Broker into the CAF config file" echo " * setListenerConfigured Indicates that the Listener is configured" echo " * setListenerStartupType startupType Sets the startup type used by the Listener (Manual, Automatic)" echo "" echo " * getAmqpQueueName Gets the AMQP Queue Name" echo "" echo " * checkTunnel Checks the AMQP Tunnel " echo " * checkCerts Checks the certificates" echo " * prtCerts Prints the certificates" echo " * checkVmwTools Checks VMware Tools" echo "" echo " * validateXml Validates the XML files against the published schema" echo " * validateInstall Validates that the files are in the right locations and have the right permissions" echo " * validateOVTInstall Validates that the files are in the right locations for OVT and have the right permissions" echo "" echo " * clearCaches Clears the CAF caches" } function validateXml() { local schemaArea="$1" local schemaPrefix="$2" validateNotEmpty "$schemaArea" "schemaArea" validateNotEmpty "$schemaPrefix" "schemaPrefix" local schemaRoot="$CAF_INPUT_DIR/schemas/caf" for file in $(find "$CAF_OUTPUT_DIR" -name '*.xml' -print0 2>/dev/null | xargs -0 egrep -IH -lw "${schemaPrefix}.xsd"); do prtHeader "Validating $schemaArea/$schemaPrefix - $file" xmllint --schema "${schemaRoot}/${schemaArea}/${schemaPrefix}.xsd" "$file"; rc=$? if [ "$rc" != "0" ]; then exit $rc fi done } function checkCerts() { local localDir="$CAF_INPUT_DIR/persistence/local" local cacertFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem" prtHeader "Checking private key - $localDir/privateKey.pem" openssl rsa -in "$localDir/privateKey.pem" -check -noout prtHeader "Checking cert - $localDir/cert.pem" openssl verify -check_ss_sig -x509_strict -CAfile "$cacertFile" "$localDir/cert.pem" prtHeader "Validating that private key and cert match - $localDir/cert.pem" local clientCertMd5=$(openssl x509 -noout -modulus -in "$localDir/cert.pem" | openssl md5 | cut -d' ' -f2) local clientKeyMd5=$(openssl rsa -noout -modulus -in "$localDir/privateKey.pem" | openssl md5 | cut -d' ' -f2) if [ "$clientCertMd5" == "$clientKeyMd5" ]; then echo "Public and Private Key md5's match" else echo "*** Public and Private Key md5's do not match" exit 1 fi } function prtCerts() { local localDir="$CAF_INPUT_DIR/persistence/local" local cacertFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem" prtHeader "Printing - $cacertFile" openssl x509 -in "$cacertFile" -text -noout prtHeader "Printing - $localDir/cert.pem" openssl x509 -in "$localDir/cert.pem" -text -noout } function checkTunnel() { local localDir="$CAF_INPUT_DIR/persistence/local" local cacertFile="$CAF_INPUT_DIR/persistence/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem" prtHeader "Connecting to tunnel" openssl s_client -connect localhost:6672 -key "$localDir/privateKey.pem" -cert "$localDir/cert.pem" -CAfile "$cacertFile" -verify 10 } function checkVmwTools() { local isToolboxCmd=$(which vmware-toolbox-cmd 2>/dev/null) if [ "$isToolboxCmd" != "" ]; then vmware-toolbox-cmd --version else echo "It doesn't appear as though VMware Tools is installed" fi local isSystemctl=$(which systemctl 2>/dev/null) if [ "$isSystemctl" != "" ]; then systemctl status vmware-tools.service fi } function validateInstall() { checkFsPermsAll checkFileExistsBin checkFileExistsLib checkFileExistsConfig checkFileExistsScripts checkFileExistsInstall checkFileExistsInvokers checkFileExistsProviderReg } function checkFsPermsAll() { checkFsPerms "$CAF_INPUT_DIR" "755" checkFsPerms "$CAF_OUTPUT_DIR" "755" checkFsPerms "$CAF_LOG_DIR" "755" checkFsPerms "$CAF_BIN_DIR" "755" checkFsPerms "$CAF_LIB_DIR" "755" } function checkFileExistsBin() { checkFileExists "$CAF_BIN_DIR/CommAmqpListener" checkFileExists "$CAF_BIN_DIR/ConfigProvider" checkFileExists "$CAF_BIN_DIR/InstallProvider" checkFileExists "$CAF_BIN_DIR/ManagementAgentHost" checkFileExists "$CAF_BIN_DIR/RemoteCommandProvider" checkFileExists "$CAF_BIN_DIR/TestInfraProvider" checkFileExists "$CAF_BIN_DIR/VGAuthService" checkFileExists "$CAF_BIN_DIR/vmware-vgauth-cmd" } function checkFileExistsLib() { checkFileExists "$CAF_LIB_DIR/libCafIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libCommAmqpIntegration.so" checkFileExists "$CAF_LIB_DIR/libCommAmqpIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libCommIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libFramework.so" checkFileExists "$CAF_LIB_DIR/libIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libMaIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libProviderFx.so" checkFileExists "$CAF_LIB_DIR/libVgAuthIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libcom_err.so.3" checkFileExists "$CAF_LIB_DIR/libcrypto.so.1.0.2" if [ "$CAF_INSTALL_MODE" = "standalone" ]; then checkFileExists "$CAF_LIB_DIR/libgcc_s.so.1" checkFileExists "$CAF_LIB_DIR/libglib-2.0.so.0.4800.1" checkFileExists "$CAF_LIB_DIR/libgthread-2.0.so.0.4800.1" checkFileExists "$CAF_LIB_DIR/libstdc++.so.6.0.13" checkFileExists "$CAF_LIB_DIR/libpcre.so.1.2.6" checkFileExists "$CAF_LIB_DIR/libiconv.so.2.5.1" checkFileExists "$CAF_LIB_DIR/libz.so.1.2.8" checkFileExists "$CAF_LIB_DIR/libffi.so.6.0.4" fi checkFileExists "$CAF_LIB_DIR/liblog4cpp.so.5.0.6" checkFileExists "$CAF_LIB_DIR/librabbitmq.so.4.2.1" checkFileExists "$CAF_LIB_DIR/libssl.so.1.0.2" checkFileExists "$CAF_LIB_DIR/libvgauth.so" checkFileExists "$CAF_LIB_DIR/libxerces-c-3.1.so" checkFileExists "$CAF_LIB_DIR/libxml-security-c.so.16" } function checkFileExistsConfig() { checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-appconfig" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-context-amqp.xml" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-context-common.xml" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-context-tunnel.xml" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-log4cpp_config" checkFileExists "$CAF_CONFIG_DIR/IntBeanConfigFile.xml" checkFileExists "$CAF_CONFIG_DIR/cafenv-appconfig" checkFileExists "$CAF_CONFIG_DIR/ma-appconfig" checkFileExists "$CAF_CONFIG_DIR/ma-context.xml" checkFileExists "$CAF_CONFIG_DIR/ma-log4cpp_config" checkFileExists "$CAF_CONFIG_DIR/providerFx-appconfig" checkFileExists "$CAF_CONFIG_DIR/providerFx-log4cpp_config" } function checkFileExistsScripts() { checkFileExists "$CAF_CONFIG_DIR/../scripts/caf-common" checkFileExists "$CAF_CONFIG_DIR/../scripts/caf-processes.sh" checkFileExists "$CAF_CONFIG_DIR/../scripts/setUpVgAuth" checkFileExists "$CAF_CONFIG_DIR/../scripts/start-VGAuthService" checkFileExists "$CAF_CONFIG_DIR/../scripts/start-listener" checkFileExists "$CAF_CONFIG_DIR/../scripts/start-ma" checkFileExists "$CAF_CONFIG_DIR/../scripts/startTestProc" checkFileExists "$CAF_CONFIG_DIR/../scripts/stop-VGAuthService" checkFileExists "$CAF_CONFIG_DIR/../scripts/stop-listener" checkFileExists "$CAF_CONFIG_DIR/../scripts/stop-ma" checkFileExists "$CAF_CONFIG_DIR/../scripts/tearDownVgAuth" checkFileExists "$CAF_CONFIG_DIR/../scripts/vgAuth" } function checkFileExistsInstall() { checkFileExists "$CAF_CONFIG_DIR/../install/caf-c-communication-service" checkFileExists "$CAF_CONFIG_DIR/../install/caf-c-management-agent" checkFileExists "$CAF_CONFIG_DIR/../install/caf-dbg.sh" checkFileExists "$CAF_CONFIG_DIR/../install/caf-vgauth" checkFileExists "$CAF_CONFIG_DIR/../install/commonenv.sh" checkFileExists "$CAF_CONFIG_DIR/../install/install.sh" checkFileExists "$CAF_CONFIG_DIR/../install/postinstallInstall.sh" checkFileExists "$CAF_CONFIG_DIR/../install/postinstallUpgrade.sh" checkFileExists "$CAF_CONFIG_DIR/../install/preinstallUpgrade.sh" checkFileExists "$CAF_CONFIG_DIR/../install/preremoveUninstall.sh" checkFileExists "$CAF_CONFIG_DIR/../install/preuninstall.sh" checkFileExists "$CAF_CONFIG_DIR/../install/preupgrade.sh" checkFileExists "$CAF_CONFIG_DIR/../install/restartServices.sh" checkFileExists "$CAF_CONFIG_DIR/../install/stopAndRemoveServices.sh" checkFileExists "$CAF_CONFIG_DIR/../install/upgrade.sh" } function checkFileExistsInvokers() { checkFileExists "$CAF_INVOKERS_DIR/cafTestInfra_CafTestInfraProvider_1_0_0.sh" checkFileExists "$CAF_INVOKERS_DIR/caf_ConfigProvider_1_0_0.sh" checkFileExists "$CAF_INVOKERS_DIR/caf_InstallProvider_1_0_0.sh" checkFileExists "$CAF_INVOKERS_DIR/caf_RemoteCommandProvider_1_0_0.sh" } function checkFileExistsProviderReg() { checkFileExists "$CAF_INPUT_DIR/providerReg/cafTestInfra_CafTestInfraProvider_1_0_0.xml" checkFileExists "$CAF_INPUT_DIR/providerReg/caf_ConfigProvider_1_0_0.xml" checkFileExists "$CAF_INPUT_DIR/providerReg/caf_InstallProvider_1_0_0.xml" checkFileExists "$CAF_INPUT_DIR/providerReg/caf_RemoteCommandProvider_1_0_0.xml" } function checkFileExists() { local path="$1" validateNotEmpty "$path" "path" if [ ! -f "$path" ]; then echo "*** File existence check failed - expected: $path" exit 1 fi } function checkFsPerms() { local dirOrFile="$1" local permExp="$2" local userExp="$3" local groupExp="$4" validateNotEmpty "$dirOrFile" "dirOrFile" validateNotEmpty "$permExp" "permExp" if [ "$userExp" = "" ]; then userExp="root" fi if [ "$groupExp" = "" ]; then groupExp="root" fi local statInfo=( $(stat -c "%a %U %G" $dirOrFile) ) local permFnd=${statInfo[0]} local userFnd=${statInfo[1]} local groupFnd=${statInfo[2]} if [ "$permExp" != "$permFnd" ]; then echo "*** Perm check failed - expected: $permExp, found: $permFnd, dir/file: $dirOrFile" exit 1 fi if [ "$userExp" != "$userFnd" ]; then echo "*** User check failed - expected: $userExp, found: $userFnd, dir/file: $dirOrFile" exit 1 fi if [ "$groupExp" != "$groupFnd" ]; then echo "*** Group check failed - expected: $groupExp, found: $groupFnd, dir/file: $dirOrFile" exit 1 fi } function clearCaches() { validateNotEmpty "$CAF_OUTPUT_DIR" "CAF_OUTPUT_DIR" validateNotEmpty "$CAF_LOG_DIR" "CAF_LOG_DIR" prtHeader "Clearing the CAF caches" rm -rf \ $CAF_OUTPUT_DIR/schemaCache/* \ $CAF_OUTPUT_DIR/comm-wrk/* \ $CAF_OUTPUT_DIR/providerHost/* \ $CAF_OUTPUT_DIR/responses/* \ $CAF_OUTPUT_DIR/requests/* \ $CAF_OUTPUT_DIR/split-requests/* \ $CAF_OUTPUT_DIR/request_state/* \ $CAF_OUTPUT_DIR/events/* \ $CAF_OUTPUT_DIR/tmp/* \ $CAF_OUTPUT_DIR/att/* \ $CAF_OUTPUT_DIR/cache/* \ $CAF_LOG_DIR/* \ $CAF_BIN_DIR/*.log } function validateInstall() { # checkFsPermsAll checkFileExistsBin checkFileExistsLib "$1" checkFileExistsConfig checkFileExistsScripts checkFileExistsInstall checkFileExistsInvokers checkFileExistsProviderReg } function checkFsPermsAll() { checkFsPerms "$CAF_INPUT_DIR" "755" checkFsPerms "$CAF_OUTPUT_DIR" "755" checkFsPerms "$CAF_CONFIG_DIR" "755" checkFsPerms "$CAF_LOG_DIR" "755" checkFsPerms "$CAF_BIN_DIR" "755" checkFsPerms "$CAF_LIB_DIR" "755" } function checkFileExistsBin() { checkFileExists "$CAF_BIN_DIR/InstallProvider" checkFileExists "$CAF_BIN_DIR/TestInfraProvider" checkFileExists "$CAF_BIN_DIR/RemoteCommandProvider" checkFileExists "$CAF_BIN_DIR/ConfigProvider" checkFileExists "$CAF_BIN_DIR/CommAmqpListener" checkFileExists "$CAF_BIN_DIR/ManagementAgentHost" } function checkFileExistsLib() { checkFileExists "$CAF_LIB_DIR/libProviderFx.so" checkFileExists "$CAF_LIB_DIR/libMaIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libCommAmqpIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libCommAmqpIntegration.so" checkFileExists "$CAF_LIB_DIR/libFramework.so" checkFileExists "$CAF_LIB_DIR/libCafIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libVgAuthIntegrationSubsys.so" checkFileExists "$CAF_LIB_DIR/libCommIntegrationSubsys.so" local OVT=$1 if [ "$OVT" != "true" ]; then checkFileExists "$CAF_LIB_DIR/libCommAmqpListener.so" checkFileExists "$CAF_LIB_DIR/libManagementAgentHost.so" checkFileExists "$CAF_LIB_DIR/liblog4cpp.so.5.0.6" checkFileExists "$CAF_LIB_DIR/librabbitmq.so.4.2.1" if [ "$CAF_INSTALL_MODE" = "standalone" ]; then checkFileExists "$CAF_LIB_DIR/libgthread-2.0.so.0.4800.1" checkFileExists "$CAF_LIB_DIR/libglib-2.0.so.0.4800.1" fi fi } function checkFileExistsConfig() { checkFileExists "$CAF_CONFIG_DIR/ma-log4cpp_config" checkFileExists "$CAF_CONFIG_DIR/ma-context.xml" checkFileExists "$CAF_CONFIG_DIR/IntBeanConfigFile.xml" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-context-amqp.xml" checkFileExists "$CAF_CONFIG_DIR/ma-appconfig" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-context-tunnel.xml" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-context-common.xml" checkFileExists "$CAF_CONFIG_DIR/providerFx-appconfig" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-log4cpp_config" checkFileExists "$CAF_CONFIG_DIR/CommAmqpListener-appconfig" checkFileExists "$CAF_CONFIG_DIR/providerFx-log4cpp_config" checkFileExists "$CAF_CONFIG_DIR/cafenv-appconfig" } function checkFileExistsScripts() { checkFileExists "$CAF_CONFIG_DIR/../scripts/startTestProc" checkFileExists "$CAF_CONFIG_DIR/../scripts/caf-processes.sh" checkFileExists "$CAF_CONFIG_DIR/../scripts/stop-ma" checkFileExists "$CAF_CONFIG_DIR/../scripts/vgAuth" checkFileExists "$CAF_CONFIG_DIR/../scripts/start-listener" checkFileExists "$CAF_CONFIG_DIR/../scripts/stop-VGAuthService" checkFileExists "$CAF_CONFIG_DIR/../scripts/start-ma" checkFileExists "$CAF_CONFIG_DIR/../scripts/setUpVgAuth" checkFileExists "$CAF_CONFIG_DIR/../scripts/start-VGAuthService" checkFileExists "$CAF_CONFIG_DIR/../scripts/tearDownVgAuth" checkFileExists "$CAF_CONFIG_DIR/../scripts/stop-listener" checkFileExists "$CAF_CONFIG_DIR/../scripts/caf-common" } function checkFileExistsInstall() { checkFileExists "$CAF_CONFIG_DIR/../install/caf-dbg.sh" checkFileExists "$CAF_CONFIG_DIR/../install/stopAndRemoveServices.sh" checkFileExists "$CAF_CONFIG_DIR/../install/preuninstall.sh" checkFileExists "$CAF_CONFIG_DIR/../install/postinstallUpgrade.sh" checkFileExists "$CAF_CONFIG_DIR/../install/install.sh" checkFileExists "$CAF_CONFIG_DIR/../install/preremoveUninstall.sh" checkFileExists "$CAF_CONFIG_DIR/../install/preupgrade.sh" checkFileExists "$CAF_CONFIG_DIR/../install/restartServices.sh" checkFileExists "$CAF_CONFIG_DIR/../install/caf-vgauth" checkFileExists "$CAF_CONFIG_DIR/../install/preinstallUpgrade.sh" checkFileExists "$CAF_CONFIG_DIR/../install/caf-c-management-agent" checkFileExists "$CAF_CONFIG_DIR/../install/upgrade.sh" checkFileExists "$CAF_CONFIG_DIR/../install/commonenv.sh" checkFileExists "$CAF_CONFIG_DIR/../install/postinstallInstall.sh" checkFileExists "$CAF_CONFIG_DIR/../install/caf-c-communication-service" } function checkFileExistsInvokers() { checkFileExists "$CAF_INVOKERS_DIR/caf_RemoteCommandProvider_1_0_0.sh" checkFileExists "$CAF_INVOKERS_DIR/caf_InstallProvider_1_0_0.sh" checkFileExists "$CAF_INVOKERS_DIR/caf_ConfigProvider_1_0_0.sh" checkFileExists "$CAF_INVOKERS_DIR/cafTestInfra_CafTestInfraProvider_1_0_0.sh" } function checkFileExistsProviderReg() { checkFileExists "$CAF_INPUT_DIR/providerReg/caf_RemoteCommandProvider_1_0_0.xml" checkFileExists "$CAF_INPUT_DIR/providerReg/cafTestInfra_CafTestInfraProvider_1_0_0.xml" checkFileExists "$CAF_INPUT_DIR/providerReg/caf_ConfigProvider_1_0_0.xml" checkFileExists "$CAF_INPUT_DIR/providerReg/caf_InstallProvider_1_0_0.xml" } function checkFileExists() { local path="$1" validateNotEmpty "$path" "path" if [ ! -f "$path" ]; then echo "*** File existence check failed - expected: $path" exit 1 fi } function getAmqpQueueName() { grep "^reactive_request_amqp_queue_id" "$CAF_CONFIG_DIR/persistence-appconfig" | cut -d'=' -f2 } if [ $# -lt 1 -o "$1" = "--help" ]; then prtHelp exit 1 fi cmd=$1 shift installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts configDir=$installDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" case "$cmd" in "validateXml") validateXml "fx" "CafInstallRequest" validateXml "fx" "DiagRequest" validateXml "fx" "Message" validateXml "fx" "MgmtRequest" validateXml "fx" "MultiPmeMgmtRequest" validateXml "fx" "ProviderInfra" validateXml "fx" "ProviderRequest" validateXml "fx" "Response" validateXml "cmdl" "ProviderResults" ;; "checkCerts") checkCerts "$certDir" ;; "prtCerts") prtCerts "$certDir" ;; "checkTunnel") checkTunnel "$certDir" ;; "checkVmwTools") checkVmwTools ;; "getAmqpQueueName") getAmqpQueueName ;; "clearCaches") clearCaches ;; "configAmqp") configAmqp "$1" "$2" "$3" ;; "enableCaf") enableCaf "$1" "$2" ;; "setBroker") setBroker "$1" ;; "setListenerConfigured") setListenerConfigured ;; "setListenerStartupType") setListenerStartupType "$1" ;; "validateInstall") validateInstall ;; "validateOVTInstall") validateInstall "true" ;; *) echo "Bad command - $cmd" prtHelp exit 1 esac open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/caf-vgauth000066400000000000000000000030001321503522500270440ustar00rootroot00000000000000#!/bin/bash # # Init file for the VMware CAF VgAuth Service # # chkconfig: 35 95 20 # description: VMware Common Agent Framework VgAuth daemon # # processname: VGAuthService if [ -f /etc/rc.d/init.d/functions ]; then . /etc/rc.d/init.d/functions elif [ -f /lib/lsb/init-functions ]; then . /lib/lsb/init-functions type success >/dev/null 2>/dev/null if [ $? -ne 0 ]; then success() { echo -en "$@" echo -e "$rc_done" } failure() { echo -en "$@" echo -e "$rc_failed" } fi fi progName="VMware CAF VgAuth" listenerName=VGAuthService prog="@binDir@/$listenerName" startScript="@scriptDir@/start-VGAuthService" stopScript="@scriptDir@/stop-VGAuthService" lockFile=/var/lock/subsys/caf-vgauth-service start() { [ -x $startScript ] || exit 0 echo -n $"Starting $progName:" msg="$progBase daemon startup" "$startScript" && success "$msg" || failure "$msg" rc=$? [ $rc -eq 0 ] && touch $lockFile echo return $rc } stop() { echo -n $"Stoppping $progName:" killproc $prog -TERM rc=$? [ -x $stopScript ] && $stopScript && [ $rc -ne 0 ] && [ -z "`pidof -x $prog`" ] && rc=0 [ $rc -eq 0 ] && rm -f $lockFile echo return $rc } restart() { stop sleep 2 start } condrestart() { [ -e $lockFile ] && restart || : } case "$1" in start) start ;; stop) stop ;; status) status $prog ;; restart) restart ;; condrestart) condrestart ;; *) echo $"Usage: $0 {start|stop|status|condrestart|restart}" exit 1 esac exit $? open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/commonenv.sh000066400000000000000000000001011321503522500274300ustar00rootroot00000000000000cafServices="caf-c-communication-service caf-c-management-agent" open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/configCaf000066400000000000000000000000001321503522500266730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/install.sh000066400000000000000000000136451321503522500271160ustar00rootroot00000000000000#!/bin/sh # Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential #Args #brokerAddr # - default: #baseLibDir # - default: /usr/lib # - expand to "$baseLibDir"/vmware-caf/pme # #baseInputDir # - default: /var/lib # - expand to "$baseInputDir"/vmware-caf/pme/data/input # #baseOutputDir # - default: /var/lib # - expand to "$baseOutputDir"/vmware-caf/pme/data/output #Standard env SCRIPT=`basename "$0"` #Set defaults baseLibDir='/usr/lib' baseBinDir='/usr/lib' baseInputDir='/var/lib' baseOutputDir='/var/lib' brokerAddr='#brokerAddr#' linkSo='yes' toolsLibDir='/usr/lib/vmware-tools/lib' # lib is symlink to either lib64 or lib32 cafInstallMode='standalone' #Help function HELP() { echo -e \\n"Help documentation for ${SCRIPT}."\\n echo -e "Basic usage: $SCRIPT"\\n echo "Command line switches are optional. The following switches are recognized." echo "b --Sets the value for the broker address. Default is '$brokerAddr'." echo "i --Sets the base location for the input data. Default is '$baseInputDir'." echo "l --Sets the base location for the libraries. Default is '$baseLibDir'." echo "B --Sets the location for the binaries. Default is '$baseLibDir'/bin or 'bin' in base location of libraries." echo "o --Sets the base location for the output data. Default is '$baseOutputDir'." echo "L --Do not create symlinks for libraries." echo "t --Sets the location for the tools lib dir. Default is '$toolsLibDir'." echo -e "h --Displays this help message. No further functions are performed."\\n echo -e "Example: $SCRIPT -b 10.25.91.81 -i \"/usr/lib\" -i \"/var/lib\" -o \"/var/lib\""\\n exit 1 } #Replace tokens with install values setupCafConfig() { local pattern="$1" local value="$2" local rconfigDir="$3" local key="$4" ## Add the key if not exists if [ ! -n "$pattern" ]; then echo 'The pattern cannot be empty!' exit 1 fi if [ -n "$value" ]; then if [ ! -f "$rconfigDir/cafenv-appconfig" ]; then echo "The config file must exist! - $rconfigDir/cafenv-appconfig" exit 1 fi if [ -n "$key" -a `grep -c -E "^$key=" "$rconfigDir/cafenv-appconfig"` -eq 0 ]; then echo >> "$rconfigDir" echo "$key=$value" >> "$rconfigDir/cafenv-appconfig" fi sed -i "s?$pattern?$value?g" "$rconfigDir/cafenv-appconfig" fi } ##BEGIN Main #Get Optional overrides while getopts ":b:i:l:B:o:t:hL" opt; do case $opt in b) brokerAddr="$OPTARG" ;; i) baseInputDir="$OPTARG" ;; l) baseLibDir="$OPTARG" ;; B) baseBinDir="$OPTARG" ;; o) baseOutputDir="$OPTARG" ;; t) toolsLibDir="$OPTARG" cafInstallMode='tools' ;; L) linkSo='no' ;; h) HELP ;; \?) echo "Invalid option: -$OPTARG" >&2 HELP ;; esac done stdQuals="vmware-caf/pme" libDir="${D}/$baseLibDir/$stdQuals/lib" binDir="${D}/$baseBinDir/$stdQuals/bin" inputDir="${D}/$baseInputDir/$stdQuals/data/input" outputDir="${D}/$baseOutputDir/$stdQuals/data/output" providersDir="$inputDir/providers" invokersDir="$inputDir/invokers" amqpBrokerDir="$inputDir/persistence/protocol/amqpBroker_default" logDir="${D}/var/log/$stdQuals" baseEtcDir="${D}/etc/$stdQuals" configDir="$baseEtcDir/config" installDir="$baseEtcDir/install" scriptDir="$baseEtcDir/scripts" mkdir -p "$amqpBrokerDir" echo -n "amqp:#amqpUsername#:#amqpPassword#@${brokerAddr}:5672/reactiveRequestAmqpQueueId" > "$amqpBrokerDir/uri_amqp.txt" echo -n "tunnel:agentId1:bogus@localhost:6672/reactiveRequestAmqpQueueId" > "$amqpBrokerDir/uri_tunnel.txt" #Substitute values into config files setupCafConfig '@installDir@' "$installDir" "$configDir" setupCafConfig '@libDir@' "$libDir" "$configDir" setupCafConfig '@binDir@' "$binDir" "$configDir" setupCafConfig '@configDir@' "$configDir" "$configDir" setupCafConfig '@inputDir@' "$inputDir" "$configDir" setupCafConfig '@outputDir@' "$outputDir" "$configDir" setupCafConfig '@providersDir@' "$providersDir" "$configDir" setupCafConfig '@invokersDir@' "$invokersDir" "$configDir" setupCafConfig '@logDir@' "$logDir" "$configDir" setupCafConfig '@toolsLibDir@' "$toolsLibDir" "$configDir" 'tools_lib_dir' setupCafConfig '@cafInstallMode@' "$cafInstallMode" "$configDir" 'install_mode' #Set default permissions if [ -d "$libDir" ]; then for directory in $(find "$libDir" -type d); do chmod 755 "$directory" done for file in $(find "$libDir" -type f); do chmod 555 "$file" done fi if [ -d "$inputDir" ]; then for file in $(find "$inputDir" -type f); do chmod 644 "$file" done if [ -d "$persistenceDir" ]; then for file in $(find "$persistenceDir" -type f); do chmod 440 "$file" done fi if [ -d "$invokersDir" ]; then for file in $(find "$invokersDir" -type f); do chmod 555 "$file" done fi fi if [ -d "$scriptDir" ]; then chmod 555 "$scriptDir"/* fi #Set up links only in case of CAF Standalone mode if [ "$linkSo" != "no" ] ; then cd "$libDir" if [ "$cafInstallMode" = "standalone" ]; then ln -sf libglib-2.0.so.0.4800.1 libglib-2.0.so ln -sf libglib-2.0.so.0.4800.1 libglib-2.0.so.0 ln -sf libgthread-2.0.so.0.4800.1 libgthread-2.0.so ln -sf libgthread-2.0.so.0.4800.1 libgthread-2.0.so.0 ln -sf libpcre.so.1.2.6 libpcre.so ln -sf libpcre.so.1.2.6 libpcre.so.1 ln -sf libiconv.so.2.5.1 libiconv.so ln -sf libiconv.so.2.5.1 libiconv.so.2 ln -sf libz.so.1.2.8 libz.so ln -sf libz.so.1.2.8 libz.so.1 ln -sf libffi.so.6.0.4 libffi.so ln -sf libffi.so.6.0.4 libffi.so.6 fi ln -sf liblog4cpp.so.5.0.6 liblog4cpp.so ln -sf liblog4cpp.so.5.0.6 liblog4cpp.so.5 ln -sf librabbitmq.so.4.2.1 librabbitmq.so ln -sf librabbitmq.so.4.2.1 librabbitmq.so.4 fi #Run provider install logic installPProviders="$installDir/installPythonProviders.sh" if [ -e "$installPProviders" ]; then "$installPProviders" fi #if previous CAF installation #migrate config #migrate other state open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/installConfig000066400000000000000000000000001321503522500276100ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/postinstallInstall.sh000066400000000000000000000002461321503522500313440ustar00rootroot00000000000000#!/bin/sh installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts $installDir/install.sh -l /usr/lib -i /var/lib -o /var/lib $scriptsDir/start-ma open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/postinstallUpgrade.sh000066400000000000000000000002021321503522500313150ustar00rootroot00000000000000#!/bin/sh installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts $installDir/upgrade.sh $scriptsDir/start-ma open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/preconfigure-listener.sh000066400000000000000000000050441321503522500317550ustar00rootroot00000000000000#!/bin/sh #Standard env SCRIPT=`basename "$0"` installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts configDir=$installDir/../config set_caf_pme_paths() { PATH=$PATH:$installDir:$scriptsDir PERSISTENCE_DIR=${CAF_INPUT_DIR}/persistence CERTS_DIR=${CERTS_DIR:-'/etc/vmware-tools/GuestProxyData/server'} } configure_caf_common() { mkdir -p ${PERSISTENCE_DIR}/local mkdir -p ${PERSISTENCE_DIR}/remote/remote_default/cmsCertCollection mkdir -p ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCertCollection mkdir -p ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCipherCollection/ echo "amqpBroker_default" > ${PERSISTENCE_DIR}/remote/remote_default/protocolName.txt echo "remote_default" > ${PERSISTENCE_DIR}/remote/remote_default/remoteId.txt echo "des-ede3-cbc" > ${PERSISTENCE_DIR}/remote/remote_default/cmsCipherName.txt echo "SRP-RSA-AES-128-CBC-SHA" > ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCipherCollection/tlsCipher0.txt echo "amqpBroker_default" > ${PERSISTENCE_DIR}/protocol/amqpBroker_default/protocolName.txt echo "TLSv1" > ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsProtocol.txt cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/local/cert.pem cp -rf ${CERTS_DIR}/key.pem ${PERSISTENCE_DIR}/local/privateKey.pem cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCert.pem cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/remote/remote_default/cmsCertCollection/cmsCert0.pem cp -rf ${CERTS_DIR}/cert.pem ${PERSISTENCE_DIR}/remote/remote_default/cmsCert.pem /usr/bin/vmware-guestproxycerttool -a ${PERSISTENCE_DIR}/local/cert.pem /usr/bin/vmware-guestproxycerttool -a ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCert.pem /usr/bin/vmware-guestproxycerttool -a ${PERSISTENCE_DIR}/protocol/amqpBroker_default/tlsCertCollection/tlsCert0.pem } ##============================================================================= ## Main ##============================================================================= . $scriptsDir/caf-common sourceCafenv "$configDir" set_caf_pme_paths configure_caf_common #echo QUIT | openssl s_client -connect localhost:6672 -cert ${CERTS_DIR}/cert.pem -key ${CERTS_DIR}/key.pem -CAfile ${CERTS_DIR}/cert.pem -tls1_2 #echo QUIT | openssl s_client -connect localhost:6672 -cert ${CERTS_DIR}/cert.pem -key ${CERTS_DIR}/key.pem -CAfile ${CERTS_DIR}/cert.pem -tls1_2 echo -n true open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/preinstallUpgrade.sh000066400000000000000000000003001321503522500311150ustar00rootroot00000000000000#!/bin/sh installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts #Shutdown any configured services $scriptsDir/stop-ma $scriptsDir/stop-listener $installDir/preupgrade.sh open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/preremoveUninstall.sh000066400000000000000000000002041321503522500313310ustar00rootroot00000000000000#!/bin/sh installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts $scriptsDir/stop-ma $scriptsDir/stop-listener open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/preuninstall.sh000066400000000000000000000022641321503522500301630ustar00rootroot00000000000000#!/bin/sh #Get info on how the installation was configured installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts configDir=$installDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" #Set a safety check string VALIDATE_STRING='vmware-caf' safe_rm() { #Only remove directory paths that contain the validate string if test "${1#*$VALIDATE_STRING}" != "$1"; then rm -rf "$1" fi } #The default of this should be /usr/lib/vmware-caf #base_binary_dir=$(dirname $(dirname $CAF_BIN_DIR)) #safe_rm "$base_binary_dir" #The default of this should be /var/lib/vmware-caf #base_data_dir=$(dirname $(dirname $(dirname $CAF_INPUT_DIR))) #safe_rm "$base_data_dir" #The default of this should be /var/log/vmware-caf base_log_dir=$(dirname $CAF_LOG_DIR) safe_rm "$base_log_dir" #07/21/2015 #Remove some log files that get put into the CAF bin dir. #This is a hack until we fix the code to prevent this from happening. base_binary_dir="$CAF_BIN_DIR" safe_rm "$base_binary_dir/CommAmqpListener-log4cpp.log" safe_rm "$base_binary_dir/CommAmqpListener-log4cpp_rolling.log" safe_rm "$base_binary_dir/ma-log4cpp.log" safe_rm "$base_binary_dir/ma-log4cpp_rolling.log" open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/preupgrade.sh000066400000000000000000000011001321503522500275650ustar00rootroot00000000000000#!/bin/sh # Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential installDir=$(dirname $(readlink -f $0)) configDir=$installDir/../config #Preserve config mkdir -p "$configDir"/_previous_ cp -pf "$configDir"/cafenv-appconfig "$configDir"/_previous_/ 2>/dev/null cp -pf "$configDir"/cafenv.config "$configDir"/_previous_/cafenv.config 2>/dev/null cat /tmp/_cafenv-appconfig_ >> "$configDir"/_previous_/cafenv.config #Temporary until we remove amqp_username/password cp -pf "$configDir"/CommAmqpListener-appconfig "$configDir"/_previous_/ 2>/dev/null open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/restartServices.sh000066400000000000000000000004001321503522500306210ustar00rootroot00000000000000#!/bin/sh dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P) . "$dir"/commonenv.sh #Stop configured services for cafService in $cafServices; do /sbin/chkconfig $cafService if [ $? -eq 0 ]; then /sbin/service $cafService restart fi done open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/setupCafServices.sh000066400000000000000000000000001321503522500307030ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/stopAndRemoveServices.sh000066400000000000000000000004411321503522500317300ustar00rootroot00000000000000#!/bin/sh dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P) . "$dir"/commonenv.sh #Stop configured services for cafService in $cafServices; do /sbin/chkconfig $cafService if [ $? -eq 0 ]; then /sbin/service $cafService stop chkconfig --del $cafService fi done open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/install/upgrade.sh000066400000000000000000000060771321503522500271000ustar00rootroot00000000000000#!/bin/sh # Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential #Standard env SCRIPT=`basename "$0"` installDir=$(dirname $(readlink -f $0)) scriptsDir=$installDir/../scripts configDir=$installDir/../config toolsLibDir='/usr/lib/vmware-tools/lib' # lib is symlink to either lib64 or lib32 cafInstallMode='standalone' #Help function HELP() { echo -e \\n"Help documentation for ${SCRIPT}."\\n echo -e "Basic usage: $SCRIPT"\\n echo "Command line switches are optional. The following switches are recognized." echo "t --Sets the location for the tools lib dir. Default is '$toolsLibDir'." echo -e "h --Displays this help message. No further functions are performed."\\n echo -e "Example: $SCRIPT -t \"/usr/lib/vmware-tools/lib\""\\n exit 1 } ##BEGIN Main #Get Optional overrides while getopts ":t:h" opt; do case $opt in t) toolsLibDir="$OPTARG" cafInstallMode='tools' ;; h) HELP ;; \?) echo "Invalid option: -$OPTARG" >&2 HELP ;; esac done prevCafenvConfig="$configDir/_previous_/cafenv.config" if [ -f "$prevCafenvConfig" ]; then echo "Upgrading from a really old version of CAF - $prevCafenvConfig" . $prevCafenvConfig inputDir=$(echo "$CAF_INPUT_DIR" | sed 's:/vmware-caf/pme/data/input::') outputDir=$(echo "$CAF_OUTPUT_DIR" | sed 's:/vmware-caf/pme/data/output::') libDir=$(echo "$CAF_LIB_DIR" | sed 's:/vmware-caf/pme/lib::') binDir=$(echo "$CAF_BIN_DIR" | sed 's:/vmware-caf/pme/bin::') if [ -n "$CAF_TOOLS_LIB_DIR" ]; then toolsLibDir="$CAF_TOOLS_LIB_DIR" fi $installDir/install.sh -L -b "$CAF_BROKER_ADDRESS" -i "$inputDir" \ -o "$outputDir" -l "$libDir" -B "$binDir" -t "$toolsLibDir" rm -f "$prevCafenvConfig" else prevCafenvAppconfig="$configDir/_previous_/cafenv-appconfig" if [ ! -f "$prevCafenvAppconfig" ]; then echo "The backup file must exist! - $prevCafenvAppconfig" exit 1 fi mv -f "$prevCafenvAppconfig" "$configDir" fi #Remove the backup directory rm -rf "$configDir"/_previous_ . $scriptsDir/caf-common sourceCafenv "$configDir" # Make newer systemd systems (OpenSuSE 13.2) happy #if [ -x /usr/bin/systemctl ]; then # /usr/bin/systemctl daemon-reload #fi #"$dir"/restartServices.sh if [ ! -d $CAF_LIB_DIR ]; then echo "CAF_LIB_DIR not found - $CAF_LIB_DIR" exit 1 fi cd $CAF_LIB_DIR if [ "$cafInstallMode" = "standalone" ]; then ln -sf libglib-2.0.so.0.4800.1 libglib-2.0.so ln -sf libglib-2.0.so.0.4800.1 libglib-2.0.so.0 ln -sf libgthread-2.0.so.0.4800.1 libgthread-2.0.so ln -sf libgthread-2.0.so.0.4800.1 libgthread-2.0.so.0 ln -sf libpcre.so.1.2.6 libpcre.so ln -sf libpcre.so.1.2.6 libpcre.so.1 ln -sf libiconv.so.2.5.1 libiconv.so ln -sf libiconv.so.2.5.1 libiconv.so.2 ln -sf libz.so.1.2.8 libz.so ln -sf libz.so.1.2.8 libz.so.1 ln -sf libffi.so.6.0.4 libffi.so ln -sf libffi.so.6.0.4 libffi.so.6 fi ln -sf liblog4cpp.so.5.0.6 liblog4cpp.so ln -sf liblog4cpp.so.5.0.6 liblog4cpp.so.5 ln -sf librabbitmq.so.4.2.1 librabbitmq.so ln -sf librabbitmq.so.4.2.1 librabbitmq.so.4 open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/000077500000000000000000000000001321503522500251245ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/Makefile.am000066400000000000000000000022331321503522500271600ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ confdir=/etc/vmware-caf/pme/scripts conf_SCRIPTS = \ caf-common \ caf-processes.sh \ is-listener-running \ is-ma-running \ setUpVgAuth \ start-listener \ start-ma \ startTestProc \ start-VGAuthService \ stop-listener \ stop-ma \ stop-VGAuthService \ tearDownVgAuth \ vgAuth open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/caf-common000066400000000000000000000124611321503522500270720ustar00rootroot00000000000000#!/bin/sh # Copyright (C) 2017 VMware, Inc. All rights reserved. -- VMware Confidential sourceCafenv() { local configDir=$1 local cafenvAppconfig="$configDir/cafenv-appconfig" if [ ! -f "$cafenvAppconfig" ]; then echo "*** cafenv-appconfig file not found - $cafenvAppconfig" exit 1 fi local tmpCafenv="/tmp/_cafenv-appconfig_" cat "$cafenvAppconfig" | sed 's/^\[/#[/g' | sed 's/^\([a-z].*=\)/export CAF_\U\1/g' > "$tmpCafenv" sed -i 's/[ ]*=[ ]*/=/g' "$tmpCafenv" . "$tmpCafenv" if [ "$CAF_INSTALL_MODE" = "standalone" ]; then export LD_LIBRARY_PATH=$CAF_LIB_DIR else export LD_LIBRARY_PATH="$CAF_TOOLS_LIB_DIR/libvgauth.so/:$CAF_TOOLS_LIB_DIR/libcrypto.so.1.0.2/:$CAF_TOOLS_LIB_DIR/libssl.so.1.0.2/:$CAF_TOOLS_LIB_DIR/libz.so.1/:$CAF_TOOLS_LIB_DIR/libffi.so.6/:$CAF_TOOLS_LIB_DIR/libiconv.so.2/:$CAF_TOOLS_LIB_DIR/libpcre.so.1/:$CAF_TOOLS_LIB_DIR/libglib-2.0.so.0/:$CAF_TOOLS_LIB_DIR/libgcc_s.so.1/:$CAF_TOOLS_LIB_DIR/libgthread-2.0.so.0/:$CAF_TOOLS_LIB_DIR/libstdc++.so.6/:$CAF_LIB_DIR" fi export VMWARE_USE_SYSTEM_LIBS=1 } getCurrentDir() { return $(dirname $(readlink -f $0)) } startCafProcess() { local startType="$1" local startDir="$2" local processDir="$3" local processName="$4" local processPath="$processDir/$processName" verifyProcessNotRunning "$processPath" setUtf8Locale mkdir -p "$startDir" cd "$startDir" case "$startType" in "daemon") $processPath ;; "foreground") $processPath -n ;; "valgrindMemChecks") G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind -v --tool=memcheck --leak-check=full --num-callers=40 --track-origins=yes --leak-resolution=med --track-fds=yes --log-file=${processPath}-valgrind-memchecks.log $processPath -n ;; "valgrindProfiling") valgrind --tool=callgrind --log-file=${processPath}-valgrind-profiling.log $processPath -n ;; "valgrindThreading") valgrind --tool=helgrind --track-lockorders=no --log-file=${processPath}-valgrind-threading.log $processPath -n ;; *) echo "Unknown startType - $startType"; exit 1 ;; esac } startVgAuthProcess() { local startType="$1" local startDir="$2" local processDir="$3" local processName="$4" local processPath="$processDir/$processName" verifyProcessNotRunning "$processPath" setUtf8Locale mkdir -p "$startDir" cd "$startDir" # Run the processes using -s rather than -d if you want the logging to go the file instead of the console case "$startType" in "daemon") # This is supposed to start the service as a daemon, but it's failing... perhaps because the service # hasn't been registered - see above. #./$processName -b # -s tells it to log to a file, -d to the console nohup $processPath -s > ${processPath}.out 2>&1 & ;; "foreground") $processPath -d ;; "valgrindMemChecks") G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind -v --tool=memcheck --leak-check=full --show-leak-kinds=all --num-callers=40 --log-file=${processPath}-valgrind.log $processPath -d ;; "valgrindProfiling") valgrind --tool=callgrind $processPath -d ;; *) echo "Unknown startType - $startType"; exit 1 ;; esac } #Set the locale to something UTF8 setUtf8Locale() { locale_list=`locale | egrep -vi '.utf8|.utf-8|=$|LANGUAGE'` if [ $? -eq 0 ]; then echo "The locale is currently set to $LANG, looking for UTF-8" default_locale=$LANG available_utf8_locales=`locale -a | egrep -i '.utf8|.utf-8' | egrep -vi '^c.utf'` if [ ! -z "$available_utf8_locales" ]; then for loc in $available_utf8_locales; do best_locale=$loc is_en_US_locale=`echo $loc | egrep -i 'en_US'` if [ ! -z $is_en_US_locale ]; then echo "$loc is the best UTF-8 locale required" break fi done echo "Using the available UTF-8 locale: $best_locale" else echo "No UTF-8 locale found, using the default locale $default_locale" best_locale=$default_locale fi export LANG=$best_locale export LANGUAGE=$best_locale export LC_ALL=$best_locale echo "The locale is now successfully set to : $LANG" else echo "The locale is already set to UTF-8 : $LANG" fi } verifyProcessNotRunning() { local processPath=$1 pid=$(ps aux | egrep "${processPath}" | egrep -v "color=auto|grep" | awk '{print $2}') if [ ! -z "$pid" ]; then echo "$processPath is already running - $pid"; exit 0 fi } stopProcess() { local processDir=$1 local processName=$2 local processPath="$processDir/$processName" pid=$(ps aux | egrep "${processPath}" | egrep -v "color=auto|grep" | awk '{print $2}') if [ -z "$pid" ]; then echo "$processPath not found" else echo "Stopping $processPath - $pid" counter=0 while [ ! -z "$pid" ]; do if [ $counter -lt 20 ]; then kill $pid else echo "Killing $processPath with prejudice- $pid" kill -9 $pid fi counter=`expr $counter + 1`; #echo "counter=$counter" sleep 1 pid=$(ps aux | egrep "${processPath}" | egrep -v "color=auto|grep" | awk '{print $2}') done fi } enableCoreFiles() { ulimit -c unlimited } open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/caf-processes.sh000066400000000000000000000125071321503522500302220ustar00rootroot00000000000000#!/bin/bash function prtHeader() { local header=$1 echo "*************************" echo "***" echo "*** $header" echo "***" echo "*************************" } function prtHelp() { echo "*** $0 cmd " echo " Runs various CAF commands" echo " cmd: The CAF command to run:" echo " * listServices Lists the CAF Services" echo " * startServices Starts the Services" echo " * stopServices Stops the Services" echo " * killServices Kills the Services" echo "" echo " * startListener Starts the Listener Service" echo " * startListenerForeground Starts the Listener in the foreground" echo " * startListenerValgrindMemChecks Starts the Listener with Valgrind Mem Checks" echo " * stopListener Stops the Listener Service" echo " * killListener Kills the Listener Service" echo "" echo " * startMa Starts the Management Agent Service" echo " * startMaForeground Starts the Management Agent in the foreground" echo " * startMaValgrindMemChecks Starts the Management Agent with Valgrind Mem Checks" echo " * stopMa Stops the Management Agent Service" echo " * killMa Kills the Management Agent Service" } function startProcess() { local process="$1" local enableConsoleLogging="$2" local cmd="$3" case "$process" in "listener") if [ -f "$scriptsDir/start-listener" ]; then prtHeader "Starting Listener - $cmd" if [ "$enableConsoleLogging" = "true" ]; then enableConsoleLogging "CommAmqpListener" else disableConsoleLogging "CommAmqpListener" fi $scriptsDir/start-listener "$cmd" fi ;; "ma") if [ -f "$scriptsDir/start-ma" ]; then prtHeader "Starting Management Agent - $cmd" if [ "$enableConsoleLogging" = "true" ]; then enableConsoleLogging "ma" else disableConsoleLogging "ma" fi $scriptsDir/start-ma "$cmd" fi ;; *) echo "Unknown process - $process" prtHelp exit 1 esac } function stopListener() { if [ -f "$scriptsDir/stop-listener" ]; then $scriptsDir/stop-listener fi } function stopMa() { if [ -f "$scriptsDir/stop-ma" ]; then $scriptsDir/stop-ma fi } function killListener() { pid=$(ps -eo pid,cmd | egrep "CommAmqpListener" | egrep -v "egrep" | awk '{print $1}') if [ "$pid" != "" ]; then echo "Killing Listener - $pid" kill -9 $pid fi } function killMa() { pid=$(ps -eo pid,cmd | egrep "ManagementAgentHost" | egrep -v "egrep" | awk '{print $1}') if [ "$pid" != "" ]; then echo "Killing Management Agent - $pid" kill -9 $pid fi } function enableConsoleLogging() { component="$1" sed -i 's/^#log4j.rootCategory=DEBUG, console/log4j.rootCategory=DEBUG, console/g' "$CAF_CONFIG_DIR/${component}-log4cpp_config" sed -i 's/^log4j.rootCategory=DEBUG, logfile/#log4j.rootCategory=DEBUG, logfile/g' "$CAF_CONFIG_DIR/${component}-log4cpp_config" } function disableConsoleLogging() { component="$1" sed -i 's/^log4j.rootCategory=DEBUG, console/#log4j.rootCategory=DEBUG, console/g' "$CAF_CONFIG_DIR/${component}-log4cpp_config" sed -i 's/^#log4j.rootCategory=DEBUG, logfile/log4j.rootCategory=DEBUG, logfile/g' "$CAF_CONFIG_DIR/${component}-log4cpp_config" } if [ $# -lt 1 -o "$1" = "--help" ]; then prtHelp exit 1 fi cmd=$1 shift cmd_params=$@ scriptsDir=$(dirname $(readlink -f $0)) configDir=$scriptsDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" case "$cmd" in "listServices") prtHeader "Listing services" ps -ef | egrep "CommAmqpListener|ManagementAgentHost|VGAuthService" | egrep -v "egrep" ;; "startListener") startProcess "listener" "false" "daemon" ;; "startMa") startProcess "ma" "false" "daemon" ;; "startServices") startProcess "listener" "false" "daemon" startProcess "ma" "false" "daemon" ;; "startListenerForeground") startProcess "listener" "true" "foreground" ;; "startMaForeground") startProcess "ma" "true" "foreground" ;; "startListenerValgrindMemChecks") startProcess "listener" "true" "valgrindMemChecks" ;; "startMaValgrindMemChecks") startProcess "ma" "true" "valgrindMemChecks" ;; "startListenerValgrindProfiling") startProcess "listener" "true" "valgrindProfiling" ;; "startMaValgrindProfiling") startProcess "ma" "true" "valgrindProfiling" ;; "startListenerValgrindThreading") startProcess "listener" "true" "valgrindThreading" ;; "startMaValgrindThreading") startProcess "ma" "true" "valgrindThreading" ;; "stopListener") stopListener ;; "stopMa") stopMa ;; "stopServices") stopListener stopMa ;; "killListener") killListener ;; "killMa") killMa ;; "killServices") killListener killMa ;; *) echo "Bad command - $cmd" prtHelp exit 1 esac open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/is-listener-running000066400000000000000000000002771321503522500307710ustar00rootroot00000000000000#!/bin/sh processName="CommAmqpListener" pid=$(ps aux | egrep "${processName}" | egrep -v "color=auto|grep" | awk '{print $2}') if [ -z "$pid" ]; then printf "false" else printf "true" fi open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/is-ma-running000066400000000000000000000003021321503522500275260ustar00rootroot00000000000000#!/bin/sh processName="ManagementAgentHost" pid=$(ps aux | egrep "${processName}" | egrep -v "color=auto|grep" | awk '{print $2}') if [ -z "$pid" ]; then printf "false" else printf "true" fi open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/setUpVgAuth000066400000000000000000000016331321503522500272710ustar00rootroot00000000000000#!/bin/sh helpMessage() { echo "*** $0 {userName} {certPath} {subject}" echo " Starts the VgAuth service and optionally adds the user and user->subject mapping" echo " userName: The name of the user to be added [default: $userName]" echo " certPath: Path to the certificate [default: $certPath]" echo " subject: Subject that maps to the userName in the SAML [default: $subject]" exit 1 } scriptsDir=$(dirname $(readlink -f $0)) certsDir=$scriptsDir/../data/input/certs userName="" certPath=$certsDir/selfSignedCert.pem subject="samlTestSubject" if [ $# -gt 3 -o "$1" = "--help" ]; then helpMessage fi if [ $# -ge 1 ]; then userName=$1 fi if [ $# -ge 2 ]; then certPath=$2 fi if [ $# -ge 3 ]; then subject=$3 fi $scriptsDir/start-VGAuthService if [ $userName != "" ]; then /usr/sbin/useradd $userName sleep 1 $scriptsDir/vgAuth addUser $userName $certPath $subject fi open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/start-VGAuthService000066400000000000000000000012501321503522500306570ustar00rootroot00000000000000#!/bin/sh helpMessage() { local defStartType=$1 echo "*** $0 {startType}" echo " Starts VgAuth" echo " startType: How to start the listener (daemon, foreground, valgrindMemChecks, valgrindProfiling) [default: $defStartType]" exit 1 } startType="daemon" if [ $# -gt 1 -o "$1" = "--help" ]; then helpMessage "$startType" fi if [ $# -ge 1 ]; then startType=$1 fi scriptsDir=$(dirname $(readlink -f $0)) configDir=$scriptsDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" processName="VGAuthService" export LD_LIBRARY_PATH=$CAF_ROOT_DIR/lib #enableCoreFiles startVgAuthProcess "$startType" "$CAF_LOG_DIR" "$CAF_BIN_DIR" "$processName" open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/start-listener000066400000000000000000000012031321503522500300230ustar00rootroot00000000000000#!/bin/sh helpMessage() { local defStartType=$1 echo "*** $0 {startType}" echo " Starts the listener" echo " startType: How to start the listener (daemon, foreground, valgrindMemChecks, valgrindProfiling) [default: $defStartType]" exit 1 } startType="daemon" if [ $# -gt 1 -o "$1" = "--help" ]; then helpMessage "$startType" fi if [ $# -ge 1 ]; then startType=$1 fi scriptsDir=$(dirname $(readlink -f $0)) configDir=$scriptsDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" processName="CommAmqpListener" #enableCoreFiles startCafProcess "$startType" "$CAF_LOG_DIR" "$CAF_BIN_DIR" "$processName" open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/start-ma000066400000000000000000000012171321503522500266000ustar00rootroot00000000000000#!/bin/sh helpMessage() { local defStartType=$1 echo "*** $0 {startType}" echo " Starts the Management Agent" echo " startType: How to start the listener (daemon, foreground, valgrindMemChecks, valgrindProfiling) [default: $defStartType]" exit 1 } startType="daemon" if [ $# -gt 1 -o "$1" = "--help" ]; then helpMessage "$startType" fi if [ $# -ge 1 ]; then startType=$1 fi scriptsDir=$(dirname $(readlink -f $0)) configDir=$scriptsDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" processName="ManagementAgentHost" #enableCoreFiles startCafProcess "$startType" "$CAF_LOG_DIR" "$CAF_BIN_DIR" "$processName" open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/startTestProc000066400000000000000000000000651321503522500276710ustar00rootroot00000000000000#!/bin/bash echo $$ while true; do sleep 1000 done open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/stop-VGAuthService000066400000000000000000000002041321503522500305050ustar00rootroot00000000000000#!/bin/sh scriptsDir=$(dirname $(readlink -f $0)) . $scriptsDir/caf-common processName="VGAuthService" stopProcess "$processName" open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/stop-listener000066400000000000000000000003201321503522500276520ustar00rootroot00000000000000#!/bin/sh scriptsDir=$(dirname $(readlink -f $0)) configDir=$scriptsDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" processName="CommAmqpListener" stopProcess "$CAF_BIN_DIR" "$processName" open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/stop-ma000066400000000000000000000003241321503522500264260ustar00rootroot00000000000000#!/bin/sh scriptsDir=$(dirname $(readlink -f $0)) configDir=$scriptsDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" processName="ManagementAgentHost" stopProcess "$CAF_BIN_DIR" "$processName" open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/tearDownVgAuth000066400000000000000000000016461321503522500277600ustar00rootroot00000000000000#!/bin/bash helpMessage() { echo "*** $0 {userName} {certPath} {subject}" echo " Stops the VgAuth service and optionally removes the user and user->subject mapping" echo " userName: The name of the user to be removed [default: $userName]" echo " certPath: Path to the certificate [default: $certPath]" echo " subject: Subject that maps to the userName in the SAML [default: $subject]" exit 1 } scriptsDir=$(dirname $(readlink -f $0)) certsDir=$scriptsDir/../data/input/certs userName="" certPath=$certsDir/selfSignedCert.pem subject="samlTestSubject" if [ $# -gt 3 -o "$1" = "--help" ]; then helpMessage fi if [ $# -ge 1 ]; then userName=$1 fi if [ $# -ge 2 ]; then certPath=$2 fi if [ $# -ge 3 ]; then subject=$3 fi if [ $userName != "" ]; then $scriptsDir/vgAuth removeUser $userName $certPath $subject sleep 1 /usr/sbin/userdel -r $userName fi $scriptsDir/stop-VGAuthService open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/etc/scripts/vgAuth000066400000000000000000000036241321503522500263120ustar00rootroot00000000000000#!/bin/bash helpMessage() { echo "*** $0 Action {Username} {CertPath} {Subject}" echo " Manages the VGAuth alias store" echo " Action: help, addUser, removeUser, listAll, listUser" echo " Username: The name of the user to add to the alias store [default: $username]" echo " CertPath: Path to the cert [default: $cert]" echo " Subject: Subject of the cert [default: $subject]" exit 1 } scriptsDir=$(dirname $(readlink -f $0)) configDir=$scriptsDir/../config . $scriptsDir/caf-common sourceCafenv "$configDir" vgAuthCliName=vmware-vgauth-cmd if [ -f /usr/lib/vmware-vgauth/$vgAuthCliName ]; then vgAuthCliPath=/usr/lib/vmware-vgauth/$vgAuthCliName else if [ -f $CAF_BIN_DIR/$vgAuthCliName ]; then vgAuthCliPath=$CAF_BIN_DIR/$vgAuthCliName export LD_LIBRARY_PATH=$CAF_LIB_DIR else echo "*** $vgAuthCliName not found" exit 1 fi fi action=$1 username="testuser" cert=$CAF_INPUT_DIR/certs/selfSignedCert.pem subject="samlTestSubject" if [ $# -lt 1 -o $# -gt 4 -o "$1" = "--help" ]; then helpMessage fi if [ $# -ge 2 ]; then username=$2 fi if [ $# -ge 3 ]; then cert=$3 fi if [ $# -ge 4 ]; then subject=$4 fi case "$action" in "addUser") userLineCnt=$($vgAuthCli list --username=$username | wc -l) if [ $userLineCnt = 0 ]; then echo "*** Addding $username ***" $vgAuthCli add --global --username=$username --file $cert --subject=$subject else echo "*** User already exists... Doing nothing - $username" fi ;; "removeUser") userLineCnt=$($vgAuthCli list --username=$username | wc -l) if [ $userLineCnt = 0 ]; then echo "*** User already gone... Doing nothing - $username" else echo "*** Removing $username ***" $vgAuthCli remove --username=$username --file $cert --subject=$subject fi ;; "listAll") $vgAuthCli list ;; "listUser") echo "*** Listing $username ***" $vgAuthCli list --username=$username ;; "help") helpMessage ;; *) helpMessage ;; esac open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/000077500000000000000000000000001321503522500240215ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/Makefile.am000066400000000000000000000017541321503522500260640ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ confdir=/var/vmware-caf/pme/data/input conf_SCRIPTS = \ installProviderHeader.sh SUBDIRS = invokers providerReg open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/installProviderHeader.sh000066400000000000000000000005241321503522500306500ustar00rootroot00000000000000#!/bin/sh export CAF_TMP_DIR=$CAF_OUTPUT_DIR/tmp export CAF_INPUT_DIR=$CAF_INPUT_DIR export CAF_OUTPUT_DIR=$CAF_OUTPUT_DIR export CAF_PROVIDERREG_DIR=$CAF_OUTPUT_DIR/providerReg export CAF_INVOKERS_DIR=$CAF_OUTPUT_DIR/invokers export CAF_PROVIDERS_DIR=$CAF_OUTPUT_DIR/providers export CAF_COMMONPACKAGES_DIR=$CAF_OUTPUT_DIR/commonPackages open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/invokers/000077500000000000000000000000001321503522500256615ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/invokers/Makefile.am000066400000000000000000000021141321503522500277130ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ confdir=/var/vmware-caf/pme/data/input/invokers conf_SCRIPTS = \ caf_ConfigProvider_1_0_0.sh \ caf_InstallProvider_1_0_0.sh \ caf_RemoteCommandProvider_1_0_0.sh \ cafTestInfra_CafTestInfraProvider_1_0_0.sh cafTestInfra_CafTestInfraProvider_1_0_0.sh000066400000000000000000000001421321503522500354660ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/invokers#!/bin/sh export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CAF_LIB_DIR $CAF_BIN_DIR/TestInfraProvider $* open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/invokers/caf_ConfigProvider_1_0_0.sh000066400000000000000000000001371321503522500326250ustar00rootroot00000000000000#!/bin/sh export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CAF_LIB_DIR $CAF_BIN_DIR/ConfigProvider $* open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/invokers/caf_InstallProvider_1_0_0.sh000066400000000000000000000001401321503522500330200ustar00rootroot00000000000000#!/bin/sh export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CAF_LIB_DIR $CAF_BIN_DIR/InstallProvider $* caf_RemoteCommandProvider_1_0_0.sh000066400000000000000000000001461321503522500340730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/invokers#!/bin/sh export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CAF_LIB_DIR $CAF_BIN_DIR/RemoteCommandProvider $* open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/providerReg/000077500000000000000000000000001321503522500263115ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/providerReg/Makefile.am000066400000000000000000000021201321503522500303400ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ confdir=/var/vmware-caf/pme/data/input/providerReg conf_DATA = \ caf_ConfigProvider_1_0_0.xml \ caf_InstallProvider_1_0_0.xml \ caf_RemoteCommandProvider_1_0_0.xml \ cafTestInfra_CafTestInfraProvider_1_0_0.xml cafTestInfra_CafTestInfraProvider_1_0_0.xml000066400000000000000000000007751321503522500363200ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/providerReg caf_ConfigProvider_1_0_0.xml000066400000000000000000000007621321503522500333700ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/providerReg caf_InstallProvider_1_0_0.xml000066400000000000000000000007641321503522500335730ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/providerReg caf_RemoteCommandProvider_1_0_0.xml000066400000000000000000000010001321503522500346770ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/common-agent/input/providerReg open-vm-tools-stable-10.2.0/open-vm-tools/configure.ac000066400000000000000000001443651321503522500226010ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2017 VMware, Inc. All rights reserved. ### ### Configure script for building the VMware OSS Tools. ### ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ ################################################################################ # In addition to the usual environment variables and command line # arguments that a configure script usually takes (CFLAGS, LDFLAGS, # etc.), this script also accepts variables of the form: # # CUSTOM_LIB_CPPFLAGS: compile-time flags for LIB # CUSTOM_LIB_LIBS: link-time flags for LIB # RPCGENFLAGS: extra flags to pass to rpcgen # # The following libraries are currently tested: DNET, FUSE, GLIB2, GMODULE, # GOBJECT, GTHREAD, GTK, GTKMM, ICU, LIBPNG, PAM, URIPARSER, ZLIB ################################################################################ ### ### Initialization ### TOOLS_VERSION="10.2.0" AC_INIT( [open-vm-tools], [10.2.0], [open-vm-tools-devel@lists.sourceforge.net]) # In order to make this configure script auto-detect situations where # people have a 32-bit userland running with a 64-bit kernel, we try to ask # the compiler (assumedly gcc) for its default Target:. # We have to set up $TEST_CC manually, since AC_PROG_CC hasn't yet been run (and can't be until AC_CANONICAL_HOST & AC_CANONICAL_BUILD are run) # The purpose of all this is to set up $host_alias/$build_alias in a more # intelligent way than config.guess currently does. TEST_CC="$CC_FOR_BUILD" test -z "$TEST_CC" && TEST_CC="$HOST_CC" test -z "$TEST_CC" && TEST_CC="$CC" if test -n "$TEST_CC" -a -z "$host_alias"; then host_alias="`$TEST_CC -dumpmachine`" if test -z "$build_alias" -a -n "$host_alias"; then build_alias="$host_alias" fi fi unset TEST_CC # checkvm/checkvm.c has no special significance - we just need to pass in a file that # helps autoconf verify that it really has found the source tree. AC_CONFIG_SRCDIR([checkvm/checkvm.c]) # Keep the top-level directory tidy by putting auxiliary build tools and local # macros in separate subdirectories. AC_CONFIG_AUX_DIR([config]) AC_CONFIG_MACRO_DIR([m4]) AC_CANONICAL_HOST AC_CANONICAL_BUILD # Quote the regular expressions case "$host_cpu" in [i[3456]86]) userSpaceBitness="32" ;; [amd64|x86_64]) userSpaceBitness="64" ;; [*]) AC_MSG_ERROR([Unknown architecture.]) ;; esac # Operational arguments. AC_ARG_WITH([root-privileges], [AS_HELP_STRING([--without-root-privileges], [does not perform any operations that require root privileges])], [], [with_root_privileges=yes]) # Kernel arguments. # The kernel args have to go here otherwise the KERNEL_RELEASE won't be visible # to getOsVersion() AC_ARG_WITH([kernel-release], [AS_HELP_STRING([--with-kernel-release], [specifies the kernel release you want to build against])], [KERNEL_RELEASE="$withval"], [KERNEL_RELEASE=`uname -r`]) AC_ARG_WITH([linuxdir], [AS_HELP_STRING([--with-linuxdir], [specifies the Linux directory you want to use])], [LINUXDIR="$withval"], [LINUXDIR=/lib/modules/$KERNEL_RELEASE]) # Turn the uname output into something we can run comparisons on. getOsVersion() { major_version="`echo $KERNEL_RELEASE | cut -f1 -d. | cut -f1 -d-`" minor_version="`echo $KERNEL_RELEASE | cut -f2 -d. | cut -f1 -d-`" micro_version="`echo $KERNEL_RELEASE | cut -f3 -d. | cut -f1 -d-`" printf '%02d%02d%03d' $major_version $minor_version $micro_version } case "$host_os" in [linux*]) os="linux" ;; [freebsd*]) os="freebsd" ;; [kfreebsd*-gnu]) os="kfreebsd-gnu" ;; [solaris*]) os="solaris" ;; [*]) AC_MSG_WARN([This is an untested and unsupported Operating System. Proceed at your own peril.]) ;; esac osVersion="`getOsVersion`" AC_ARG_ENABLE( glibc-check, AS_HELP_STRING( [--disable-glibc-check], [Skip checking the glibc version on the system. (off by default)]), [enable_glibc_check=$enableval], [enable_glibc_check="yes"]) if test "x$enable_glibc_check" != "xno" ; then if test "x$os" = "xlinux" ; then libc_ver=`ldd --version 2>/dev/null | head -1 | sed 's/.* //;q'` if test "x$libc_ver" = "x"; then AC_MSG_ERROR(["Failed to detect glibc version installed in the system."]) fi libc_ver_mjr=`expr "$libc_ver" : "\([[0-9]]*\)"` libc_ver_mnr=`expr "$libc_ver" : "[[0-9]]*\.\([[0-9]]*\)"` libc_ver_num=`expr $libc_ver_mjr \* 1000 + $libc_ver_mnr` if test "$libc_ver_num" -lt 2012; then AC_MSG_ERROR(["glibc version $libc_ver detected. This version of open-vm-tools requires glibc version 2.12 or later. Please use an older version of open-vm-tools for this system."]) fi fi fi if test "x$os" = "xfreebsd" -a "$osVersion" -lt 1000000; then AC_MSG_ERROR(["This version of open-vm-tools requires FreeBSD version 10 or later. Please use an older version of open-vm-tools for this system."]) fi AC_ARG_WITH([kernel-modules], [AS_HELP_STRING([--with-kernel-modules], [compile and install the kernel modules])], [], [if test "x$os" = "xlinux" ; then with_kernel_modules=no else with_kernel_modules=yes fi ]) if test "$with_kernel_modules" = "yes"; then case "$os" in linux) AC_MSG_ERROR([Building kernel modules for Linux is no longer supported.]) ;; freebsd) freebsd_sysdir=/usr/src/sys if test -n "$SYSDIR"; then freebsd_sysdir="$SYSDIR" fi if test ! -f "$freebsd_sysdir/conf/kmod.mk"; then AC_MSG_ERROR([FreeBSD kernel tree not found. Please install the kernel sources (or provide the location using SYSDIR) or configure using --without-kernel-modules.]) fi ;; esac fi # Arguments for disabling individual open-vm-tools features or libraries. AC_ARG_ENABLE( multimon, AS_HELP_STRING( [--disable-multimon], [disables multimon, enabled by default]), [enable_multimon="$enableval"], [enable_multimon="yes"]) AC_ARG_WITH( gtk3, AS_HELP_STRING( [--without-gtk3], [compiles without Gtk 3.0]), [with_gtk3="$withval"], [with_gtk3="auto"]) AC_ARG_WITH( gtk2, AS_HELP_STRING( [--without-gtk2], [compiles without Gtk 2.0]), [with_gtk2="$withval"], [with_gtk2="auto"]) if test "$with_gtk2" = "auto" ; then if test "$with_gtk3" = "auto" ; then with_gtk2="no" with_gtk3="yes" elif test "$with_gtk3" = "no" ; then with_gtk2="yes" elif test "$with_gtk3" = "yes" ; then with_gtk2="no" fi elif test "$with_gtk2" = "no" ; then if test "$with_gtk3" = "auto" ; then with_gtk3="yes" elif test "$with_gtk3" = "no" ; then AC_MSG_ERROR('need either gtk2 or gtk3 or build with --without-x to disable building desktop plugins') fi elif test "$with_gtk2" = "yes" ; then if test "$with_gtk3" = "auto" ; then with_gtk3="no" elif test "$with_gtk3" = "yes" ; then AC_MSG_ERROR('cannot set both --with-gtk2 and --with-gtk3') fi fi if test "$with_gtk2" = "no" ; then with_gtkmm="no" fi if test "$with_gtk3" = "no" ; then with_gtkmm3="no" fi if test "$with_gtk3" = "yes"; then AC_ARG_WITH( gtkmm3, AS_HELP_STRING( [--without-gtkmm3], [compiles without Gtkmm 3, sigc++, and related libs]), [with_gtkmm3="$withval"], [with_gtkmm3="yes"]) with_gtkmm="no" elif test "$with_gtk2" = "yes"; then AC_ARG_WITH( gtkmm, AS_HELP_STRING( [--without-gtkmm], [compiles without Gtkmm, sigc++, and related libs]), [with_gtkmm="$withval"], [with_gtkmm="yes"]) with_gtkmm3="no" fi AC_ARG_ENABLE( docs, AS_HELP_STRING( [--disable-docs], [disables generation of API documentation; by default, docs are built if doxygen is available.]), [enable_docs="$enableval"], [enable_docs="yes"]) AC_ARG_ENABLE( tests, AS_HELP_STRING( [--disable-tests], [disable compilation of test code.]), [enable_tests="$enableval"], [enable_tests="auto"]) AC_ARG_ENABLE( resolutionkms, AS_HELP_STRING( [--enable-resolutionkms], [build the linux / unix resolutionkms module.]), [], [enable_resolutionkms="auto"]) AM_INIT_AUTOMAKE ### ### Constants ### # These need to be declared after initialization. # Some of our macro call-sites require changes to # CPPFLAGS/CFLAGS/LDFLAGS. In such places, we save the original value # of CPPFLAGS/CFLAGS/LDFLAGS before the macro call and restore it when # the call is done. We must perform this save at each macro site, # because CPPFLAGS/CFLAGS/LDFLAGS may change over the course of # configuration. # # CPPFLAGS is intended for preprocessor options (-D and -I mainly) # CFLAGS is intended for compiler options (-O, -f, -W, and so forth) CPPFLAGS="$CPPFLAGS -DUSING_AUTOCONF=1 -DOPEN_VM_TOOLS" ### ### Programs ### # C preprocessor and compiler. AC_PROG_CPP AC_PROG_CC # C++ compiler. Note that unlike AC_PROG_CC, this call does not trigger an # error if no C++ compiler was found; it'll just set the variable CXX to 'g++'. AC_PROG_CXX # This allows features like per-target compiler flags. I.e., you can compile # one copy of the same sources twice with different flags. (See lib/guestApp # for an example.) AM_PROG_CC_C_O # Needed for the various install and uninstall hooks. AC_PROG_INSTALL AC_PROG_SED AC_PROG_LN_S AC_PROG_MKDIR_P # Needed for creating the archives in lib/ and the shared libraries. AC_PROG_LIBTOOL if test "$ac_cv_prog_AR" = false; then AC_MSG_ERROR([The 'ar' utility was not found. Please put ar on the path.]) fi # We use pkg-config to set up the cflags and libs for gtk. AC_CHECK_PROG( [HAVE_PKG_CONFIG], [pkg-config], [yes], [no]) if test "$GCC" != "yes"; then AC_MSG_ERROR([Only GCC is currently supported. Please put gcc in the path.]) fi ### ### Libraries ### AC_PATH_XTRA # # Check for libintl.h. When configuring using "--without-x", /usr/local/include # may not be added to the include path, so code that use glib's i18n functions # would fail to compile because it can't find libintl.h. # AC_CHECK_HEADER([libintl.h], [], [have_libintl=no], []) if test "$have_libintl" = "no"; then unset ac_cv_header_libintl_h CPPFLAGS="$CPPFLAGS -I/usr/local/include" AC_CHECK_HEADER([libintl.h], [], [AC_MSG_ERROR([libintl.h not found. Make sure you have the gettext headers installed.])], []) fi AC_ARG_ENABLE([deploypkg], [AS_HELP_STRING([--disable-deploypkg], [do not build deploypkg plugin.])], [], [ if test "$os" = "linux"; then enable_deploypkg=yes else enable_deploypkg=no fi ]) if test "$enable_deploypkg" = "yes"; then AC_VMW_CHECK_LIB([mspack], [MSPACK], [libmspack], [], [0.0.20040308alpha], [mspack.h], [], [], [AC_MSG_ERROR([mspack >= 0.0.20040308alpha is required.])]) fi AC_ARG_ENABLE([grabbitmqproxy], [AS_HELP_STRING([--disable-grabbitmqproxy], [do not build grabbitmqproxy plugin.])], [], [ if test "$os" = "linux"; then enable_grabbitmqproxy=yes else enable_grabbitmqproxy=no fi ]) # # Check for glib 2.6.14 or greater. # AC_VMW_CHECK_LIB([glib-2.0], [GLIB2], [glib-2.0], [], [2.14.0], [glib.h], [g_key_file_new], [], [AC_MSG_ERROR([glib2 >= 2.14.0 is required.])]) AC_VMW_CHECK_LIB([gmodule-2.0], [GMODULE], [gmodule-2.0], [], [2.14.0], [], [], [], [AC_MSG_ERROR([gmodule >= 2.14.0 is required.])]) AC_VMW_CHECK_LIB([gobject-2.0], [GOBJECT], [gobject-2.0], [], [2.14.0], [glib-object.h], [], [], [AC_MSG_ERROR([gobject >= 2.14.0 is required.])]) AC_VMW_CHECK_LIB([gthread-2.0], [GTHREAD], [gthread-2.0], [], [2.14.0], [], [], [], [AC_MSG_ERROR([glib >= 2.14.0 is required.])]) AC_CHECK_PROG([have_genmarshal], [glib-genmarshal], [yes], [no]) if test "$have_genmarshal" != "yes"; then AC_MSG_ERROR([glib-genmarshal is required; make sure it is available in your path.]) fi # # Check for fuse. # AC_VMW_CHECK_LIB([fuse], [FUSE], [fuse], [], [], [fuse.h], [fuse_main], [have_fuse=yes], [have_fuse=no; AC_MSG_WARN([Fuse is missing, vmblock-fuse/vmhgfs-fuse will be disabled.])]) # # Check for PAM. # AC_ARG_WITH([pam], [AS_HELP_STRING([--without-pam], [compiles without PAM support.])], [], [with_pam=yes]) if test "$with_pam" = "yes"; then AC_VMW_DEFAULT_FLAGS([PAM]) AC_VMW_CHECK_LIB([pam], [PAM], [], [], [], [security/pam_appl.h], [pam_start], [PAM_CPPFLAGS="$PAM_CPPFLAGS -DUSE_PAM"], [AC_VMW_LIB_ERROR([PAM], [pam])]) fi AC_ARG_ENABLE([vgauth], [AS_HELP_STRING([--disable-vgauth], [do not build vgauth.])], [ enable_vgauth="$enableval" use_xmlsec1=no ], [ if test "$os" = "linux"; then enable_vgauth=yes use_xmlsec1=no else enable_vgauth=no use_xmlsec1=no fi ]) AC_ARG_ENABLE([xmlsec1], [AS_HELP_STRING([--enable-xmlsec1], [build vgauth with xmlsec1 instead of xml-security-c (off by default).])], [use_xmlsec1="$enableval"], [use_xmlsec1=no]) AC_ARG_ENABLE([xmlsecurity], [AS_HELP_STRING([--enable-xmlsecurity], [build vgauth with xml-security-c instead of xmlsec1 (on by default).])], [ if test "$enableval" = "yes"; then use_xmlsec1="no" else use_xmlsec1="yes" fi ], []) if test "$enable_vgauth" = "yes" ; then AC_ARG_ENABLE([caf], [AS_HELP_STRING([--disable-caf], [do not build CAF (Common Agent Framework).])], [], [enable_caf=no]) else enable_caf=no fi # # Check for openssl, xerces-c and xml-security-c # AC_ARG_WITH([ssl], [AS_HELP_STRING([--without-ssl], [compiles without openssl support (disables grabbitmqproxy, vgauth and CAF).])], [ enable_grabbitmqproxy=no enable_vgauth=no enable_caf=no ], [with_ssl=yes]) AC_ARG_WITH([xmlsecurity], [AS_HELP_STRING([--without-xmlsecurity], [compiles without xml-security-c support (disables vgauth).])], [enable_vgauth=no], [with_xmlsecurity=yes]) AC_ARG_WITH([xerces], [AS_HELP_STRING([--without-xerces], [compiles without xerces support (disables vgauth).])], [enable_vgauth=no], [with_xerces=yes]) AC_ARG_WITH([xmlsec1], [AS_HELP_STRING([--without-xmlsec1], [compiles without xmlsec1 support (disables vgauth).])], [enable_vgauth=no], [with_xmlsec1=yes]) AC_ARG_WITH([xml2], [AS_HELP_STRING([--without-xml2], [compiles without xml2 support (disables vgauth).])], [enable_vgauth=no], [with_xml2=yes]) # Make sure we are building with openssl 1.0.1 and above so that # we use only TLSv1_2. if test "$enable_vgauth" = "yes" -o "$enable_grabbitmqproxy" = "yes"; then AC_VMW_DEFAULT_FLAGS([SSL]) AC_VMW_CHECK_LIB([ssl], [SSL], [openssl], [], [1.0.1], [], [BIO_new_file], [], [AC_VMW_LIB_ERROR([SSL], [ssl])]) fi if test "$enable_vgauth" = "yes"; then CPPFLAGS="$CPPFLAGS -DUSE_VGAUTH" if test "$use_xmlsec1" = "yes"; then AC_VMW_DEFAULT_FLAGS([XML2]) AC_VMW_CHECK_LIB([xml2], [XML2], [], [], [], [], [], [], [AC_VMW_LIB_ERROR([XML2], [xml2])]) # Multiple distros built xmlsec1 with -DXMLSEC_NO_SIZE_T but # their xmlssec1-config --cflags doesn't properly report it, # so force it on. AC_VMW_DEFAULT_FLAGS([XMLSEC1]) AC_VMW_CHECK_LIB([xmlsec1], [XMLSEC1], [], [xmlsec1-config], [], [xmlsec/xmlsec.h], [xmlSecCheckVersion], [XMLSEC1_CPPFLAGS="$XMLSEC1_CPPFLAGS -DXMLSEC_NO_SIZE_T"], [AC_VMW_LIB_ERROR([XMLSEC1], [xmlsec1])]) else AC_VMW_DEFAULT_FLAGS([XERCES]) AC_VMW_CHECK_LIB([xerces-c], [XERCES], [], [], [], [], [], [], [AC_VMW_LIB_ERROR([XERCES], [xerces])]) AC_VMW_DEFAULT_FLAGS([XMLSECURITY]) AC_VMW_CHECK_LIB([xml-security-c], [XMLSECURITY], [], [], [], [], [], [], [AC_VMW_LIB_ERROR([XMLSECURITY], [xmlsecurity])]) fi else enable_caf=no fi # # Check for CUnit and disable test code if not available. # if test "$enable_tests" = "auto" -o "$enable_tests" = "yes"; then AC_VMW_DEFAULT_FLAGS([CUNIT]) AC_VMW_CHECK_LIB([cunit], [CUNIT], [], [], [], [CUnit/CUnit.h], [CU_initialize_registry], [have_cunit=yes], [have_cunit=no]) if test "$have_cunit" = "no"; then if test "$enable_tests" = "yes"; then AC_VMW_LIB_ERROR([CUNIT], [cunit]) else AC_MSG_WARN([CUnit not found, tests won't be compiled.]) fi fi fi # If the user explicitly disables X11, then don't try to detect the X-related libraries if test "$have_x" = "disabled"; then enable_multimon="no" elif test "$have_x" != "yes"; then AC_MSG_ERROR( [The X11 libraries were not found. Please configure without X11 (using --without-x), or install the libX11 devel package(s).]) else CPPFLAGS="$CPPFLAGS $X_CFLAGS" COMMON_XLIBS="$X_PRE_LIBS $X_LIBS -lX11 $X_EXTRA_LIBS" AC_CHECK_LIB( [Xext], [XeviQueryVersion], [COMMON_XLIBS="-lXext $COMMON_XLIBS"], [AC_MSG_ERROR( [libXext not found. Please configure without X11 (using --without-x), or install the libXext devel package(s).])], [$COMMON_XLIBS]) AC_CHECK_HEADER( [X11/extensions/extutil.h], [], [AC_MSG_ERROR( [X11/extensions/extutil.h header not found - you are probably on Solaris 10 or older. Please copy that header file onto your system manually, or configure without X11 (using --without-x).])], [#include #include ]) if test "$enable_multimon" != "no"; then AC_CHECK_LIB( [Xinerama], [XineramaQueryVersion], [COMMON_XLIBS="-lXinerama $COMMON_XLIBS"], [AC_MSG_ERROR( [libXinerama not found. Please configure without multimon (using --disable-multimon), configure without X11 (using --without-x), or install the libXinerama devel package(s).])], [$COMMON_XLIBS]) fi AC_CHECK_LIB( [Xi], [XOpenDevice], [COMMON_XLIBS="-lXi $COMMON_XLIBS"], [AC_MSG_ERROR( [libXi not found. Please configure without X11 (using --without-x), or install the libXi devel package(s).])], [$COMMON_XLIBS]) AC_CHECK_LIB( [Xrender], [XRenderQueryVersion], [COMMON_XLIBS="-lXrender $COMMON_XLIBS"], [AC_MSG_ERROR( [libXrender not found. Please configure without X11 (using --without-x), or install the libXrender devel package(s).])], [$COMMON_XLIBS]) AC_CHECK_LIB( [Xrandr], [XRRQueryVersion], [COMMON_XLIBS="-lXrandr $COMMON_XLIBS"], [AC_MSG_ERROR( [libXrandr not found. Please configure without X11 (using --without-x) or install the libXrandr devel package(s).])], [$COMMON_XLIBS]) AC_CHECK_LIB( [Xtst], [XTestQueryExtension], [COMMON_XLIBS="-lXtst $COMMON_XLIBS"], [AC_MSG_ERROR( [libXtst not found. Please configure without X11 (using --without-x) or install the libXtst devel package(s).])], [$COMMON_XLIBS]) AC_CHECK_LIB( [SM], [SmcOpenConnection], [XSM_LIBS="-lSM -lICE" && have_xsm_lib="yes"], [] [-lICE]) AC_CHECK_HEADERS([X11/SM/SMlib.h X11/ICE/ICElib.h], [have_xsm_header="yes"], [], []) if test "$have_xsm_lib" = "yes" -a "$have_xsm_header" = "yes"; then have_xsm="yes" fi AC_CHECK_LIB( [Xcomposite], [XCompositeQueryExtension], [XCOMPOSITE_LIBS="-lXcomposite"], [have_xcomposite="no"] []) AC_CHECK_HEADERS([X11/extensions/Xcomposite.h], [], [have_xcomposite="no"], []) if test "$have_xcomposite" != "no"; then have_xcomposite="yes" fi AC_VMW_CHECK_LIB([gdk_pixbuf_xlib-2.0], [GDK_PIXBUF_XLIB2], [gdk-pixbuf-xlib-2.0], [], [], [gdk-pixbuf-xlib/gdk-pixbuf-xlib.h], [], [], [AC_MSG_ERROR([gdk-pixbuf-xlib-2.0 not found. Please configure without X11 (using --without-x) or install the gdk-pixbuf-xlib-2.0 devel package.])]) # Check whether we have gtk+ 3.0. if test "$with_gtk3" != "no"; then # gdk_display_get_default_group (added in gtk+ 2.4.0) is function currently # needed by vmware-user. AC_VMW_CHECK_LIB([gtk-3], [GTK], [gtk+-3.0], [], [3.0.0], [gtk/gtk.h], [gdk_display_get_default_group], [GTK_CPPFLAGS="$GTK_CPPFLAGS -DGTK3"], [AC_MSG_ERROR([Gtk+ 3.0 library not found or too old. Please configure without Gtk+ support (using --without-gtk3) or install the Gtk+ 3.0 devel package.])]) # Check whether we have gtk+ 2.0. elif test "$with_gtk2" != "no"; then AC_VMW_CHECK_LIB([gtk-x11-2.0], [GTK], [gtk+-2.0], [], [2.4.0], [gtk/gtk.h], [gdk_display_get_default_group], [GTK_CPPFLAGS="$GTK_CPPFLAGS -DGTK2"], [AC_MSG_ERROR([Gtk+ 2.0 library not found or too old. Please configure without Gtk+ support (using --without-gtk2) or install the Gtk+ 2.0 devel package.])]) fi # # Check for gtkmm 2.4.0 or greater. # if test "$with_gtkmm" != "no" -o "$with_gtkmm3" != "no"; then if test "$with_gtkmm3" != "no"; then AC_VMW_CHECK_LIBXX([gtkmm-3.0], [GTKMM], [gtkmm-3.0], [], [3.0.0], [], [], [GTKMM_CPPFLAGS="$GTKMM_CPPFLAGS -DHAVE_GTKMM"], [AC_MSG_ERROR([gtkmm3 library not found. Please install the libgtkmm devel package(s), or re-configure using --without-gtkmm3.])]) elif test "$with_gtkmm" != "no"; then CUSTOM_GTKMM_CPPFLAGS="$CUSTOM_GTKMM_CPPFLAGS $GTK_CPPFLAGS" AC_VMW_CHECK_LIBXX([gtkmm-2.4], [GTKMM], [gtkmm-2.4], [], [2.4.0], [gtkmm.h], [], [GTKMM_CPPFLAGS="$GTKMM_CPPFLAGS -DHAVE_GTKMM"], [AC_MSG_ERROR([gtkmm library not found. Please install the libgtkmm devel package(s), or re-configure using --without-gtkmm.])]) fi # # libsigc++-2.0 >= 2.5.1 requires C++11 support # # Calling AC_VMW_CHECK_LIBXX would duplicate the sigc++ # flags we would have already got as part of gtkmm call # above. This is OK because we are not seeing any issues # because of this and calling AC_VMW_CHECK_LIBXX function # provides other benefits like picking custom flags. # # AC_VMW_CHECK_LIBXX sets CPPFLAGS and LIBS variables only, # so we have to use SIGCXX_CPPFLAGS instead of SIGCXX_CXXFLAGS. # AC_VMW_CHECK_LIBXX([sigc++-2.0], [SIGCXX], [sigc++-2.0], [], [2.5.1], [sigc++.h], [], [SIGCXX_CPPFLAGS="$SIGCXX_CPPFLAGS -std=c++11"], [SIGCXX_CPPFLAGS="$SIGCXX_CPPFLAGS"]) fi fi # End of checks for X libraries AC_CHECK_LIB( [crypt], [crypt], [HAVE_CRYPT="yes"], [AC_MSG_ERROR( [libcrypt not found. Please install the libc/libcrypt devel package(s).])]) AC_CHECK_FUNCS( dlopen, , [AC_CHECK_LIB( dl, dlopen, [VIX_LIBADD="$VIX_LIBADD -ldl" LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -ldl" VGAUTH_LIBADD="$VGAUTH_LIBADD -ldl" RESOLUTIONSET_LIBADD="$RESOLUTIONSET_LIBADD -ldl" ], [AC_MSG_ERROR( [dlopen was not found, but is required for open-vm-tools to function properly. Please contact your OS vendor.])])]) AC_CHECK_FUNCS([ecvt]) AC_CHECK_FUNCS([fcvt]) AC_CHECK_FUNC([mkdtemp], [have_mkdtemp=yes]) if test "$os" = "freebsd" -a "$osVersion" -ge 600000; then AC_CHECK_LIB( [thr], [pthread_mutex_init], [THREAD_LIB=-lthr], [AC_MSG_ERROR( [Unable to locate required threading library libthr.])]) else AC_CHECK_LIB( [pthread], [pthread_mutex_init], [THREAD_LIB=-lpthread], [AC_MSG_ERROR( [libpthread not found. Please install the libc/libpthread devel package(s).])]) fi # PAM prefix AC_ARG_WITH([pam-prefix], [AS_HELP_STRING([--with-pam-prefix], [specifies where pam files go. Default is $(sysconfdir)])], [PAM_PREFIX="$withval"], [if test "$os" = "freebsd" ; then PAM_PREFIX='$(sysconfdir)'; else PAM_PREFIX='/etc'; fi]) AC_ARG_WITH([dnet], [AS_HELP_STRING([--without-dnet], [compiles without libdnet (disables support for nicinfo)])], [], [with_dnet=yes]) have_dnet="no" if test "$with_dnet" = "yes"; then # On Debian, dnet is installed via the libdumbnet package. We need to # detect this so that our source files include dumbnet.h instead of # dnet.h, which is part of a different package altogether. AC_VMW_CHECK_LIB([dumbnet], [DNET], [], [dumbnet-config], [], [dumbnet.h], [intf_open], [have_dnet="yes"; AC_DEFINE([DNET_IS_DUMBNET], 1, [Define to 1 if substituting libdumbnet for libdnet in Debian.])], []) if test $have_dnet = "no"; then AC_VMW_CHECK_LIB([dnet], [DNET], [], [dnet-config], [], [dnet.h], [intf_open], [have_dnet="yes"], []) fi if test $have_dnet = "no"; then AC_MSG_ERROR( [dnet-config was not found on your PATH. Please configure without dnet (using --without-dnet) or install dnet - http://libdnet.sourceforge.net]) fi fi if test "$with_dnet" != "yes"; then AC_DEFINE([NO_DNET], 1, [Define to 1 if building without libdnet.]) fi AC_ARG_WITH([icu], [AS_HELP_STRING([--without-icu], [disables support for ICU])], [], [with_icu=yes]) if test "$have_x" = "yes" -o "$with_icu" = "yes"; then AC_CHECK_TOOL([have_cxx], [$CXX], [no]) if test "$have_cxx" = "no"; then AC_MSG_ERROR([C++ compiler not found. Make sure you have a C++ compiler installed or configure without X11 (using --without-x) and without ICU (using --without-icu).]) fi fi if test "$with_icu" = "yes"; then AC_VMW_CHECK_LIBXX([icuuc], [ICU], [], [icu-config], [], [unicode/utf.h], [], [ICU_CPPFLAGS="$ICU_CPPFLAGS -DUSE_ICU"], [AC_MSG_ERROR([ICU library not found. Please configure without ICU (using --without-icu) or install ICU - http://www.icu-project.org])]) # Check whether we have ICU >= 3.8. AC_LANG_PUSH([C++]) AC_MSG_CHECKING([for ucasemap_utf8ToTitle in ICU]) ORIGINAL_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$CPPFLAGS $ICU_CPPFLAGS" AC_TRY_COMPILE([#include ], [ (void) &ucasemap_utf8ToTitle; return 0; ], [ ICU_CPPFLAGS="$ICU_CPPFLAGS -DHAVE_ICU_38" AC_MSG_RESULT([yes]) ], [AC_MSG_RESULT([no])]) CPPFLAGS="$ORIGINAL_CPPFLAGS" AC_LANG_POP([C++]) # Easier to give all modules the ICU defines/includes... CPPFLAGS="$CPPFLAGS $ICU_CPPFLAGS" else CPPFLAGS="$CPPFLAGS -DNO_ICU" fi if test "$enable_caf" = "yes"; then AC_VMW_CHECK_LIBXX([log4cpp], [LOG4CPP], [], [log4cpp-config], [], [Appender.hh], [], [have_log4cpp="yes"], [AC_VMW_LIB_ERROR([LOG4CPP], [log4cpp])]) AC_VMW_CHECK_LIB([rabbitmq], [LIBRABBITMQ], [librabbitmq], [], [0.8.0], [amqp_tcp_socket.h], [], [have_librabbitmq="yes"], [AC_VMW_LIB_ERROR([LIBRABBITMQ], [librabbitmq])]) # # CAF requires glib 2.34 or greater. # AC_VMW_CHECK_LIB([glib-2.0], [GLIB2], [glib-2.0], [], [2.34.0], [glib.h], [g_key_file_new], [], [AC_MSG_ERROR([glib2 >= 2.34.0 is required.])]) AC_VMW_CHECK_LIB([gthread-2.0], [GTHREAD], [gthread-2.0], [], [2.34.0], [], [], [], [AC_MSG_ERROR([glib >= 2.34.0 is required.])]) fi AC_PATH_PROG( [RPCGEN], [rpcgen], [ AC_MSG_ERROR([rpcgen not found. Please install the libc devel package.]) ]) ### ### Headers ### AC_CHECK_HEADERS([crypt.h]) AC_CHECK_HEADERS([inttypes.h]) AC_CHECK_HEADERS([stdint.h]) AC_CHECK_HEADERS([stdlib.h]) AC_CHECK_HEADERS([wchar.h]) AC_CHECK_HEADERS([sys/inttypes.h]) AC_CHECK_HEADERS([sys/io.h]) AC_CHECK_HEADERS([sys/param.h]) # Required to make the sys/user.h check work correctly on FreeBSD AC_CHECK_HEADERS([sys/sysinfo.h]) AC_CHECK_HEADERS([sys/types.h]) AC_CHECK_HEADERS([sys/user.h], [], [], [ #ifdef HAVE_SYS_PARAM_H # include #endif ]) AC_CHECK_HEADERS([sys/vfs.h]) AC_CHECK_HEADERS([syslimits.h]) AC_CHECK_HEADERS([unwind.h]) AC_CHECK_HEADER( [wchar.h], [HAVE_WCHAR_H="yes"], [HAVE_WCHAR_H="no"]) if test "$os" = "linux"; then # Make sure kernel-headers package is installed. AC_CHECK_HEADER( [linux/unistd.h], [], [AC_MSG_ERROR(linux/unistd.h is not found. Please install kernel-headers/linux-userspace-headers/linux-libc-dev package.)]) fi if test "$enable_multimon" != "no"; then AC_CHECK_HEADER( [X11/extensions/panoramiXproto.h], [], [AC_MSG_ERROR( [panoramiXproto.h not found. Please configure without multimon (using --disable-multimon) or install the libXinerama devel package(s).])], [#include #include ]) fi ### ### Typdefs, structs, and compiler quarks. ### AC_HEADER_STDBOOL AC_C_CONST AC_TYPE_UID_T AC_C_INLINE AC_TYPE_MODE_T AC_TYPE_OFF_T AC_TYPE_PID_T AC_TYPE_SIZE_T AC_CHECK_MEMBERS([struct stat.st_rdev]) AC_HEADER_TIME AC_STRUCT_TM AC_C_VOLATILE ### ### Specific features and OS/arch flags / actions ### ### General flags / actions CFLAGS="$CFLAGS -Wall" CFLAGS="$CFLAGS -Werror" # -Wno-unknown-pragmas is due to gcc not understanding '#pragma ident' # in Xlib.h on OpenSolaris. # Glib2 keep changing mutex APIs so we also need to disable 'deprecated' # warnings for now (-Wno-deprecated-declarations). for TEST_CFLAG in -Wno-pointer-sign -Wno-unused-value -fno-strict-aliasing \ -Wno-unknown-pragmas -Wno-uninitialized -Wno-deprecated-declarations \ -Wno-unused-const-variable; do AC_MSG_CHECKING([for GCC flag $TEST_CFLAG]) ORIGINAL_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $TEST_CFLAG" NEW_CFLAG="" AC_TRY_COMPILE( [], [ return 0; ], [NEW_CFLAG=" $TEST_CFLAG" AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no)]) CFLAGS="$ORIGINAL_CFLAGS$NEW_CFLAG" done CPPFLAGS="$CPPFLAGS -DVMX86_TOOLS" CPPFLAGS="$CPPFLAGS" # -fvisibility is used by "core service" plugins, but not required. ORIGINAL_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -fvisibility=hidden" AC_MSG_CHECKING([for GCC flag -fvisibility]) AC_TRY_COMPILE([], [return 0;], [PLUGIN_CPPFLAGS="-fvisibility=hidden -DGCC_EXPLICIT_EXPORT"; AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no)]) CFLAGS="$ORIGINAL_CFLAGS" # Detect "unused-but-set-variable" gcc warning and disable it. ORIGINAL_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -Wno-unused-but-set-variable" AC_MSG_CHECKING([for GCC flag -Wno-unused-but-set-variable]) AC_TRY_COMPILE([], [return 0;], [ORIGINAL_CFLAGS="$ORIGINAL_CFLAGS -Wno-unused-but-set-variable"; AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no)]) CFLAGS="$ORIGINAL_CFLAGS" BUILDDIR="`pwd`" INCLUDE_DIR="`cd $srcdir; pwd`/lib/include" BLD_INCLUDE_DIR="$BUILDDIR/lib/include" CPPFLAGS="-I$INCLUDE_DIR -I$BLD_INCLUDE_DIR $CPPFLAGS" ### ### Documentation. ### if test "$enable_docs" = "yes"; then AC_CHECK_PROG([have_doxygen], [doxygen], [yes], [no]) if test "$have_doxygen" = "no"; then AC_MSG_WARN([doxygen not found; API documentation will not be generated.]) else AC_PATH_PROG([DOT], [dot], []) if test "$DOT" = ""; then HAVE_DOT=NO else DOT=`dirname $DOT` HAVE_DOT=YES fi AC_SUBST([DOT]) AC_SUBST([HAVE_DOT]) AC_PATH_PROG([MSCGEN], [mscgen], [no]) if test "$MSCGEN" != "no"; then MSCGEN_DIR="`dirname $MSCGEN`" else MSCGEN_DIR= fi AC_SUBST([MSCGEN_DIR]) fi fi ### ### OS/arch-specific flags / actions ### MODULES="" MODULES_OS="$os" TARGET_OS="$os" MODULES_DIR="" buildHgfsmounter=no if test "$os" = "linux"; then MODULES_DIR="$LINUXDIR/kernel/" CPPFLAGS="$CPPFLAGS -D_FILE_OFFSET_BITS=64" CPPFLAGS="$CPPFLAGS -D_LARGEFILE64_SOURCE" CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=500" CPPFLAGS="$CPPFLAGS -D_BSD_SOURCE" CPPFLAGS="$CPPFLAGS -D_SVID_SOURCE" CPPFLAGS="$CPPFLAGS -D_DEFAULT_SOURCE" LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -lrt" # vmxnet is not supported for kernels 3.3.0 and newer if test "$osVersion" -lt 303000; then MODULES="$MODULES vmxnet" fi # See if we need vmhgfs module. Starting with 4.0.0 we use FUSE if test "$osVersion" -lt 400000; then MODULES="$MODULES vmhgfs" fi # See if we need vmci and vsock modules. Starting with 3.9 they made # their way into mainline kernel. if test "$osVersion" -lt 309000; then MODULES="$MODULES vmci vsock" fi if test "$osVersion" -lt 300000; then MODULES="$MODULES vmblock vmsync" fi buildHgfsmounter=yes if test "x$enable_resolutionkms" != "xno"; then PKG_CHECK_MODULES( [LIBUDEV], libdrm libudev, [LIBUDEV_CFLAGS="$LIBUDEV_CFLAGS -DHAVE_LIBUDEV"], [AC_MSG_WARN( [Missing libdrm or libudev. The resolutionKMS plugin will search for them at run-time.])]) enable_resolutionkms="yes" fi fi if test "$os" = "freebsd" || test "$os" = "kfreebsd-gnu"; then LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -lkvm" MODULES_DIR="/boot/modules" if test "$osVersion" -ge 302000; then MODULES="$MODULES vmmemctl" fi if test "$osVersion" -ge 409000; then MODULES="$MODULES vmxnet" fi if test "$osVersion" -ge 600000; then MODULES="$MODULES vmblock" fi if test "$with_kernel_modules" = "yes"; then echo "****************************************************************" echo " You are building FreeBSD kernel modules. Make sure you use " echo " 'make' to build open-vm-tools, and not GNU make ('gmake'). " echo "****************************************************************" fi fi if test "$os" = "solaris"; then LIB_IMPERSONATE_CPPFLAGS="$LIB_IMPERSONATE_CPPFLAGS -D_POSIX_PTHREAD_SEMANTICS" LIB_USER_CPPFLAGS="$LIB_USER_CPPFLAGS -D_POSIX_PTHREAD_SEMANTICS" LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -lsocket" LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -lnsl" LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -lresolv" LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -lrpcsvc" LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -lrt" # Setup defines to identify the OS version. if test "$osVersion" -eq 509000; then CPPFLAGS="$CPPFLAGS -DSOL9" fi if test "$osVersion" -eq 510000; then CPPFLAGS="$CPPFLAGS -DSOL10" fi if test "$osVersion" -eq 511000; then CPPFLAGS="$CPPFLAGS -DSOL11" fi MODULES="$MODULES vmxnet vmmemctl" # HGFS and vmblock need Solaris 10 at least. if test "$osVersion" -ge 510000; then MODULES="$MODULES vmhgfs vmblock" fi # vmxnet3 is built on Solaris 10 / 11 only if GLDv3 is installed. if test "$osVersion" -gt 510000; then AC_CHECK_HEADER( [sys/mac.h], [MODULES="$MODULES vmxnet3"], [AC_MSG_WARN([GLDv3 (sys/mac.h) is not installed, vmxnet3 will not be compiled.])]) fi if test "$with_kernel_modules" = "yes"; then echo "****************************************************************" echo " You are building Solaris kernel modules. Make sure you use " echo " GNU make to build open-vm-tools. " echo "****************************************************************" fi fi if test "$os" = "linux"; then have_udev="yes" AC_ARG_WITH([udev-rules-dir], [AS_HELP_STRING([--with-udev-rules-dir=DIR], [where to install udev rules])], [UDEVRULESDIR="$withval"], [ UDEVRULESDIR="/lib/udev/rules.d" if test $HAVE_PKG_CONFIG = "yes"; then udevdir=$(pkg-config udev --variable=udevdir) if test "x$udevdir" != "x"; then UDEVRULESDIR="$udevdir/rules.d" fi fi ]) else have_udev="no" UDEVRULESDIR="" fi if test "x$enable_resolutionkms" = "xauto"; then enable_resolutionkms="no" fi if test "x$enable_resolutionkms" = "xyes"; then CPPFLAGS="$CPPFLAGS -DENABLE_RESOLUTIONKMS" fi AM_CONDITIONAL(BUILD_HGFSMOUNTER, test "$buildHgfsmounter" = "yes") AM_CONDITIONAL(LINUX, test "$os" = "linux") AM_CONDITIONAL(SOLARIS, test "$os" = "solaris") AM_CONDITIONAL(FREEBSD, test "$os" = "freebsd" -o "$os" = "kfreebsd-gnu") AM_CONDITIONAL(FREEBSD_CUSTOM_SYSDIR, test \( "$os" = "freebsd" -o "$os" = "kfreebsd-gnu" \) -a -n "$SYSDIR") AM_CONDITIONAL(THIRTY_TWO_BIT_USERSPACE, test "$userSpaceBitness" = "32") AM_CONDITIONAL(HAVE_X11, test "$have_x" = "yes") AM_CONDITIONAL(HAVE_ICU, test "$with_icu" = "yes") AM_CONDITIONAL(WITH_KERNEL_MODULES, test "$with_kernel_modules" = "yes") AM_CONDITIONAL(HAVE_XSM, test "$have_xsm" = "yes") AM_CONDITIONAL(HAVE_XCOMPOSITE, test "$have_xcomposite" = "yes") AM_CONDITIONAL(ENABLE_TESTS, test "$have_cunit" = "yes") AM_CONDITIONAL(WITH_ROOT_PRIVILEGES, test "$with_root_privileges" = "yes") AM_CONDITIONAL(HAVE_DNET, test "$have_dnet" = "yes") AM_CONDITIONAL(HAVE_DOXYGEN, test "$have_doxygen" = "yes") AM_CONDITIONAL(HAVE_FUSE, test "$have_fuse" = "yes") AM_CONDITIONAL(HAVE_GNU_LD, test "$with_gnu_ld" = "yes") AM_CONDITIONAL(HAVE_GTKMM, test "$have_x" = "yes" -a \( "$with_gtkmm" = "yes" -o "$with_gtkmm3" = "yes" \) ) AM_CONDITIONAL(HAVE_PAM, test "$with_pam" = "yes") AM_CONDITIONAL(USE_SLASH_PROC, test "$os" = "linux") AM_CONDITIONAL(ENABLE_DEPLOYPKG, test "$enable_deploypkg" = "yes") AM_CONDITIONAL(ENABLE_GRABBITMQPROXY, test "$enable_grabbitmqproxy" = "yes") AM_CONDITIONAL(ENABLE_VGAUTH, test "$enable_vgauth" = "yes") AM_CONDITIONAL(USE_XMLSEC1, test "$use_xmlsec1" = "yes") AM_CONDITIONAL(ENABLE_CAF, test "$enable_caf" = "yes") AM_CONDITIONAL(HAVE_VSOCK, test "$os" = "linux") AM_CONDITIONAL(HAVE_MKDTEMP, test "$have_mkdtemp" = "yes") AM_CONDITIONAL(HAVE_UDEV, test "$have_udev" = "yes") AM_CONDITIONAL(ENABLE_RESOLUTIONKMS, test "x$enable_resolutionkms" = "xyes") AM_CONDITIONAL(VGAUTH_USE_CXX, test "$with_icu" = "yes" -o "$use_xmlsec1" != "yes") if test "$have_xsm" != "yes"; then AC_DEFINE([NO_XSM], 1, []) fi if test "$have_xcomposite" != "yes"; then AC_DEFINE([NO_XCOMPOSITE]) fi ### Feature-specific flags / actions # Combine where possible # If control reaches this point and multimon is still enabled, then we know # all of the tests for required components have passed and it's safe to allow # multimon. Otherwise, it should be disabled. if test "$enable_multimon" = "no"; then # XXX: For consistency, change this to ENABLE_MULTIMON. This will require # some additional code cleanup. AC_DEFINE([NO_MULTIMON], 1, [Define to 1 if building without multimon support.]) fi LIB_AUTH_CPPFLAGS="$LIB_AUTH_CPPFLAGS $PAM_CPPFLAGS" if test "$HAVE_CRYPT" = "yes"; then LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD -lcrypt" VIX_LIBADD="$VIX_LIBADD -lcrypt" fi LIBVMTOOLS_LIBADD="$LIBVMTOOLS_LIBADD $THREAD_LIB" VIX_LIBADD="$VIX_LIBADD $THREAD_LIB" ### Core Services definitions. HGFS_LIBS="$BUILDDIR/libhgfs/libhgfs.la" VMTOOLS_LIBS="$BUILDDIR/libvmtools/libvmtools.la $GLIB2_LIBS" VMTOOLS_CPPFLAGS="-DVMTOOLS_USE_GLIB $GLIB2_CPPFLAGS" PLUGIN_CPPFLAGS="$VMTOOLS_CPPFLAGS $PLUGIN_CPPFLAGS" PLUGIN_LDFLAGS="-Wl,-z,defs -Wl,-lc -shared -module -avoid-version" # In Solaris, the XDR-related functions are not in libc like in Linux and # FreeBSD, so binaries need to be linked to some extra libraries. XDR_LIBS= if test "$os" = "solaris"; then XDR_LIBS="-lnsl -lrpcsvc" fi # Installation directories for core services plugins. TEST_PLUGIN_INSTALLDIR=$datadir/open-vm-tools/tests COMMON_PLUGIN_INSTALLDIR=$libdir/open-vm-tools/plugins/common VMSVC_PLUGIN_INSTALLDIR=$libdir/open-vm-tools/plugins/vmsvc VMUSR_PLUGIN_INSTALLDIR=$libdir/open-vm-tools/plugins/vmusr # Installation directories for caf binary/so files #CAF_PME_BIN_DIR=${sbindir}/vmware-caf/pme/bin CAF_PME_BIN_DIR=${libdir}/open-vm-tools/vmware-caf/pme/bin CAF_PME_LIB_DIR=${libdir}/open-vm-tools/vmware-caf/pme/lib # Installation directories for caf subsys so files CAF_SUBSYS_DIR=${libdir}/open-vm-tools/vmware-caf/pme/lib CAF_SUBSYS_LDFLAGS="-Wl,-z,defs -Wl,-lc -shared -module -avoid-version" # General definitions INSTVMSG='$(SHELL) $(top_srcdir)/scripts/build/instvmsg.sh' RPCGEN_WRAPPER='$(SHELL) $(top_builddir)/scripts/build/rpcgen_wrapper.sh' ### General substs AC_SUBST([HGFS_LIBS]) AC_SUBST([TOOLS_VERSION]) AC_SUBST([TARGET_OS]) AC_SUBST([KERNEL_RELEASE]) AC_SUBST([LINUXINCLUDE]) AC_SUBST([MODULES_OS]) AC_SUBST([MODULES_DIR]) AC_SUBST([MODULES]) AC_SUBST([COMMON_XLIBS]) AC_SUBST([XSM_LIBS]) AC_SUBST([XCOMPOSITE_LIBS]) AC_SUBST([PAM_PREFIX]) AC_SUBST([PLUGIN_CPPFLAGS]) AC_SUBST([PLUGIN_LDFLAGS]) AC_SUBST([VMTOOLS_CPPFLAGS]) AC_SUBST([VMTOOLS_LIBS]) AC_SUBST([RPCGENFLAGS]) AC_SUBST([XDR_LIBS]) AC_SUBST([TEST_PLUGIN_INSTALLDIR]) AC_SUBST([COMMON_PLUGIN_INSTALLDIR]) AC_SUBST([VMSVC_PLUGIN_INSTALLDIR]) AC_SUBST([VMUSR_PLUGIN_INSTALLDIR]) AC_SUBST([CAF_SUBSYS_DIR]) AC_SUBST([CAF_SUBSYS_LDFLAGS]) AC_SUBST([CAF_PME_BIN_DIR]) AC_SUBST([CAF_PME_LIB_DIR]) if test "$os" = "freebsd" -a -n "$SYSDIR"; then # If SYSDIR is not defined, AC_SUBST expands to nothing, so we need something # inside this block. true AC_SUBST([SYSDIR]) fi AC_SUBST([INSTVMSG]) AC_SUBST([RPCGEN_WRAPPER]) ### Lib substs AC_SUBST([LIB_AUTH_CPPFLAGS]) AC_SUBST([LIB_IMPERSONATE_CPPFLAGS]) AC_SUBST([LIB_USER_CPPFLAGS]) AC_SUBST([LIBVMTOOLS_LIBADD]) AC_SUBST([RESOLUTIONSET_LIBADD]) ### Program substs AC_SUBST([VIX_LIBADD]) AC_SUBST([VGAUTH_LIBADD]) AC_SUBST([UDEVRULESDIR]) ### ### Create the Makefiles ### AC_CONFIG_FILES([ \ Makefile \ lib/Makefile \ lib/appUtil/Makefile \ lib/auth/Makefile \ lib/backdoor/Makefile \ lib/asyncsocket/Makefile \ lib/sslDirect/Makefile \ lib/pollGtk/Makefile \ lib/poll/Makefile \ lib/dataMap/Makefile \ lib/hashMap/Makefile \ lib/dict/Makefile \ lib/dynxdr/Makefile \ lib/err/Makefile \ lib/file/Makefile \ lib/foundryMsg/Makefile \ lib/glibUtils/Makefile \ lib/guestApp/Makefile \ lib/guestRpc/Makefile \ lib/hgfs/Makefile \ lib/hgfsBd/Makefile \ lib/hgfsHelper/Makefile \ lib/hgfsServer/Makefile \ lib/hgfsServerManagerGuest/Makefile \ lib/hgfsServerPolicyGuest/Makefile \ lib/hgfsUri/Makefile \ lib/impersonate/Makefile \ lib/lock/Makefile \ lib/message/Makefile \ lib/misc/Makefile \ lib/netUtil/Makefile \ lib/nicInfo/Makefile \ lib/panic/Makefile \ lib/panicDefault/Makefile \ lib/procMgr/Makefile \ lib/rpcChannel/Makefile \ lib/rpcIn/Makefile \ lib/rpcOut/Makefile \ lib/rpcVmx/Makefile \ lib/slashProc/Makefile \ lib/string/Makefile \ lib/stubs/Makefile \ lib/syncDriver/Makefile \ lib/system/Makefile \ lib/unicode/Makefile \ lib/user/Makefile \ lib/vmCheck/Makefile \ lib/vmSignal/Makefile \ lib/wiper/Makefile \ lib/xdg/Makefile \ services/Makefile \ services/vmtoolsd/Makefile \ services/plugins/Makefile \ services/plugins/desktopEvents/Makefile \ services/plugins/dndcp/Makefile \ services/plugins/grabbitmqProxy/Makefile \ services/plugins/guestInfo/Makefile \ services/plugins/hgfsServer/Makefile \ services/plugins/powerOps/Makefile \ services/plugins/resolutionSet/Makefile \ services/plugins/resolutionKMS/Makefile \ services/plugins/timeSync/Makefile \ services/plugins/vix/Makefile \ services/plugins/vmbackup/Makefile \ services/plugins/deployPkg/Makefile \ vmware-user-suid-wrapper/Makefile \ toolbox/Makefile \ hgfsclient/Makefile \ hgfsmounter/Makefile \ checkvm/Makefile \ rpctool/Makefile \ guestproxycerttool/Makefile \ vgauth/Makefile \ vgauth/lib/Makefile \ namespacetool/Makefile \ vgauth/cli/Makefile \ vgauth/test/Makefile \ vgauth/service/Makefile \ libguestlib/Makefile \ libguestlib/vmguestlib.pc \ libDeployPkg/Makefile \ libDeployPkg/libDeployPkg.pc \ libhgfs/Makefile \ libvmtools/Makefile \ common-agent/Cpp/Framework/Makefile \ common-agent/Cpp/Communication/Makefile \ common-agent/Cpp/InternalProviders/Makefile \ common-agent/Cpp/ManagementAgent/Makefile \ common-agent/Cpp/ProviderFx/Makefile \ common-agent/input/Makefile \ common-agent/input/invokers/Makefile \ common-agent/input/providerReg/Makefile \ common-agent/etc/Makefile \ common-agent/etc/config/Makefile \ common-agent/etc/scripts/Makefile \ common-agent/etc/install/Makefile \ xferlogs/Makefile \ modules/Makefile \ vmblock-fuse/Makefile \ vmhgfs-fuse/Makefile \ vmblockmounter/Makefile \ tests/Makefile \ tests/vmrpcdbg/Makefile \ tests/testDebug/Makefile \ tests/testPlugin/Makefile \ tests/testVmblock/Makefile \ docs/Makefile \ docs/api/Makefile \ scripts/Makefile \ scripts/build/rpcgen_wrapper.sh \ udev/Makefile \ ]) ### ### Output ### AC_OUTPUT open-vm-tools-stable-10.2.0/open-vm-tools/docs/000077500000000000000000000000001321503522500212265ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/docs/Makefile.am000066400000000000000000000016561321503522500232720ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2009-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ SUBDIRS = if HAVE_DOXYGEN SUBDIRS += api endif open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/000077500000000000000000000000001321503522500217775ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/Makefile.am000066400000000000000000000053561321503522500240440ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2009-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ DOXYGEN_INPUT = DOXYGEN_INPUT += $(top_srcdir)/docs/api DOXYGEN_INPUT += $(top_srcdir)/docs/api/services DOXYGEN_INPUT += $(top_srcdir)/lib/include/vmware/tools DOXYGEN_INPUT += $(top_srcdir)/libvmtools DOXYGEN_INPUT += $(top_srcdir)/tests/vmrpcdbg DOXYGEN_CPP_PREDEFINED = DOXYGEN_CPP_PREDEFINED += G_LOCK_DEFINE_STATIC(x) DOXYGEN_CPP_PREDEFINED += G_LOG_DOMAIN= DOXYGEN_CPP_EXPAND = DOXYGEN_EXTRA_PATTERNS = DOXYGEN_EXTRA_PATTERNS += *.c DOXYGEN_EXTRA_PATTERNS += *.doxy DOXYGEN_EXTRA_PATTERNS += *.h DOXYGEN_EXTRA_PATTERNS += *.txt # This rule has no dependencies, so it's executed every time. Not optimal, # but generation of the docs is pretty quick, and having the right dependencies # here is very non-trivial. build/index.html: mkdir -p build sed \ -e 's,##{BUILD_DIR}##,$(top_builddir),' \ -e 's,##{BUILD_OUTPUT}##,build,' \ -e 's,##{CLIENT_ROOT}##,$(top_srcdir),' \ -e 's,##{CPP_EXPAND}##,$(DOXYGEN_CPP_EXPAND),' \ -e 's,##{CPP_PREDEFINED}##,$(DOXYGEN_CPP_PREDEFINED),' \ -e 's,##{DOT}##,@DOT@,' \ -e 's,##{FILE_PATTERNS}##,$(DOXYGEN_EXTRA_PATTERNS),' \ -e 's,##{HAVE_DOT}##,@HAVE_DOT@,' \ -e 's,##{INCLUDE_PATHS}##,$(top_srcdir)/lib/include,' \ -e 's,##{INPUT_PATHS}##,$(DOXYGEN_INPUT),' \ -e 's,##{MSCGEN_DIR}##,@MSCGEN_DIR@,' \ -e 's,##{PERL}##,,' \ -e 's,##{PROJECT_NAME}##,@PACKAGE_STRING@,' \ -e 's,##{PROJECT_VERSION}##,@TOOLS_VERSION@,' \ -e 's,##{WARNING_LOG}##,warnings.log,' \ $(top_srcdir)/docs/api/doxygen.conf > doxygen.parsed.conf doxygen doxygen.parsed.conf > /dev/null all-local: build/index.html install-data-local: mkdir -p $(DESTDIR)$(docdir)/api cp -r build/* $(DESTDIR)$(docdir)/api open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/doxygen.conf000066400000000000000000000111561321503522500243270ustar00rootroot00000000000000### ### profile-api.conf - "Public API" Doxygen profile. Includes only non-static ### functions and non-internal documentation. ### #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- PROJECT_NAME = "##{PROJECT_NAME}##" PROJECT_NUMBER = "##{PROJECT_VERSION}##" OUTPUT_DIRECTORY = ##{BUILD_OUTPUT}## TAB_SIZE = 3 OPTIMIZE_OUTPUT_FOR_C = YES FULL_PATH_NAMES = YES STRIP_FROM_PATH = ##{CLIENT_ROOT}## #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- EXTRACT_LOCAL_CLASSES = NO #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- WARNINGS = YES WARN_IF_UNDOCUMENTED = YES WARN_IF_DOC_ERROR = YES WARN_NO_PARAMDOC = YES WARN_FORMAT = "$file:$line: $text" WARN_LOGFILE = ##{WARNING_LOG}## #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- INPUT = ##{INPUT_PATHS}## FILE_PATTERNS = ##{FILE_PATTERNS}## #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- GENERATE_HTML = YES HTML_OUTPUT = html HTML_FILE_EXTENSION = .html #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- GENERATE_LATEX = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- GENERATE_RTF = NO #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- GENERATE_MAN = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- GENERATE_XML = NO #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- MACRO_EXPANSION = YES EXPAND_ONLY_PREDEF = YES INCLUDE_PATH = ##{INCLUDE_PATHS}## PREDEFINED = ##{CPP_PREDEFINED}## EXPAND_AS_DEFINED = ##{CPP_EXPAND}## #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- TAGFILES = GENERATE_TAGFILE = ALLEXTERNALS = NO EXTERNAL_GROUPS = YES PERL_PATH = ##{PERL}## #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- CLASS_DIAGRAMS = YES MSCGEN_PATH = ##{MSCGEN_DIR}## HIDE_UNDOC_RELATIONS = YES HAVE_DOT = ##{HAVE_DOT}## CLASS_GRAPH = YES COLLABORATION_GRAPH = YES GROUP_GRAPHS = YES UML_LOOK = NO TEMPLATE_RELATIONS = NO INCLUDE_GRAPH = YES INCLUDED_BY_GRAPH = YES CALL_GRAPH = NO CALLER_GRAPH = NO GRAPHICAL_HIERARCHY = YES DIRECTORY_GRAPH = YES DOT_IMAGE_FORMAT = png DOT_PATH = ##{DOT}## DOTFILE_DIRS = DOT_GRAPH_MAX_NODES = 50 MAX_DOT_GRAPH_DEPTH = 0 DOT_TRANSPARENT = NO DOT_MULTI_TARGETS = NO GENERATE_LEGEND = YES DOT_CLEANUP = NO #--------------------------------------------------------------------------- # Configuration::additions related to the search engine #--------------------------------------------------------------------------- SEARCHENGINE = NO open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/services/000077500000000000000000000000001321503522500236225ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/services/debug.txt000066400000000000000000000057611321503522500254620ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * *********************************************************/ /** @defgroup vmtools_debug Debugging Tools Plugins @brief Defines functions and interfaces for debugging Tools plugins. This module provides functions for writing "debug plugins" - plugins which provide functionality for driving the Tools Services when they're running in "debug mode". Debug plugins are dynamically loaded by providing specific command-line options to the Tools service process. @section vmtools_debug_how How debug plugins work Currently, there's only support for GuestRPC-based debug plugins. The debug library implements an RPC channel that can be driven by a debug plugin, according to information provided by the plugin at load time. The debug plugin can provide two types of information: - RPCs to be sent to the application: these are input to the application, and can be tied to a validation function to make sure the response from the application is correct. - Validation functions for "outgoing" RPCs: these are functions called in response to RPCs initiated by the applications; they can be mapped to specific RPC command strings, to make writing the plugin easier. For more details, check the RpcDebugPlugin data structure. Plugins that depend on events that are not only responses to RPC messages (such as timer-based outgoing RPCs) should make sure they tell the library that it should not stop running by incrementing its ref count (see RpcDebug_IncRef()). When the test is complete, the code can then call RpcDebug_DecRef() and, when the ref count reaches zero, the main application loop will be stopped. */ open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/services/guestrpc.txt000066400000000000000000000031111321503522500262130ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * *********************************************************/ /** @defgroup vmtools_guestrpc GuestRPC functions @brief Functions related to reading and writing data on a GuestRPC channel. */ open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/services/main.doxy000066400000000000000000000040011321503522500254460ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * *********************************************************/ /** @mainpage VMware Tools Core API The Tools Core API provides functionality for extending Tools by building plugins, and loading them as part of the existing Tools services or by creating new plugin containers. @section tc_main_plugins Basic Plugin Functionality - @ref vmtools_plugins - @ref vmtools_guestrpc - @ref vmtools_vmcf @section tc_main_utils Miscelaneous Utilities - @ref vmtools_utils - @ref vmtools_logging - @ref vmtools_threads - @ref vmtools_i18n @section tc_main_debug Debugging Support - @ref vmtools_debug */ open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/services/plugins.txt000066400000000000000000000041401321503522500260430ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * *********************************************************/ /** @defgroup vmtools_plugins VMware Tools Plugins @brief Defines the API used by the Tools Services for dynamically loading plugins. Plugins are dynamically loaded into the Tools service process, and may provide applications that hook into the functionality provided by the service, such as the glib main loop and the GuestRPC channel. Plugins that want to remain loaded by the service should always return registration data when their registration function (ToolsPluginOnLoad()) is called. The registration data, defined by the ToolsPluginData data structure, provides information about what events the plugin is interested in (for example, incoming RPCs). */ open-vm-tools-stable-10.2.0/open-vm-tools/docs/api/services/utils.txt000066400000000000000000000000001321503522500255110ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/000077500000000000000000000000001321503522500243035ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/COPYING000066400000000000000000000634711321503522500253510ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/Makefile.am000066400000000000000000000034251321503522500263430ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2014-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ bin_PROGRAMS = vmware-guestproxycerttool vmware_guestproxycerttool_LDADD = vmware_guestproxycerttool_LDADD += @SSL_LIBS@ vmware_guestproxycerttool_LDADD += -lcrypto vmware_guestproxycerttool_LDADD += @GLIB2_LIBS@ vmware_guestproxycerttool_CPPFLAGS = vmware_guestproxycerttool_CPPFLAGS += @SSL_CPPFLAGS@ vmware_guestproxycerttool_CPPFLAGS += @GLIB2_CPPFLAGS@ vmware_guestproxycerttool_SOURCES = vmware_guestproxycerttool_SOURCES += cert_key.c vmware_guestproxycerttool_SOURCES += cert_util.c vmware_guestproxycerttool_SOURCES += cert_tool.c if HAVE_ICU vmware_guestproxycerttool_LDADD += @ICU_LIBS@ vmware_guestproxycerttool_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXX) \ $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ else vmware_guestproxycerttool_LINK = $(LINK) endif open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/cert_key.c000066400000000000000000000370521321503522500262630ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * certKey.c -- * * Utilities to handle key and certificate generation. */ #include #include #include #include #include #include #include #include #include #include #include #include "cert_util.h" #include "cert_key.h" #define BSIZE 4096 /* *---------------------------------------------------------------------- * * GetSSLError -- * * Get the latest human readable error message from SSL library. * * Results: * Return the error message. Callers should free the returned * error message. * * Side effects: * None. * *---------------------------------------------------------------------- */ gchar * GetSSLError(gchar **errorStr) // OUT { unsigned long code; GString *str = g_string_new(NULL); gboolean first = TRUE; char buf[BSIZE]; while ((code = ERR_get_error()) != 0) { ERR_error_string_n(code, buf, sizeof buf); g_string_append_printf(str, "%s%s", first ? "" : ", ", buf); first = FALSE; } *errorStr = g_string_free(str, FALSE); return *errorStr; } /* *---------------------------------------------------------------------- * * CertKey_InitOpenSSLLib -- * * Initialize OpenSSL for key and certificate generation. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ void CertKey_InitOpenSSLLib(void) { ERR_load_crypto_strings(); OpenSSL_add_all_digests(); } /* *---------------------------------------------------------------------- * * CertKey_ComputeCertPemFileHash -- * * Compute the certificate subject name hash. * * Results: * Return the computed hash string. Callers should free the returned * string. * * Side effects: * None. * *---------------------------------------------------------------------- */ gchar * CertKey_ComputeCertPemFileHash(const gchar *certPemFile) // IN { FILE *file; gchar *hash = NULL; X509 *cert = NULL; gchar *err = NULL; file = g_fopen(certPemFile, "r"); if (!file) { Error("Failed to open %s: %s.\n", certPemFile, strerror(errno)); goto exit; } cert = PEM_read_X509(file, NULL, NULL, NULL); if (!cert) { Error("Error reading certificate file %s: %s.\n", certPemFile, GetSSLError(&err)); goto exit; } hash = g_strdup_printf("%08lx", X509_subject_name_hash(cert)); exit: if (file) { fclose(file); } X509_free(cert); g_free(err); return hash; } /* *---------------------------------------------------------------------- * * SetCertSerialNumber -- * * Set the certificate serial number. * * Results: * Return TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean SetCertSerialNumber(X509 *cert) // IN { BIGNUM *btmp = NULL; ASN1_INTEGER *sno; gboolean ret = FALSE; gchar *err = NULL; sno = ASN1_INTEGER_new(); if (!sno) { Error("Failed to allocate an ASN1 integer.\n"); goto exit; } btmp = BN_new(); if (!btmp) { Error("Failed to allocate a BIGNUM structure.\n"); goto exit; } if (!BN_rand(btmp, 64, 0, 0)) { Error("Failed to generate random number: %s.\n", GetSSLError(&err)); goto exit; } if (!BN_to_ASN1_INTEGER(btmp, sno)) { Error("Failed to convert from BIGNUM to ASN1_INTEGER: %s.\n", GetSSLError(&err)); goto exit; } if (!X509_set_serialNumber(cert, sno)) { Error("Failed to set the certificate serial number: %s.\n", GetSSLError(&err)); goto exit; } ret = TRUE; exit: BN_free(btmp); ASN1_INTEGER_free(sno); g_free(err); return ret; } /* *---------------------------------------------------------------------- * * LoadOpenSSLConf -- * * Loading the OpenSSL configuration file. * * Results: * Return the configuration structure if success, otherwise NULL. * * Side effects: * None. * *---------------------------------------------------------------------- */ static CONF * LoadOpenSSLConf(const gchar *fname) // IN { CONF *config; const char *mask; gboolean ret = FALSE; gchar *err = NULL; config = NCONF_new(NULL); if (!config) { Error("Failed to allocate the OpenSSL config.\n"); goto exit; } if (!NCONF_load(config, fname, NULL)) { Error("Failed to load the configuration file %s: %s.\n", fname, GetSSLError(&err)); goto exit; } OPENSSL_load_builtin_modules(); if (!CONF_modules_load(config, NULL, 0)) { Error("Error configuring OpenSSL modules: %s.\n", GetSSLError(&err)); goto exit; } mask = NCONF_get_string(config, "req", "string_mask"); if (mask) { ASN1_STRING_set_default_mask_asc(mask); } ret = TRUE; exit: if (!ret) { NCONF_free(config); config = NULL; } g_free(err); return config; } /* *---------------------------------------------------------------------- * * GenerateRSAKeyPair -- * * Interface to OpenSSL library to create RSA key pair. * * Results: * Return the generated RSA key structure if success, * otherwise NULL. * * Side effects: * None. * *---------------------------------------------------------------------- */ static RSA * GenerateRSAKeyPair(int bits) // IN { BIGNUM *bn; RSA *rsa = NULL; gchar *err = NULL; bn = BN_new(); if (!bn) { Error("Failed to allocate a BIGNUM.\n"); goto exit; } if (!BN_set_word(bn, RSA_F4)) { Error("Failed to assign a value to BIGNUM: %s.\n", GetSSLError(&err)); goto exit; } rsa = RSA_new(); if (!rsa) { Error("Failed to allocate a RSA structure.\n"); goto exit; } if (!RSA_generate_key_ex(rsa, bits, bn, NULL)) { Error("Error generating RSA key pair: %s.\n", GetSSLError(&err)); RSA_free(rsa); rsa = NULL; } exit: BN_free(bn); g_free(err); return rsa; } /* *---------------------------------------------------------------------- * * GenerateRSAPrivateKey -- * * Create the RSA private key structure. * * Results: * Return the generated RSA private key structure if success, * otherwise NULL. * * Side effects: * None. * *---------------------------------------------------------------------- */ static EVP_PKEY * GenerateRSAPrivateKey(int bits) // IN { RSA *rsa; EVP_PKEY *pkey = NULL; rsa = GenerateRSAKeyPair(bits); if (!rsa) { goto exit; } pkey = EVP_PKEY_new(); if (!pkey) { Error("Failed to allocate a private key structure.\n"); goto exit; } EVP_PKEY_assign_RSA(pkey, rsa); rsa = NULL; exit: RSA_free(rsa); return pkey; } /* *---------------------------------------------------------------------- * * ConfigX509CertReq -- * * Configure the X509 certificate request. * * Results: * Return TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean ConfigX509CertReq(X509_REQ *req, // OUT CONF *config) // IN { int idx; X509_NAME *subject; gboolean ret = FALSE; const char *dname; gchar *err = NULL; if (!X509_REQ_set_version(req, 0L)) { Error("Failed to set the certificate request version: %s.\n", GetSSLError(&err)); goto exit; } subject = X509_REQ_get_subject_name(req); if (!subject) { Error("Failed to get the certificate request subject name: %s.\n", GetSSLError(&err)); goto exit; } dname = NCONF_get_string(config, "req", "distinguished_name"); if (dname) { STACK_OF(CONF_VALUE) *dn_sk = NCONF_get_section(config, dname); if (!dn_sk) { Error("Failed to get section %s: %s.\n", dname, GetSSLError(&err)); goto exit; } for (idx = 0; idx < sk_CONF_VALUE_num(dn_sk); idx++) { CONF_VALUE *v = sk_CONF_VALUE_value(dn_sk, idx); if (!X509_NAME_add_entry_by_txt(subject, v->name, MBSTRING_ASC, v->value, -1, -1, 0)) { Error("Failed to set certificate request pair %s/%s: %s.\n", v->name, v->value, GetSSLError(&err)); goto exit; } } } ret = TRUE; exit: g_free(err); return ret; } /* *---------------------------------------------------------------------- * * GenerateX509CertReq -- * * Create X509 certificate request. * * Results: * Return the generated X509 request if success, otherwise NULL. * * Side effects: * None. * *---------------------------------------------------------------------- */ static X509_REQ * GenerateX509CertReq(EVP_PKEY **pkey, // OUT CONF *config, // IN int bits) // IN { X509_REQ *req = NULL; gboolean ret = FALSE; gchar *err = NULL; *pkey = GenerateRSAPrivateKey(bits); if (!*pkey) { goto exit; } req = X509_REQ_new(); if (!req) { Error("Failed to allocate a X509 certificate request.\n"); goto exit; } if (!ConfigX509CertReq(req, config)) { goto exit; } if (!X509_REQ_set_pubkey(req, *pkey)) { Error("Failed to set certificate request public key: %s.\n", GetSSLError(&err)); goto exit; } ret = TRUE; exit: if (!ret) { X509_REQ_free(req); req = NULL; } g_free(err); return req; } /* *---------------------------------------------------------------------- * * GenerateX509Cert -- * * Generate a X509 certificate. * * Results: * Return a X509 structure if success, otherwise NULL. * * Side effects: * None. * *---------------------------------------------------------------------- */ static X509 * GenerateX509Cert(X509_REQ *req, // IN CONF *config, // IN int days) // IN { X509 *cert; X509V3_CTX ctx; char *extensions; gboolean ret = FALSE; gchar *err = NULL; cert = X509_new(); if (!cert) { Error("Failed to allocate a X509 certificate: %s.\n", GetSSLError(&err)); goto exit; } if (!SetCertSerialNumber(cert)) { goto exit; } if (!X509_set_issuer_name(cert, X509_REQ_get_subject_name(req)) || !X509_gmtime_adj(X509_get_notBefore(cert), 0) || !X509_gmtime_adj(X509_get_notAfter(cert), (long)60*60*24*days) || !X509_set_subject_name(cert, X509_REQ_get_subject_name(req))) { Error("Failed to configure the X509 certificate: %s.\n", GetSSLError(&err)); goto exit; } X509V3_set_ctx(&ctx, cert, cert, NULL, NULL, 0); X509V3_set_nconf(&ctx, config); extensions = NCONF_get_string(config, "req", "x509_extensions"); if (extensions) { if (!X509_set_version(cert, 2)) { Error("Failed to set the certificate version: %s.\n", GetSSLError(&err)); goto exit; } if (!X509V3_EXT_add_nconf(config, &ctx, extensions, cert)) { Error("Error loading extension section %s: %s.\n", extensions, GetSSLError(&err)); goto exit; } } ret = TRUE; exit: if (!ret) { X509_free(cert); cert = NULL; } g_free(err); return cert; } #ifndef _WIN32 /* *---------------------------------------------------------------------- * * WritePemFile -- * * Output RSA private key and X509 certificate in PEM format. * * Results: * TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ gboolean WritePemFile(EVP_PKEY *pkey, // IN const gchar *keyFile, // IN X509 *cert, // IN const gchar *certFile) // IN { FILE *file; gboolean ret = FALSE; gchar *err = NULL; mode_t mode; mode = umask(066); file = g_fopen(keyFile, "w"); if (!file) { Error("Failed to open %s: %s.\n", keyFile, strerror(errno)); goto exit; } if (!PEM_write_PrivateKey(file, pkey, NULL, NULL, 0, NULL, NULL)) { Error("Failed to write the private key file %s: %s.\n", keyFile, GetSSLError(&err)); goto exit; } fclose(file); umask(022); file = g_fopen(certFile, "w"); if (!file) { Error("Failed to open %s: %s.\n", certFile, strerror(errno)); goto exit; } if (!PEM_write_X509(file, cert)) { Error("Failed to write the certificate file %s: %s.\n", certFile, GetSSLError(&err)); goto exit; } ret = TRUE; exit: if (file) { fclose(file); } g_free(err); umask(mode); return ret; } #endif /* *---------------------------------------------------------------------- * * CertKey_GenerateKeyCert -- * * Generate the server key and certificate files. * * Results: * TRUE if success, otherwise FALSE. When success, key and * certificate files are generated. * * Side effects: * None. * *---------------------------------------------------------------------- */ gboolean CertKey_GenerateKeyCert(int bits, // IN int days, // IN const gchar *confFile, // IN const gchar *keyFile, // IN const gchar *certFile) // IN { gboolean ret = FALSE; X509 *cert = NULL; X509_REQ *req = NULL; EVP_PKEY *pkey = NULL; CONF *config; gchar *err = NULL; config = LoadOpenSSLConf(confFile); if (!config) { goto exit; } req = GenerateX509CertReq(&pkey, config, bits); if (!req) { goto exit; } cert = GenerateX509Cert(req, config, days); if (!cert) { goto exit; } if (!X509_set_pubkey(cert, pkey)) { Error("Failed to set certificate public key: %s.\n", GetSSLError(&err)); goto exit; } if (!X509_sign(cert, pkey, EVP_sha256())) { Error("Failed to sign the X509 certificate: %s.\n", GetSSLError(&err)); goto exit; } /* * Write private key and certificate PEM files. */ if (WritePemFile(pkey, keyFile, cert, certFile)) { ret = TRUE; } exit: g_free(err); NCONF_free(config); EVP_PKEY_free(pkey); X509_REQ_free(req); X509_free(cert); return ret; } open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/cert_key.h000066400000000000000000000034371321503522500262700ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2014-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _CERT_KEY_H_ #define _CERT_KEY_H_ #include #include #include gchar * CertKey_ComputeCertPemFileHash(const gchar *certPemFile); // IN gboolean CertKey_GenerateKeyCert(int bits, // IN int days, // IN const gchar *confFile, // IN const gchar *keyFile, // IN const gchar *certFile); // IN void CertKey_InitOpenSSLLib(void); gboolean WritePemFile(EVP_PKEY *pkey, // IN const gchar *keyFile, // IN X509 *cert, // IN const gchar *certFile); // IN gchar * GetSSLError(gchar **errorStr); // OUT #ifdef _WIN32 gboolean CheckKeyFile(const gchar *keyFile); #endif #endif // #ifndef _CERT_KEY_H_ open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/cert_tool.c000066400000000000000000000425631321503522500264530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2014-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * cert_tool.c -- * * Utility to manage the certificates for 'rabbitmqproxy' * plugin in 'VMware Tools'. */ #include #include #include #include #ifndef _WIN32 #include #endif #include #include "cert_util.h" #include "cert_key.h" #include "cert_tool_version.h" #ifdef _WIN32 #include "common_win.h" #endif #include "vm_version.h" #include "embed_version.h" VM_EMBED_VERSION(GUESTPROXYCERTTOOL_VERSION_STRING); /* * The following variables are set up during the validation of system * environment. They are initialized only once and are not freed until * the program exits. */ static gboolean initialized = FALSE; static gchar *guestProxyDir; static gchar *guestProxyServerDir; static gchar *guestProxyTrustedDir; static gchar *guestProxySslConf; #define RSA_KEY_LENGTH 2048 #define CERT_EXPIRED_IN_DAYS (365 * 10) gboolean gIsLogEnabled = FALSE; /* *---------------------------------------------------------------------- * * PrintUsage -- * * Print command usage information. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void PrintUsage(const gchar *cmd) // IN { fprintf(stderr, "Guest Proxy Certificate Management Tool.\n"); fprintf(stderr, "Usage: %s [OPTION] [ARGUMENTS]\n\n", cmd); fprintf(stderr, "Options\n" " -h, --help Prints the usage information.\n\n" " -v, --verbose Prints additional log messages.\n\n" " -f, --force Forces to regenerate the new server key/cert\n" " when used with -g.\n\n" " -g, --generate_key_cert Generates the server key/cert if they don't\n" " exist. Use with -f to force the regeneration.\n\n" " -a, --add_trust_cert \n" " Adds the client cert to the trusted\n" " certificates directory.\n\n" " -r, --remove_trust_cert \n" " Removes the client cert from the trusted\n" " certificates directory.\n\n" " -d, --display_server_cert []\n" " Prints the server's certificate to the\n" " standard output. If the file path is\n" " specified, then the server's certificate\n" " is stored in the file.\n\n"); } static void InitProxyPaths(const gchar *toolDir) { guestProxyDir = g_build_filename(toolDir, "GuestProxyData", NULL); guestProxyServerDir = g_build_filename(guestProxyDir, "server", NULL); guestProxyTrustedDir = g_build_filename(guestProxyDir, "trusted", NULL); guestProxySslConf = g_build_filename(toolDir, "guestproxy-ssl.conf", NULL); } #ifndef _WIN32 /* *---------------------------------------------------------------------- * * CheckRootPriv -- * * Check if the effect user id is root. * * Results: * TRUE if it is, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ gboolean CheckRootPriv(void) { if (geteuid() != 0) { Error("Please re-run this program as the super user to execute " "this operation.\n"); return FALSE; } return TRUE; } #endif /* *---------------------------------------------------------------------- * * ValidateEnvironment -- * * Initialize command and directory paths, which are used to hold * key and certificate files, and find commands to operate on them. * * Results: * TRUE if successfully find all the paths. Otherwise FALSE. * * Side effects: * Path global variables are set accordingly and guest proxy data * directories are created on-demand. * *---------------------------------------------------------------------- */ static gboolean ValidateEnvironment(gboolean requireRootPriv) // IN { gboolean ret = FALSE; if (requireRootPriv && !CheckRootPriv()) { Error("Current user has insufficient privileges.\n"); goto exit; } if (!initialized) { CertKey_InitOpenSSLLib(); initialized = TRUE; } if (!g_file_test(guestProxySslConf, G_FILE_TEST_IS_REGULAR)) { Error("Couldn't find the GuestProxy Config file at '%s'.\n", guestProxySslConf); goto exit; } /* Create guest proxy data directories on-demand */ if (!g_file_test(guestProxyDir, G_FILE_TEST_IS_DIR)) { if (g_mkdir(guestProxyDir, 0755) < 0) { Error("Couldn't create the directory '%s'.\n", guestProxyDir); goto exit; } } if (!g_file_test(guestProxyServerDir, G_FILE_TEST_IS_DIR)) { if (g_mkdir(guestProxyServerDir, 0755) < 0) { Error("Couldn't create the directory '%s'.\n", guestProxyServerDir); goto exit; } } if (!g_file_test(guestProxyTrustedDir, G_FILE_TEST_IS_DIR)) { if (g_mkdir(guestProxyTrustedDir, 0700) < 0) { Error("Couldn't create the directory '%s'.\n", guestProxyTrustedDir); goto exit; } } ret = TRUE; exit: return ret; } /* *---------------------------------------------------------------------- * * AddTrustCert -- * * Add the supplied certificate file (clientCertPemFile) to the * trusted certificate directory. * * Results: * TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean AddTrustCert(const gchar *clientCertPemFile) // IN { gboolean ret = FALSE; int last, num; gchar *hash = NULL; gchar *path = NULL; if (!ValidateEnvironment(TRUE)) { goto exit; } if (!g_file_test(clientCertPemFile, G_FILE_TEST_IS_REGULAR)) { Error("No certificate file found at %s.\n", clientCertPemFile); goto exit; } hash = CertKey_ComputeCertPemFileHash(clientCertPemFile); if (!hash) { goto exit; } if (CertUtil_FindCert(clientCertPemFile, guestProxyTrustedDir, hash, &num, &last) && num >= 0) { Error("The specified certificate file already exists: %s.%d.\n", hash, num); goto exit; } path = CertUtil_CreateCertFileName(guestProxyTrustedDir, hash, last + 1); if (!CertUtil_CopyFile(clientCertPemFile, path)) { Error("Unable to add %s to the trusted certificate store.\n", clientCertPemFile); goto exit; } printf("Successfully added the %s to the trusted certificate store.\n", clientCertPemFile); ret = TRUE; exit: g_free(hash); g_free(path); return ret; } /* *---------------------------------------------------------------------- * * DisplayServerCert -- * * Display the server certificate file to console. If a file name * (serverCertPemFile) is supplied, write to that file instead. * * Results: * TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean DisplayServerCert(const gchar *serverCertPemFile) // IN { gboolean ret = FALSE; gchar *cert = NULL; FILE *file = NULL; GMappedFile *fmap = NULL; if (!ValidateEnvironment(FALSE)) { goto exit; } cert = g_build_filename(guestProxyServerDir, "cert.pem", NULL); if (!g_file_test(cert, G_FILE_TEST_IS_REGULAR)) { Error("Couldn't find the server certificate file: %s.\n", cert); goto exit; } if (serverCertPemFile && strlen(serverCertPemFile)) { printf("Copying the server certificate to %s.\n", serverCertPemFile); if (!CertUtil_CopyFile(cert, serverCertPemFile)) { Error("Failed to copy the certificate file to the file.\n"); goto exit; } printf("Successfully copied the server certificate.\n"); } else { fmap = g_mapped_file_new(cert, FALSE, NULL); if (fmap) { const gchar *content = g_mapped_file_get_contents(fmap); gsize length = g_mapped_file_get_length(fmap); if (fwrite(content, 1, length, stdout) < length) { Error("Failed to display %s: %s.\n", cert, strerror(errno)); goto exit; } } else { Error("Couldn't open the server certificate file.\n"); goto exit; } } ret = TRUE; exit: g_free(cert); if (file) { fclose(file); } if (fmap) { g_mapped_file_unref(fmap); } return ret; } /* *---------------------------------------------------------------------- * * CreateKeyCert -- * * Create the server key and certificate files. * * Results: * TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean CreateKeyCert(gboolean force) { gboolean ret = FALSE; gchar *cert = NULL; gchar *key = NULL; if (!ValidateEnvironment(TRUE)) { goto exit; } key = g_build_filename(guestProxyServerDir, "key.pem", NULL); cert = g_build_filename(guestProxyServerDir, "cert.pem", NULL); /* * If both server key and certificate files already exist and the * program is not asked to create them by force, print an warning * message about server key/cert files not regenerating. */ if (g_file_test(key, G_FILE_TEST_IS_REGULAR) && g_file_test(cert, G_FILE_TEST_IS_REGULAR) && !force) { printf("\nNOTE: both %s and \n %s already exist.\n" " They are not generated again. To regenerate " "them by force,\n use the \"%s -g -f\" command.\n\n", key, cert, g_get_prgname()); ret = TRUE; goto exit; } printf("Generating the key and certificate files.\n"); if (!CertKey_GenerateKeyCert(RSA_KEY_LENGTH, CERT_EXPIRED_IN_DAYS, guestProxySslConf, key, cert)) { goto exit; } ret = TRUE; printf("Successfully generated the key and certificate files.\n"); exit: g_free(key); g_free(cert); return ret; } /* *---------------------------------------------------------------------- * * RemoveTrustCert -- * * Remove the specified certificate from the trusted certificate * store. * * Results: * TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean RemoveTrustCert(const gchar *clientCertPemFile) { gboolean ret = FALSE; int last, num; gchar *hash = NULL; gchar *src = NULL; gchar *dst = NULL; if (!ValidateEnvironment(TRUE)) { goto exit; } if (!g_file_test(clientCertPemFile, G_FILE_TEST_IS_REGULAR)) { Error("No certificate file found at %s.\n", clientCertPemFile); goto exit; } hash = CertKey_ComputeCertPemFileHash(clientCertPemFile); if (!hash) { goto exit; } if (!CertUtil_FindCert(clientCertPemFile, guestProxyTrustedDir, hash, &num, &last) || num < 0) { Error("Couldn't find any certificate in the trusted directory.\n"); goto exit; } dst = CertUtil_CreateCertFileName(guestProxyTrustedDir, hash, num); if (last != num) { src = CertUtil_CreateCertFileName(guestProxyTrustedDir, hash, last); if (rename(src, dst) != 0) { Error("Failed to rename %s to %s with error: %s.", src, dst, strerror(errno)); goto exit; } } else { if (unlink(dst) != 0) { Error("Failed to remove %s with error: %s.", dst, strerror(errno)); goto exit; } } ret = TRUE; printf("Successfully removed the certificate.\n"); exit: g_free(hash); g_free(src); g_free(dst); return ret; } /* " -e, --erase_proxy_data Erases the trusted and server directories,\n" " and their contents including server key/cert.\n\n" */ /* *---------------------------------------------------------------------- * * EraseProxyData -- * * Delete the guest proxy data diectory and its contents. * * Results: * TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean EraseProxyData(void) { gboolean ret = FALSE; if (!CheckRootPriv()) { goto exit; } if (g_file_test(guestProxyDir, G_FILE_TEST_IS_DIR)) { if (!CertUtil_RemoveDir(guestProxyDir)) { Error("Fail to remove the directory '%s'.\n", guestProxyDir); goto exit; } } ret = TRUE; exit: return ret; } /* * Aggregation of command options. */ static struct _options { gchar *addCert; gchar *deleteCert; gchar *outputCert; gboolean displayCert; gboolean generateCert; gboolean usage; gboolean verbose; gboolean force; gboolean erase; } options = { NULL, NULL, NULL, FALSE, FALSE, FALSE, FALSE}; static gboolean ParseDisplayCert(const gchar* name, const gchar* value, gpointer data, GError **error) { options.displayCert = TRUE; if (value) { options.outputCert = g_strdup(value); } return TRUE; } static GOptionEntry cmdOptions[] = { { "help", 'h', 0, G_OPTION_ARG_NONE, &options.usage, NULL, NULL }, { "verbose", 'v', 0, G_OPTION_ARG_NONE, &options.verbose, NULL, NULL }, { "erase_proxy_data", 'e', 0, G_OPTION_ARG_NONE, &options.erase, NULL, NULL }, { "force", 'f', 0, G_OPTION_ARG_NONE, &options.force, NULL, NULL }, { "generate_key_cert", 'g', 0, G_OPTION_ARG_NONE, &options.generateCert, NULL, NULL }, { "add_trust_cert", 'a', 0, G_OPTION_ARG_FILENAME, &options.addCert, NULL, NULL }, { "remove_trust_cert", 'r', 0, G_OPTION_ARG_FILENAME, &options.deleteCert, NULL, NULL }, { "display_server_cert", 'd', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, ParseDisplayCert, NULL, NULL }, { NULL } }; /* *---------------------------------------------------------------------- * * ParseOptions -- * * Parse command options. * * Results: * Recognized options are saved into the options variable. * * Side effects: * Both argc and argv are updated to remove those already * recognized options. * *---------------------------------------------------------------------- */ static void ParseOptions(int *argc, // IN/OUT char ***argv) // IN/OUT { GError *error = NULL; GOptionContext *context; context = g_option_context_new(NULL); g_option_context_add_main_entries(context, cmdOptions, NULL); /* * Turn off glib option parser help message in order to provide the * complete help messages compatible to those from the original perl * implementation script. */ g_option_context_set_help_enabled(context, FALSE); if (!g_option_context_parse(context, argc, argv, &error)) { printf("Option parsing failed: %s\n", error->message); PrintUsage(g_get_prgname()); exit(1); } g_option_context_free(context); } int main(int argc, char **argv) { ParseOptions(&argc, &argv); if (options.usage) { PrintUsage(g_get_prgname()); exit(0); } if (options.verbose) { gIsLogEnabled = TRUE; } InitProxyPaths(CertUtil_GetToolDir()); #ifdef _WIN32 /* * The old VB script created the key with bad perms; regenerate if we * find it looks bad. */ { gchar *keyFilename = g_build_filename(guestProxyServerDir, "key.pem", NULL); if (g_file_test(keyFilename, G_FILE_TEST_EXISTS)) { if (!CheckKeyFile(keyFilename)) { printf("Warning! Insecure keyfile (%s) found," " regenerating key and cert.\n", keyFilename); options.force = TRUE; } } g_free(keyFilename); } #endif if ((options.generateCert && !CreateKeyCert(options.force)) || (options.displayCert && !DisplayServerCert(options.outputCert)) || (options.addCert && !AddTrustCert(options.addCert)) || (options.deleteCert && !RemoveTrustCert(options.deleteCert)) || (options.erase && !EraseProxyData())) { return 1; } else { return 0; } } open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/cert_tool_version.h000066400000000000000000000031221321503522500302110ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * cert_tool_version.h -- * * Version definitions for the vmware-guestproxycerttool program */ #ifndef _GUESTPROXYCERTTOOL_VERSION_H_ #define _GUESTPROXYCERTTOOL_VERSION_H_ /* * This component's version is coupled with Tools versioning. The effect * is that the version increments with each build, and with each Tools * version bump. If and when it becomes necessary to version the component * manually, make sure that the version is bumped any time the component or * its dependencies are changed. */ #include "vm_tools_version.h" #define GUESTPROXYCERTTOOL_VERSION_COMMAS TOOLS_VERSION_EXT_CURRENT_CSV #define GUESTPROXYCERTTOOL_VERSION_STRING TOOLS_VERSION_EXT_CURRENT_STR #endif /* _GUESTPROXYCERTTOOL_VERSION_H_*/ open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/cert_util.c000066400000000000000000000267241321503522500264540ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * cert_util.c -- * * Utilities to manage the certificates. */ #include #include #include #include #include "cert_util.h" /* *---------------------------------------------------------------------- * * CompareFile -- * * Check if two files are the same. * * Results: * TRUE if file comparison is performed successfully, otherwise * FALSE. When the returned value is TRUE, 'same' is TRUE if two * input files are the same, otherwise FALSE. When the returned * value is FALSE, 'same' is not defined. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean CompareFile(const gchar *fname1, // IN const gchar *fname2, // IN gboolean *same) // OUT { gsize num; gboolean ret = FALSE; GMappedFile *m1; GMappedFile *m2 = NULL; GError *error = NULL; m1 = g_mapped_file_new(fname1, FALSE, &error); if (m1 == NULL) { Error("Unable to map %s: %s.\n", fname1, error->message); goto exit; } m2 = g_mapped_file_new(fname2, FALSE, &error); if (m2 == NULL) { Error("Unable to map %s: %s.\n", fname2, error->message); goto exit; } ret = TRUE; *same = FALSE; num = g_mapped_file_get_length(m1); if (g_mapped_file_get_length(m2) == num) { if (num) { if (memcmp(g_mapped_file_get_contents(m1), g_mapped_file_get_contents(m2), num) == 0) { *same = TRUE; } } else { /* Two empty files */ *same = TRUE; } } exit: g_clear_error(&error); if (m1) { g_mapped_file_unref(m1); } if (m2) { g_mapped_file_unref(m2); } return ret; } /* *---------------------------------------------------------------------- * * CertUtil_CreateCertFileName -- * * A convenient function to make up the certificate file name based * on the supplied guest proxy certificate store (certDir), subject * name hash (hash), and certificate version (version). * * Results: * Return the full path name of the certificate. Callers should free * the returned string. * * Side effects: * None. * *---------------------------------------------------------------------- */ gchar * CertUtil_CreateCertFileName(const gchar *certDir, // IN const gchar *hash, // IN int version) // IN { gchar *ret; gchar *tmp; tmp = g_strdup_printf("%s.%d", hash, version); ret = g_build_filename(certDir, tmp, NULL); g_free(tmp); return ret; } /* *---------------------------------------------------------------------- * * IntCmp -- * * This is an integer comparator, which is used to sort a list * with ascending order. * * Results: * The difference of ga and gb. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gint IntCmp(gconstpointer ga, // IN gconstpointer gb) // IN { gint a = GPOINTER_TO_INT(ga); gint b = GPOINTER_TO_INT(gb); return (a - b); } /* *---------------------------------------------------------------------- * * MatchFile -- * * Scan each file at the directory and collect file extensions of * matched files. Sort the file extension list in ascending order. * * Results: * Return a list of file extensions, their file names matching the * regular expression. These extensions are file version numbers. * * Side effects: * None. * *---------------------------------------------------------------------- */ static GList * MatchFile(GDir *dir, // IN GRegex *regExpr) // IN { const gchar *fn, *cp; GList *list = NULL; while ((fn = g_dir_read_name(dir)) != NULL) { if (g_regex_match(regExpr, fn, 0, NULL)) { cp = strrchr(fn, '.'); list = g_list_prepend(list, GINT_TO_POINTER(atoi(cp + 1))); } } list = g_list_sort(list, IntCmp); return list; } /* *---------------------------------------------------------------------- * * SearchFile -- * * Search files with pattern (.[0-9]+) at a directory . * * Results: * Return TRUE if file search is performed successfully, otherwise * FALSE. When the returned value is TRUE, 'list' is set to include * a list of file extensions matching the pattern. * * Side effects: * None. * *---------------------------------------------------------------------- */ static gboolean SearchFile(const gchar *path, // IN const gchar *fname, // IN GList **list) // OUT { gboolean ret = FALSE; gchar *pattern; GRegex *regExpr; GDir *dir = NULL; GError *error = NULL; pattern = g_strdup_printf("%s.[0-9]+", fname); regExpr = g_regex_new(pattern, 0, 0, &error); if (!regExpr) { Error("Failed to compile %s: %s.\n", pattern, error->message); goto exit; } dir = g_dir_open(path, 0, &error); if (!dir) { Error("Failed to open %s: %s.\n", path, error->message); goto exit; } *list = MatchFile(dir, regExpr); ret = TRUE; exit: g_free(pattern); g_clear_error(&error); if (dir) { g_dir_close(dir); } if (regExpr) { g_regex_unref(regExpr); } return ret; } /* *---------------------------------------------------------------------- * * CertUtil_FindCert -- * * From the trusted certificate directory (certDir), check if * there is any certificate file matching the contents of the * supplied one. In general, certificate files are saved in the * directory by the format of .[0-9]+. * * Results: * Return TRUE if the function is successfully executed. Otherwise * FALSE. When return TRUE, 'num' is set to the version of matching * certificate file or -1 if no matching. For 'last', it is set to * the highest version, or -1 if the store has no certificate file. * * Side effects: * None. * *---------------------------------------------------------------------- */ gboolean CertUtil_FindCert(const gchar *certFile, // IN const gchar *certDir, // IN const gchar *hash, // IN int *num, // OUT int *last) // OUT { gboolean ret = FALSE; const GList *node; GList *list = NULL; gchar *path = NULL; *last = *num = -1; if (!SearchFile(certDir, hash, &list)) { goto exit; } ret = TRUE; if (!list) { goto exit; } /* *last = the highest file version */ node = g_list_last(list); *last = GPOINTER_TO_INT(node->data); for (node = g_list_first(list); node; node = g_list_next(node)) { gboolean same = FALSE; int ext = GPOINTER_TO_INT(node->data); g_free(path); path = CertUtil_CreateCertFileName(certDir, hash, ext); if (!CompareFile(certFile, path, &same)) { ret = FALSE; goto exit; } if (same) { *num = ext; break; } } exit: g_free(path); if (list) { g_list_free(list); } return ret; } #ifndef _WIN32 /* *---------------------------------------------------------------------- * * CertUtil_GetToolDir -- * * Get the VMware tool installation directory. * * Results: * The VMware tool installation directory. Callers should not free * the returned string. * * Side effects: * None. * *---------------------------------------------------------------------- */ const gchar * CertUtil_GetToolDir(void) { static gchar *path = NULL; if (!path) { path = g_build_filename(G_DIR_SEPARATOR_S, "etc", "vmware-tools", NULL); } return path; } #endif /* *---------------------------------------------------------------------- * * CertUtil_CopyFile -- * * Copy a file from source to destination. * * Results: * TRUE if success, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ gboolean CertUtil_CopyFile(const gchar *src, // IN const gchar *dst) // IN { gsize length; gboolean ret = FALSE; GMappedFile *smap; GError *error = NULL; FILE *file = NULL; const gchar *content; smap = g_mapped_file_new(src, FALSE, &error); if (!smap) { Error("Unable to map %s: %s.\n", src, error->message); goto exit; } file = g_fopen(dst, "w"); if (!file) { Error("Failed to open %s: %s.\n", dst, strerror(errno)); goto exit; } length = g_mapped_file_get_length(smap); content = g_mapped_file_get_contents(smap); if (fwrite(content, 1, length, file) < length) { Error("Failed to copy %s to %s: %s.\n", src, dst, strerror(errno)); goto exit; } ret = TRUE; exit: g_clear_error(&error); if (smap) { g_mapped_file_unref(smap); } if (file) { fclose(file); } return ret; } /* *---------------------------------------------------------------------- * * CertUtil_RemoveDir -- * * Remove a directory. This directory can be non-empty. When it is * non-empty, all of its files and subdirectories are removed too. * * Results: * TRUE if the directory is successfully removed, otherwise FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ gboolean CertUtil_RemoveDir(const gchar *dirToRemove) { gboolean ret = FALSE; GDir *dir = NULL; const gchar *file; GError *error = NULL; gchar *fname = NULL; if ((dir = g_dir_open(dirToRemove, 0, &error)) == NULL) { Error("Failed to open %s: %s.\n", dirToRemove, error->message); goto exit; } while ((file = g_dir_read_name(dir)) != NULL) { g_free(fname); fname = g_build_filename(dirToRemove, file, NULL); if (g_file_test(fname, G_FILE_TEST_IS_DIR)) { if (!CertUtil_RemoveDir(fname)) { Error("Couldn't remove the directory '%s'.\n", fname); goto exit; } } else if (g_remove(fname) < 0) { Error("Couldn't remove the file '%s'.\n", fname); goto exit; } } g_dir_close(dir); dir = NULL; if (g_rmdir(dirToRemove) < 0) { Error("Couldn't remove the directory '%s'.\n", dirToRemove); goto exit; } ret = TRUE; exit: g_free(fname); g_clear_error(&error); if (dir) { g_dir_close(dir); } return ret; } open-vm-tools-stable-10.2.0/open-vm-tools/guestproxycerttool/cert_util.h000066400000000000000000000044541321503522500264550ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _CERT_UTIL_H_ #define _CERT_UTIL_H_ #include #include /* *---------------------------------------------------------------------- * * Error -- * * Prefix the error message with the program name and output the * message to the standard error. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ #ifdef _WIN32 #define Error(fmt, ...) \ fprintf(stderr, "%s: " fmt, g_get_prgname(), __VA_ARGS__); #else #define Error(fmt, args...) \ fprintf(stderr, "%s: " fmt, g_get_prgname(), ##args); #endif gchar * CertUtil_CreateCertFileName(const gchar *certDir, // IN const gchar *hash, // IN int version); // IN gboolean CertUtil_FindCert(const gchar *certFile, // IN const gchar *certDir, // IN const gchar *hash, // IN int *num, // OUT int *last); // OUT gboolean CertUtil_CopyFile(const gchar *src, // IN const gchar *dst); // IN gboolean CertUtil_RemoveDir(const gchar *dirToRemove); // IN const gchar *CertUtil_GetToolDir(void); gboolean CheckRootPriv(void); #endif // #ifndef _CERT_UTIL_H_ open-vm-tools-stable-10.2.0/open-vm-tools/hgfsclient/000077500000000000000000000000001321503522500224245ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/hgfsclient/COPYING000066400000000000000000000634711321503522500234720ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! open-vm-tools-stable-10.2.0/open-vm-tools/hgfsclient/Makefile.am000066400000000000000000000030671321503522500244660ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ bin_PROGRAMS = vmware-hgfsclient vmware_hgfsclient_LDADD = vmware_hgfsclient_LDADD += ../lib/hgfsBd/libHgfsBd.la vmware_hgfsclient_LDADD += @VMTOOLS_LIBS@ vmware_hgfsclient_LDADD += @HGFS_LIBS@ vmware_hgfsclient_CPPFLAGS = vmware_hgfsclient_CPPFLAGS += @VMTOOLS_CPPFLAGS@ vmware_hgfsclient_SOURCES = vmware_hgfsclient_SOURCES += hgfsclient.c if HAVE_ICU vmware_hgfsclient_LDADD += @ICU_LIBS@ vmware_hgfsclient_LINK = $(LIBTOOL) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXX) \ $(AM_CXXFLAGS) $(CXXFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ else vmware_hgfsclient_LINK = $(LINK) endif open-vm-tools-stable-10.2.0/open-vm-tools/hgfsclient/hgfsclient.c000066400000000000000000000254031321503522500247220ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsclient.c -- * * Userspace HGFS client. Will one day be as full featured as an HGFS * filesystem driver. * */ #define G_LOG_DOMAIN "hgfsClient" #include "vmware.h" #include "guestApp.h" #include "vmcheck.h" #include "escBitvector.h" #include "hgfsEscape.h" #include "hgfs.h" #include "hgfsBd.h" #include "hgfsProto.h" #include "conf.h" #include "str.h" #include "vmware/tools/log.h" #include "vmware/tools/utils.h" #include "hgfsclient_version.h" #include "vm_version.h" #include "embed_version.h" VM_EMBED_VERSION(HGFSCLIENT_VERSION_STRING); #include #include #include #include #include RpcOut *gChannel = NULL; char *gPacketBuffer = NULL; static Bool HgfsClient_Open(HgfsHandle *rootHandle); static HgfsFileName *HgfsClient_Read(HgfsHandle rootHandle, int offset); static Bool HgfsClient_Close(HgfsHandle rootHandle); static Bool HgfsClient_PrintShares(void); static Bool HgfsClient_Init(void); static Bool HgfsClient_Cleanup(void); /* *----------------------------------------------------------------------------- * * HgfsClient_Open -- * * Open the root directory on the host. * * Results: * TRUE on success. FALSE otherwise. When TRUE, the root directory handle * is returned as an argument. * * Side effects: * The host has cached an open search for us. * *----------------------------------------------------------------------------- */ static Bool HgfsClient_Open(HgfsHandle *rootHandle) // OUT: Handle to root directory { Bool success = FALSE; HgfsRequestSearchOpen *searchOpenReq; HgfsReplySearchOpen *searchOpenRep = NULL; int err; char const *replyPacket; size_t packetSize; /* Create a SearchOpen and send it. */ searchOpenReq = (HgfsRequestSearchOpen *)gPacketBuffer; memset(searchOpenReq, 0, sizeof *searchOpenReq); searchOpenReq->header.id = 0; searchOpenReq->header.op = HGFS_OP_SEARCH_OPEN; searchOpenReq->dirName.length = 0; searchOpenReq->dirName.name[0] = 0; packetSize = sizeof *searchOpenReq; err = HgfsBd_Dispatch(gChannel, (char *)searchOpenReq, &packetSize, &replyPacket); if (err != 0) { Warning("Failed to send search open request.\n"); goto out; } /* replyPacket has our search handle. */ searchOpenRep = (HgfsReplySearchOpen *)replyPacket; if (searchOpenRep->header.status != HGFS_STATUS_SUCCESS) { Warning("Error in opening root directory.\n"); goto out; } success = TRUE; out: /* We got the root handle. */ if (success) { *rootHandle = searchOpenRep->search; } return success; } /* *----------------------------------------------------------------------------- * * HgfsClient_Read -- * * Read a share name from the host. * * Results: * Pointer into the packet buffer where the caller can find the * HgfsFileName struct. Since this is a pointer into the global * packet buffer, the caller should not free it. * * NULL if there was an error. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static HgfsFileName * HgfsClient_Read(HgfsHandle rootHandle, // IN: Handle to root directory int offset) // IN: Offset of dirent to read { HgfsFileName *shareName = NULL; HgfsRequestSearchRead *searchReadReq; HgfsReplySearchRead *searchReadRep; int err; char const *replyPacket; size_t packetSize; /* Create searchRead and send it. */ searchReadReq = (HgfsRequestSearchRead *)gPacketBuffer; memset(searchReadReq, 0, sizeof *searchReadReq); searchReadReq->header.id = 0; searchReadReq->header.op = HGFS_OP_SEARCH_READ; searchReadReq->search = rootHandle; searchReadReq->offset = offset; packetSize = sizeof *searchReadReq; err = HgfsBd_Dispatch(gChannel, (char *)searchReadReq, &packetSize, &replyPacket); if (err != 0) { Warning("Failed to send search read request.\n"); goto out; } /* replyPacket has our share name. */ searchReadRep = (HgfsReplySearchRead *)replyPacket; if (searchReadRep->header.status != HGFS_STATUS_SUCCESS) { Warning("Error in getting share name.\n"); goto out; } /* We got the share name. */ shareName = &searchReadRep->fileName; out: return shareName; } /* *----------------------------------------------------------------------------- * * HgfsClient_Close -- * * Closes the root directory on the host. * * Results: * TRUE on success, FALSE otherwise. * * Side effects: * Host releases state on our opened search. * *----------------------------------------------------------------------------- */ static Bool HgfsClient_Close(HgfsHandle rootHandle) // IN: Handle to root directory { HgfsRequestSearchClose *searchCloseReq; HgfsReplySearchClose *searchCloseRep; int err; char const *replyPacket; size_t packetSize; /* Create a SearchClose and send it. */ searchCloseReq = (HgfsRequestSearchClose *)gPacketBuffer; memset(searchCloseReq, 0, sizeof *searchCloseReq); searchCloseReq->header.id = 0; searchCloseReq->header.op = HGFS_OP_SEARCH_CLOSE; searchCloseReq->search = rootHandle; packetSize = sizeof *searchCloseReq; err = HgfsBd_Dispatch(gChannel, (char *)searchCloseReq, &packetSize, &replyPacket); if (err != 0) { Warning("Failed to send search close request.\n"); return FALSE; } /* replyPacket has success/failure. */ searchCloseRep = (HgfsReplySearchClose *)replyPacket; if (searchCloseRep->header.status != HGFS_STATUS_SUCCESS) { Warning("Error closing root directory.\n"); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsClient_PrintShares -- * * List all the shares available on the host. * * Results: * TRUE if successful, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsClient_PrintShares(void) { Bool success = FALSE; int offset = 0; char escapedName[PATH_MAX + 1]; HgfsHandle rootHandle; HgfsFileName *fileName; if (!HgfsClient_Open(&rootHandle)) { return success; } while (TRUE) { fileName = HgfsClient_Read(rootHandle, offset++); if (fileName == NULL) { break; } /* Are we done? */ if (fileName->length == 0) { success = TRUE; break; } /* * Escape this filename. If we get back a negative result, it means that * the escaped filename is too big, so skip this share. */ if (HgfsEscape_Do(fileName->name, fileName->length, sizeof escapedName, escapedName) < 0) { continue; } /* Skip "." and ".." which can be returned. */ if (strcmp(".", escapedName) == 0 || strcmp("..", escapedName) == 0) { continue; } printf("%s\n", escapedName); } if (!HgfsClient_Close(rootHandle)) { success = FALSE; } return success; } /* *----------------------------------------------------------------------------- * * HgfsClient_Init -- * * Do some initialization "stuff". * * Results: * TRUE if initialization succeeded, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsClient_Init(void) { Bool success = FALSE; GKeyFile *conf = NULL; VMTools_LoadConfig(NULL, G_KEY_FILE_NONE, &conf, NULL); VMTools_ConfigLogging("hgfsclient", conf, FALSE, FALSE); if (conf != NULL) { g_key_file_free(conf); conf = NULL; } if (!VmCheck_IsVirtualWorld()) { Warning("This application must be run in a Virtual Machine.\n"); goto out; } /* Setup an HGFS channel and packet buffer. */ gChannel = HgfsBd_GetChannel(); if (gChannel == NULL) { Warning("Failed to create RPC channel\n"); goto out; } gPacketBuffer = HgfsBd_GetBuf(); if (gPacketBuffer == NULL) { Warning("Failed to create packet buffer\n"); goto out; } /* Find out if HGFS is enabled in the VMX. */ if (!HgfsBd_Enabled(gChannel, gPacketBuffer)) { Warning("HGFS is disabled in the host\n"); goto out; } success = TRUE; out: if (!success) { HgfsClient_Cleanup(); } return success; } /* *----------------------------------------------------------------------------- * * HgfsClient_Cleanup -- * * Do some cleanup crap. * * Results: * TRUE if cleanup succeeded, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsClient_Cleanup(void) { Bool success = TRUE; if (gPacketBuffer != NULL) { HgfsBd_PutBuf(gPacketBuffer); } if (gChannel != NULL) { if (!HgfsBd_CloseChannel(gChannel)) { Warning("Failed to close RPC channel\n"); success = FALSE; } } return success; } /* *----------------------------------------------------------------------------- * * main -- * * Main entry point. Calls into the host's HGFS server and prints out * a list of the available shares. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ int main(int argc, // IN char *argv[]) // IN { if (argc == 2 && (!strncmp(argv[1], "-h", 2) || !strncmp(argv[1], "--help", 6))) { fprintf(stderr, "hgfsclient: lists any shared folders.\n"); return 0; } if (!HgfsClient_Init()) { return EXIT_FAILURE; } if (!HgfsClient_PrintShares()) { return EXIT_FAILURE; } if (!HgfsClient_Cleanup()) { return EXIT_FAILURE; } return EXIT_SUCCESS; } open-vm-tools-stable-10.2.0/open-vm-tools/hgfsclient/hgfsclient_version.h000066400000000000000000000030551321503522500264730ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsclient_version.h -- * * Version definitions for the HGFS userspace client application. */ #ifndef _HGFSCLIENT_VERSION_H_ #define _HGFSCLIENT_VERSION_H_ /* * This component's version is coupled with Tools versioning. The effect * is that the version increments with each build, and with each Tools * version bump. If and when it becomes necessary to version the component * manually, make sure that the version is bumped any time the component or * its dependencies are changed. */ #include "vm_tools_version.h" #define HGFSCLIENT_VERSION_COMMAS TOOLS_VERSION_EXT_CURRENT_CSV #define HGFSCLIENT_VERSION_STRING TOOLS_VERSION_EXT_CURRENT_STR #endif /* _HGFSCLIENT_VERSION_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/hgfsmounter/000077500000000000000000000000001321503522500226375ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/hgfsmounter/COPYING000066400000000000000000000634711321503522500237050ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! open-vm-tools-stable-10.2.0/open-vm-tools/hgfsmounter/Makefile.am000066400000000000000000000034021321503522500246720ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ sbin_PROGRAMS = mount.vmhgfs mount_vmhgfs_LDADD = mount_vmhgfs_LDADD += ../lib/string/libString.la mount_vmhgfs_LDADD += ../lib/panicDefault/libPanicDefault.la mount_vmhgfs_LDADD += ../lib/panic/libPanic.la mount_vmhgfs_LDADD += ../lib/lock/libLock.la mount_vmhgfs_LDADD += ../lib/misc/libMisc.la mount_vmhgfs_LDADD += ../lib/stubs/libStubs.la mount_vmhgfs_SOURCES = mount_vmhgfs_SOURCES += hgfsmounter.c if FREEBSD install-exec-hook: mv $(DESTDIR)$(sbindir)/mount.vmhgfs \ $(DESTDIR)$(sbindir)/mount_vmhgfs -$(MKDIR_P) $(DESTDIR)/sbin -$(LN_S) $(DESTDIR)$(sbindir)/mount_vmhgfs \ $(DESTDIR)/sbin/mount_vmhgfs &> /dev/null uninstall-hook: rm -f $(DESTDIR)$(sbindir)/mount_vmhgfs else install-exec-hook: -$(MKDIR_P) $(DESTDIR)/sbin -$(LN_S) $(DESTDIR)$(sbindir)/mount.vmhgfs \ $(DESTDIR)/sbin/mount.vmhgfs &> /dev/null uninstall-hook: rm -f $(DESTDIR)/sbin/mount.vmhgfs endif !FREEBSD open-vm-tools-stable-10.2.0/open-vm-tools/hgfsmounter/hgfsmounter.c000066400000000000000000001046071321503522500253540ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsmounter.c -- * * Helper app for mounting HGFS shares on Linux and FreeBSD. On Linux, we need this * because we must pass a binary blob through mount(2) to the HGFS driver, in order * to properly communicate the share name that we're interested in mounting. On * FreeBSD, we need this because FreeBSD requires that each filesystem type have a * separate mount program installed as /sbin/mount_fstype */ #define _GNU_SOURCE #include #include #include #include #if defined(__linux__) # include #endif #if defined(__FreeBSD__) || defined(__APPLE__) # include # include # define MS_MANDLOCK 0 # define MS_RDONLY MNT_RDONLY # define MS_SYNCHRONOUS MNT_SYNCHRONOUS # define MS_NOEXEC MNT_NOEXEC # define MS_NOSUID MNT_NOSUID /* * MNT_NODEV does not exist, or is set to 0, on newer versions of FreeBSD. */ # if defined(MNT_NODEV) && MNT_NODEV # define MS_NODEV MNT_NODEV # endif # define MS_UNION MNT_UNION # define MS_ASYNC MNT_ASYNC # define MS_SUIDDIR MNT_SUIDDIR # define MS_SOFTDEP MNT_SOFTDEP # define MS_NOSYMFOLLOW MNT_NOSYMFOLLOW # define MS_JAILDEVFS MNT_JAILDEVFS # define MS_MULTILABEL MNT_MULTILABEL # define MS_ACLS MNT_ACLS # define MS_NODIRATIME 0 # define MS_NOCLUSTERR MNT_NOCLUSTERR # define MS_NOCLUSTERW MNT_NOCLUSTERW # define MS_REMOUNT MNT_RELOAD # if defined(__FreeBSD__) # define MS_NOATIME MNT_NOATIME # elif defined(__APPLE__) /* * XXX This is defined in the sys/mount.h in the OS X 10.5 Kernel.framework but not the * 10.4 one. Once this is built against the newer library, this should be changed. */ # define MS_NOATIME 0 # endif #endif #include #include #include #include #include #include #include #include #ifdef MOUNTED /* defined in mntent.h */ /* * If VM_HAVE_MTAB is set, hgfsmounter will update /etc/mtab. This is not necessary on * systems such as FreeBSD (and possibly Solaris) that don't have a mtab or the mntent.h * routines. */ # define VM_HAVE_MTAB 1 #endif #include "hgfsDevLinux.h" #include "vm_basic_types.h" #include "vm_basic_defs.h" #include "vm_assert.h" #include "str.h" #include "strutil.h" #include "vm_version.h" #include "hgfsmounter_version.h" /* XXX embed_version.h does not currently support Mach-O binaries (OS X). */ #if defined(__linux__) || defined(__FreeBSD__) # include "vm_version.h" # include "embed_version.h" VM_EMBED_VERSION(HGFSMOUNTER_VERSION_STRING); #endif /* * Not defined in glibc 2.1.3 */ #ifndef MS_BIND #define MS_BIND 4096 #endif #ifndef MS_MOVE #define MS_MOVE 8192 #endif #define MOUNT_OPTS_BUFFER_SIZE 256 #if defined(__GNUC__) && __GNUC__ < 3 /* __VA_ARGS__ isn't supported by old gcc's, so hack around the situation */ #define LOG(format...) (beVerbose ? printf(format) : 0) #else #define LOG(format, ...) (beVerbose ? printf(format, ##__VA_ARGS__) : 0) #endif typedef struct MountOptions { char *opt; /* Option name */ int flag; /* Corresponding flag */ Bool set; /* Whether the flag should be set or reset */ char *helpMsg; /* Help message for the option */ char *logMsg; /* Log message to emit when option was detected */ /* Special handler for more complex options */ Bool (*handler)(const char *opt, HgfsMountInfo *mountInfo, int *flags); } MountOptions; static char *thisProgram; static char *thisProgramBase; static char *shareName; static char *mountPoint; static Bool beVerbose = FALSE; /* *----------------------------------------------------------------------------- * * PrintVersion -- * * Displays version and exits with success. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void PrintVersion(void) { printf("%s version: %s\n", thisProgramBase, HGFSMOUNTER_VERSION_STRING); exit(EXIT_SUCCESS); } /* *----------------------------------------------------------------------------- * * GetPathMax * * Helper function to get the system's maximum path length for a given * path. In userspace, PATH_MAX may not be defined, and we must use * pathconf(3) to get its value. * * This is the realpath(3)-approved way of getting the maximum path size, * inasmuch as realpath(3) can be an approved function (see the BUGS section * in the manpage for details). * * Results: * Always succeeds, returns the maximum path size. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static size_t GetPathMax(const char *path) // IN: path to check { size_t pathMax; #ifndef PATH_MAX long sysPathMax; /* * pathconf(3) may return -1 if the system imposes no pathname bound, or if * there was an error. In any case, we're advised by realpath(3)'s manpage * not to use the result of pathconf for direct allocation, as it may be too * large. So we declare 4096 as our upper bound, to be used when pathconf(3) * returns an error, returns zero, returns a very large quantity, or when * we learn that there's no limit. */ sysPathMax = pathconf(path, _PC_PATH_MAX); if (sysPathMax <= 0 || sysPathMax > 4096) { pathMax = 4096; } else { pathMax = sysPathMax; } #else pathMax = PATH_MAX; #endif return pathMax; } /* *----------------------------------------------------------------------------- * * IsValidShareName * * A helper function to parse the share name from "host:share" format into * two separate strings, reporting errors if any. * * Results: * TRUE on success, shareNameHost and shareNameDir have been set. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool ParseShareName(const char *shareName, // IN: Share name to validate const char **shareNameHost, // OUT: Share name, host component const char **shareNameDir) // OUT: Share name, dir component { const char *colon; const char *dir; /* 1) Must be colon separated into host and dir. */ colon = strchr(shareName, ':'); if (colon == NULL) { printf("Share name must be in host:dir format\n"); return FALSE; } /* 2) Dir must not be empty. */ dir = colon + 1; if (*dir == '\0') { printf("Directory in share name must not be empty\n"); return FALSE; } /* 3) Dir must start with forward slash. */ if (*dir != '/') { printf("Directory in share name must be an absolute path\n"); return FALSE; } /* 4) Host must be ".host". */ if (strncmp(shareName, ".host:", 6) != 0) { printf("Host in share name must be \".host\"\n"); return FALSE; } *shareNameHost = ".host"; LOG("Host component of share name is \"%s\"\n", *shareNameHost); *shareNameDir = dir; LOG("Directory component of share name is \"%s\"\n", *shareNameDir); return TRUE; } /* *----------------------------------------------------------------------------- * * ParseUid * * A helper function to process a string containing either a user name * or a uid and set up mountInfo accordingly. * * Results: * TRUE on success, mountInfo modified appropriately, FALSE on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ #ifndef sun static Bool ParseUid(const char *option, // IN: option string along with value HgfsMountInfo *mountInfo, // OUT: mount data int *flags) // OUT: mount flags { Bool success = FALSE; unsigned int idx = 0; char *optString; char *uidString; uid_t myUid = 0; ASSERT(option); ASSERT(mountInfo); ASSERT(flags); /* Figure where value starts, we don't need result, just index. */ optString = StrUtil_GetNextToken(&idx, option, "="); ASSERT(optString); uidString = StrUtil_GetNextToken(&idx, option, "="); if (!uidString) { LOG("Error getting the value for uid\n"); goto out; } /* * The uid can be a direct value or a username which we must first * translate to its numeric value. */ if (isdigit(*uidString)) { errno = 0; myUid = strtoul(uidString, NULL, 10); if (errno == 0) { success = TRUE; } else { printf("Bad UID value \"%s\"\n", uidString); } } else { struct passwd *pw; if (!(pw = getpwnam(uidString))) { printf("Bad user name \"%s\"\n", uidString); } else { myUid = pw->pw_uid; success = TRUE; } endpwent(); } if (success) { mountInfo->uid = myUid; mountInfo->uidSet = TRUE; LOG("Setting mount owner to %"FMTUID"\n", myUid); } free(uidString); out: free(optString); return success; } #endif /* *----------------------------------------------------------------------------- * * ParseGid * * A helper function to process a string containing either a group name * or a gid and set up mountInfo accordingly. * * Results: * TRUE on success, mountInfo modified appropriately, FALSE on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ #ifndef sun static Bool ParseGid(const char *option, // IN: option string along with value HgfsMountInfo *mountInfo, // OUT: mount data int *flags) // OUT: mount flags { Bool success = FALSE; unsigned int idx = 0; char *optString; char *gidString; gid_t myGid = 0; ASSERT(option); ASSERT(mountInfo); ASSERT(flags); /* Figure where value starts, we don't need result, just index. */ optString = StrUtil_GetNextToken(&idx, option, "="); ASSERT(optString); gidString = StrUtil_GetNextToken(&idx, option, "="); if (!gidString) { LOG("Error getting the value for gid\n"); goto out; } /* * The gid can be a direct value or a group name which we must first * translate to its numeric value. */ if (isdigit(*gidString)) { errno = 0; myGid = strtoul(gidString, NULL, 10); if (errno == 0) { success = TRUE; } else { printf("Bad GID value \"%s\"\n", gidString); } } else { struct group *gr; if (!(gr = getgrnam(gidString))) { printf("Bad group name \"%s\"\n", gidString); } else { myGid = gr->gr_gid; success = TRUE; } endpwent(); } if (success) { mountInfo->gid = myGid; mountInfo->gidSet = TRUE; LOG("Setting mount group to %"FMTUID"\n", myGid); } free(gidString); out: free(optString); return success; } #endif /* *----------------------------------------------------------------------------- * * ParseMask * * A helper function to parse a string containing File/Directory * mask value. * * Results: * TRUE on success, along with the mask, FALSE on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ #ifndef sun static Bool ParseMask(const char *option, // IN: option string along with value unsigned short *pmask) // OUT: parsed mask { Bool success = FALSE; unsigned int idx = 0; char *optString; char *maskString; unsigned short mask; optString = StrUtil_GetNextToken(&idx, option, "="); ASSERT(optString); maskString = StrUtil_GetNextToken(&idx, option, "="); if (!maskString) { LOG("Error getting the value for %s\n", optString); goto out; } /* * The way to check for an overflow in strtol(3), according to its * man page. */ errno = 0; mask = strtol(maskString, NULL, 8); if (errno == 0) { *pmask = mask; success = TRUE; } else { LOG("Error, overflow in %s\n", optString); } free(maskString); out: free(optString); return success; } #endif /* *----------------------------------------------------------------------------- * * ParseFmask * * A helper function to process a string containing File mask value. * * Results: * TRUE on success, mountInfo modified appropriately, FALSE on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ #ifndef sun static Bool ParseFmask(const char *option, // IN: option string along with value HgfsMountInfo *mountInfo, // OUT: mount data int *flags) // OUT: mount flags { ASSERT(option); ASSERT(mountInfo); if (ParseMask(option, &mountInfo->fmask)) { LOG("Setting mount fmask to %o\n", mountInfo->fmask); return TRUE; } return FALSE; } #endif /* *----------------------------------------------------------------------------- * * ParseDmask * * A helper function to process a string containing dmask value. * * Results: * TRUE on success, mountInfo modified appropriately, FALSE on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ #ifndef sun static Bool ParseDmask(const char *option, // IN: option string along with value HgfsMountInfo *mountInfo, // OUT: mount data int *flags) // OUT: mount flags { ASSERT(option); ASSERT(mountInfo); if (ParseMask(option, &mountInfo->dmask)) { LOG("Setting mount dmask to %o\n", mountInfo->dmask); return TRUE; } return FALSE; } #endif /* *----------------------------------------------------------------------------- * * ParseTtl * * A helper function to process a string containing TTL value. * * Results: * TRUE on success, mountInfo modified appropriately, FALSE on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ #ifndef sun static Bool ParseTtl(const char *option, // IN: option string along with value HgfsMountInfo *mountInfo, // OUT: mount data int *flags) // OUT: mount flags { Bool success = FALSE; unsigned int idx = 0; char *optString; int32 ttl; ASSERT(option); ASSERT(mountInfo); ASSERT(flags); /* Figure where value starts, we don't need result, just index. */ optString = StrUtil_GetNextToken(&idx, option, "="); ASSERT(optString); if (StrUtil_GetNextIntToken(&ttl, &idx, option, "=") && ttl >= 0) { LOG("Setting maximum attribute TTL to %u\n", ttl); mountInfo->ttl = ttl; success = TRUE; } else { LOG("Error getting the value for ttl\n"); } free(optString); return success; } #endif /* *----------------------------------------------------------------------------- * * ParseServerIno -- * * A helper function to process a string containing serverino value. * * Results: * TRUE always success. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool ParseServerIno(const char *option, // IN: option string along with value HgfsMountInfo *mountInfo, // OUT: mount data int *flags) // OUT: mount flags unused { ASSERT(option); ASSERT(mountInfo); mountInfo->flags |= HGFS_MNTINFO_SERVER_INO; LOG("Setting mount flag server ino in 0x%x\n", mountInfo->flags); return TRUE; } /* *----------------------------------------------------------------------------- * * ParseNoServerIno -- * * A helper function to process a string containing noserverino value. * * Results: * TRUE always success. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool ParseNoServerIno(const char *option, // IN: option string along with value HgfsMountInfo *mountInfo, // OUT: mount data int *flags) // OUT: mount flags unused { ASSERT(option); ASSERT(mountInfo); mountInfo->flags &= ~HGFS_MNTINFO_SERVER_INO; LOG("Clearing mount flag server ino in 0x%x\n", mountInfo->flags); return TRUE; } static MountOptions mountOptions[] = { { "ro", MS_RDONLY, TRUE, "mount read-only", "Setting mount read-only", NULL }, { "rw", MS_RDONLY, FALSE, "mount read-write", "Setting mount read-write", NULL }, { "nosuid", MS_NOSUID, TRUE, "ignore suid/sgid bits", "Setting mount option for allowing suid/sgid bits off", NULL }, { "suid", MS_NOSUID, FALSE, "allow suid/sgid bits (default)", "Setting mount option for allowing suid/sgid bits on", NULL }, #ifndef sun /* Solaris does not have any of these options */ { "uid=", 0, TRUE, "mount owner (by uid or username)", NULL, ParseUid }, { "gid=", 0, TRUE, "mount group (by gid or groupname)", NULL, ParseGid }, { "fmask=", 0, TRUE, "file umask (in octal)", NULL, ParseFmask }, { "dmask=", 0, TRUE, "directory umask (in octal)", NULL, ParseDmask }, #ifdef MS_NODEV { "nodev", MS_NODEV, TRUE, "prevent device node access", "Setting mount option for accessing device nodes off", NULL }, { "dev", MS_NODEV, FALSE, "allow device node access (default)", "Setting mount option for accessing device nodes on", NULL }, #endif { "noexec", MS_NOEXEC, TRUE, "prevent program execution", "Setting mount option for program execution off", NULL }, { "exec", MS_NOEXEC, FALSE, "allow program execution (default)", "Setting mount option for program execution on", NULL }, { "sync", MS_SYNCHRONOUS, TRUE, "file writes are synchronous", "Setting mount synchronous writes", NULL }, { "async", MS_SYNCHRONOUS, FALSE, "file writes are asynchronous (default)", "Setting mount synchronous writes", NULL }, { "mand", MS_MANDLOCK, TRUE, "allow mandatory locks", "Setting mount option for allow mandatory locks on", NULL }, { "nomand", MS_MANDLOCK, FALSE, "prevent mandatory locks (default)", "Setting mount option for allow mandatory locks off", NULL }, { "noatime", MS_NOATIME, TRUE, "do not update access times", "Setting mount option for updating access times off", NULL }, { "atime", MS_NOATIME, FALSE, "update access times (default)", "Setting mount option for updating access times on", NULL }, { "nodiratime", MS_NOATIME, TRUE, "do not update directory access times", "Setting mount option for updating directory access times off", NULL }, { "diratime", MS_NOATIME, FALSE, "update access directory times (default)", "Setting mount option for updating directory access times on", NULL }, { "ttl=", 0, TRUE, "time before file attributes must be\n" "revalidated (in seconds). Improves\n" "performance but decreases coherency.\n" "Defaults to 1 if not set.\n", NULL, ParseTtl }, { "bind", MS_BIND, TRUE, "perform bind mount", "Setting mount type to bind", NULL }, { "bind", MS_MOVE, TRUE, "move an existig mount point", "Setting mount type to move", NULL }, #endif { "serverino", 0, TRUE, "Use server generated inode numbers.\n", "Setting mount option for using Server inode numbers on", ParseServerIno }, { "noserverino", 0, FALSE, "Use client generated inode numbers.\n", "Setting mount option for using Server inode numbers off", ParseNoServerIno }, { "remount", MS_REMOUNT, TRUE, "remount already mounted filesystem", "Setting mount type to remount", NULL } }; /* *----------------------------------------------------------------------------- * * ParseOptions -- * * Parses the options passed in by mount. Note that this doesn't correspond * to the entire argument string, merely the "-o opt1=val1,opt2=val2" * section. * * Results: * TRUE if there were no problems. * FALSE if there was an issue parsing an option. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool ParseOptions(const char *optionString, // IN: Option string to parse HgfsMountInfo *mountInfo, // OUT: Where we put the results int *flags) // OUT: Flags we might modify { unsigned int commaIndex = 0; Bool success = FALSE; char *key = NULL; char *keyVal = NULL; int i; ASSERT(optionString); ASSERT(mountInfo); ASSERT(flags); /* Parse the options string. */ LOG("Parsing option string: %s\n", optionString); /* Loop to tokenize ,,. */ while ((keyVal = StrUtil_GetNextToken(&commaIndex, optionString, ",")) != NULL) { /* Now tokenize [=]. */ unsigned int equalsIndex = 0; key = StrUtil_GetNextToken(&equalsIndex, keyVal, "="); if (key == NULL) { printf("Malformed options string\n"); goto out; } for (i = 0; i < ARRAYSIZE(mountOptions); i++) { Bool match = FALSE; unsigned int idx = 0; char *optName = StrUtil_GetNextToken(&idx, mountOptions[i].opt, "="); if (!optName) { printf("Failed to parse option name, out of memory?\n"); goto out; } match = strcmp(key, optName) == 0; free(optName); if (match) { if (mountOptions[i].handler) { if (!mountOptions[i].handler(keyVal, mountInfo, flags)) { goto out; } } else { if (mountOptions[i].set) { *flags |= mountOptions[i].flag; } else { *flags &= ~mountOptions[i].flag; } LOG("%s\n", mountOptions[i].logMsg); } break; } } if (i == ARRAYSIZE(mountOptions)) { LOG("Skipping unrecognized option \"%s\"\n", key); } free(key); free(keyVal); key = NULL; keyVal = NULL; } success = TRUE; out: free(key); free(keyVal); return success; } /* *----------------------------------------------------------------------------- * * PrintUsage -- * * Displays usage for the HGFS mounting utility, and exits with failure. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void PrintUsage(void) { int i; printf("Usage: %s [-o ]\n", thisProgramBase); printf("Mount the HGFS share, specified by name, to a local directory.\n"); printf("Share name must be in host:dir format.\n\nOptions:\n"); for (i = 0; i < ARRAYSIZE(mountOptions); i++) { Bool printOptName = TRUE; unsigned int tokidx = 0; char *msg; while ((msg = StrUtil_GetNextToken(&tokidx, mountOptions[i].helpMsg, "\n")) != NULL) { printf(" %-15s %s\n", printOptName ? mountOptions[i].opt : "", msg); free(msg); printOptName = FALSE; } } printf("\n"); printf("This command is intended to be run from within /bin/mount by\n"); printf("passing the option '-t %s'. For example:\n", HGFS_NAME); printf(" mount -t %s .host:/ /mnt/hgfs/\n", HGFS_NAME); printf(" mount -t %s .host:/foo /mnt/foo\n", HGFS_NAME); printf(" mount -t %s .host:/foo/bar /var/lib/bar\n", HGFS_NAME); exit(EXIT_FAILURE); } #ifdef VM_HAVE_MTAB /* *----------------------------------------------------------------------------- * * UpdateMtab -- * * Write the results of the mount into /etc/mtab. * * Results: * None. * * Side effects: * May write to /etc/mtab. * *----------------------------------------------------------------------------- */ static void UpdateMtab(HgfsMountInfo *mountInfo, // IN: Info to write into mtab int flags) // IN: Flags (read-only, etc.) { struct mntent mountEnt; FILE *mountFile; struct passwd *password; char *userName = NULL; ASSERT(mountInfo); mountFile = setmntent(MOUNTED, "a+"); if (mountFile == NULL) { printf("Could not open mtab for appending, continuing sans mtab\n"); return; } /* We only care about the mounting user if it isn't root. */ if (getuid() != 0) { password = getpwuid(getuid()); if (password == NULL) { printf("Could not get user for mounting uid, skipping user entry\n"); } else { userName = password->pw_name; } } /* * Create the mtab entry to be written. We'll go ahead and try to write * even if we fail to allocate the mount options. */ mountEnt.mnt_fsname = shareName; mountEnt.mnt_dir = mountPoint; mountEnt.mnt_type = HGFS_NAME; mountEnt.mnt_freq = 0; mountEnt.mnt_passno = 0; mountEnt.mnt_opts = malloc(MOUNT_OPTS_BUFFER_SIZE); if (mountEnt.mnt_opts) { char *ttlString; memset(mountEnt.mnt_opts, 0, MOUNT_OPTS_BUFFER_SIZE); /* * These are typically the displayed options in /etc/mtab (note that not * all options are typically displayed, just those the user may find * interesting). */ if (flags & MS_RDONLY) { Str_Strcat(mountEnt.mnt_opts, "ro", MOUNT_OPTS_BUFFER_SIZE); } else { Str_Strcat(mountEnt.mnt_opts, "rw", MOUNT_OPTS_BUFFER_SIZE); } if (flags & MS_NOSUID) { Str_Strcat(mountEnt.mnt_opts, ",nosuid", MOUNT_OPTS_BUFFER_SIZE); } #ifdef MS_NODEV if (flags & MS_NODEV) { Str_Strcat(mountEnt.mnt_opts, ",nodev", MOUNT_OPTS_BUFFER_SIZE); } #endif if (flags & MS_NOEXEC) { Str_Strcat(mountEnt.mnt_opts, ",noexec", MOUNT_OPTS_BUFFER_SIZE); } if (flags & MS_SYNCHRONOUS) { Str_Strcat(mountEnt.mnt_opts, ",sync", MOUNT_OPTS_BUFFER_SIZE); } if (flags & MS_MANDLOCK) { Str_Strcat(mountEnt.mnt_opts, ",mand", MOUNT_OPTS_BUFFER_SIZE); } if (flags & MS_NOATIME) { Str_Strcat(mountEnt.mnt_opts, ",noatime", MOUNT_OPTS_BUFFER_SIZE); } if (flags & MS_NODIRATIME) { Str_Strcat(mountEnt.mnt_opts, ",nodiratime", MOUNT_OPTS_BUFFER_SIZE); } if (userName != NULL) { Str_Strcat(mountEnt.mnt_opts, ",user=", MOUNT_OPTS_BUFFER_SIZE); Str_Strcat(mountEnt.mnt_opts, userName, MOUNT_OPTS_BUFFER_SIZE); } ttlString = Str_Asprintf(NULL, "%u", mountInfo->ttl); if (ttlString != NULL) { Str_Strcat(mountEnt.mnt_opts, ",ttl=", MOUNT_OPTS_BUFFER_SIZE); Str_Strcat(mountEnt.mnt_opts, ttlString, MOUNT_OPTS_BUFFER_SIZE); free(ttlString); } else { printf("Could not allocate memory for ttl entry in mtab, " "continuing\n"); } } /* Add the entry and close. */ if (addmntent(mountFile, &mountEnt)) { printf("Could not add entry to mtab, continuing\n"); } endmntent(mountFile); if (mountEnt.mnt_opts) { free(mountEnt.mnt_opts); } } #endif /*----------------------------------------------------------------------------- * * main -- * * Main entry point. Parses the mount options received, makes a call to * mount(2), and handles the results. * * Results: * Zero on success, non-zero on failure. * * Side effects: * May mount an HGFS filesystem. * *----------------------------------------------------------------------------- */ int main(int argc, // IN char *argv[]) // IN { #ifdef VM_HAVE_MTAB Bool doMtab = TRUE; #endif char c; int i; int result = EXIT_FAILURE; int flags = 0; int mntRes = -1; char *optionString = NULL; const char *shareNameHost = NULL; const char *shareNameDir = NULL; struct stat statBuf; HgfsMountInfo mountInfo; char *canonicalizedPath = NULL; size_t pathMax; thisProgram = argv[0]; /* Compute the base name of the program, too. */ thisProgramBase = strrchr(thisProgram, '/'); if (thisProgramBase != NULL) { thisProgramBase++; } else { thisProgramBase = thisProgram; } setpwent(); if (argc < 3) { PrintUsage(); } while ((c = getopt(argc, argv, "hno:vV")) != -1) { switch (c) { case '?': case 'h': PrintUsage(); #ifdef VM_HAVE_MTAB case 'n': doMtab = FALSE; break; #endif case 'o': if (optionString == NULL) { optionString = strdup(optarg); } else { size_t newLength; char *savedString = optionString; newLength = strlen(optionString) + strlen(",") + strlen(optarg) + sizeof '\0'; optionString = realloc(optionString, newLength); if (optionString != NULL) { Str_Strcat(optionString, ",", newLength); Str_Strcat(optionString, optarg, newLength); } else { free(savedString); } } if (optionString == NULL) { printf("Error: could not allocate memory for options\n"); goto out; } break; case 'v': beVerbose = TRUE; break; case 'V': PrintVersion(); default: printf("Error: unknown mount option %c\n", c); PrintUsage(); } } LOG("Original command line: \"%s", thisProgram); for (i = 1; i < argc; i++) { LOG(" %s", argv[i]); } LOG("\"\n"); /* After getopt_long(3), optind is the first non-option argument. */ shareName = argv[optind]; mountPoint = argv[optind + 1]; /* * We canonicalize the mount point to avoid any discrepancies between the actual mount * point and the listed mount point in /etc/mtab (such discrepancies could prevent * umount(8) from removing the mount point from /etc/mtab). */ pathMax = GetPathMax(mountPoint); canonicalizedPath = malloc(pathMax * sizeof *canonicalizedPath); if (canonicalizedPath == NULL) { printf("Error: cannot allocate memory for canonicalized path, " "aborting mount\n"); goto out; } else if (!realpath(mountPoint, canonicalizedPath)) { perror("Error: cannot canonicalize mount point"); goto out; } mountPoint = canonicalizedPath; if (!ParseShareName(shareName, &shareNameHost, &shareNameDir)) { printf("Error: share name is invalid, aborting mount\n"); goto out; } mountInfo.magicNumber = HGFS_SUPER_MAGIC; mountInfo.infoSize = sizeof mountInfo; mountInfo.version = HGFS_MOUNTINFO_VERSION_2; #ifndef sun mountInfo.fmask = 0; mountInfo.dmask = 0; mountInfo.uidSet = FALSE; mountInfo.gidSet = FALSE; mountInfo.ttl = HGFS_DEFAULT_TTL; #if defined(__APPLE__) strlcpy(mountInfo.shareNameHost, shareNameHost, MAXPATHLEN); strlcpy(mountInfo.shareNameDir, shareNameDir, MAXPATHLEN); #else mountInfo.shareNameHost = shareNameHost; mountInfo.shareNameDir = shareNameDir; #endif #endif /* * Default flags which maybe modified by user passed options. */ mountInfo.flags = HGFS_MNTINFO_SERVER_INO; /* * This'll write the rest of the options into HgfsMountInfo and possibly * modify the flags. */ if (optionString && !ParseOptions(optionString, &mountInfo, &flags)) { printf("Error: could not parse options string\n"); goto out; } /* Do some sanity checks on our desired mount point. */ if (stat(mountPoint, &statBuf)) { perror("Error: cannot stat mount point"); goto out; } if (S_ISDIR(statBuf.st_mode) == 0) { printf("Error: mount point \"%s\" is not a directory\n", mountPoint); goto out; } /* * Must be root in one flavor or another. If we're suid root, only proceed * if the user owns the mountpoint. */ if (geteuid() != 0) { printf("Error: either you're not root, or %s isn't installed SUID\n", thisProgram); goto out; } else if (getuid() != 0 && (getuid() != statBuf.st_uid || (statBuf.st_mode & S_IRWXU) != S_IRWXU)) { printf("Error: for user mounts, user must own the mount point\n"); goto out; } /* Go! */ #if defined(__linux__) mntRes = mount(shareName, mountPoint, HGFS_NAME, flags, &mountInfo); #elif defined(__FreeBSD__) { struct iovec iov[] = {{"fstype", sizeof("fstype")}, {HGFS_NAME, sizeof(HGFS_NAME)}, {"target", sizeof("target")}, {shareName, strlen(shareName) + 1}, {"fspath", sizeof("fspath")}, {(void *)mountPoint, strlen(mountPoint) + 1}, {"uidSet", sizeof("uidSet")}, {&mountInfo.uidSet, sizeof(mountInfo.uidSet)}, {"uid", sizeof("uid")}, {&mountInfo.uid, sizeof(mountInfo.uid)}, {"gidSet", sizeof("gidSet")}, {&mountInfo.gidSet, sizeof(mountInfo.gidSet)}, {"gid", sizeof("gid")}, {&mountInfo.gid, sizeof(mountInfo.gid)}}; mntRes = nmount(iov, ARRAYSIZE(iov), flags); } #elif defined(__APPLE__) mntRes = mount(HGFS_NAME, mountPoint, flags, &mountInfo); #elif defined(sun) mntRes = mount(mountPoint, mountPoint, MS_DATA | flags, HGFS_NAME, &mountInfo, sizeof mountInfo); #endif if (mntRes) { perror("Error: cannot mount filesystem"); goto out; } result = EXIT_SUCCESS; #ifdef VM_HAVE_MTAB if (doMtab) { UpdateMtab(&mountInfo, flags); } #endif out: free(optionString); free(canonicalizedPath); return result; } open-vm-tools-stable-10.2.0/open-vm-tools/hgfsmounter/hgfsmounter_version.h000066400000000000000000000030571321503522500271230ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsmounter_version.h -- * * Version definitions for the HGFS mount helper application. */ #ifndef _HGFSMOUNTER_VERSION_H_ #define _HGFSMOUNTER_VERSION_H_ /* * This component's version is coupled with Tools versioning. The effect * is that the version increments with each build, and with each Tools * version bump. If and when it becomes necessary to version the component * manually, make sure that the version is bumped any time the component or * its dependencies are changed. */ #include "vm_tools_version.h" #define HGFSMOUNTER_VERSION_COMMAS TOOLS_VERSION_EXT_CURRENT_CSV #define HGFSMOUNTER_VERSION_STRING TOOLS_VERSION_EXT_CURRENT_STR #endif /* _HGFSMOUNTER_VERSION_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/000077500000000000000000000000001321503522500210445ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/COPYING000066400000000000000000000634711321503522500221120ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! open-vm-tools-stable-10.2.0/open-vm-tools/lib/Makefile.am000066400000000000000000000036051321503522500231040ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ SUBDIRS = SUBDIRS += guestRpc if HAVE_X11 SUBDIRS += appUtil endif SUBDIRS += auth SUBDIRS += backdoor if HAVE_VSOCK SUBDIRS += asyncsocket endif SUBDIRS += sslDirect SUBDIRS += pollGtk SUBDIRS += poll SUBDIRS += dataMap SUBDIRS += hashMap SUBDIRS += dict SUBDIRS += dynxdr SUBDIRS += err SUBDIRS += file SUBDIRS += foundryMsg SUBDIRS += glibUtils SUBDIRS += guestApp SUBDIRS += hgfs SUBDIRS += hgfsBd SUBDIRS += hgfsHelper SUBDIRS += hgfsServer SUBDIRS += hgfsServerManagerGuest SUBDIRS += hgfsServerPolicyGuest if HAVE_GTKMM SUBDIRS += hgfsUri endif SUBDIRS += impersonate SUBDIRS += lock SUBDIRS += message SUBDIRS += misc SUBDIRS += netUtil SUBDIRS += nicInfo SUBDIRS += panic SUBDIRS += panicDefault SUBDIRS += procMgr SUBDIRS += rpcChannel SUBDIRS += rpcIn SUBDIRS += rpcOut SUBDIRS += rpcVmx if USE_SLASH_PROC SUBDIRS += slashProc endif SUBDIRS += string SUBDIRS += stubs SUBDIRS += syncDriver SUBDIRS += system SUBDIRS += unicode SUBDIRS += user SUBDIRS += vmCheck SUBDIRS += vmSignal SUBDIRS += wiper SUBDIRS += xdg open-vm-tools-stable-10.2.0/open-vm-tools/lib/appUtil/000077500000000000000000000000001321503522500224625ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/appUtil/Makefile.am000066400000000000000000000020371321503522500245200ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2008-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libAppUtil.la libAppUtil_la_SOURCES = libAppUtil_la_SOURCES += appUtil.c libAppUtil_la_SOURCES += appUtilX11.c AM_CFLAGS = @GTK_CPPFLAGS@ open-vm-tools-stable-10.2.0/open-vm-tools/lib/appUtil/appUtil.c000066400000000000000000000045771321503522500242610ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * appUtil.c -- * * Utility functions for guest applications. */ #include "appUtil.h" #include #include #include "vmware.h" #include "appUtil.h" #include "debug.h" #include "rpcout.h" #include "str.h" /* *---------------------------------------------------------------------------- * * AppUtil_SendGuestCaps -- * * Send a list of guest capabilities to the host. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ void AppUtil_SendGuestCaps(const GuestCapabilities *caps, // IN: array of capabilities size_t numCaps, // IN: number of capabilities Bool enabled) // IN: capabilities status { char *capsStr = NULL; char *capsTemp = NULL; size_t capIdx; ASSERT(caps); ASSERT(numCaps > 0); capsStr = strdup(GUEST_CAP_FEATURES); for (capIdx = 0; capIdx < numCaps; capIdx++) { if (!capsStr) { Debug("%s: Not enough memory to create capabilities string\n", __FUNCTION__); return; } capsTemp = Str_Asprintf(NULL, "%s %d=%d", capsStr, caps[capIdx], (int)enabled); free(capsStr); capsStr = capsTemp; } if (!RpcOut_sendOne(NULL, NULL, capsStr)) { Debug("%s: could not set capabilities: older vmx?\n", __FUNCTION__); } free(capsStr); } open-vm-tools-stable-10.2.0/open-vm-tools/lib/appUtil/appUtilX11.c000066400000000000000000000601751321503522500245470ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * appUtilX11.c -- * * Utility functions to retrieve application icons. */ #define _GNU_SOURCE 1 #include #include #include #include "vmware.h" #include "str.h" #include "posix.h" #include "debug.h" #ifndef GTK2 #ifndef GTK3 #error "Gtk 2.0 or 3.0 is required" #endif #endif #include #include #include #include #include #include #include /* *----------------------------------------------------------------------------- * * AppUtilIconThemeReallyHasIcon -- * * Utility function to detect whether an icon is really available. This is necessary * because sometimes gtk_icon_theme_has_icon() lies to us... * * Results: * TRUE if the icon theme really has a usable icon, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool AppUtilIconThemeReallyHasIcon(GtkIconTheme *iconTheme, // IN const char *iconName) // IN { gint *iconSizes; Bool retval; if (!gtk_icon_theme_has_icon(iconTheme, iconName)) { return FALSE; } iconSizes = gtk_icon_theme_get_icon_sizes(iconTheme, iconName); retval = iconSizes && iconSizes[0]; g_free(iconSizes); return retval; } /* *----------------------------------------------------------------------------- * * AppUtilCollectNamedIcons -- * * Tries to find icons with a particular name (which may be a full filesystem path, * a filename with extension, or just an abstract app name). * * Results: * None. * * Side effects: * May add icons into 'pixbufs' * *----------------------------------------------------------------------------- */ static void AppUtilCollectNamedIcons(GPtrArray *pixbufs, // IN/OUT const char *iconName) // IN { char *myIconName = NULL; char *baseIconName; /* * Use the GtkIconTheme to track down any available icons for this app. */ GtkIconTheme *iconTheme = NULL; char *ctmp2; Bool foundItInTheme = FALSE; // Did we find this icon in the GtkIconTheme? Bool foundItInFile = FALSE; // Did we find this icon directly in a file? static const char *extraIconPaths[] = { "/usr/share/icons", "/usr/share/pixmaps", "/usr/local/share/pixmaps", "/usr/local/share/icons", "/opt/kde3/share/icons", "/opt/kde3/share/pixmaps", "/opt/kde4/share/icons", "/opt/kde4/share/pixmaps", "/opt/gnome/share/icons", "/opt/gnome/share/pixmaps" }; int iconNameLen; ASSERT(iconName); Debug("Collecting icons named %s\n", iconName); iconNameLen = strlen(iconName) + 1; baseIconName = g_alloca(iconNameLen); // We need to modify the name sometimes Str_Strcpy(baseIconName, iconName, iconNameLen); ctmp2 = strrchr(baseIconName, '.'); if (*baseIconName != '/' && ctmp2 && strlen(ctmp2) <= 5) { /* * If it's a plain filename that we could possibly feed into GtkIconTheme as an * icon ID, trim the file extension to turn it into an icon ID string and make * GtkIconTheme happy. */ *ctmp2 = '\0'; } iconTheme = gtk_icon_theme_get_default(); g_object_ref(G_OBJECT(iconTheme)); foundItInTheme = AppUtilIconThemeReallyHasIcon(iconTheme, baseIconName); if (!foundItInTheme) { /* * Try looking for it as a non-GtkIconTheme managed file, to deal with older * systems. */ if (iconName[0] != '/') { gchar *iconSearchName; gsize iconSearchNameSize; gboolean triedOtherExts = FALSE; char *ctmp2; int i; static const char *iconExtensions[] = { "", // MUST be first entry. ".png", ".xpm", ".gif", ".svg", }; /* * Make a local copy of iconName in case we need to search for icons with * alternate extensions. */ iconSearchNameSize = strlen(iconName) + 1; iconSearchName = g_alloca(iconSearchNameSize); g_strlcpy(iconSearchName, iconName, iconSearchNameSize); myIconName = NULL; ctmp2 = g_alloca(PATH_MAX); tryingOtherExts: for (i = 0; !myIconName && i < ARRAYSIZE(extraIconPaths); i++) { int j; if (!extraIconPaths[i]) { continue; } /* * Per Desktop Entry Specification and Icon Theme Specification, I don't * believe that the iconName, unless it's an absolute path, should include * the file extension. * * However, empirical evidence shows that -many- applications ignore that * and may specify an icon of, for example, "foo.png". We'll also handle * those special cases here. */ for (j = 0; !myIconName && j < ARRAYSIZE(iconExtensions); j++) { g_snprintf(ctmp2, PATH_MAX, "%s/%s%s", extraIconPaths[i], iconSearchName, iconExtensions[j]); if (!g_file_test(ctmp2, G_FILE_TEST_EXISTS)) { continue; } if (j != 0) { /* * Case 1: We located an icon by appending an image extension to * IconName. Success! */ myIconName = ctmp2; // Will break "i" loop. foundItInFile = TRUE; break; } else { /* * Case 2: We found an icon without appending an extension. Verify * that the filename contains a valid image extension. */ int k; char *ctmpext = strrchr(ctmp2, '.'); for (k = 1; ctmpext && k < ARRAYSIZE(iconExtensions); k++) { if (strcmp(ctmpext, iconExtensions[k]) == 0) { myIconName = ctmp2; // Will break "i" loop. foundItInFile = TRUE; break; } } } } } /* * No dice. But we won't give up hope just yet! In some cases, icon-foo.png * may not exist while icon-foo.xpm does. (Ex: Ubuntu 8.04's hwtest.) We'll * try once more by searching for an icon with an alternate extension. */ if (!foundItInFile && !triedOtherExts) { int extIndex; triedOtherExts = TRUE; /* * Look to see if iconSearchName contains any of the known extensions * listed above. If so, chop it off, then reattempt the search. */ for (extIndex = 1; extIndex < ARRAYSIZE(iconExtensions); extIndex++) { if (g_str_has_suffix(iconSearchName, iconExtensions[extIndex])) { gchar *extension; extension = g_strrstr(iconSearchName, iconExtensions[extIndex]); *extension = '\0'; goto tryingOtherExts; } } } } else { myIconName = g_alloca(iconNameLen + 1); Str_Strcpy(myIconName, iconName, iconNameLen); foundItInFile = TRUE; } } if (!foundItInTheme && !foundItInFile) { /* * Try looking through some auxiliary icon themes. */ int i; static const char *extraThemes[] = { /* * Some other icon themes to try. */ "hicolor", "Bluecurve", "HighContrast-SVG", "HighContrastLargePrint", "crystalsvg", "slick", NULL }; g_object_unref(G_OBJECT(iconTheme)); iconTheme = gtk_icon_theme_new(); for (i = 0; i < ARRAYSIZE(extraIconPaths); i++) { if (extraIconPaths[i]) { if (g_file_test(extraIconPaths[i], G_FILE_TEST_EXISTS)) { gtk_icon_theme_append_search_path(iconTheme, extraIconPaths[i]); } else { extraIconPaths[i] = NULL; } } } for (i = 0; extraThemes[i]; i++) { gtk_icon_theme_set_custom_theme(iconTheme, extraThemes[i]); foundItInTheme = AppUtilIconThemeReallyHasIcon(iconTheme, baseIconName); if (foundItInTheme) { break; } } } if (foundItInTheme) { /* * If we know this icon can be loaded via GtkIconTheme, do so. */ gint *iconSizes; int i; Bool needToUseScalable; iconSizes = gtk_icon_theme_get_icon_sizes(iconTheme, baseIconName); Debug("Loading icon %s from iconTheme\n", baseIconName); ASSERT(iconSizes); needToUseScalable = (iconSizes[0] == -1 && iconSizes[1] == 0); /* * Before we try to actually dump the icons out to the host, count how many we * actually can load. */ for (i = 0; iconSizes[i]; i++) { GdkPixbuf *pixbuf; GtkIconInfo *iconInfo; gint thisSize; thisSize = iconSizes[i]; if (thisSize == -1 && !needToUseScalable) { continue; // Skip scalable icons if we have prerendered versions } if (thisSize == -1) { thisSize = 64; // Render SVG icons to 64x64 } iconInfo = gtk_icon_theme_lookup_icon(iconTheme, baseIconName, thisSize, 0); if (!iconInfo) { Debug("Couldn't find %s icon for size %d\n", baseIconName, thisSize); continue; } pixbuf = gtk_icon_info_load_icon(iconInfo, NULL); if (!pixbuf) { pixbuf = gtk_icon_info_get_builtin_pixbuf(iconInfo); } if (pixbuf) { g_ptr_array_add(pixbufs, pixbuf); } else { Debug("WARNING: Not even a built-in pixbuf for icon %s\n", baseIconName); } gtk_icon_info_free(iconInfo); } g_free(iconSizes); } else if (foundItInFile && myIconName && myIconName[0] == '/') { GdkPixbuf *pixbuf; Debug("Loading icon %s from file\n", myIconName); pixbuf = gdk_pixbuf_new_from_file(myIconName, NULL); if (pixbuf) { g_ptr_array_add(pixbufs, pixbuf); } } if (iconTheme) { g_object_unref(G_OBJECT(iconTheme)); } } /* *----------------------------------------------------------------------------- * * AppUtilComparePixbufSizes -- * * Compares two GdkPixbufs to sort them by image dimensions * * Results: * -1 if A is larger than B, 0 if equal, 1 if A is smaller than B * * Side effects: * None. * *----------------------------------------------------------------------------- */ static gint AppUtilComparePixbufSizes(gconstpointer a, // IN gconstpointer b) // IN { GdkPixbuf *pba; GdkPixbuf *pbb; int asize; int bsize; if (a && !b) { return -1; } else if (!a && b) { return 1; } else if (!a && !b) { return 0; } pba = GDK_PIXBUF(*(gconstpointer *)a); asize = gdk_pixbuf_get_width(pba) * gdk_pixbuf_get_height(pba); pbb = GDK_PIXBUF(*(gconstpointer *)b); bsize = gdk_pixbuf_get_width(pbb) * gdk_pixbuf_get_height(pbb); if (asize > bsize) { return -1; } else if (asize < bsize) { return 1; } return 0; } /* *----------------------------------------------------------------------------- * * AppUtil_CollectIconArray -- * * Given a variety of information about an application (its icon name, X window ID, * etc.), return an array of GdkPixbufs that represent the icons for that * application. * * Results: * GPtrArray of GdkPixbufs, or NULL on failure. The returned array may have zero * elements. The array will be sorted by icon size, largest to smallest. * * Side effects: * Caller becomes owner of the array and pixbufs that are allocated during this * function. * *----------------------------------------------------------------------------- */ GPtrArray * AppUtil_CollectIconArray(const char *iconName, // IN unsigned long windowID) // IN { GPtrArray *pixbufs; pixbufs = g_ptr_array_new(); if (iconName) { AppUtilCollectNamedIcons(pixbufs, iconName); } if (!pixbufs->len && windowID != None) { /* * Try loading the icon from the X Window's _NET_WM_ICON/WM_HINTS property. */ Display *dpy; XWMHints *wmh; Atom actualType = None; int actualFormat; unsigned long nitems = 0; unsigned long bytesLeft; XID *value; XTextProperty wmIconName; dpy = gdk_x11_get_default_xdisplay(); XGetWindowProperty(dpy, windowID, XInternAtom(dpy, "_NET_WM_ICON", FALSE), 0, LONG_MAX, False, XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft, (unsigned char **)&value); if (nitems) { /* * _NET_WM_ICON: Transform ARGB data into pixbufs... */ int i; for (i = 0; i < nitems; ) { GdkPixbuf *pixbuf; int width; int height; int x; int y; int rowstride; guchar *pixels; ASSERT((nitems - i) >= 2); width = value[i]; height = value[i + 1]; i += 2; pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, width, height); if (pixbuf) { pixels = gdk_pixbuf_get_pixels(pixbuf); rowstride = gdk_pixbuf_get_rowstride(pixbuf); for (y = 0; y < height; y++) { for (x = 0; x < width && i < nitems; x++, i++) { guchar *pixel = &pixels[y * rowstride + x * 4]; XID currentValue = value[i]; /* * Input data: BGRA data (high byte is A, low byte is B - * freedesktop calls this ARGB, but that's not correct). * * Output data: RGBA data. */ *pixel = (currentValue >> 16) & 0xFF; *(pixel + 1) = (currentValue >> 8) & 0xFF; *(pixel + 2) = currentValue & 0xFF; *(pixel + 3) = (currentValue >> 24) & 0xFF; } } g_ptr_array_add(pixbufs, pixbuf); } else { Debug("gdk_pixbuf_new failed when decoding _NET_WM_ICON\n"); break; } } XFree(value); } nitems = 0; if (!pixbufs->len && XGetWindowProperty(dpy, windowID, XInternAtom(dpy, "_NET_WM_ICON_NAME", FALSE), 0, LONG_MAX, False, XInternAtom(dpy, "UTF8_STRING", FALSE), &actualType, &actualFormat, &nitems, &bytesLeft, (unsigned char **)&value) == Success && nitems) { /* * _NET_WM_ICON_NAME */ AppUtilCollectNamedIcons(pixbufs, (char *)value); XFree(value); } if (!pixbufs->len && XGetWMIconName(dpy, windowID, &wmIconName)) { /* * WM_ICON_NAME */ AppUtilCollectNamedIcons(pixbufs, wmIconName.value); XFree(wmIconName.value); } if (!pixbufs->len && (wmh = XGetWMHints(dpy, windowID))) { /* * WM_HINTS */ if (wmh->flags & IconPixmapHint) { Window dummyWin; int x; int y; unsigned int width; unsigned int height; unsigned int border; unsigned int depth; GdkPixbuf *pixbuf = NULL; if (XGetGeometry(dpy, wmh->icon_pixmap, &dummyWin, &x, &y, &width, &height, &border, &depth)) { pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, width, height); if (!gdk_pixbuf_xlib_get_from_drawable (pixbuf, wmh->icon_pixmap, DefaultColormap(dpy, 0), DefaultVisual(dpy, 0), 0, 0, 0, 0, width, height)) { g_object_unref(G_OBJECT(pixbuf)); pixbuf = NULL; } if (pixbuf && (wmh->flags & IconMaskHint)) { /* * Apply the X bitmap mask. */ GdkPixbuf *pixbuf_mask; pixbuf_mask = gdk_pixbuf_xlib_get_from_drawable(pixbuf, wmh->icon_mask, DefaultColormap(dpy, 0), DefaultVisual(dpy, 0), 0, 0, 0, 0, width, height); if (pixbuf_mask) { int x; int y; int rowstride; int rowstride_mask; guchar *pixels; guchar *pixels_mask; int depth_mask; int n_channels_mask; pixels = gdk_pixbuf_get_pixels(pixbuf); pixels_mask = gdk_pixbuf_get_pixels(pixbuf_mask); rowstride = gdk_pixbuf_get_rowstride(pixbuf); rowstride_mask = gdk_pixbuf_get_rowstride(pixbuf_mask); depth_mask = gdk_pixbuf_get_bits_per_sample(pixbuf_mask); ASSERT(gdk_pixbuf_get_bits_per_sample(pixbuf) == 8); n_channels_mask = gdk_pixbuf_get_n_channels(pixbuf_mask); for (y = 0; y < height; y++) { guchar *thisrow_mask = pixels_mask + y * rowstride_mask; guchar *thisrow = pixels + y * rowstride; for (x = 0; x < width; x++) { guchar newAlpha = 0xFF; switch(depth_mask) { case 1: newAlpha = thisrow_mask[x * n_channels_mask / 8]; newAlpha >>= (x % 8); newAlpha = newAlpha ? 0xFF : 0; break; case 8: /* * For some reason, gdk-pixbuf-xlib turns a monochrome * bitmap into 0/1 values in the blue channel of an RGBA * pixmap. */ newAlpha = (thisrow_mask[x * n_channels_mask + 2]) ? 0xFF : 0; break; default: NOT_REACHED(); break; } thisrow[x * 4 + 3] = newAlpha; } } } } if (pixbuf) { g_ptr_array_add(pixbufs, pixbuf); } } } XFree(wmh); } if (!pixbufs->len) { /* * Last resort - try using the WM_CLASS as an icon name */ XClassHint hints; if (XGetClassHint(dpy, windowID, &hints)) { if (hints.res_name) { AppUtilCollectNamedIcons(pixbufs, hints.res_name); } XFree(hints.res_name); XFree(hints.res_class); } } } /* * In order to make it easy for AppUtil users to pick the icon they want, we sort them * largest-to-smallest. */ g_ptr_array_sort(pixbufs, AppUtilComparePixbufSizes); if (!pixbufs->len) { Debug("WARNING: No icons found for %s / %#lx\n", iconName, windowID); } return pixbufs; } /* *----------------------------------------------------------------------------- * * AppUtil_FreeIconArray -- * * Frees the result of AppUtil_CollectIconArray * * Results: * None. * * Side effects: * Array and its contents are destroyed * *----------------------------------------------------------------------------- */ void AppUtil_FreeIconArray(GPtrArray *pixbufs) // IN { int i; if (!pixbufs) { return; } for (i = 0; i < pixbufs->len; i++) { g_object_unref(G_OBJECT(g_ptr_array_index(pixbufs, i))); } g_ptr_array_free(pixbufs, TRUE); } /* *----------------------------------------------------------------------------- * * AppUtil_AppIsSkippable -- * * Can an executable be ignored for the purposes of determining the path to run an * app with? Usually true for interpreters and the like, for which the script path * should be used instead. * * Results: * TRUE if the app should be ignored, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool AppUtil_AppIsSkippable(const char *appName) { static const char *skipAppsList[] = { "python", "python2.5", "python2.4", "python2.3", "python2.2", "perl", "sh", "bash", }; char cbuf[PATH_MAX]; int i; char *ctmp; Str_Strcpy(cbuf, appName, sizeof cbuf); ctmp = basename(cbuf); for (i = 0; i < ARRAYSIZE(skipAppsList); i++) { if (!strcmp(ctmp, skipAppsList[i])) { return TRUE; } } return FALSE; } /* *----------------------------------------------------------------------------- * * AppUtil_CanonicalizeAppName -- * * Turns the app name (or path) into a full path for the executable. * * Results: * Path, or NULL if not available * * Side effects: * Allocated memory is returned * *----------------------------------------------------------------------------- */ char * AppUtil_CanonicalizeAppName(const char *appName, // IN const char *cwd) // IN { char *ctmp; ASSERT(appName); if (appName[0] == '/') { ctmp = g_strdup(appName); goto exit; } ctmp = g_find_program_in_path(appName); if (ctmp) { goto exit; } /* * It's probably safe to assume that cwd is an absolute path (at the time of * writing, it is derived from /proc), but let's check to be sure. */ if (cwd && cwd[0] == '/') { /* Don't add any unnecessary path separators. */ char *cbuf = Str_Asprintf(NULL, "%s%s%s", cwd, cwd[strlen(cwd) - 1] == '/' ? "" : "/", appName); if (cbuf) { ctmp = Posix_RealPath(cbuf); free(cbuf); } } exit: return ctmp; } /* *----------------------------------------------------------------------------- * * AppUtil_Init -- * * Initializes the AppUtil library for subsequent use. * * Results: * None. * * Side effects: * Internal state is initialized. Currently this is just gdk-pixbuf-xlib. * *----------------------------------------------------------------------------- */ void AppUtil_Init(void) { gdk_pixbuf_xlib_init(gdk_x11_get_default_xdisplay(), 0); } open-vm-tools-stable-10.2.0/open-vm-tools/lib/asyncsocket/000077500000000000000000000000001321503522500233725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/asyncsocket/Makefile.am000066400000000000000000000021731321503522500254310ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2013-2017 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libAsyncSocket.la libAsyncSocket_la_SOURCES = libAsyncSocket_la_SOURCES += asyncsocket.c libAsyncSocket_la_SOURCES += asyncSocketBase.c libAsyncSocket_la_SOURCES += asyncSocketInterface.c AM_CFLAGS = AM_CFLAGS += -DUSE_SSL_DIRECT open-vm-tools-stable-10.2.0/open-vm-tools/lib/asyncsocket/asyncSocketBase.c000066400000000000000000000521041321503522500266210ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * asyncSocketBase.c -- * * This exposes the public functions of the AsyncSocket library. * This file itself just contains stubs which call the function * pointers in the socket's virtual table. * */ #include "vmware.h" #include "asyncsocket.h" #include "asyncSocketBase.h" #include "msg.h" #include "log.h" #define LOGLEVEL_MODULE asyncsocket #include "loglevel_user.h" /* * A version of ASOCKLOG() which is safe to call from inside IncRef, * DecRef or any of the other functions which the regular ASOCKLOG() * implicitly calls. We don't log fd as that isn't available at the * base class level. */ #define ASOCKLOG_NORECURSION(_level, _asock, _logargs) \ do { \ if (((_level) == 0) || DOLOG_BYNAME(asyncsocket, (_level))) { \ Log(ASOCKPREFIX "%d ", (_asock)->id); \ Log _logargs; \ } \ } while(0) /* *----------------------------------------------------------------------------- * * AsyncSocketInternalIncRef -- * * Increments reference count on AsyncSocket struct and optionally * takes the lock. This function is used to implement both Lock * and AddRef. * * Results: * New reference count. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE void AsyncSocketInternalIncRef(AsyncSocket *asock, // IN Bool lock) // IN { if (lock && asock->pollParams.lock) { MXUser_AcquireRecLock(asock->pollParams.lock); } ASSERT(asock->refCount > 0); ++asock->refCount; } /* *----------------------------------------------------------------------------- * * AsyncSocketInternalDecRef -- * * Decrements reference count on AsyncSocket struct, freeing it when it * reaches 0. If "unlock" is TRUE, releases the lock after decrementing * the count. * * This function is used to implement both Unlock and DecRef. * * Results: * None. * * Side effects: * May free struct. * *----------------------------------------------------------------------------- */ static INLINE void AsyncSocketInternalDecRef(AsyncSocket *s, // IN Bool unlock) // IN { int count = --s->refCount; if (unlock && s->pollParams.lock) { MXUser_ReleaseRecLock(s->pollParams.lock); } ASSERT(count >= 0); if (UNLIKELY(count == 0)) { ASOCKLOG_NORECURSION(1, s, ("Final release; freeing asock struct\n")); VT(s)->destroy(s); } else { ASOCKLOG_NORECURSION(1, s, ("Release (count now %d)\n", count)); } } /* *---------------------------------------------------------------------------- * * AsyncSocketLock -- * AsyncSocketUnlock -- * * Acquire/Release the lock provided by the client when creating the * AsyncSocket object. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ void AsyncSocketLock(AsyncSocket *asock) // IN: { AsyncSocketInternalIncRef(asock, TRUE); } void AsyncSocketUnlock(AsyncSocket *asock) // IN: { AsyncSocketInternalDecRef(asock, TRUE); } /* *---------------------------------------------------------------------------- * * AsyncSocketIsLocked -- * * If a lock is associated with the socket, check whether the calling * thread holds the lock. * * Results: * TRUE if calling thread holds the lock, or if there is no assoicated * lock. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool AsyncSocketIsLocked(AsyncSocket *asock) // IN: { if (asock->pollParams.lock && Poll_LockingEnabled()) { return MXUser_IsCurThreadHoldingRecLock(asock->pollParams.lock); } return TRUE; } /* *----------------------------------------------------------------------------- * * AsyncSocketAddRef -- * * Increments reference count on AsyncSocket struct. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void AsyncSocketAddRef(AsyncSocket *s) // IN { AsyncSocketInternalIncRef(s, FALSE); } /* *----------------------------------------------------------------------------- * * AsyncSocketRelease -- * * Decrements reference count on AsyncSocket struct, freeing it when it * reaches 0. If "unlock" is TRUE, releases the lock after decrementing * the count. * * Results: * None. * * Side effects: * May free struct. * *----------------------------------------------------------------------------- */ void AsyncSocketRelease(AsyncSocket *s) // IN: { AsyncSocketInternalDecRef(s, FALSE); } /* *---------------------------------------------------------------------------- * * AsyncSocketGetState -- * * Accessor function for the state in the base class. * *---------------------------------------------------------------------------- */ AsyncSocketState AsyncSocketGetState(AsyncSocket *asock) // IN { ASSERT(AsyncSocketIsLocked(asock)); return asock->state; } /* *---------------------------------------------------------------------------- * * AsyncSocketSetState -- * * Modifier function for the state in the base class. * *---------------------------------------------------------------------------- */ void AsyncSocketSetState(AsyncSocket *asock, // IN/OUT AsyncSocketState state) // IN { asock->state = state; } /* *----------------------------------------------------------------------------- * * AsyncSocketGetPollParams -- * * Accessor function for the pollParams struct in the base socket. * *----------------------------------------------------------------------------- */ AsyncSocketPollParams * AsyncSocketGetPollParams(AsyncSocket *s) // IN { return &s->pollParams; } /* *----------------------------------------------------------------------------- * * AsyncSocketInitSocket -- * * Initialize the AsyncSocket base struct. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void AsyncSocketInitSocket(AsyncSocket *s, // IN/OUT AsyncSocketPollParams *pollParams, // IN const AsyncSocketVTable *vtable) // IN { /* * The sockets each have a "unique" ID, which is just an * incrementing integer. */ static Atomic_uint32 nextid = { 1 }; s->id = Atomic_ReadInc32(&nextid); s->refCount = 1; s->vt = vtable; s->inited = TRUE; if (pollParams) { s->pollParams = *pollParams; } else { s->pollParams.pollClass = POLL_CS_MAIN; s->pollParams.flags = 0; s->pollParams.lock = NULL; s->pollParams.iPoll = NULL; } } /* *----------------------------------------------------------------------------- * * AsyncSocketTeardownSocket -- * * Tear down the AsyncSocket base struct. Currently this just * clears the inited flag and releases the initial (user) refcount. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void AsyncSocketTeardownSocket(AsyncSocket *asock) // IN/OUT { /* * Release the initial refcount created when we initialize the * socket struct. */ ASSERT(AsyncSocketIsLocked(asock)); ASSERT(asock->refCount >= 1); ASSERT(asock->inited); asock->inited = FALSE; AsyncSocketRelease(asock); } /* *---------------------------------------------------------------------------- * * AsyncSocket_Init -- * * Initialize the various socket subsytems. Currently just TCP, this * will expand. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * See subsystems. * *---------------------------------------------------------------------------- */ int AsyncSocket_Init(void) { return AsyncTCPSocket_Init(); } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetID -- * * Returns a unique identifier for the asock. * * Results: * Integer id or ASOCKERR_INVAL. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_GetID(AsyncSocket *asock) // IN { if (!asock) { return ASOCKERR_INVAL; /* For some reason we return ID 5 for null pointers! */ } else { return asock->id; } } /* *---------------------------------------------------------------------------- * * AsyncSocket_SetErrorFn -- * * Sets the error handling function for the asock. The error function * is invoked automatically on I/O errors. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_INVAL. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_SetErrorFn(AsyncSocket *asock, // IN/OUT AsyncSocketErrorFn errorFn, // IN void *clientData) // IN { if (!asock) { return ASOCKERR_INVAL; } else { AsyncSocketLock(asock); asock->errorFn = errorFn; asock->errorClientData = clientData; AsyncSocketUnlock(asock); return ASOCKERR_SUCCESS; } } /* *---------------------------------------------------------------------------- * * AsyncSocketHandleError -- * * Internal error handling helper. Changes the socket's state to error, * and calls the registered error handler or closes the socket. * * Results: * None. * * Side effects: * Lots. * *---------------------------------------------------------------------------- */ void AsyncSocketHandleError(AsyncSocket *asock, // IN int asockErr) // IN { ASSERT(asock); asock->errorSeen = TRUE; if (asock->errorFn) { ASOCKLOG(3, asock, ("firing error callback (%s)\n", AsyncSocket_Err2String(asockErr))); asock->errorFn(asockErr, asock, asock->errorClientData); } else { ASOCKLOG(3, asock, ("no error callback, closing socket (%s)\n", AsyncSocket_Err2String(asockErr))); AsyncSocket_Close(asock); } } /* *---------------------------------------------------------------------------- * * AsyncSocketCheckAndDispatchRecv -- * * Check if the recv buffer is full and dispatch the client callback. * * Handles the possibility that the client registers a new receive buffer * or closes the socket in their callback. * * Results: * TRUE if the socket was closed or the receive was cancelled, * FALSE if the caller should continue to try to receive data. * * Side effects: * Could fire recv completion or trigger socket destruction. * *---------------------------------------------------------------------------- */ Bool AsyncSocketCheckAndDispatchRecv(AsyncSocket *s, // IN int *result) // OUT { ASSERT(s); ASSERT(result); ASSERT(s->recvFn); ASSERT(s->recvBuf); ASSERT(s->recvLen > 0); ASSERT(s->recvPos > 0); ASSERT(s->recvPos <= s->recvLen); /* * The application may close the socket in this callback. This * asserts that even if that happens, the socket will not be * immediately freed in the middle of our function. */ ASSERT(s->refCount > 1); if (s->recvPos == s->recvLen || s->recvFireOnPartial) { void *recvBuf = s->recvBuf; ASOCKLOG(3, s, ("recv buffer full, calling recvFn\n")); /* * We do this dance in case the handler frees the buffer (so * that there's no possible window where there are dangling * references here. Obviously if the handler frees the buffer, * but them fails to register a new one, we'll put back the * dangling reference in the automatic reset case below, but * there's currently a limit to how far we go to shield clients * who use our API in a broken way. */ s->recvBuf = NULL; s->recvFn(recvBuf, s->recvPos, s, s->recvClientData); if (s->state == AsyncSocketClosed) { ASOCKLG0(s, ("owner closed connection in recv callback\n")); *result = ASOCKERR_CLOSED; return TRUE; } else if (s->recvFn == NULL && s->recvLen == 0) { /* * Further recv is cancelled from within the last recvFn, see * AsyncSocket_CancelRecv(). So exit from the loop. */ *result = ASOCKERR_SUCCESS; return TRUE; } else if (s->recvPos > 0) { /* * Automatically reset keeping the current handler. Checking * that recvPos is still non-zero implies that the * application has not called AsyncSocket_Recv or * _RecvPartial in the callback. */ s->recvPos = 0; s->recvBuf = recvBuf; *result = ASOCKERR_SUCCESS; return FALSE; } else { *result = ASOCKERR_SUCCESS; return FALSE; } } else { *result = ASOCKERR_SUCCESS; return FALSE; } } /* *---------------------------------------------------------------------------- * * AsyncSocketSetRecvBuf -- * * Helper function to validate socket state and recvBuf * parameters before setting the recvBuf values in the base * class. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_*. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocketSetRecvBuf(AsyncSocket *asock, // IN: void *buf, // IN: int len, // IN: Bool fireOnPartial, // IN: void *cb, // IN: void *cbData) // IN: { ASSERT(AsyncSocketIsLocked(asock)); if (!asock->errorFn) { ASOCKWARN(asock, ("%s: no registered error handler!\n", __FUNCTION__)); return ASOCKERR_INVAL; } if (!buf || !cb || len <= 0) { ASOCKWARN(asock, ("Recv called with invalid arguments!\n")); return ASOCKERR_INVAL; } if (AsyncSocketGetState(asock) != AsyncSocketConnected) { ASOCKWARN(asock, ("recv called but state is not connected!\n")); return ASOCKERR_NOTCONNECTED; } if (asock->recvBuf && asock->recvPos != 0) { ASOCKWARN(asock, ("Recv called -- partially read buffer discarded.\n")); } asock->recvBuf = buf; asock->recvLen = len; asock->recvFireOnPartial = fireOnPartial; asock->recvFn = cb; asock->recvClientData = cbData; asock->recvPos = 0; return ASOCKERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * WebSocketCancelRecv -- * * Call this function if you know what you are doing. This should * be called if you want to synchronously receive the outstanding * data on the socket. It returns number of partially read bytes * (if any). A partially read response may exist as * AsyncSocketRecvCallback calls the recv callback only when all * the data has been received. * * Results: * None * * Side effects: * Subsequent client call to AsyncSocket_Recv can reinstate async behaviour. * *----------------------------------------------------------------------------- */ void AsyncSocketCancelRecv(AsyncSocket *asock, // IN int *partialRecvd, // OUT void **recvBuf, // OUT void **recvFn) // IN { if (partialRecvd) { *partialRecvd = asock->recvPos; } if (recvFn) { *recvFn = asock->recvFn; } if (recvBuf) { *recvBuf = asock->recvBuf; } asock->recvBuf = NULL; asock->recvFn = NULL; asock->recvPos = 0; asock->recvLen = 0; } /* *---------------------------------------------------------------------------- * * AsyncSocket_Err2String -- * * Returns the error string associated with error code. * * Results: * Error string. * * Side effects: * None. * *---------------------------------------------------------------------------- */ const char * AsyncSocket_Err2String(int err) // IN { return Msg_StripMSGID(AsyncSocket_MsgError(err)); } /* *---------------------------------------------------------------------------- * * AsyncSocket_MsgError -- * * Returns the message associated with error code. * * Results: * Message string. * * Side effects: * None. * *---------------------------------------------------------------------------- */ const char * AsyncSocket_MsgError(int asyncSockError) // IN { const char *result = NULL; switch (asyncSockError) { case ASOCKERR_SUCCESS: result = MSGID(asyncsocket.success) "Success"; break; case ASOCKERR_GENERIC: result = MSGID(asyncsocket.generic) "Asyncsocket error"; break; case ASOCKERR_INVAL: result = MSGID(asyncsocket.invalid) "Invalid parameters"; break; case ASOCKERR_TIMEOUT: result = MSGID(asyncsocket.timeout) "Time-out error"; break; case ASOCKERR_NOTCONNECTED: result = MSGID(asyncsocket.notconnected) "Local socket not connected"; break; case ASOCKERR_REMOTE_DISCONNECT: result = MSGID(asyncsocket.remotedisconnect) "Remote disconnected"; break; case ASOCKERR_CLOSED: result = MSGID(asyncsocket.closed) "Closed socket"; break; case ASOCKERR_CONNECT: result = MSGID(asyncsocket.connect) "Connection error"; break; case ASOCKERR_POLL: result = MSGID(asyncsocket.poll) "Poll registration error"; break; case ASOCKERR_BIND: result = MSGID(asyncsocket.bind) "Socket bind error"; break; case ASOCKERR_BINDADDRINUSE: result = MSGID(asyncsocket.bindaddrinuse) "Socket bind address already in use"; break; case ASOCKERR_LISTEN: result = MSGID(asyncsocket.listen) "Socket listen error"; break; case ASOCKERR_CONNECTSSL: result = MSGID(asyncsocket.connectssl) "Connection error: could not negotiate SSL"; break; case ASOCKERR_NETUNREACH: result = MSGID(asyncsocket.netunreach) "Network unreachable"; break; case ASOCKERR_ADDRUNRESV: result = MSGID(asyncsocket.addrunresv) "Address unresolvable"; break; case ASOCKERR_BUSY: result = MSGID(asyncsocket.busy) "Concurrent operations on socket"; } if (!result) { Warning("%s was passed bad code %d\n", __FUNCTION__, asyncSockError); result = MSGID(asyncsocket.unknown) "Unknown error"; } return result; } /** *----------------------------------------------------------------------------- * * stristr -- * * Do you know strstr from ? * So this one is the same, but without the case sensitivity. * * Results: * return a pointer to the first occurrence of needle in haystack, * or NULL if needle does not appear in haystack. If needle is zero * length, the function returns haystack. * * Side effects: * none * *----------------------------------------------------------------------------- */ const char * stristr(const char *haystack, // IN const char *needle) // IN { if (*needle) { int len = strlen(needle); for (; *haystack; haystack++) { if (strncasecmp(haystack, needle, len) == 0) { return haystack; } } return NULL; } else { return haystack; } } open-vm-tools-stable-10.2.0/open-vm-tools/lib/asyncsocket/asyncSocketBase.h000066400000000000000000000060721321503522500266310ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2011,2014-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #ifndef __ASYNC_SOCKET_BASE_H__ #define __ASYNC_SOCKET_BASE_H__ #ifdef USE_SSL_DIRECT #include "sslDirect.h" #else #include "ssl.h" #endif #include "asyncSocketVTable.h" /* * The abstract base class for all asyncsocket implementations. */ struct AsyncSocket { uint32 id; uint32 refCount; AsyncSocketPollParams pollParams; AsyncSocketState state; Bool inited; Bool errorSeen; AsyncSocketErrorFn errorFn; void *errorClientData; void *recvBuf; int recvPos; int recvLen; AsyncSocketRecvFn recvFn; void *recvClientData; Bool recvFireOnPartial; const AsyncSocketVTable *vt; }; void AsyncSocketInitSocket(AsyncSocket *asock, AsyncSocketPollParams *params, const AsyncSocketVTable *vtable); void AsyncSocketTeardownSocket(AsyncSocket *s); void AsyncSocketLock(AsyncSocket *asock); void AsyncSocketUnlock(AsyncSocket *asock); Bool AsyncSocketIsLocked(AsyncSocket *asock); void AsyncSocketAddRef(AsyncSocket *asock); void AsyncSocketRelease(AsyncSocket *s); AsyncSocketState AsyncSocketGetState(AsyncSocket *sock); void AsyncSocketSetState(AsyncSocket *sock, AsyncSocketState state); int AsyncSocketSetRecvBuf(AsyncSocket *asock, void *buf, int len, Bool fireOnPartial, void *cb, void *cbData); Bool AsyncSocketCheckAndDispatchRecv(AsyncSocket *s, int *result); AsyncSocketPollParams *AsyncSocketGetPollParams(AsyncSocket *s); void AsyncSocketHandleError(AsyncSocket *asock, int asockErr); void AsyncSocketCancelRecv(AsyncSocket *asock, int *partialRecvd, void **recvBuf, void **recvFn); int AsyncTCPSocket_Init(void); #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/asyncsocket/asyncSocketInterface.c000066400000000000000000001442401321503522500276520ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2016-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * asyncSocketInterface.c -- * * This exposes the public functions of the AsyncSocket library. * This file itself just contains stubs which call the function * pointers in the socket's virtual table. * * Which entrypoints are virtual and which are base functionality? * Guidelines: * - functions affecting the underlying transport (e.g. TCP timeouts) * are backend-specific and generally ARE virtualized. * - functions with an immediate effect (e.g. queue bytes for send) * generally ARE virtualized. * - functions affecting the socket abstraction (e.g. how it reports errors * to the caller) are basic functionality and generally are NOT virtualized. * - functions affecting state which is queried later (e.g. close behavior) * generally are NOT virtualized. */ #ifdef _WIN32 #include #else #include #include #include #endif #include "vmware.h" #include "asyncsocket.h" #include "asyncSocketBase.h" #include "msg.h" #include "log.h" #define LOGLEVEL_MODULE asyncsocket #include "loglevel_user.h" /* *---------------------------------------------------------------------------- * * AsyncSocket_SetCloseOptions -- * * Enables optional behavior for AsyncSocket_Close(): * * - If flushEnabledMaxWaitMsec is non-zero, the output stream * will be flushed synchronously before the socket is closed. * (default is zero: close socket right away without flushing) * * - If closeCb is set, the callback will be called asynchronously * when the socket is actually destroyed. * (default is NULL: no callback) * * Results: * ASOCKERR_SUCCESS or ASOCKERR_*. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_SetCloseOptions(AsyncSocket *asock, // IN int flushEnabledMaxWaitMsec, // IN AsyncSocketCloseFn closeCb) // IN { int ret; if (VALID(asock, setCloseOptions)) { AsyncSocketLock(asock); ret = VT(asock)->setCloseOptions(asock, flushEnabledMaxWaitMsec, closeCb); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetState -- * * Returns the state of the provided asock or ASOCKERR_INVAL. Note that * unless this is called from a callback function, the state should be * treated as transient (except the state AsyncSocketClosed). * * Results: * AsyncSocketState enum. * * Side effects: * None. * *---------------------------------------------------------------------------- */ AsyncSocketState AsyncSocket_GetState(AsyncSocket *asock) // IN { AsyncSocketState ret; if (VALID(asock, getState)) { AsyncSocketLock(asock); ret = VT(asock)->getState(asock); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetGenericErrno -- * * Used when an ASOCKERR_GENERIC is returned due to a system error. * The errno that was returned by the system is stored in the asock * struct and returned to the user in this function. * * XXX: This function is not thread-safe. The errno should be returned * in a parameter to any function that can return ASOCKERR_GENERIC. * * Results: * int error code * * Side effects: * None * *---------------------------------------------------------------------------- */ int AsyncSocket_GetGenericErrno(AsyncSocket *asock) // IN: { int ret; if (VALID(asock, getGenericErrno)) { AsyncSocketLock(asock); ret = VT(asock)->getGenericErrno(asock); AsyncSocketUnlock(asock); } else { ret = -1; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetFd -- * * Returns the fd for this socket. * * Results: * File descriptor. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_GetFd(AsyncSocket *asock) // IN { int ret; if (VALID(asock, getFd)) { AsyncSocketLock(asock); ret = VT(asock)->getFd(asock); AsyncSocketUnlock(asock); } else { ret = -1; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetRemoteIPStr -- * * Given an AsyncSocket object, returns the remote IP address associated * with it, or an error if the request is meaningless for the underlying * connection. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_INVAL. * * Side effects: * * *---------------------------------------------------------------------------- */ int AsyncSocket_GetRemoteIPStr(AsyncSocket *asock, // IN const char **ipRetStr) // OUT { int ret; if (VALID(asock, getRemoteIPStr)) { AsyncSocketLock(asock); ret = VT(asock)->getRemoteIPStr(asock, ipRetStr); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetINETIPStr -- * * Given an AsyncSocket object, returns the IP addresses associated with * the requested address family's file descriptor if available. * * Passing AF_UNSPEC to socketFamily will provide you with the first * usable IP address found (if multiple are available), with a preference * given to IPv6. * * It is the caller's responsibility to free ipRetStr. * * Results: * ASOCKERR_SUCCESS. ASOCKERR_INVAL if there is no socket associated with * address family requested. ASOCKERR_GENERIC for all other errors. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_GetINETIPStr(AsyncSocket *asock, // IN int socketFamily, // IN char **ipRetStr) // OUT { int ret; if (VALID(asock, getINETIPStr)) { AsyncSocketLock(asock); ret = VT(asock)->getINETIPStr(asock, socketFamily, ipRetStr); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetPort -- * * Given an AsyncSocket object, returns the port number associated with * the requested address family's file descriptor if available. * * Results: * Port number in host byte order. MAX_UINT32 on error. * * Side effects: * None. * *---------------------------------------------------------------------------- */ unsigned int AsyncSocket_GetPort(AsyncSocket *asock) // IN { int ret; if (VALID(asock, getPort)) { AsyncSocketLock(asock); ret = VT(asock)->getPort(asock); AsyncSocketUnlock(asock); } else { ret = MAX_UINT32; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_UseNodelay -- * * THIS IS DEPRECATED in favor of AsyncSocket_SetOption(...TCP_NODELAY...). * It exists for now to avoid having to change all existing calling code. * TODO: Remove it fully and fix up all calling code accordingly. * * Sets the setsockopt() value TCP_NODELAY. * asyncSocket may be an AsyncTCPSocket itself * or contain one on which the option will be set. * * This fails if there is no applicable AsyncTCPSocket (asyncSocket or * one inside it). * * Results: * ASOCKERR_SUCCESS on success, ASOCKERR_* otherwise. * There being no applicable AsyncTCPSocket yields ASOCKERR_INVAL. * OS error when setting value yields ASOCKERR_GENERIC. * * Side effects: * Possibly increased bandwidth usage for short messages on this socket * due to TCP overhead, in exchange for lower latency. * *---------------------------------------------------------------------------- */ int AsyncSocket_UseNodelay(AsyncSocket *asyncSocket, // IN/OUT Bool noDelay) // IN { const int noDelayNative = noDelay ? 1 : 0; return AsyncSocket_SetOption(asyncSocket, IPPROTO_TCP, TCP_NODELAY, &noDelayNative, sizeof noDelayNative); } /* *---------------------------------------------------------------------------- * * AsyncSocket_SetTCPTimeouts -- * * Sets setsockopt() TCP_KEEP{INTVL|IDLE|CNT} if available in the OS. * asyncSocket may be an AsyncTCPSocket itself * or contain one on which the option will be set. * * This fails if there is no applicable AsyncTCPSocket (asyncSocket or * one inside it). * * Results: * ASOCKERR_SUCCESS if no error, or OS doesn't support options. * There being no applicable AsyncTCPSocket yields ASOCKERR_INVAL. * OS error when setting any one value yields ASOCKERR_GENERIC. * * Side effects: * None. * Note that in case of error ASOCKERR_GENERIC, 0, 1, or 2 of the values * may have still been successfully set (the successful changes are * not rolled back). * *---------------------------------------------------------------------------- */ int AsyncSocket_SetTCPTimeouts(AsyncSocket *asyncSocket, // IN/OUT int keepIdleSec, // IN int keepIntvlSec, // IN int keepCnt) // IN { /* * This function is NOT deprecated like the nearby setOption()-wrapping * functions. It's valuable because it: enapsulates OS-dependent logic; and * performs one lock before settong all applicable options together. */ #if defined(__linux__) || defined(VMX86_SERVER) /* * Tempting to call AsyncSocket_SetOption() x 3 instead of worrying about * locking and VT() ourselves, but this way we can reduce amount of * locking/unlocking at the cost of code verbosity. * * Reason for bailing on first error instead of trying all three: * it's what the original code (that this adapts) did. TODO: Find out from * author, explain here. */ int ret; if (VALID(asyncSocket, setOption)) { AsyncSocketLock(asyncSocket); ret = VT(asyncSocket)->setOption (asyncSocket, IPPROTO_TCP, TCP_KEEPIDLE, &keepIdleSec, sizeof keepIdleSec); if (ret == ASOCKERR_SUCCESS) { ret = VT(asyncSocket)->setOption (asyncSocket, IPPROTO_TCP, TCP_KEEPINTVL, &keepIntvlSec, sizeof keepIntvlSec); if (ret == ASOCKERR_SUCCESS) { ret = VT(asyncSocket)->setOption (asyncSocket, IPPROTO_TCP, TCP_KEEPCNT, &keepCnt, sizeof keepCnt); } } AsyncSocketUnlock(asyncSocket); } else { ret = ASOCKERR_INVAL; } return ret; #else // #ifndef __linux__ return ASOCKERR_SUCCESS; #endif } /* *----------------------------------------------------------------------------- * * AsyncSocket_EstablishMinBufferSizes -- * * Meant to be invoked around socket creation time, this tries to ensure * that SO_{SND|RCV}BUF setsockopt() values are set to at least the values * provided as arguments. That is, it sets the given buffer size but only * if the current value reported by the OS is smaller. * * This fails unless asyncSocket is of the "applicable socket type." * Being of "applicable socket type" is defined as supporting the * option: * * layer = SOL_SOCKET, * optID = SO_{SND|RCV}BUF. * * As of this writing, only AsyncTCPSockets (or derivations thereof) * are supported, but (for example) UDP sockets could be added over time. * * Results: * TRUE: on success; FALSE: on failure. * Determining that no setsockopt() is required is considered success. * * Side effects: * None. * Note that in case of a setsockopt() failing, 0 or 1 of the values * may have still been successfully set (the successful changes are * not rolled back). * *----------------------------------------------------------------------------- */ Bool AsyncSocket_EstablishMinBufferSizes(AsyncSocket *asyncSocket, // IN/OUT int sendSz, // IN int recvSz) // IN { Bool ok; if (VALID(asyncSocket, setOption)) { int curSendSz; socklen_t curSendSzSz = sizeof curSendSz; int curRecvSz; socklen_t curRecvSzSz = sizeof curRecvSz; AsyncSocketLock(asyncSocket); /* * For each buffer size, see if the current reported size is already * at least as large (in which case we needn't do anything for that one). * Bail out the moment anything fails, but don't worry about undoing any * change already made (as advertised in doc comment). * * Reason for bailing on first error instead of trying everything: * it's what the original code (that this adapts) did. TODO: Find out from * author, explain here. * * Note that depending on the type of socket and the particular * implementation (e.g., the TCP stack), asking for buffer size N might * result in an even larger buffer, like a multiple 2N. It's not an exact * science. */ ok = (VT(asyncSocket)->getOption(asyncSocket, SOL_SOCKET, SO_SNDBUF, &curSendSz, &curSendSzSz) == ASOCKERR_SUCCESS) && (VT(asyncSocket)->getOption(asyncSocket, SOL_SOCKET, SO_RCVBUF, &curRecvSz, &curRecvSzSz) == ASOCKERR_SUCCESS); if (ok && (curSendSz < sendSz)) { ok = VT(asyncSocket)->setOption(asyncSocket, SOL_SOCKET, SO_SNDBUF, &sendSz, sizeof sendSz) == ASOCKERR_SUCCESS; } if (ok && (curRecvSz < recvSz)) { ok = VT(asyncSocket)->setOption(asyncSocket, SOL_SOCKET, SO_RCVBUF, &recvSz, sizeof recvSz) == ASOCKERR_SUCCESS; } AsyncSocketUnlock(asyncSocket); } else { ok = FALSE; } return ok; } /* *---------------------------------------------------------------------------- * * AsyncSocket_SetSendLowLatencyMode -- * * THIS IS DEPRECATED in favor of * AsyncSocket_SetOption(ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE). * It exists for now to avoid having to change all existing calling code. * TODO: Remove it fully and fix up all calling code accordingly. * * Sets the aforementioned value. See doc comment on * ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE for more info. * * This fails unless asyncSocket is of the "applicable socket type." * Being of "applicable socket type" is defined as supporting the * option: * * layer = ASYNC_SOCKET_OPTS_LAYER_BASE, * optID = ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE. * * Results: * ASOCKERR_SUCCESS on success, ASOCKERR_* otherwise. * asyncSocket being of inapplicable socket type yields ASOCKERR_INVAL. * * Side effects: * See ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE doc comment. * *---------------------------------------------------------------------------- */ int AsyncSocket_SetSendLowLatencyMode(AsyncSocket *asyncSocket, // IN Bool enable) // IN { int ret; if (VALID(asyncSocket, setOption)) { AsyncSocketLock(asyncSocket); ret = VT(asyncSocket)->setOption (asyncSocket, ASYNC_SOCKET_OPTS_LAYER_BASE, ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE, &enable, sizeof enable); AsyncSocketUnlock(asyncSocket); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_SetOption -- * * Sets the value of the given socket option belonging to the given * option layer to the given value. The socket options mechanism is * discussed in more detail in asyncsocket.h. * * The exact behavior and supported options are dependent on the socket * type. See the doc header for the specific implementation for details. * If ->setOption is NULL, all options are invalid for that socket. * Setting an invalid layer+option results in a no-op + error result. * * For native options, layer = setsockopt() level, * optID = setsockopt() option_name. * * For non-native options, optID is obtained as follows: it is converted * from an enum option ID value for your socket type; for example, * from ASYNC_TCP_SOCKET_OPT_ALLOW_DECREASING_BUFFER_SIZE, * where the latter is of type AsyncTCPSocket_OptID. * * The option's value must reside at the buffer valuePtr that is * inBufLen long. If inBufLen does not match the expected size for * the given option, behavior is undefined. * * Results: * ASOCKERR_SUCCESS on success, ASOCKERR_* otherwise. * Invalid option+layer yields ASOCKERR_INVAL. * Failure to set a native OS option yields ASOCKERR_GENERIC. * inBufLen being wrong (for the given option) yields undefined behavior. * * Side effects: * Depends on option. * *---------------------------------------------------------------------------- */ int AsyncSocket_SetOption(AsyncSocket *asyncSocket, // IN/OUT AsyncSocketOpts_Layer layer, // IN AsyncSocketOpts_ID optID, // IN const void *valuePtr, // IN socklen_t inBufLen) // IN { int ret; /* * Lacking a setOption() implementation is conceptually the same as * ->setOption() existing but determining layer+optID to be invalid * (ASOCKERR_INVAL results). */ if (VALID(asyncSocket, setOption)) { AsyncSocketLock(asyncSocket); ret = VT(asyncSocket)->setOption(asyncSocket, layer, optID, valuePtr, inBufLen); AsyncSocketUnlock(asyncSocket); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetOption -- * * Gets the value of the given socket option belonging to the given * option layer. The socket options mechanism is * discussed in more detail in asyncsocket.h. * This is generally symmetrical to ..._SetOption(); most comments applying * to that function apply to this one in common-sense ways. * In particular a layer+optID combo is supported here if and only if it * is supported for ..._SetOption(). * * The length of the output buffer at valuePtr must reside at *outBufLen * at entry to this function. If *outBufLen does not match or exceed the * expected size for the given option, behavior is undefined. * At successful return from function, *outBufLen will be set to the * length of the value written to at valuePtr. * * Results: * ASOCKERR_SUCCESS on success, ASOCKERR_* otherwise. * Invalid option+layer yields ASOCKERR_INVAL. * Failure to get a native OS option yields ASOCKERR_GENERIC. * *outBufLen being wrong (for the given option) yields undefined behavior. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_GetOption(AsyncSocket *asyncSocket, // IN/OUT AsyncSocketOpts_Layer layer, // IN AsyncSocketOpts_ID optID, // IN void *valuePtr, // OUT socklen_t *outBufLen) // IN/OUT { int ret; /* * Lacking a getOption() implementation is conceptually the same as * ->getOption() existing but determining layer+optID to be invalid * (ASOCKERR_INVAL results). */ if (VALID(asyncSocket, getOption)) { AsyncSocketLock(asyncSocket); ret = VT(asyncSocket)->getOption(asyncSocket, layer, optID, valuePtr, outBufLen); AsyncSocketUnlock(asyncSocket); } else { ret = ASOCKERR_INVAL; } return ret; } /* *----------------------------------------------------------------------------- * * AsyncSocket_StartSslConnect -- * * Start an asynchronous SSL connect operation. * * The supplied callback function is called when the operation is complete * or an error occurs. The caller should only free the verifyParam argument * after the sslConnectFn callback is called. * * Results: * ASOCKERR_SUCCESS indicates we have started async connect. * ASOCKERR_* indicates a failure to start the connect. * * Errors during asynchronous processing is reported using the * callback supplied. Detailed SSL verification error can be * retrieved from verifyParam structure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ int AsyncSocket_StartSslConnect(AsyncSocket *asock, // IN SSLVerifyParam *verifyParam, // IN/OPT void *sslCtx, // IN AsyncSocketSslConnectFn sslConnectFn, // IN void *clientData) // IN { int ret; if (VALID(asock, startSslConnect)) { AsyncSocketLock(asock); ret = VT(asock)->startSslConnect(asock, verifyParam, sslCtx, sslConnectFn, clientData); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *----------------------------------------------------------------------------- * * AsyncSocket_ConnectSSL -- * * Initialize the socket's SSL object, by calling SSL_ConnectAndVerify. * NOTE: This call is blocking. * * Results: * TRUE if SSL_ConnectAndVerify succeeded, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool AsyncSocket_ConnectSSL(AsyncSocket *asock, // IN SSLVerifyParam *verifyParam, // IN/OPT void *sslContext) // IN/OPT { Bool ret; if (VALID(asock, connectSSL)) { AsyncSocketLock(asock); ret = VT(asock)->connectSSL(asock, verifyParam, sslContext); AsyncSocketUnlock(asock); } else { ret = FALSE; } return ret; } /* *----------------------------------------------------------------------------- * * AsyncSocket_AcceptSSL -- * * Initialize the socket's SSL object, by calling SSL_Accept. * * Results: * TRUE if SSL_Accept succeeded, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool AsyncSocket_AcceptSSL(AsyncSocket *asock, // IN void *sslCtx) // IN: optional { Bool ret; if (VALID(asock, acceptSSL)) { AsyncSocketLock(asock); ret = VT(asock)->acceptSSL(asock, sslCtx); AsyncSocketUnlock(asock); } else { ret = FALSE; } return ret; } /* *----------------------------------------------------------------------------- * * AsyncSocket_StartSslAccept -- * * Start an asynchronous SSL accept operation. * * The supplied callback function is called when the operation is complete * or an error occurs. * * Results: * ASOCKERR_SUCCESS indicates we have started async accept. * ASOCKERR_* indicates a failure to start the accept. * * Errors during asynchronous processing are reported using the * callback supplied. * * Side effects: * None. * *----------------------------------------------------------------------------- */ int AsyncSocket_StartSslAccept(AsyncSocket *asock, // IN void *sslCtx, // IN AsyncSocketSslAcceptFn sslAcceptFn, // IN void *clientData) // IN { int ret; if (VALID(asock, startSslAccept)) { AsyncSocketLock(asock); ret = VT(asock)->startSslAccept(asock, sslCtx, sslAcceptFn, clientData); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_Flush -- * * Try to send any pending out buffers until we run out of buffers, or * the timeout expires. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call * failures, and ASOCKERR_TIMEOUT if we couldn't send enough data * before the timeout expired. ASOCKERR_INVAL on invalid * parameters or operation not implemented on this socket. * * Side effects: * None. *---------------------------------------------------------------------------- */ int AsyncSocket_Flush(AsyncSocket *asock, // IN int timeoutMS) // IN { int ret; if (VALID(asock, flush)) { AsyncSocketLock(asock); ret = VT(asock)->flush(asock, timeoutMS); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_Recv -- * AsyncSocket_RecvPartial -- * * Registers a callback that will fire once the specified amount of data * has been received on the socket. * * In the case of AsyncSocket_RecvPartial, the callback is fired * once all or part of the data has been received on the socket. * * TCP usage: * AsyncSocket_Recv(AsyncSocket *asock, * void *buf, * int len, * AsyncSocketRecvFn recvFn, * void *clientData) * * Results: * ASOCKERR_*. * * Side effects: * Could register poll callback. * *---------------------------------------------------------------------------- */ int AsyncSocket_Recv(AsyncSocket *asock, // IN void *buf, // IN (buffer to fill) int len, // IN void *cb, // IN void *cbData) // IN { int ret; if (VALID(asock, recv)) { AsyncSocketLock(asock); ret = VT(asock)->recv(asock, buf, len, FALSE, cb, cbData); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } int AsyncSocket_RecvPartial(AsyncSocket *asock, // IN void *buf, // IN (buffer to fill) int len, // IN void *cb, // IN void *cbData) // IN { int ret; if (VALID(asock, recv)) { AsyncSocketLock(asock); ret = VT(asock)->recv(asock, buf, len, TRUE, cb, cbData); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_RecvPassedFd -- * * See AsyncSocket_Recv. Besides that it allows for receiving one * file descriptor... * * Results: * ASOCKERR_*. * * Side effects: * Could register poll callback. * *---------------------------------------------------------------------------- */ int AsyncSocket_RecvPassedFd(AsyncSocket *asock, // IN/OUT: socket void *buf, // OUT: buffer with data int len, // IN: length void *cb, // IN: completion calback void *cbData) // IN: callback's data { int ret; if (VALID(asock, recvPassedFd)) { AsyncSocketLock(asock); ret = VT(asock)->recvPassedFd(asock, buf, len, cb, cbData); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *----------------------------------------------------------------------------- * * AsyncSocket_GetReceivedFd -- * * Retrieve received file descriptor from socket. * * Results: * File descriptor. Or -1 if none was received. * * Side effects: * None. * *----------------------------------------------------------------------------- */ int AsyncSocket_GetReceivedFd(AsyncSocket *asock) // IN { int ret; if (VALID(asock, getReceivedFd)) { AsyncSocketLock(asock); ret = VT(asock)->getReceivedFd(asock); AsyncSocketUnlock(asock); } else { ret = -1; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_Send -- * * Queues the provided data for sending on the socket. If a send callback * is provided, the callback is fired after the data has been written to * the socket. Note that this only guarantees that the data has been * copied to the transmit buffer, we make no promises about whether it * has actually been transmitted, or received by the client, when the * callback is fired. * * Send callbacks should also be able to deal with being called if none * or only some of the queued buffer has been transmitted, since the send * callbacks for any remaining buffers are fired by AsyncSocket_Close(). * This condition can be detected by checking the len parameter passed to * the send callback. * * Results: * ASOCKERR_*. * * Side effects: * May register poll callback or perform I/O. * *---------------------------------------------------------------------------- */ int AsyncSocket_Send(AsyncSocket *asock, // IN void *buf, // IN int len, // IN AsyncSocketSendFn sendFn, // IN void *clientData) // IN { int ret; if (VALID(asock, send)) { AsyncSocketLock(asock); ret = VT(asock)->send(asock, buf, len, sendFn, clientData); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_IsSendBufferFull -- * * Indicate if socket send buffer is full. Note that unless this is * called from a callback function, the return value should be treated * as transient. * * Results: * 0: send space probably available, * 1: send has reached maximum, * ASOCKERR_INVAL: null socket or operation not supported. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_IsSendBufferFull(AsyncSocket *asock) // IN { int ret; if (VALID(asock, isSendBufferFull)) { AsyncSocketLock(asock); ret = VT(asock)->isSendBufferFull(asock); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetNetworkStats -- * * Get network statistics from the active socket. * * Results: * ASOCKERR_* * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_GetNetworkStats(AsyncSocket *asock, // IN AsyncSocketNetworkStats *stats) // OUT { int ret; if (VALID(asock, getNetworkStats)) { AsyncSocketLock(asock); ret = VT(asock)->getNetworkStats(asock, stats); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_Close -- * * AsyncSocket destructor. The destructor should be safe to call at any * time. It's invoked automatically for I/O errors on slots that have no * error handler set, and should be called manually by the error handler * as necessary. It could also be called as part of the normal program * flow. * * Results: * ASOCKERR_*. * * Side effects: * Closes the socket fd, unregisters all Poll callbacks, and fires the * send triggers for any remaining output buffers. * *---------------------------------------------------------------------------- */ int AsyncSocket_Close(AsyncSocket *asock) // IN { int ret; if (VALID(asock, close)) { AsyncSocketLock(asock); ret = VT(asock)->close(asock); ASSERT(!asock->inited); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *----------------------------------------------------------------------------- * * AsyncSocket_CancelRecv -- * AsyncSocket_CancelRecvEx -- * * Call this function if you know what you are doing. This should be * called if you want to synchronously receive the outstanding data on * the socket. It removes the recv poll callback. It also returns number of * partially read bytes (if any). A partially read response may exist as * AsyncSocketRecvCallback calls the recv callback only when all the data * has been received. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_INVAL. * * Side effects: * Subsequent client call to AsyncSocket_Recv can reinstate async behaviour. * *----------------------------------------------------------------------------- */ int AsyncSocket_CancelRecv(AsyncSocket *asock, // IN int *partialRecvd, // OUT void **recvBuf, // OUT void **recvFn) // OUT { return AsyncSocket_CancelRecvEx(asock, partialRecvd, recvBuf, recvFn, FALSE); } int AsyncSocket_CancelRecvEx(AsyncSocket *asock, // IN int *partialRecvd, // OUT void **recvBuf, // OUT void **recvFn, // OUT Bool cancelOnSend) // IN { int ret; if (VALID(asock, cancelRecv)) { AsyncSocketLock(asock); ret = VT(asock)->cancelRecv(asock, partialRecvd, recvBuf, recvFn, cancelOnSend); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_CancelCbForClose -- * * This is the external version of AsyncSocketCancelCbForCloseInt(). It * takes care of acquiring any necessary lock before calling the internal * function. * * Results: * ASOCKERR_*. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_CancelCbForClose(AsyncSocket *asock) // IN: { int ret; if (VALID(asock, cancelCbForClose)) { AsyncSocketLock(asock); ret = VT(asock)->cancelCbForClose(asock); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetLocalVMCIAddress -- * * Given an AsyncSocket object, returns the local VMCI context ID and * port number associated with it, or an error if the request is * meaningless for the underlying connection. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * * *---------------------------------------------------------------------------- */ int AsyncSocket_GetLocalVMCIAddress(AsyncSocket *asock, // IN uint32 *cid, // OUT: optional uint32 *port) // OUT: optional { int ret; if (VALID(asock, getLocalVMCIAddress)) { AsyncSocketLock(asock); ret = VT(asock)->getLocalVMCIAddress(asock, cid, port); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetRemoteVMCIAddress -- * * Given an AsyncSocket object, returns the remote VMCI context ID and * port number associated with it, or an error if the request is * meaningless for the underlying connection. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * * *---------------------------------------------------------------------------- */ int AsyncSocket_GetRemoteVMCIAddress(AsyncSocket *asock, // IN uint32 *cid, // OUT: optional uint32 *port) // OUT: optional { int ret; if (VALID(asock, getRemoteVMCIAddress)) { AsyncSocketLock(asock); ret = VT(asock)->getRemoteVMCIAddress(asock, cid, port); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetWebSocketError -- * * Return the HTTP error code supplied during a failed WebSocket * upgrade negotiation. * * Results: * Numeric HTTP error code, 0 if no error, or -1 on invalid arguments. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_GetWebSocketError(AsyncSocket *asock) // IN { int ret; if (VALID(asock, getWebSocketError)) { AsyncSocketLock(asock); ret = VT(asock)->getWebSocketError(asock); AsyncSocketUnlock(asock); } else { ret = -1; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetWebSocketURI -- * * Return the URI supplied during a WebSocket connection request. * * Results: * URI or Null if no URI was specified. * * Side effects: * None. * *---------------------------------------------------------------------------- */ char * AsyncSocket_GetWebSocketURI(AsyncSocket *asock) // IN { char *ret; if (VALID(asock, getWebSocketURI)) { AsyncSocketLock(asock); ret = VT(asock)->getWebSocketURI(asock); AsyncSocketUnlock(asock); } else { ret = NULL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetWebSocketCookie -- * * Return the Cookie field value supplied during a WebSocket * connection request. * * Results: * Cookie, if asock is WebSocket. * NULL, if asock is not WebSocket. * * Side effects: * None. * *---------------------------------------------------------------------------- */ char * AsyncSocket_GetWebSocketCookie(AsyncSocket *asock) // IN { char *ret; if (VALID(asock, getWebSocketCookie)) { AsyncSocketLock(asock); ret = VT(asock)->getWebSocketCookie(asock); AsyncSocketUnlock(asock); } else { ret = NULL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_SetWebSocketCookie -- * * Return the Cookie field value supplied during a WebSocket * connection request. * * Results: * Cookie, if asock is WebSocket. * NULL, if asock is not WebSocket. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int AsyncSocket_SetWebSocketCookie(AsyncSocket *asock, // IN void *clientData, // IN const char *path, // IN const char *sessionId) // IN { int ret = ASOCKERR_GENERIC; if (VALID(asock, setWebSocketCookie)) { AsyncSocketLock(asock); ret = VT(asock)->setWebSocketCookie(asock, clientData, path, sessionId); AsyncSocketUnlock(asock); } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetWebSocketCloseStatus -- * * Retrieve the close status, if received, for a websocket connection. * * Results: * Websocket close status code (>= 1000), or 0 if never received. * * Side effects: * None. * *---------------------------------------------------------------------------- */ uint16 AsyncSocket_GetWebSocketCloseStatus(AsyncSocket *asock) // IN { uint16 ret; if (VALID(asock, getWebSocketCloseStatus)) { AsyncSocketLock(asock); ret = VT(asock)->getWebSocketCloseStatus(asock); AsyncSocketUnlock(asock); } else { ret = 0; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_GetWebSocketProtocol -- * * Return the negotiated websocket protocol. Only valid until asock is * destroyed. * * Results: * NULL, if asock is not WebSocket. * AsyncWebSocketProtocol *, if asock is WebSocket. * * Side effects: * None. * *---------------------------------------------------------------------------- */ const char * AsyncSocket_GetWebSocketProtocol(AsyncSocket *asock) // IN { const char *ret; if (VALID(asock, getWebSocketProtocol)) { AsyncSocketLock(asock); ret = VT(asock)->getWebSocketProtocol(asock); AsyncSocketUnlock(asock); } else { ret = NULL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_RecvBlocking -- * * Implement "blocking + timeout" operations on the socket. These are * simple wrappers around the AsyncTCPSocketBlockingWork function, which * operates on the actual non-blocking socket, using poll to determine * when it's ok to keep reading/writing. If we can't finish within the * specified time, we give up and return the ASOCKERR_TIMEOUT error. * * Note that if these are called from a callback and a lock is being * used (pollParams.lock), the whole blocking operation takes place * with that lock held. Regardless, it is the caller's responsibility * to make sure the synchronous and asynchronous operations do not mix. * * Results: * ASOCKERR_SUCCESS if we finished the operation, ASOCKERR_* error codes * otherwise. * * Side effects: * Reads/writes the socket. * *---------------------------------------------------------------------------- */ int AsyncSocket_RecvBlocking(AsyncSocket *asock, // IN void *buf, // OUT int len, // IN int *received, // OUT int timeoutMS) // IN { int ret; if (VALID(asock, recvBlocking)) { AsyncSocketLock(asock); ret = VT(asock)->recvBlocking(asock, buf, len, received, timeoutMS); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_RecvPartialBlocking -- * * Implement "blocking + timeout" version of RecvPartial * * Results: * ASOCKERR_SUCCESS if we finished the operation, ASOCKERR_* error codes * otherwise. * * Side effects: * Reads/writes the socket. * *---------------------------------------------------------------------------- */ int AsyncSocket_RecvPartialBlocking(AsyncSocket *asock, // IN void *buf, // OUT int len, // IN int *received, // OUT int timeoutMS) // IN { int ret; if (VALID(asock, recvPartialBlocking)) { AsyncSocketLock(asock); ret = VT(asock)->recvPartialBlocking(asock, buf, len, received, timeoutMS); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_SendBlocking -- * * Implement "blocking + timeout" version of Send * * Results: * ASOCKERR_SUCCESS if we finished the operation, ASOCKERR_* error codes * otherwise. * * Side effects: * Reads/writes the socket. * *---------------------------------------------------------------------------- */ int AsyncSocket_SendBlocking(AsyncSocket *asock, // IN void *buf, // IN int len, // IN int *sent, // OUT int timeoutMS) // IN { int ret; if (VALID(asock, sendBlocking)) { AsyncSocketLock(asock); ret = VT(asock)->sendBlocking(asock, buf, len, sent, timeoutMS); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_DoOneMsg -- * * Spins a socket until the specified amount of time has elapsed or * data has arrived / been sent. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call * failures * ASOCKERR_TIMEOUT if nothing happened in the allotted time. * * Side effects: * None. *---------------------------------------------------------------------------- */ int AsyncSocket_DoOneMsg(AsyncSocket *asock, // IN Bool read, // IN int timeoutMS) // IN { int ret; if (VALID(asock, doOneMsg)) { AsyncSocketLock(asock); ret = VT(asock)->doOneMsg(asock, read, timeoutMS); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_WaitForConnection -- * * Spins a socket currently listening or connecting until the * connection completes or the allowed time elapses. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on failures, and * ASOCKERR_TIMEOUT if nothing happened in the allotted time. * * Side effects: * None. *---------------------------------------------------------------------------- */ int AsyncSocket_WaitForConnection(AsyncSocket *asock, // IN int timeoutMS) // IN { int ret; if (VALID(asock, waitForConnection)) { AsyncSocketLock(asock); ret = VT(asock)->waitForConnection(asock, timeoutMS); AsyncSocketUnlock(asock); } else { ret = ASOCKERR_INVAL; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncSocket_WaitForReadMultiple -- * * Waits on a list of sockets, returning when a socket becomes * available for read, or when the allowed time elapses. * * Note, if this function is called by two threads with overlapping * sets of sockets, a deadlock can occur. The caller should guard * against such scenarios from happening, or making sure that there * is a consistent ordering to the lists of sockets. * * The caller must also make sure synchronous and asynchronous * operations do not mix, as this function does not hold locks * for the entirety of the call. * * Results: * ASOCKERR_SUCCESS if one of the sockets is ready for read, * ASOCKERR_GENERIC on failures, and ASOCKERR_TIMEOUT if nothing * happened in the allotted time. * * Side effects: * None. *---------------------------------------------------------------------------- */ int AsyncSocket_WaitForReadMultiple(AsyncSocket **asock, // IN int numSock, // IN int timeoutMS, // IN int *outIdx) // OUT { int i; int ret; if (numSock > 0 && VALID(asock[0], waitForReadMultiple)) { for (i = 0; i < numSock; i++) { AsyncSocketLock(asock[i]); } ret = VT(asock[0])->waitForReadMultiple(asock, numSock, timeoutMS, outIdx); for (i = numSock - 1; i >= 0; i--) { AsyncSocketUnlock(asock[i]); } } else { ret = ASOCKERR_INVAL; } return ret; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/asyncsocket/asyncSocketVTable.h000066400000000000000000000143241321503522500271330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2011,2014-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #ifndef __ASYNC_SOCKET_VTABLE_H__ #define __ASYNC_SOCKET_VTABLE_H__ #ifdef USE_SSL_DIRECT #include "sslDirect.h" #else #include "ssl.h" #endif /* * If we change the AsyncSocketVTable, we also need to change the follow files: * lib/blastSockets/asyncProxySocket.c * lib/asyncsocket/asyncsocket.c * lib/asyncsocket/asyncWebSocket.c * lib/asyncsocket/asyncNamedPipe.c * lib/udpfec/fecAsyncSocket.c * lib/udpfec/fecAsyncSslSocket.c * devices/vsock/asyncVmciSocket.c */ typedef struct AsyncSocketVTable { AsyncSocketState (*getState)(AsyncSocket *sock); /* * The socket options mechanism is discussed in asyncsocket.h. * If you're considering adding a new virtual function table entry whose * effect is to call setsockopt() and/or save a value inside the socket * structure and/or forward such a call to a contained AsyncSocket, * strongly consider using this setOption() mechanism instead. * Your life is likely to be made easier by this. */ int (*setOption)(AsyncSocket *asyncSocket, AsyncSocketOpts_Layer layer, AsyncSocketOpts_ID optID, const void *valuePtr, socklen_t inBufLen); /* * A setOption() implementation must have a symmetrical getOption() * counterpart. The converse is not true -- a getOption() * implementation need not have a setOption() counterpart. (One * way to look at this is that an option may be read-only, but it * must not be write-only.) */ int (*getOption)(AsyncSocket *asyncSocket, AsyncSocketOpts_Layer layer, AsyncSocketOpts_ID optID, void *valuePtr, socklen_t *outBufLen); int (*getGenericErrno)(AsyncSocket *s); int (*getFd)(AsyncSocket *asock); int (*getRemoteIPStr)(AsyncSocket *asock, const char **ipStr); int (*getINETIPStr)(AsyncSocket *asock, int socketFamily, char **ipRetStr); unsigned int (*getPort)(AsyncSocket *asock); int (*setCloseOptions)(AsyncSocket *asock, int flushEnabledMaxWaitMsec, AsyncSocketCloseFn closeCb); Bool (*connectSSL)(AsyncSocket *asock, struct _SSLVerifyParam *verifyParam, void *sslContext); int (*startSslConnect)(AsyncSocket *asock, struct _SSLVerifyParam *verifyParam, void *sslCtx, AsyncSocketSslConnectFn sslConnectFn, void *clientData); Bool (*acceptSSL)(AsyncSocket *asock, void *sslCtx); int (*startSslAccept)(AsyncSocket *asock, void *sslCtx, AsyncSocketSslAcceptFn sslAcceptFn, void *clientData); int (*flush)(AsyncSocket *asock, int timeoutMS); int (*recv)(AsyncSocket *asock, void *buf, int len, Bool partial, void *cb, void *cbData); int (*recvPassedFd)(AsyncSocket *asock, void *buf, int len, void *cb, void *cbData); int (*getReceivedFd)(AsyncSocket *asock); int (*send)(AsyncSocket *asock, void *buf, int len, AsyncSocketSendFn sendFn, void *clientData); int (*isSendBufferFull)(AsyncSocket *asock); int (*getNetworkStats)(AsyncSocket *asock, AsyncSocketNetworkStats *stats); int (*close)(AsyncSocket *asock); int (*cancelRecv)(AsyncSocket *asock, int *partialRecvd, void **recvBuf, void **recvFn, Bool cancelOnSend); int (*cancelCbForClose)(AsyncSocket *asock); int (*getLocalVMCIAddress)(AsyncSocket *asock, uint32 *cid, uint32 *port); int (*getRemoteVMCIAddress)(AsyncSocket *asock, uint32 *cid, uint32 *port); int (*getWebSocketError)(AsyncSocket *asock); char *(*getWebSocketURI)(AsyncSocket *asock); char *(*getWebSocketCookie)(AsyncSocket *asock); uint16 (*getWebSocketCloseStatus)(AsyncSocket *asock); const char *(*getWebSocketProtocol)(AsyncSocket *asock); int (*setWebSocketCookie)(AsyncSocket *asock, void *clientData, const char *path, const char *sessionId); int (*recvBlocking)(AsyncSocket *s, void *buf, int len, int *received, int timeoutMS); int (*recvPartialBlocking)(AsyncSocket *s, void *buf, int len, int *received, int timeoutMS); int (*sendBlocking)(AsyncSocket *s, void *buf, int len, int *sent, int timeoutMS); int (*doOneMsg)(AsyncSocket *s, Bool read, int timeoutMS); int (*waitForConnection)(AsyncSocket *s, int timeoutMS); int (*waitForReadMultiple)(AsyncSocket **asock, int numSock, int timeoutMS, int *outIdx); /* * Internal function, called when refcount drops to zero: */ void (*destroy)(AsyncSocket *asock); } AsyncSocketVTable; #define VT(x) ((x)->vt) #define VALID(asock, x) LIKELY(asock && VT(asock)->x) #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/asyncsocket/asyncsocket.c000066400000000000000000005416131321503522500260760ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * asyncsocket.c -- * * The AsyncTCPSocket object is a fairly simple wrapper around a basic TCP * socket. It's potentially asynchronous for both read and write * operations. Reads are "requested" by registering a receive function * that is called once the requested amount of data has been read from * the socket. Similarly, writes are queued along with a send function * that is called once the data has been written. Errors are reported via * a separate callback. */ #include #include #include #include #ifdef _WIN32 /* * We redefine strcpy/strcat because the Windows SDK uses it for getaddrinfo(). * When we upgrade SDKs, this redefinition can go away. * Note: Now we are checking if we have secure libs for string operations */ #if !(defined(__GOT_SECURE_LIB__) && __GOT_SECURE_LIB__ >= 200402L) #define strcpy(dst,src) Str_Strcpy((dst), (src), 0x7FFFFFFF) #define strcat(dst,src) Str_Strcat((dst), (src), 0x7FFFFFFF) #endif #include #include #include #include #include #if !(defined(__GOT_SECURE_LIB__) && __GOT_SECURE_LIB__ >= 200402L) #undef strcpy #undef strcat #endif #else #include #include #include #include #include #include #include #include #include #include #include #include #endif #include "vmware.h" #include "str.h" #include "random.h" #include "asyncsocket.h" #include "asyncSocketBase.h" #include "poll.h" #include "log.h" #include "err.h" #include "hostinfo.h" #include "util.h" #include "msg.h" #include "posix.h" #include "vmci_sockets.h" #ifndef VMX86_TOOLS #include "vmdblib.h" #endif #ifdef _WIN32 #define ASOCK_LASTERROR() WSAGetLastError() #else #define ASOCK_LASTERROR() errno #endif #define LOGLEVEL_MODULE asyncsocket #include "loglevel_user.h" #ifdef VMX86_SERVER #include "uwvmkAPI.h" #endif #ifdef __linux__ /* * Our toolchain does not support IPV6_V6ONLY, but the host we are running on * may support it. Since setsockopt will return a error that we treat as * non-fatal, it is fine to attempt it. See define in in6.h. */ #ifndef IPV6_V6ONLY #define IPV6_V6ONLY 26 #endif /* * Linux versions can lack support for IPV6_V6ONLY while still supporting * V4MAPPED addresses. We check for a V4MAPPED address during accept to cover * this scenario. In case IN6_IS_ADDR_V4MAPPED is also not avaiable, define it. */ #ifndef IN6_IS_ADDR_V4MAPPED #define IN6_IS_ADDR_V4MAPPED(a) \ (*(const u_int32_t *)(const void *)(&(a)->s6_addr[0]) == 0 && \ *(const u_int32_t *)(const void *)(&(a)->s6_addr[4]) == 0 && \ *(const u_int32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) #endif #endif #define PORT_STRING_LEN 6 /* "12345\0" or ":12345" */ #define IN_IPOLL_RECV (1 << 0) #define IN_IPOLL_SEND (1 << 1) /* * INET6_ADDRSTRLEN allows for only 45 characters. If we somehow have a * non-recommended V4MAPPED address we can exceed 45 total characters in our * address string format. While this should not be the case it is possible. * Account for the possible: * "[XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:AAA.BBB.CCC.DDD]:12345\0" * (XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:AAA.BBB.CCC.DDD\0 + [] + :12345) */ #define ADDR_STRING_LEN (INET6_ADDRSTRLEN + 2 + PORT_STRING_LEN) /* Local types. */ /* * Output buffer list data type, for the queue of outgoing buffers */ typedef struct SendBufList { struct SendBufList *next; void *buf; int len; AsyncSocketSendFn sendFn; void *clientData; } SendBufList; typedef struct AsyncTCPSocket { /* * The base class, which is just a vtable: */ AsyncSocket base; /* * Everything for the TCP AsyncSocket implementation: */ int fd; SSLSock sslSock; int genericErrno; struct sockaddr_storage localAddr; socklen_t localAddrLen; struct sockaddr_storage remoteAddr; socklen_t remoteAddrLen; AsyncSocketConnectFn connectFn; AsyncSocketSslAcceptFn sslAcceptFn; AsyncSocketSslConnectFn sslConnectFn; int sslPollFlags; /* shared by sslAcceptFn, sslConnectFn */ /* shared by connectFn, sslAcceptFn and sslConnectFn */ void *clientData; PollerFunction internalConnectFn; PollerFunction internalSendFn; PollerFunction internalRecvFn; /* governs optional AsyncSocket_Close() behavior */ int flushEnabledMaxWaitMsec; AsyncSocketCloseFn closeCb; void *closeCbData; Bool recvCb; Bool recvCbTimer; SendBufList *sendBufList; SendBufList **sendBufTail; int sendPos; Bool sendCb; Bool sendCbTimer; Bool sendCbRT; Bool sendBufFull; Bool sendLowLatency; int inLowLatencySendCb; Bool sslConnected; uint8 inIPollCb; Bool inRecvLoop; Bool inDoOneMsg; uint32 inBlockingRecv; struct AsyncTCPSocket *listenAsock4; struct AsyncTCPSocket *listenAsock6; struct { Bool expected; int fd; } passFd; } AsyncTCPSocket; /* * Local Functions */ static AsyncTCPSocket *AsyncTCPSocketCreate(AsyncSocketPollParams *pollParams); static void AsyncTCPSocketSendCallback(void *clientData); static void AsyncTCPSocketRecvCallback(void *clientData); static int AsyncTCPSocketResolveAddr(const char *hostname, unsigned int port, int family, Bool passive, struct sockaddr_storage *addr, socklen_t *addrLen, char **addrString); static AsyncTCPSocket *AsyncTCPSocketAttachToFd( int fd, AsyncSocketPollParams *pollParams, int *outError); static Bool AsyncTCPSocketHasDataPending(AsyncTCPSocket *asock); static int AsyncTCPSocketMakeNonBlocking(int fd); static void AsyncTCPSocketAcceptCallback(void *clientData); static void AsyncTCPSocketConnectCallback(void *clientData); static int AsyncTCPSocketBlockingWork(AsyncTCPSocket *asock, Bool read, void *buf, int len, int *completed, int timeoutMS, Bool partial); static VMwareStatus AsyncTCPSocketPollAdd(AsyncTCPSocket *asock, Bool socket, int flags, PollerFunction callback, ...); static Bool AsyncTCPSocketPollRemove(AsyncTCPSocket *asock, Bool socket, int flags, PollerFunction callback); static unsigned int AsyncTCPSocketGetPortFromAddr( struct sockaddr_storage *addr); static AsyncTCPSocket *AsyncTCPSocketConnect(struct sockaddr_storage *addr, socklen_t addrLen, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketConnectFlags flags, AsyncSocketPollParams *pollParams, int *outError); static int AsyncTCPSocketConnectInternal(AsyncTCPSocket *s); static VMwareStatus AsyncTCPSocketIPollAdd(AsyncTCPSocket *asock, Bool socket, int flags, PollerFunction callback, int info); static Bool AsyncTCPSocketIPollRemove(AsyncTCPSocket *asock, Bool socket, int flags, PollerFunction callback); static void AsyncTCPSocketIPollSendCallback(void *clientData); static void AsyncTCPSocketIPollRecvCallback(void *clientData); static Bool AsyncTCPSocketAddListenCb(AsyncTCPSocket *asock); static void AsyncTCPSocketSslConnectCallback(void *clientData); static void AsyncTCPSocketSslAcceptCallback(void *clientData); static Bool AsyncTCPSocketBind(AsyncTCPSocket *asock, struct sockaddr_storage *addr, socklen_t addrLen, int *outError); static Bool AsyncTCPSocketListen(AsyncTCPSocket *asock, AsyncSocketConnectFn connectFn, void *clientData, int *outError); static AsyncTCPSocket *AsyncTCPSocketInit(int socketFamily, AsyncSocketPollParams *pollParams, int *outError); static void AsyncTCPSocketCancelListenCb(AsyncTCPSocket *asock); static int AsyncTCPSocketRegisterRecvCb(AsyncTCPSocket *asock); static Bool AsyncTCPSocketCancelCbForConnectingClose(AsyncTCPSocket *asock); static int AsyncTCPSocketWaitForConnection(AsyncSocket *s, int timeoutMS); static int AsyncTCPSocketGetGenericErrno(AsyncSocket *s); static int AsyncTCPSocketGetFd(AsyncSocket *asock); static int AsyncTCPSocketGetRemoteIPStr(AsyncSocket *asock, const char **ipStr); static int AsyncTCPSocketGetINETIPStr(AsyncSocket *asock, int socketFamily, char **ipRetStr); static unsigned int AsyncTCPSocketGetPort(AsyncSocket *asock); static Bool AsyncTCPSocketConnectSSL(AsyncSocket *asock, struct _SSLVerifyParam *verifyParam, void *sslContext); static int AsyncTCPSocketStartSslConnect(AsyncSocket *asock, SSLVerifyParam *verifyParam, void *sslCtx, AsyncSocketSslConnectFn sslConnectFn, void *clientData); static Bool AsyncTCPSocketAcceptSSL(AsyncSocket *asock, void *sslCtx); static int AsyncTCPSocketStartSslAccept(AsyncSocket *asock, void *sslCtx, AsyncSocketSslAcceptFn sslAcceptFn, void *clientData); static int AsyncTCPSocketFlush(AsyncSocket *asock, int timeoutMS); static void AsyncTCPSocketCancelRecvCb(AsyncTCPSocket *asock); static int AsyncTCPSocketRecv(AsyncSocket *asock, void *buf, int len, Bool partial, void *cb, void *cbData); static int AsyncTCPSocketRecvPassedFd(AsyncSocket *asock, void *buf, int len, void *cb, void *cbData); static int AsyncTCPSocketGetReceivedFd(AsyncSocket *asock); static int AsyncTCPSocketSend(AsyncSocket *asock, void *buf, int len, AsyncSocketSendFn sendFn, void *clientData); static int AsyncTCPSocketIsSendBufferFull(AsyncSocket *asock); static int AsyncTCPSocketClose(AsyncSocket *asock); static int AsyncTCPSocketCancelRecv(AsyncSocket *asock, int *partialRecvd, void **recvBuf, void **recvFn, Bool cancelOnSend); static int AsyncTCPSocketCancelCbForClose(AsyncSocket *asock); static int AsyncTCPSocketGetLocalVMCIAddress(AsyncSocket *asock, uint32 *cid, uint32 *port); static int AsyncTCPSocketGetRemoteVMCIAddress(AsyncSocket *asock, uint32 *cid, uint32 *port); static int AsyncTCPSocketSetCloseOptions(AsyncSocket *asock, int flushEnabledMaxWaitMsec, AsyncSocketCloseFn closeCb); static void AsyncTCPSocketDestroy(AsyncSocket *s); static int AsyncTCPSocketRecvBlocking(AsyncSocket *s, void *buf, int len, int *received, int timeoutMS); static int AsyncTCPSocketRecvPartialBlocking(AsyncSocket *s, void *buf, int len, int *received, int timeoutMS); static int AsyncTCPSocketSendBlocking(AsyncSocket *s, void *buf, int len, int *sent, int timeoutMS); static int AsyncTCPSocketDoOneMsg(AsyncSocket *s, Bool read, int timeoutMS); static int AsyncTCPSocketWaitForReadMultiple(AsyncSocket **asock, int numSock, int timeoutMS, int *outIdx); static int AsyncTCPSocketSetOption(AsyncSocket *asyncSocket, AsyncSocketOpts_Layer layer, AsyncSocketOpts_ID optID, const void *valuePtr, socklen_t inBufLen); static int AsyncTCPSocketGetOption(AsyncSocket *asyncSocket, AsyncSocketOpts_Layer layer, AsyncSocketOpts_ID optID, void *valuePtr, socklen_t *outBufLen); static void AsyncTCPSocketListenerError(int error, AsyncSocket *asock, void *clientData); /* Local constants. */ static const AsyncSocketVTable asyncTCPSocketVTable = { AsyncSocketGetState, AsyncTCPSocketSetOption, AsyncTCPSocketGetOption, AsyncTCPSocketGetGenericErrno, AsyncTCPSocketGetFd, AsyncTCPSocketGetRemoteIPStr, AsyncTCPSocketGetINETIPStr, AsyncTCPSocketGetPort, AsyncTCPSocketSetCloseOptions, AsyncTCPSocketConnectSSL, AsyncTCPSocketStartSslConnect, AsyncTCPSocketAcceptSSL, AsyncTCPSocketStartSslAccept, AsyncTCPSocketFlush, AsyncTCPSocketRecv, AsyncTCPSocketRecvPassedFd, AsyncTCPSocketGetReceivedFd, AsyncTCPSocketSend, AsyncTCPSocketIsSendBufferFull, NULL, /* getNetworkStats */ AsyncTCPSocketClose, AsyncTCPSocketCancelRecv, AsyncTCPSocketCancelCbForClose, AsyncTCPSocketGetLocalVMCIAddress, AsyncTCPSocketGetRemoteVMCIAddress, NULL, /* getWebSocketError */ NULL, /* getWebSocketURI */ NULL, /* getWebSocketCookie */ NULL, /* getWebSocketCloseStatus */ NULL, /* getWebSocketProtocol */ NULL, /* setWebSocketCookie */ AsyncTCPSocketRecvBlocking, AsyncTCPSocketRecvPartialBlocking, AsyncTCPSocketSendBlocking, AsyncTCPSocketDoOneMsg, AsyncTCPSocketWaitForConnection, AsyncTCPSocketWaitForReadMultiple, AsyncTCPSocketDestroy }; /* Function bodies. */ /* *---------------------------------------------------------------------- * * BaseSocket -- * * Return a pointer to the tcp socket's base class. * *---------------------------------------------------------------------- */ static INLINE AsyncSocket * BaseSocket(AsyncTCPSocket *s) { ASSERT((void *)s == (void *)&s->base); return &s->base; } /* *---------------------------------------------------------------------- * * TCPSocket -- * * Cast a generic AsyncSocket pointer to AsyncTCPSocket, after * asserting this is legal. * *---------------------------------------------------------------------- */ static INLINE AsyncTCPSocket * TCPSocket(AsyncSocket *s) { ASSERT(s->vt == &asyncTCPSocketVTable); ASSERT(s == &((AsyncTCPSocket *)s)->base); return (AsyncTCPSocket *)s; } /* *---------------------------------------------------------------------- * * TCPSocketLock -- * TCPSocketUnlock -- * TCPSocketIsLocked -- * TCPSocketAddRef -- * TCPSocketRelease -- * TCPSocketPollParams -- * TCPSocketGetState -- * TCPSocketSetState -- * TCPSocketHandleError -- * * AsyncTCPSocket versions of base class interfaces. These * simply invoke the corresponding function on the base class * pointer. * *---------------------------------------------------------------------- */ static INLINE void AsyncTCPSocketLock(AsyncTCPSocket *asock) { AsyncSocketLock(BaseSocket(asock)); } static INLINE void AsyncTCPSocketUnlock(AsyncTCPSocket *asock) { AsyncSocketUnlock(BaseSocket(asock)); } static INLINE Bool AsyncTCPSocketIsLocked(AsyncTCPSocket *asock) { return AsyncSocketIsLocked(BaseSocket(asock)); } static INLINE void AsyncTCPSocketAddRef(AsyncTCPSocket *asock) { AsyncSocketAddRef(BaseSocket(asock)); } static INLINE void AsyncTCPSocketRelease(AsyncTCPSocket *asock) { AsyncSocketRelease(BaseSocket(asock)); } static INLINE AsyncSocketPollParams * AsyncTCPSocketPollParams(AsyncTCPSocket *asock) { return AsyncSocketGetPollParams(BaseSocket(asock)); } static INLINE Bool AsyncTCPSocketGetState(AsyncTCPSocket *asock) { return AsyncSocketGetState(BaseSocket(asock)); } static INLINE void AsyncTCPSocketSetState(AsyncTCPSocket *asock, AsyncSocketState state) { AsyncSocketSetState(BaseSocket(asock), state); } static INLINE void AsyncTCPSocketHandleError(AsyncTCPSocket *asock, int error) { AsyncSocketHandleError(BaseSocket(asock), error); } /* *---------------------------------------------------------------------- * * TCPSOCKWARN -- * TCPSOCKLOG -- * TCPSOCKLG0 -- * * AsyncTCPSocket versions of base class logging macros. These * simply invoke the corresponding macro on the base class * pointer. * *---------------------------------------------------------------------- */ #define TCPSOCKWARN(a,b) ASOCKWARN(BaseSocket(a), b) #define TCPSOCKLOG(a,b,c) ASOCKLOG(a, BaseSocket(b), c) #define TCPSOCKLG0(a,b) ASOCKLG0(BaseSocket(a), b) /* *---------------------------------------------------------------------------- * * AsyncTCPSocket_Init -- * * Initializes the host's socket library. NOP on Posix. * On Windows, calls WSAStartup(). * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * On Windows, loads winsock library. * *---------------------------------------------------------------------------- */ int AsyncTCPSocket_Init(void) { #ifdef _WIN32 WSADATA wsaData; WORD versionRequested = MAKEWORD(2, 0); return WSAStartup(versionRequested, &wsaData) ? ASOCKERR_GENERIC : ASOCKERR_SUCCESS; #endif return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetFd -- * * Returns the fd for this socket. If listening, return one of * the asock6/asock4 fds. * * Results: * File descriptor. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketGetFd(AsyncSocket *base) // IN { AsyncTCPSocket *asock = TCPSocket(base); if (asock->fd != -1) { return asock->fd; } else if (asock->listenAsock4 && asock->listenAsock4->fd != -1) { return asock->listenAsock4->fd; } else if (asock->listenAsock6 && asock->listenAsock6->fd != -1) { return asock->listenAsock6->fd; } else { return -1; } } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetAddr -- * * Given an AsyncTCPSocket object, return the sockaddr associated with the * requested address family's file descriptor if available. * * Passing AF_UNSPEC to socketFamily will provide you with the first * usable sockaddr found (if multiple are available), with a preference * given to IPv6. * * Results: * ASOCKERR_SUCCESS. ASOCKERR_INVAL if there is no socket associated with * address family requested. ASOCKERR_GENERIC for all other errors. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketGetAddr(AsyncTCPSocket *asock, // IN int socketFamily, // IN struct sockaddr_storage *outAddr, // OUT socklen_t *outAddrLen) // IN/OUT { AsyncTCPSocket *tempAsock; int tempFd; struct sockaddr_storage addr; socklen_t addrLen = sizeof addr; if (asock->fd != -1) { tempAsock = asock; } else if ((socketFamily == AF_UNSPEC || socketFamily == AF_INET6) && asock->listenAsock6 && asock->listenAsock6->fd != -1) { tempAsock = asock->listenAsock6; } else if ((socketFamily == AF_UNSPEC || socketFamily == AF_INET) && asock->listenAsock4 && asock->listenAsock4->fd != -1) { tempAsock = asock->listenAsock4; } else { return ASOCKERR_INVAL; } ASSERT(AsyncTCPSocketIsLocked(tempAsock)); tempFd = tempAsock->fd; if (getsockname(tempFd, (struct sockaddr*)&addr, &addrLen) == 0) { if (socketFamily != AF_UNSPEC && addr.ss_family != socketFamily) { return ASOCKERR_INVAL; } memcpy(outAddr, &addr, Min(*outAddrLen, addrLen)); *outAddrLen = addrLen; return ASOCKERR_SUCCESS; } else { TCPSOCKWARN(tempAsock, ("%s: could not locate socket.\n", __FUNCTION__)); return ASOCKERR_GENERIC; } } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetRemoteIPStr -- * * Given an AsyncTCPSocket object, returns the remote IP address * associated with it, or an error if the request is meaningless * for the underlying connection. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketGetRemoteIPStr(AsyncSocket *base, // IN const char **ipRetStr) // OUT { AsyncTCPSocket *asock = TCPSocket(base); int ret = ASOCKERR_SUCCESS; ASSERT(asock); ASSERT(ipRetStr != NULL); if (ipRetStr == NULL || asock == NULL || AsyncTCPSocketGetState(asock) != AsyncSocketConnected || (asock->remoteAddrLen != sizeof (struct sockaddr_in) && asock->remoteAddrLen != sizeof (struct sockaddr_in6))) { ret = ASOCKERR_GENERIC; } else { char addrBuf[NI_MAXHOST]; if (Posix_GetNameInfo((struct sockaddr *)&asock->remoteAddr, asock->remoteAddrLen, addrBuf, sizeof addrBuf, NULL, 0, NI_NUMERICHOST) != 0) { ret = ASOCKERR_GENERIC; } else { *ipRetStr = Util_SafeStrdup(addrBuf); } } return ret; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetINETIPStr -- * * Given an AsyncTCPSocket object, returns the IP addresses associated with * the requested address family's file descriptor if available. * * Passing AF_UNSPEC to socketFamily will provide you with the first * usable IP address found (if multiple are available), with a preference * given to IPv6. * * It is the caller's responsibility to free ipRetStr. * * Results: * ASOCKERR_SUCCESS. ASOCKERR_INVAL if there is no socket associated with * address family requested. ASOCKERR_GENERIC for all other errors. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketGetINETIPStr(AsyncSocket *base, // IN int socketFamily, // IN char **ipRetStr) // OUT { AsyncTCPSocket *asock = TCPSocket(base); struct sockaddr_storage addr; socklen_t addrLen = sizeof addr; int ret; ASSERT(AsyncTCPSocketIsLocked(asock)); ret = AsyncTCPSocketGetAddr(asock, socketFamily, &addr, &addrLen); if (ret == ASOCKERR_SUCCESS) { char addrBuf[NI_MAXHOST]; if (ipRetStr == NULL) { TCPSOCKWARN(asock, ("%s: Output string is not usable.\n", __FUNCTION__)); ret = ASOCKERR_INVAL; } else if (Posix_GetNameInfo((struct sockaddr *)&addr, addrLen, addrBuf, sizeof addrBuf, NULL, 0, NI_NUMERICHOST) == 0) { *ipRetStr = Util_SafeStrdup(addrBuf); } else { TCPSOCKWARN(asock, ("%s: could not find IP address.\n", __FUNCTION__)); ret = ASOCKERR_GENERIC; } } return ret; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetLocalVMCIAddress -- * * Given an AsyncTCPSocket object, returns the local VMCI context ID and * port number associated with it, or an error if the request is * meaningless for the underlying connection. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketGetLocalVMCIAddress(AsyncSocket *base, // IN uint32 *cid, // OUT: optional uint32 *port) // OUT: optional { AsyncTCPSocket *asock = TCPSocket(base); ASSERT(asock); if (asock->localAddrLen != sizeof(struct sockaddr_vm)) { return ASOCKERR_GENERIC; } if (cid != NULL) { *cid = ((struct sockaddr_vm *)&asock->localAddr)->svm_cid; } if (port != NULL) { *port = ((struct sockaddr_vm *)&asock->localAddr)->svm_port; } return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetRemoteVMCIAddress -- * * Given an AsyncTCPSocket object, returns the remote VMCI context ID and * port number associated with it, or an error if the request is * meaningless for the underlying connection. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketGetRemoteVMCIAddress(AsyncSocket *base, // IN uint32 *cid, // OUT: optional uint32 *port) // OUT: optional { AsyncTCPSocket *asock = TCPSocket(base); ASSERT(asock); if (asock->remoteAddrLen != sizeof(struct sockaddr_vm)) { return ASOCKERR_GENERIC; } if (cid != NULL) { *cid = ((struct sockaddr_vm *)&asock->remoteAddr)->svm_cid; } if (port != NULL) { *port = ((struct sockaddr_vm *)&asock->remoteAddr)->svm_port; } return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketListenImpl -- * * Initializes, binds, and listens on pre-populated address structure. * * Results: * New AsyncTCPSocket in listening state or NULL on error. * * Side effects: * Creates new socket, binds and listens. * *---------------------------------------------------------------------------- */ static AsyncTCPSocket * AsyncTCPSocketListenImpl(struct sockaddr_storage *addr, // IN socklen_t addrLen, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketPollParams *pollParams, // IN: optional int *outError) // OUT: optional { AsyncTCPSocket *asock = AsyncTCPSocketInit(addr->ss_family, pollParams, outError); if (asock != NULL) { if (AsyncTCPSocketBind(asock, addr, addrLen, outError) && AsyncTCPSocketListen(asock, connectFn, clientData, outError)) { return asock; } } return NULL; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketListenerCreateImpl -- * * Listens on specified address and/or port for resolved/requested socket * family and accepts new connections. Fires the connect callback with * new AsyncTCPSocket object for each connection. * * Results: * New AsyncTCPSocket in listening state or NULL on error. * * Side effects: * Creates new socket, binds and listens. * *---------------------------------------------------------------------------- */ static AsyncTCPSocket * AsyncTCPSocketListenerCreateImpl( const char *addrStr, // IN: optional unsigned int port, // IN: optional int socketFamily, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT: optional { AsyncTCPSocket *asock = NULL; struct sockaddr_storage addr; socklen_t addrLen; char *ipString = NULL; int getaddrinfoError = AsyncTCPSocketResolveAddr(addrStr, port, socketFamily, TRUE, &addr, &addrLen, &ipString); if (getaddrinfoError == 0) { asock = AsyncTCPSocketListenImpl(&addr, addrLen, connectFn, clientData, pollParams, outError); if (asock) { TCPSOCKLG0(asock, ("Created new %s %s listener for (%s)\n", addr.ss_family == AF_INET ? "IPv4" : "IPv6", "socket", ipString)); } else { Log(ASOCKPREFIX "Could not create %s listener socket, error %d: %s\n", addr.ss_family == AF_INET ? "IPv4" : "IPv6", *outError, AsyncSocket_Err2String(*outError)); } free(ipString); } else { Log(ASOCKPREFIX "Could not resolve listener socket address.\n"); if (outError) { *outError = ASOCKERR_ADDRUNRESV; } } return asock; } /* *---------------------------------------------------------------------------- * * AsyncSocket_Listen -- * * Listens on specified address and/or port for all resolved socket * families and accepts new connections. Fires the connect callback with * new AsyncTCPSocket object for each connection. * * If address string is present and that string is not the "localhost" * loopback, then we will listen on resolved address only. * * If address string is NULL or is "localhost" we will listen on all * address families that will resolve on the host. * * If port requested is 0, we will let the system assign the first * available port. * * If address string is NULL and port requested is not 0, we will listen * on any address for all resolved protocols for the port requested. * * If address string is "localhost" and port is 0, we will use the first * port we are given if the host supports multiple address families. * If by chance we try to bind on a port that is available for one * protocol and not the other, we will attempt a second time with the * order of address families reversed. * * If address string is NULL, port cannot be 0. * * Results: * New AsyncTCPSocket in listening state or NULL on error. * * Side effects: * Creates new socket/s, binds and listens. * *---------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_Listen(const char *addrStr, // IN: optional unsigned int port, // IN: optional AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT: optional { if (addrStr != NULL && *addrStr != '\0' && Str_Strcmp(addrStr, "localhost")) { AsyncTCPSocket *asock; asock = AsyncTCPSocketListenerCreateImpl(addrStr, port, AF_UNSPEC, connectFn, clientData, pollParams, outError); return BaseSocket(asock); } else { Bool localhost = addrStr != NULL && !Str_Strcmp(addrStr, "localhost"); unsigned int tempPort = port; AsyncTCPSocket *asock6 = NULL; AsyncTCPSocket *asock4 = NULL; int tempError4; int tempError6; asock6 = AsyncTCPSocketListenerCreateImpl(addrStr, port, AF_INET6, connectFn, clientData, pollParams, &tempError6); if (localhost && port == 0) { tempPort = AsyncSocket_GetPort(BaseSocket(asock6)); if (tempPort == MAX_UINT32) { Log(ASOCKPREFIX "Could not resolve IPv6 listener socket port number.\n"); tempPort = port; } } asock4 = AsyncTCPSocketListenerCreateImpl(addrStr, tempPort, AF_INET, connectFn, clientData, pollParams, &tempError4); if (localhost && port == 0 && tempError4 == ASOCKERR_BINDADDRINUSE) { Log(ASOCKPREFIX "Failed to reuse IPv6 localhost port number for IPv4 " "listener socket.\n"); AsyncSocket_Close(BaseSocket(asock6)); tempError4 = ASOCKERR_SUCCESS; asock4 = AsyncTCPSocketListenerCreateImpl(addrStr, port, AF_INET, connectFn, clientData, pollParams, &tempError4); tempPort = AsyncSocket_GetPort(BaseSocket(asock4)); if (tempPort == MAX_UINT32) { Log(ASOCKPREFIX "Could not resolve IPv4 listener socket port number.\n"); tempPort = port; } tempError6 = ASOCKERR_SUCCESS; asock6 = AsyncTCPSocketListenerCreateImpl(addrStr, tempPort, AF_INET6, connectFn, clientData, pollParams, &tempError6); if (!asock6 && tempError6 == ASOCKERR_BINDADDRINUSE) { Log(ASOCKPREFIX "Failed to reuse IPv4 localhost port number for " "IPv6 listener socket.\n"); AsyncSocket_Close(BaseSocket(asock4)); } } if (asock6 && asock4) { AsyncTCPSocket *asock; asock = AsyncTCPSocketCreate(pollParams); AsyncTCPSocketSetState(asock, AsyncSocketListening); asock->listenAsock6 = asock6; asock->listenAsock4 = asock4; AsyncSocket_SetErrorFn(BaseSocket(asock4), AsyncTCPSocketListenerError, asock); AsyncSocket_SetErrorFn(BaseSocket(asock6), AsyncTCPSocketListenerError, asock); return BaseSocket(asock); } else if (asock6) { return BaseSocket(asock6); } else if (asock4) { return BaseSocket(asock4); } if (outError) { /* Client only gets one error and the one for IPv6 is favored. */ if (!asock6) { *outError = tempError6; } else if (!asock4) { *outError = tempError4; } else { *outError = ASOCKERR_LISTEN; } } return NULL; } } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketListenerCreateLoopback -- * * Listens on loopback interface and port for all resolved socket * families and accepts new connections. Fires the connect callback with * new AsyncTCPSocket object for each connection. * * Results: * New AsyncTCPSocket in listening state or NULL on error. * * Side effects: * Creates new socket/s, binds and listens. * *---------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_ListenLoopback(unsigned int port, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT: optional { AsyncTCPSocket *asock6 = NULL; AsyncTCPSocket *asock4 = NULL; int tempError4; int tempError6; /* * "localhost6" does not work on Windows. "localhost" does * not work for IPv6 on old Linux versions like 2.6.18. So, * using IP address for both the cases to be consistent. */ asock6 = AsyncTCPSocketListenerCreateImpl("::1", port, AF_INET6, connectFn, clientData, pollParams, &tempError6); asock4 = AsyncTCPSocketListenerCreateImpl("127.0.0.1", port, AF_INET, connectFn, clientData, pollParams, &tempError4); if (asock6 && asock4) { AsyncTCPSocket *asock; asock = AsyncTCPSocketCreate(pollParams); AsyncTCPSocketSetState(asock, AsyncSocketListening); asock->listenAsock6 = asock6; asock->listenAsock4 = asock4; return BaseSocket(asock); } else if (asock6) { return BaseSocket(asock6); } else if (asock4) { return BaseSocket(asock4); } if (outError) { /* Client only gets one error and the one for IPv6 is favored. */ if (!asock6) { *outError = tempError6; } else if (!asock4) { *outError = tempError4; } else { *outError = ASOCKERR_LISTEN; } } return NULL; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocket_ListenVMCI -- * * Listens on the specified port and accepts new connections. Fires the * connect callback with new AsyncTCPSocket object for each connection. * * Results: * New AsyncTCPSocket in listening state or NULL on error. * * Side effects: * Creates new socket, binds and listens. * *---------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_ListenVMCI(unsigned int cid, // IN unsigned int port, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { struct sockaddr_vm addr; AsyncTCPSocket *asock; int vsockDev = -1; memset(&addr, 0, sizeof addr); addr.svm_family = VMCISock_GetAFValueFd(&vsockDev); addr.svm_cid = cid; addr.svm_port = port; asock = AsyncTCPSocketListenImpl((struct sockaddr_storage *)&addr, sizeof addr, connectFn, clientData, pollParams, outError); VMCISock_ReleaseAFValueFd(vsockDev); return BaseSocket(asock); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketInit -- * * This is an internal routine that sets up a SOCK_STREAM (TCP) socket. * * Results: * New AsyncTCPSocket or NULL on error. * * Side effects: * Creates new socket. * *---------------------------------------------------------------------------- */ static AsyncTCPSocket * AsyncTCPSocketInit(int socketFamily, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { AsyncTCPSocket *asock = NULL; int error = ASOCKERR_GENERIC; int sysErr; int fd; /* * Create a new socket */ if ((fd = socket(socketFamily, SOCK_STREAM, 0)) == -1) { sysErr = ASOCK_LASTERROR(); Warning(ASOCKPREFIX "could not create new socket, error %d: %s\n", sysErr, Err_Errno2String(sysErr)); goto errorNoFd; } /* * Wrap it with an asock object */ if ((asock = AsyncTCPSocketAttachToFd(fd, pollParams, &error)) == NULL) { goto error; } return asock; error: SSLGeneric_close(fd); errorNoFd: if (outError) { *outError = error; } return NULL; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetPortFromAddr -- * * This is an internal routine that gets a port given an address. The * address must be in either AF_INET, AF_INET6 or AF_VMCI format. * * Results: * Port number (in host byte order for INET). * * Side effects: * None. * *---------------------------------------------------------------------------- */ static unsigned int AsyncTCPSocketGetPortFromAddr(struct sockaddr_storage *addr) // IN { ASSERT(NULL != addr); if (AF_INET == addr->ss_family) { return ntohs(((struct sockaddr_in *)addr)->sin_port); } else if (AF_INET6 == addr->ss_family) { return ntohs(((struct sockaddr_in6 *)addr)->sin6_port); #ifndef _WIN32 } else if (AF_UNIX == addr->ss_family) { return MAX_UINT32; // Not applicable #endif } else { #ifdef VMX86_DEBUG int vsockDev = -1; ASSERT(VMCISock_GetAFValueFd(&vsockDev) == addr->ss_family); VMCISock_ReleaseAFValueFd(vsockDev); #endif return ((struct sockaddr_vm *)addr)->svm_port; } } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetPort -- * * Given an AsyncTCPSocket object, returns the port number associated with * the requested address family's file descriptor if available. * * Results: * Port number in host byte order. MAX_UINT32 on error. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static unsigned int AsyncTCPSocketGetPort(AsyncSocket *base) // IN { AsyncTCPSocket *asock = TCPSocket(base); AsyncTCPSocket *tempAsock; struct sockaddr_storage addr; socklen_t addrLen = sizeof addr; unsigned int ret = MAX_UINT32; if (asock->fd != -1) { tempAsock = asock; } else if (asock->listenAsock6 && asock->listenAsock6->fd != -1) { tempAsock = asock->listenAsock6; } else if (asock->listenAsock4 && asock->listenAsock4->fd != -1) { tempAsock = asock->listenAsock4; } else { return ret; } ASSERT(AsyncTCPSocketIsLocked(asock)); ASSERT(AsyncTCPSocketIsLocked(tempAsock)); if (AsyncTCPSocketGetAddr(tempAsock, AF_UNSPEC, &addr, &addrLen) == ASOCKERR_SUCCESS) { return AsyncTCPSocketGetPortFromAddr(&addr); } else { return MAX_UINT32; } return ret; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketOSVersionSupportsV4Mapped -- * * Determine if runtime environment supports IPv4-mapped IPv6 addressed * and all the functionality needed to deal with this scenario. * * Results: * Returns TRUE if supported. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static Bool AsyncTCPSocketOSVersionSupportsV4Mapped(void) { #if defined(_WIN32) && !defined(VM_WIN_UWP) OSVERSIONINFOW osvi = {sizeof(OSVERSIONINFOW)}; /* * Starting with msvc-12.0 / SDK v8.1 GetVersionEx is deprecated. * Bug 1259185 tracks switching to VerifyVersionInfo. */ #pragma warning(suppress : 4996) // 'function': was declared deprecated GetVersionExW(&osvi); /* Windows version is at least Vista or higher */ return osvi.dwMajorVersion >= 6; #else return TRUE; #endif } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketBind -- * * This is an internal routine that binds a socket to a port. * * Results: * Returns TRUE upon success, FALSE upon failure. * * Side effects: * Socket is bound to a particular port. * *---------------------------------------------------------------------------- */ static Bool AsyncTCPSocketBind(AsyncTCPSocket *asock, // IN struct sockaddr_storage *addr, // IN socklen_t addrLen, // IN int *outError) // OUT { int error = ASOCKERR_BIND; int sysErr; unsigned int port; ASSERT(NULL != asock); ASSERT(NULL != asock->sslSock); ASSERT(NULL != addr); port = AsyncTCPSocketGetPortFromAddr(addr); TCPSOCKLG0(asock, ("creating new listening socket on port %d\n", port)); #ifndef _WIN32 /* * Don't ever use SO_REUSEADDR on Windows; it doesn't mean what you think * it means. */ if (addr->ss_family == AF_INET || addr->ss_family == AF_INET6) { int reuse = port != 0; if (setsockopt(asock->fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &reuse, sizeof(reuse)) != 0) { sysErr = ASOCK_LASTERROR(); Warning(ASOCKPREFIX "could not set SO_REUSEADDR, error %d: %s\n", sysErr, Err_Errno2String(sysErr)); } } #else /* * Always set SO_EXCLUSIVEADDRUSE on Windows, to prevent other applications * from stealing this socket. (Yes, Windows is that stupid). */ { int exclusive = 1; if (setsockopt(asock->fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const void *) &exclusive, sizeof(exclusive)) != 0) { sysErr = ASOCK_LASTERROR(); Warning(ASOCKPREFIX "could not set SO_EXCLUSIVEADDRUSE, error %d: " "%s\n", sysErr, Err_Errno2String(sysErr)); } } #endif #if defined(IPV6_V6ONLY) /* * WINDOWS: By default V4MAPPED was not supported until Windows Vista. * IPV6_V6ONLY was disabled by default until Windows 7. So if we are binding * to a AF_INET6 socket and IPV6_V6ONLY existed, we need to turn it on no * matter what the setting is to disable V4 mapping. * * MAC OSX: Support for IPV6_V6ONLY can be found in 10.5+. * * LINUX: IPV6_V6ONLY was released after V4MAPPED was implemented. There is * no way to turn V4MAPPED off on those systems. The default behavior * differs from distro-to-distro so attempt to turn V4MAPPED off on all * systems that have IPV6_V6ONLY define. There is no good solution for the * case where we cannot enable IPV6_V6ONLY, if we error in this case and do * not have a IPv4 option then we render the application useless. * See AsyncTCPSocketAcceptInternal for the IN6_IS_ADDR_V4MAPPED validation * for incomming addresses to close this loophole. */ if (addr->ss_family == AF_INET6 && AsyncTCPSocketOSVersionSupportsV4Mapped()) { int on = 1; if (setsockopt(asock->fd, IPPROTO_IPV6, IPV6_V6ONLY, (const void *) &on, sizeof(on)) != 0) { Warning(ASOCKPREFIX "Cannot set IPV6_V6ONLY socket option.\n"); } } #else #error No compiler definition for IPV6_V6ONLY #endif /* * Bind to a port */ if (bind(asock->fd, (struct sockaddr *)addr, addrLen) != 0) { sysErr = ASOCK_LASTERROR(); if (sysErr == ASOCK_EADDRINUSE) { error = ASOCKERR_BINDADDRINUSE; } Warning(ASOCKPREFIX "Could not bind socket, error %d: %s\n", sysErr, Err_Errno2String(sysErr)); goto error; } return TRUE; error: SSL_Shutdown(asock->sslSock); free(asock); if (outError) { *outError = error; } return FALSE; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketListen -- * * This is an internal routine that calls listen() on a socket. * * Results: * Returns TRUE upon success, FALSE upon failure. * * Side effects: * Socket is in listening state. * *---------------------------------------------------------------------------- */ static Bool AsyncTCPSocketListen(AsyncTCPSocket *asock, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN int *outError) // OUT { VMwareStatus pollStatus; int error; ASSERT(NULL != asock); ASSERT(NULL != asock->sslSock); if (!connectFn) { Warning(ASOCKPREFIX "invalid arguments to listen!\n"); error = ASOCKERR_INVAL; goto error; } /* * Listen on the socket */ if (listen(asock->fd, 5) != 0) { int sysErr = ASOCK_LASTERROR(); Warning(ASOCKPREFIX "could not listen on socket, error %d: %s\n", sysErr, Err_Errno2String(sysErr)); error = ASOCKERR_LISTEN; goto error; } /* * Register a read callback to fire each time the socket * is ready for accept. */ AsyncTCPSocketLock(asock); pollStatus = AsyncTCPSocketPollAdd(asock, TRUE, POLL_FLAG_READ | POLL_FLAG_PERIODIC, AsyncTCPSocketAcceptCallback); if (pollStatus != VMWARE_STATUS_SUCCESS) { TCPSOCKWARN(asock, ("could not register accept callback!\n")); error = ASOCKERR_POLL; AsyncTCPSocketUnlock(asock); goto error; } AsyncTCPSocketSetState(asock, AsyncSocketListening); asock->connectFn = connectFn; asock->clientData = clientData; AsyncTCPSocketUnlock(asock); return TRUE; error: SSL_Shutdown(asock->sslSock); free(asock); if (outError) { *outError = error; } return FALSE; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketConnectImpl -- * * AsyncTCPSocket AF_INET/AF_INET6 connect. * * NOTE: This function can block. * * Results: * AsyncTCPSocket * on success and NULL on failure. * On failure, error is returned in *outError. * * Side effects: * Allocates an AsyncTCPSocket, registers a poll callback. * *---------------------------------------------------------------------------- */ static AsyncTCPSocket * AsyncTCPSocketConnectImpl(int socketFamily, // IN const char *hostname, // IN unsigned int port, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketConnectFlags flags, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT: optional { struct sockaddr_storage addr; int getaddrinfoError; int error; AsyncTCPSocket *asock; char *ipString = NULL; socklen_t addrLen; /* * Resolve the hostname. Handles dotted decimal strings, too. */ getaddrinfoError = AsyncTCPSocketResolveAddr(hostname, port, socketFamily, FALSE, &addr, &addrLen, &ipString); if (0 != getaddrinfoError) { Log(ASOCKPREFIX "Failed to resolve %s address '%s' and port %u\n", socketFamily == AF_INET ? "IPv4" : "IPv6", hostname, port); error = ASOCKERR_ADDRUNRESV; goto error; } Log(ASOCKPREFIX "creating new %s socket, connecting to %s (%s)\n", socketFamily == AF_INET ? "IPv4" : "IPv6", ipString, hostname); free(ipString); asock = AsyncTCPSocketConnect(&addr, addrLen, connectFn, clientData, flags, pollParams, &error); if (!asock) { Warning(ASOCKPREFIX "%s connection attempt failed: %s\n", socketFamily == AF_INET ? "IPv4" : "IPv6", AsyncSocket_MsgError(error)); goto error; } return asock; error: if (outError) { *outError = error; } return NULL; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocket_Connect -- * * AsyncTCPSocket connect. Connection is attempted with AF_INET socket * family, when that fails AF_INET6 is attempted. * * NOTE: This function can block. * * Results: * AsyncTCPSocket * on success and NULL on failure. * On failure, error is returned in *outError. * * Side effects: * Allocates an AsyncTCPSocket, registers a poll callback. * *---------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_Connect(const char *hostname, // IN unsigned int port, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketConnectFlags flags, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT: optional { int error = ASOCKERR_CONNECT; AsyncTCPSocket *asock = NULL; if (!connectFn || !hostname) { error = ASOCKERR_INVAL; Warning(ASOCKPREFIX "invalid arguments to connect!\n"); goto error; } asock = AsyncTCPSocketConnectImpl(AF_INET, hostname, port, connectFn, clientData, flags, pollParams, &error); if (!asock) { asock = AsyncTCPSocketConnectImpl(AF_INET6, hostname, port, connectFn, clientData, flags, pollParams, &error); } error: if (!asock && outError) { *outError = error; } return BaseSocket(asock); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocket_ConnectVMCI -- * * AsyncTCPSocket AF_VMCI constructor. Connects to the specified cid:port, * and passes the caller a valid asock via the callback once the * connection has been established. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * Allocates an AsyncTCPSocket, registers a poll callback. * *---------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_ConnectVMCI(unsigned int cid, // IN unsigned int port, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketConnectFlags flags, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT: optional { int vsockDev = -1; struct sockaddr_vm addr; AsyncTCPSocket *asock; memset(&addr, 0, sizeof addr); addr.svm_family = VMCISock_GetAFValueFd(&vsockDev); addr.svm_cid = cid; addr.svm_port = port; Log(ASOCKPREFIX "creating new socket, connecting to %u:%u\n", cid, port); asock = AsyncTCPSocketConnect((struct sockaddr_storage *)&addr, sizeof addr, connectFn, clientData, flags, pollParams, outError); VMCISock_ReleaseAFValueFd(vsockDev); return BaseSocket(asock); } #ifndef _WIN32 /* *---------------------------------------------------------------------------- * * AsyncSocket_ConnectUnixDomain -- * * AsyncTCPSocket AF_UNIX constructor. Connects to the specified unix socket, * and passes the caller a valid asock via the callback once the * connection has been established. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * Allocates an AsyncTCPSocket, registers a poll callback. * *---------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_ConnectUnixDomain(const char *path, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketConnectFlags flags, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { struct sockaddr_un addr; AsyncTCPSocket *asock; memset(&addr, 0, sizeof addr); addr.sun_family = AF_UNIX; if (strlen(path) + 1 > sizeof addr.sun_path) { Warning(ASOCKPREFIX "Path '%s' is too long for a unix domain socket!\n", path); return NULL; } Str_Strcpy(addr.sun_path, path, sizeof addr.sun_path); Log(ASOCKPREFIX "creating new socket, connecting to %s\n", path); asock = AsyncTCPSocketConnect((struct sockaddr_storage *)&addr, sizeof addr, connectFn, clientData, flags, pollParams, outError); return BaseSocket(asock); } #endif /* *---------------------------------------------------------------------------- * * AsyncTCPSocketConnectErrorCheck -- * * Check for error on a connecting socket and fire the connect callback * is any error is found. This is only used on Windows. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketConnectErrorCheck(void *data) // IN: AsyncTCPSocket * { AsyncTCPSocket *asock = data; Bool removed; PollerFunction func = NULL; ASSERT(AsyncTCPSocketIsLocked(asock)); if (AsyncTCPSocketGetState(asock) == AsyncSocketConnecting) { int sockErr = 0; int sockErrLen = sizeof sockErr; if (getsockopt(asock->fd, SOL_SOCKET, SO_ERROR, (void *)&sockErr, (void *)&sockErrLen) == 0) { if (sockErr == 0) { /* There is no error; keep waiting. */ return; } asock->genericErrno = sockErr; } else { asock->genericErrno = ASOCK_LASTERROR(); } TCPSOCKLG0(asock, ("Connection failed: %s\n", Err_Errno2String(asock->genericErrno))); /* Remove connect callback. */ removed = AsyncTCPSocketPollRemove(asock, TRUE, POLL_FLAG_WRITE, asock->internalConnectFn); ASSERT(removed); func = asock->internalConnectFn; } /* Remove this callback. */ removed = AsyncTCPSocketPollRemove(asock, FALSE, POLL_FLAG_PERIODIC, AsyncTCPSocketConnectErrorCheck); ASSERT(removed); asock->internalConnectFn = NULL; if (func) { func(asock); } } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketConnect -- * * Internal AsyncTCPSocket constructor. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_GENERIC. * * Side effects: * Allocates an AsyncTCPSocket, registers a poll callback. * *---------------------------------------------------------------------------- */ static AsyncTCPSocket * AsyncTCPSocketConnect(struct sockaddr_storage *addr, // IN socklen_t addrLen, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketConnectFlags flags, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { int fd; VMwareStatus pollStatus; AsyncTCPSocket *asock = NULL; int error = ASOCKERR_GENERIC; int sysErr; ASSERT(addr); if (!connectFn) { error = ASOCKERR_INVAL; Warning(ASOCKPREFIX "invalid arguments to connect!\n"); goto error; } /* * Create a new IP socket */ if ((fd = socket(addr->ss_family, SOCK_STREAM, 0)) == -1) { sysErr = ASOCK_LASTERROR(); Warning(ASOCKPREFIX "failed to create socket, error %d: %s\n", sysErr, Err_Errno2String(sysErr)); error = ASOCKERR_CONNECT; goto error; } /* * Wrap it with an asock */ if ((asock = AsyncTCPSocketAttachToFd(fd, pollParams, &error)) == NULL) { SSLGeneric_close(fd); goto error; } /* * Call connect(), which can either succeed immediately or return an error * indicating that the connection is in progress. In the latter case, we * can poll the fd for write to find out when the connection attempt * has succeeded (or failed). In either case, we want to invoke the * caller's connect callback from Poll rather than directly, so if the * connection succeeds immediately, we just schedule the connect callback * as a one-time (RTime) callback instead. */ AsyncTCPSocketLock(asock); if (connect(asock->fd, (struct sockaddr *)addr, addrLen) != 0) { if (ASOCK_LASTERROR() == ASOCK_ECONNECTING) { ASSERT(!(vmx86_server && addr->ss_family == AF_UNIX)); TCPSOCKLOG(1, asock, ("registering write callback for socket connect\n")); pollStatus = AsyncTCPSocketPollAdd(asock, TRUE, POLL_FLAG_WRITE, AsyncTCPSocketConnectCallback); if (vmx86_win32 && pollStatus == VMWARE_STATUS_SUCCESS && AsyncTCPSocketPollParams(asock)->iPoll == NULL) { /* * Work around WSAPoll's bug of not reporting failed connection * by periodically (500 ms) checking for error. */ pollStatus = AsyncTCPSocketPollAdd(asock, FALSE, POLL_FLAG_PERIODIC, AsyncTCPSocketConnectErrorCheck, 500 * 1000); if (pollStatus == VMWARE_STATUS_SUCCESS) { asock->internalConnectFn = AsyncTCPSocketConnectCallback; } else { TCPSOCKLG0(asock, ("failed to register periodic error check\n")); AsyncTCPSocketPollRemove(asock, TRUE, POLL_FLAG_WRITE, AsyncTCPSocketConnectCallback); } } } else { sysErr = ASOCK_LASTERROR(); Log(ASOCKPREFIX "connect failed, error %d: %s\n", sysErr, Err_Errno2String(sysErr)); /* * If "network unreachable" error happens, explicitly propogate * the error to trigger the reconnection if possible. */ error = (sysErr == ASOCK_ENETUNREACH) ? ASOCKERR_NETUNREACH : ASOCKERR_CONNECT; goto errorHaveAsock; } } else { TCPSOCKLOG(2, asock, ("socket connected, registering RTime callback for connect\n")); pollStatus = AsyncTCPSocketPollAdd(asock, FALSE, 0, AsyncTCPSocketConnectCallback, 0); } if (pollStatus != VMWARE_STATUS_SUCCESS) { TCPSOCKWARN(asock, ("failed to register callback in connect!\n")); error = ASOCKERR_POLL; goto errorHaveAsock; } AsyncTCPSocketSetState(asock, AsyncSocketConnecting); asock->connectFn = connectFn; asock->clientData = clientData; /* Store a copy of the sockaddr_storage so we can look it up later. */ asock->remoteAddr = *addr; asock->remoteAddrLen = addrLen; AsyncTCPSocketUnlock(asock); return asock; errorHaveAsock: SSL_Shutdown(asock->sslSock); AsyncTCPSocketUnlock(asock); free(asock); error: if (outError) { *outError = error; } return NULL; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketCreate -- * * AsyncSocket constructor for fields common to all TCP-based * AsyncSocket types. * * Results: * New AsyncSocket object. * * Side effects: * Allocates memory. * *---------------------------------------------------------------------------- */ static AsyncTCPSocket * AsyncTCPSocketCreate(AsyncSocketPollParams *pollParams) // IN { AsyncTCPSocket *s; s = Util_SafeCalloc(1, sizeof *s); AsyncSocketInitSocket(BaseSocket(s), pollParams, &asyncTCPSocketVTable); s->fd = -1; s->inRecvLoop = FALSE; s->sendBufFull = FALSE; s->sendBufTail = &(s->sendBufList); s->passFd.fd = -1; if (pollParams && pollParams->iPoll) { s->internalSendFn = AsyncTCPSocketIPollSendCallback; s->internalRecvFn = AsyncTCPSocketIPollRecvCallback; } else { s->internalSendFn = AsyncTCPSocketSendCallback; s->internalRecvFn = AsyncTCPSocketRecvCallback; } return s; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketAttachToSSLSock -- * * AsyncTCPSocket constructor. Wraps an existing SSLSock object with an * AsyncTCPSocket and returns the latter. * * Results: * New AsyncTCPSocket object or NULL on error. * * Side effects: * Allocates memory, makes the underlying fd for the socket non-blocking. * *---------------------------------------------------------------------------- */ static AsyncTCPSocket * AsyncTCPSocketAttachToSSLSock(SSLSock sslSock, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { AsyncTCPSocket *s; int fd; int error; ASSERT(sslSock); fd = SSL_GetFd(sslSock); if ((AsyncTCPSocketMakeNonBlocking(fd)) != ASOCKERR_SUCCESS) { int sysErr = ASOCK_LASTERROR(); Warning(ASOCKPREFIX "failed to make fd %d non-blocking!: %d, %s\n", fd, sysErr, Err_Errno2String(sysErr)); error = ASOCKERR_GENERIC; goto error; } s = AsyncTCPSocketCreate(pollParams); AsyncTCPSocketSetState(s, AsyncSocketConnected); s->sslSock = sslSock; s->fd = fd; /* From now on socket is ours. */ SSL_SetCloseOnShutdownFlag(sslSock); TCPSOCKLOG(1, s, ("new asock id %u attached to fd %d\n", s->base.id, s->fd)); return s; error: if (outError) { *outError = error; } return NULL; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketAttachToFd -- * * AsyncTCPSocket constructor. Wraps a valid socket fd with an * AsyncTCPSocket object. * * Results: * New AsyncTCPSocket or NULL on error. * * Side effects: * If function succeeds, fd is owned by AsyncTCPSocket and should not be * used (f.e. closed) anymore. * *---------------------------------------------------------------------------- */ static AsyncTCPSocket * AsyncTCPSocketAttachToFd(int fd, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { SSLSock sslSock; AsyncTCPSocket *asock; /* * Create a new SSL socket object with the current socket */ if (!(sslSock = SSL_New(fd, FALSE))) { if (outError) { *outError = ENOMEM; } LOG(0, (ASOCKPREFIX "failed to create SSL socket object\n")); return NULL; } asock = AsyncTCPSocketAttachToSSLSock(sslSock, pollParams, outError); if (asock) { return asock; } SSL_Shutdown(sslSock); return NULL; } /* *---------------------------------------------------------------------------- * * AsyncSocket_AttachToFd -- * * Wrap a pre-existing file descriptor in an AsyncSocket entity. * * Results: * New AsyncSocket or NULL on error. * * Side effects: * If function succeeds, fd is owned by AsyncSocket and should not be * used (f.e. closed) anymore. * *---------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_AttachToFd(int fd, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { AsyncTCPSocket *asock; asock = AsyncTCPSocketAttachToFd(fd, pollParams, outError); return BaseSocket(asock); } /* *---------------------------------------------------------------------------- * * AsyncSocket_AttachToSSLSock -- * * Wrap a pre-existing SSLSock in an AsyncSocket entity. * * Results: * New AsyncSocket or NULL on error. * * Side effects: * If function succeeds, fd is owned by AsyncSocket and should not be * used (f.e. closed) anymore. * *---------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_AttachToSSLSock(SSLSock sslSock, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { AsyncTCPSocket *asock; asock = AsyncTCPSocketAttachToSSLSock(sslSock, pollParams, outError); return BaseSocket(asock); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketRegisterRecvCb -- * * Register poll callbacks as required to be notified when data is ready * following a AsyncTCPSocket_Recv call. * * Results: * ASOCKERR_*. * * Side effects: * Could register poll callback. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketRegisterRecvCb(AsyncTCPSocket *asock) // IN: { int retVal = ASOCKERR_SUCCESS; if (!asock->recvCb) { VMwareStatus pollStatus; /* * Register the Poll callback */ TCPSOCKLOG(3, asock, ("installing recv periodic poll callback\n")); pollStatus = AsyncTCPSocketPollAdd(asock, TRUE, POLL_FLAG_READ | POLL_FLAG_PERIODIC, asock->internalRecvFn); if (pollStatus != VMWARE_STATUS_SUCCESS) { TCPSOCKWARN(asock, ("failed to install recv callback!\n")); retVal = ASOCKERR_POLL; goto out; } asock->recvCb = TRUE; } if (AsyncTCPSocketHasDataPending(asock) && !asock->inRecvLoop) { TCPSOCKLOG(0, asock, ("installing recv RTime poll callback\n")); if (AsyncTCPSocketPollAdd(asock, FALSE, 0, asock->internalRecvFn, 0) != VMWARE_STATUS_SUCCESS) { retVal = ASOCKERR_POLL; goto out; } asock->recvCbTimer = TRUE; } out: return retVal; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocket_Recv -- * * Registers a callback that will fire once the specified amount of data * has been received on the socket. * * In the case of AsyncTCPSocket_RecvPartial, the callback is fired * once all or part of the data has been received on the socket. * * Data that was not retrieved at the last call of SSL_read() could still * be buffered inside the SSL layer and will be retrieved on the next * call to SSL_read(). However poll/select might not mark the socket as * for reading since there might not be any data in the underlying network * socket layer. Hence in the read callback, we keep spinning until all * all the data buffered inside the SSL layer is retrieved before * returning to the poll loop (See AsyncTCPSocketFillRecvBuffer()). * * However, we might not have come out of Poll in the first place, e.g. * if this is the first call to AsyncTCPSocket_Recv() after creating a new * connection. In this situation, if there is buffered SSL data pending, * we have to schedule an RTTime callback to force retrieval of the data. * This could also happen if the client calls AsyncTCPSocket_RecvBlocking, * some data is left in the SSL layer, and the client then calls * AsyncTCPSocket_Recv. We use the inRecvLoop variable to detect and handle * this condition, i.e., if inRecvLoop is FALSE, we need to schedule the * RTime callback. * * TCP usage: * AsyncTCPSocket_Recv(AsyncTCPSocket *asock, * void *buf, * int len, * AsyncSocketRecvFn recvFn, * void *clientData) * * Results: * ASOCKERR_*. * * Side effects: * Could register poll callback. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketRecv(AsyncSocket *base, // IN: void *buf, // IN: unused int len, // IN: unused Bool fireOnPartial, // IN: void *cb, // IN: void *cbData) // IN: { AsyncTCPSocket *asock = TCPSocket(base); int retVal; if (!asock->base.errorFn) { TCPSOCKWARN(asock, ("%s: no registered error handler!\n", __FUNCTION__)); return ASOCKERR_INVAL; } /* * XXX We might want to allow passing NULL for the recvFn, to indicate that * the client is no longer interested in reading from the socket. This * would be useful e.g. for HTTP, where the client sends a request and * then the client->server half of the connection is closed. */ if (!buf || !cb || len <= 0) { Warning(ASOCKPREFIX "Recv called with invalid arguments!\n"); return ASOCKERR_INVAL; } ASSERT(AsyncTCPSocketIsLocked(asock)); if (AsyncTCPSocketGetState(asock) != AsyncSocketConnected) { TCPSOCKWARN(asock, ("recv called but state is not connected!\n")); return ASOCKERR_NOTCONNECTED; } if (asock->inBlockingRecv) { TCPSOCKWARN(asock, ("Recv called while a blocking recv is pending.\n")); return ASOCKERR_INVAL; } retVal = AsyncTCPSocketRegisterRecvCb(asock); if (retVal != ASOCKERR_SUCCESS) { return retVal; } AsyncSocketSetRecvBuf(BaseSocket(asock), buf, len, fireOnPartial, cb, cbData); return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketRecvPassedFd -- * * See AsyncTCPSocket_Recv. Besides that it allows for receiving one * file descriptor... * * Results: * ASOCKERR_*. * * Side effects: * Could register poll callback. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketRecvPassedFd(AsyncSocket *base, // IN/OUT: socket void *buf, // OUT: buffer with data int len, // IN: length void *cb, // IN: completion calback void *cbData) // IN: callback's data { AsyncTCPSocket *asock = TCPSocket(base); int err; if (!asock->base.errorFn) { TCPSOCKWARN(asock, ("%s: no registered error handler!\n", __FUNCTION__)); return ASOCKERR_INVAL; } ASSERT(AsyncTCPSocketIsLocked(asock)); if (asock->passFd.fd != -1) { SSLGeneric_close(asock->passFd.fd); asock->passFd.fd = -1; } asock->passFd.expected = TRUE; err = AsyncTCPSocketRecv(BaseSocket(asock), buf, len, FALSE, cb, cbData); if (err != ASOCKERR_SUCCESS) { asock->passFd.expected = FALSE; } return err; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketPollWork -- * * Blocks on the specified sockets until there's data pending or a * timeout occurs. * * If the asyncsocket is a dual stack listener, parentSock will not be * NULL, and the asock array will contain the IPv4 and v6 sockets. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call * failures * ASOCKERR_TIMEOUT if we just didn't receive enough data. * * Side effects: * None. *---------------------------------------------------------------------------- */ static int AsyncTCPSocketPollWork(AsyncTCPSocket **asock, // IN: int numSock, // IN: void *p, // IN: Bool read, // IN: int timeoutMS, // IN: AsyncTCPSocket *parentSock, // IN: AsyncTCPSocket **outAsock) // OUT: { AsyncTCPSocket *warnSock = parentSock ? parentSock : asock[0]; #ifndef _WIN32 struct pollfd *pfd = (struct pollfd *)p; #else /* * We use select() to do this on Windows, since there ain't no poll(). * Fortunately, select() doesn't have the 1024 fd value limit. */ struct timeval tv; struct fd_set rwfds; struct fd_set exceptfds; #endif int i; int retval; ASSERT(outAsock != NULL && *outAsock == NULL && asock != NULL && numSock > 0); for (i = 0; i < numSock; i++) { if (read && SSL_Pending(asock[i]->sslSock)) { *outAsock = asock[i]; return ASOCKERR_SUCCESS; } } while (1) { #ifndef _WIN32 for (i = 0; i < numSock; i++) { pfd[i].fd = asock[i]->fd; pfd[i].events = read ? POLLIN : POLLOUT; } if (parentSock != NULL) { AsyncTCPSocketUnlock(parentSock); retval = poll(pfd, numSock, timeoutMS); AsyncTCPSocketLock(parentSock); } else { for (i = numSock - 1; i >= 0; i--) { AsyncTCPSocketUnlock(asock[i]); } retval = poll(pfd, numSock, timeoutMS); for (i = 0; i < numSock; i++) { AsyncTCPSocketLock(asock[i]); } } #else tv.tv_sec = timeoutMS / 1000; tv.tv_usec = (timeoutMS % 1000) * 1000; FD_ZERO(&rwfds); FD_ZERO(&exceptfds); for (i = 0; i < numSock; i++) { FD_SET(asock[i]->fd, &rwfds); FD_SET(asock[i]->fd, &exceptfds); } if (parentSock != NULL) { AsyncTCPSocketUnlock(parentSock); retval = select(1, read ? &rwfds : NULL, read ? NULL : &rwfds, &exceptfds, timeoutMS >= 0 ? &tv : NULL); AsyncTCPSocketLock(parentSock); } else { for (i = numSock - 1; i >= 0; i--) { AsyncTCPSocketUnlock(asock[i]); } retval = select(1, read ? &rwfds : NULL, read ? NULL : &rwfds, &exceptfds, timeoutMS >= 0 ? &tv : NULL); for (i = 0; i < numSock; i++) { AsyncTCPSocketLock(asock[i]); } } #endif switch (retval) { case 0: /* * No sockets were ready within the specified time. */ TCPSOCKLG0(warnSock, ("%s: Timeout waiting for a ready socket.\n", __FUNCTION__)); return ASOCKERR_TIMEOUT; case -1: { int sysErr = ASOCK_LASTERROR(); if (sysErr == EINTR) { /* * We were somehow interrupted by signal. Let's loop and retry. * XXX: update the timeout by the amount we had previously waited. */ TCPSOCKLG0(warnSock, ("%s: Socket interrupted by a signal.\n", __FUNCTION__)); continue; } if (parentSock != NULL) { parentSock->genericErrno = sysErr; } else { for (i = 0; i < numSock; i++) { asock[i]->genericErrno = sysErr; } } TCPSOCKLG0(warnSock, ("%s: Failed with error %d: %s\n", __FUNCTION__, sysErr, Err_Errno2String(sysErr))); return ASOCKERR_GENERIC; } default: { Bool failed = FALSE; #ifndef _WIN32 for (i = 0; i < numSock; i++) { if (pfd[i].revents & (POLLERR | POLLNVAL)) { failed = TRUE; } } #else for (i = 0; i < numSock; i++) { if (FD_ISSET(asock[i]->fd, &exceptfds)) { failed = TRUE; } } #endif if (failed) { int sockErr = 0; int sysErr; int sockErrLen = sizeof sockErr; for (i = 0; i < numSock; i++) { if (getsockopt(asock[i]->fd, SOL_SOCKET, SO_ERROR, (void *) &sockErr, (void *) &sockErrLen) == 0) { if (sockErr) { asock[i]->genericErrno = sockErr; TCPSOCKLG0(asock[i], ("%s: Socket error lookup returned %d: %s\n", __FUNCTION__, sockErr, Err_Errno2String(sockErr))); } } else { sysErr = ASOCK_LASTERROR(); asock[i]->genericErrno = sysErr; TCPSOCKLG0(asock[i], ("%s: Last socket error %d: %s\n", __FUNCTION__, sysErr, Err_Errno2String(sysErr))); } } return ASOCKERR_GENERIC; } /* * If one socket is ready, and it wasn't in an exception state, * everything is ok. The socket is ready for reading/writing. */ #ifndef _WIN32 for (i = 0; i < numSock; i++) { if (pfd[i].revents & (read ? POLLIN : POLLOUT)) { *outAsock = asock[i]; return ASOCKERR_SUCCESS; } } #else for (i = 0; i < numSock; i++) { if (FD_ISSET(asock[i]->fd, &rwfds)) { *outAsock = asock[i]; return ASOCKERR_SUCCESS; } } #endif TCPSOCKWARN(warnSock, ("%s: Failed to return a ready socket.\n", __FUNCTION__)); return ASOCKERR_GENERIC; } } } } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketPoll -- * * Blocks on the specified socket until there's data pending or a * timeout occurs. * * If the specified socket is a dual stack listener, we will poll on all * listening sockets and will return when one is ready with data for a * connection. If both socket families happen to race with connect data, * we will favor IPv6 for the return. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call * failures * ASOCKERR_TIMEOUT if we just didn't receive enough data. * * Side effects: * None. *---------------------------------------------------------------------------- */ static int AsyncTCPSocketPoll(AsyncTCPSocket *s, // IN: Bool read, // IN: int timeoutMS, // IN: AsyncTCPSocket **outAsock) // OUT: { AsyncTCPSocket *asock[2]; #ifndef _WIN32 struct pollfd p[2]; #else void *p = NULL; #endif int numSock = 0; if (read && s->fd == -1) { if (!s->listenAsock4 && !s->listenAsock6) { TCPSOCKLG0(s, ("%s: Failed to find listener socket.\n", __FUNCTION__)); return ASOCKERR_GENERIC; } if (s->listenAsock6 && s->listenAsock6->fd != -1) { asock[numSock++] = s->listenAsock6; } if (s->listenAsock4 && s->listenAsock4->fd != -1) { asock[numSock++] = s->listenAsock4; } } else { asock[numSock++] = s; } return AsyncTCPSocketPollWork(asock, numSock, p, read, timeoutMS, s, outAsock); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketWaitForReadMultiple -- * * Blocks on the list of sockets until there's data readable or a * timeout occurs. * * Please see the comment in asyncSocketInterface.c for more * information about using this function. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call * failures * ASOCKERR_TIMEOUT if no sockets were ready with readable data. * * Side effects: * None. *---------------------------------------------------------------------------- */ static int AsyncTCPSocketWaitForReadMultiple(AsyncSocket **asock, // IN: int numSock, // IN: int timeoutMS, // IN: int *outIdx) // OUT: { int i; int err; AsyncTCPSocket *outAsock = NULL; #ifndef _WIN32 struct pollfd *p = Util_SafeCalloc(numSock, sizeof *p); #else void *p = NULL; #endif for (i = 0; i < numSock; i++) { ASSERT(AsyncTCPSocketIsLocked(TCPSocket(asock[i]))); } err = AsyncTCPSocketPollWork((AsyncTCPSocket **)asock, numSock, p, TRUE, timeoutMS, NULL, &outAsock); for (i = numSock - 1; i >= 0; i--) { AsyncTCPSocket *tcpAsock = TCPSocket(asock[i]); if (outAsock == tcpAsock) { *outIdx = i; } } free(p); return err; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketRecvBlocking -- * AsyncTCPSocketRecvPartialBlocking -- * AsyncTCPSocketSendBlocking -- * * Implement "blocking + timeout" operations on the socket. These are * simple wrappers around the AsyncTCPSocketBlockingWork function, which * operates on the actual non-blocking socket, using poll to determine * when it's ok to keep reading/writing. If we can't finish within the * specified time, we give up and return the ASOCKERR_TIMEOUT error. * * Note that if these are called from a callback and a lock is being * used (pollParams.lock), the whole blocking operation takes place * with that lock held. Regardless, it is the caller's responsibility * to make sure the synchronous and asynchronous operations do not mix. * * Results: * ASOCKERR_SUCCESS if we finished the operation, ASOCKERR_* error codes * otherwise. * * Side effects: * Reads/writes the socket. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketRecvBlocking(AsyncSocket *base, // IN void *buf, // OUT int len, // IN int *received, // OUT int timeoutMS) // IN { AsyncTCPSocket *s = TCPSocket(base); return AsyncTCPSocketBlockingWork(s, TRUE, buf, len, received, timeoutMS, FALSE); } static int AsyncTCPSocketRecvPartialBlocking(AsyncSocket *base, // IN void *buf, // OUT int len, // IN int *received, // OUT int timeoutMS) // IN { AsyncTCPSocket *s = TCPSocket(base); return AsyncTCPSocketBlockingWork(s, TRUE, buf, len, received, timeoutMS, TRUE); } static int AsyncTCPSocketSendBlocking(AsyncSocket *base, // IN void *buf, // OUT int len, // IN int *sent, // OUT int timeoutMS) // IN { AsyncTCPSocket *s = TCPSocket(base); return AsyncTCPSocketBlockingWork(s, FALSE, buf, len, sent, timeoutMS, FALSE); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketBlockingWork -- * * Try to complete the specified read/write operation within the * specified time. * * Results: * ASOCKERR_*. * * Side effects: * None. *---------------------------------------------------------------------------- */ static int AsyncTCPSocketBlockingWork(AsyncTCPSocket *s, // IN: Bool read, // IN: void *buf, // IN/OUT: int len, // IN: int *completed, // OUT: int timeoutMS, // IN: Bool partial) // IN: { VmTimeType now, done; int sysErr; if (s == NULL || buf == NULL || len <= 0) { Warning(ASOCKPREFIX "Recv called with invalid arguments!\n"); return ASOCKERR_INVAL; } if (AsyncTCPSocketGetState(s) != AsyncSocketConnected) { TCPSOCKWARN(s, ("recv called but state is not connected!\n")); return ASOCKERR_NOTCONNECTED; } if (completed) { *completed = 0; } now = Hostinfo_SystemTimerUS() / 1000; done = now + timeoutMS; do { int numBytes, error; AsyncTCPSocket *asock = NULL; if ((numBytes = read ? SSL_Read(s->sslSock, buf, len) : SSL_Write(s->sslSock, buf, len)) > 0) { if (completed) { *completed += numBytes; } len -= numBytes; if (len == 0 || partial) { return ASOCKERR_SUCCESS; } buf = (uint8*)buf + numBytes; } else if (numBytes == 0) { TCPSOCKLG0(s, ("blocking %s detected peer closed connection\n", read ? "recv" : "send")); return ASOCKERR_REMOTE_DISCONNECT; } else if ((sysErr = ASOCK_LASTERROR()) != ASOCK_EWOULDBLOCK) { s->genericErrno = sysErr; TCPSOCKWARN(s, ("blocking %s error %d: %s\n", read ? "recv" : "send", sysErr, Err_Errno2String(sysErr))); return ASOCKERR_GENERIC; } now = Hostinfo_SystemTimerUS() / 1000; if (now >= done && timeoutMS >= 0) { return ASOCKERR_TIMEOUT; } /* * Only call in to Poll if we weren't able to send/recv directly * off the socket. But always make sure that the call to Poll() * is followed by a read/send. */ error = AsyncTCPSocketPoll(s, read, done - now, &asock); if (error != ASOCKERR_SUCCESS) { return error; } ASSERT(asock == s); } while (TRUE); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketSend -- * * Queues the provided data for sending on the socket. If a send callback * is provided, the callback is fired after the data has been written to * the socket. Note that this only guarantees that the data has been * copied to the transmit buffer, we make no promises about whether it * has actually been transmitted, or received by the client, when the * callback is fired. * * Send callbacks should also be able to deal with being called if none * or only some of the queued buffer has been transmitted, since the send * callbacks for any remaining buffers are fired by AsyncSocket_Close(). * This condition can be detected by checking the len parameter passed to * the send callback. * * Results: * ASOCKERR_*. * * Side effects: * May register poll callback or perform I/O. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketSend(AsyncSocket *base, // IN void *buf, // IN int len, // IN AsyncSocketSendFn sendFn, // IN void *clientData) // IN { AsyncTCPSocket *asock = TCPSocket(base); int retVal; Bool bufferListWasEmpty = FALSE; SendBufList **pcur; SendBufList *newBuf; /* * Note: I think it should be fine to send with a length of zero and a * buffer of NULL or any other garbage value. However the code * downstream of here is unprepared for it (silently misbehaves). Hence * the <= zero check instead of just a < zero check. --Jeremy. */ if (!buf || len <= 0) { Warning(ASOCKPREFIX "Send called with invalid arguments!" "buffer: %p length: %d\n", buf, len); return ASOCKERR_INVAL; } LOG(2, ("%s: sending %d bytes\n", __FUNCTION__, len)); ASSERT(AsyncTCPSocketIsLocked(asock)); /* * In low-latency mode, we want to guard against recursive calls to * Send from within the send callback, as these have the capacity * to blow up the stack. However some operations generate implicit * sends (such as Close on a websocket) seem like they should be * legal from the send callback. So, allow a small degree of * recursive use of the send callback to accomodate these internal * paths. */ ASSERT(asock->inLowLatencySendCb < 2); if (AsyncTCPSocketGetState(asock) != AsyncSocketConnected) { TCPSOCKWARN(asock, ("send called but state is not connected!\n")); return ASOCKERR_NOTCONNECTED; } /* * Allocate and initialize new send buffer entry */ newBuf = Util_SafeCalloc(1, sizeof *newBuf); newBuf->buf = buf; newBuf->len = len; newBuf->sendFn = sendFn; newBuf->clientData = clientData; /* * Append new send buffer to the tail of list. */ *asock->sendBufTail = newBuf; asock->sendBufTail = &(newBuf->next); bufferListWasEmpty = (asock->sendBufList == newBuf); if (bufferListWasEmpty && !asock->sendCb) { if (asock->sendLowLatency) { /* * For low-latency sockets, call the callback directly from * this thread. It is non-blocking and will schedule device * callbacks if necessary to complete the operation. * * Unfortunately we can't make this the default as current * consumers of asyncsocket are not expecting the completion * callback to be invoked prior to the call to * AsyncTCPSocket_Send() returning. */ asock->inLowLatencySendCb++; asock->internalSendFn((void *)asock); asock->inLowLatencySendCb--; } else { #ifdef _WIN32 /* * If the send buffer list was empty, we schedule a one-time * callback to "prime" the output. This is necessary to * support the FD_WRITE network event semantic for sockets on * Windows (see WSAEventSelect documentation). The event * won't signal unless a previous write() on the socket * failed with WSAEWOULDBLOCK, so we have to perform at least * one partial write before we can start polling for write. * * XXX: This can be a device callback once all poll * implementations know to get around this Windows quirk. * Both PollVMX and PollDefault already make 0-byte send() to * force WSAEWOULDBLOCK. */ if (AsyncTCPSocketPollAdd(asock, FALSE, 0, asock->internalSendFn, AsyncTCPSocketPollParams(asock)->iPoll != NULL ? 1 : 0) != VMWARE_STATUS_SUCCESS) { retVal = ASOCKERR_POLL; TCPSOCKLOG(1, asock, ("Failed to register poll callback for send\n")); goto outUndoAppend; } asock->sendCbTimer = TRUE; asock->sendCb = TRUE; #else if (AsyncTCPSocketPollAdd(asock, TRUE, POLL_FLAG_WRITE, asock->internalSendFn) != VMWARE_STATUS_SUCCESS) { retVal = ASOCKERR_POLL; TCPSOCKLOG(1, asock, ("Failed to register poll callback for send\n")); goto outUndoAppend; } asock->sendCb = TRUE; #endif } } return ASOCKERR_SUCCESS; outUndoAppend: /* * Remove the appended buffer from the sendBufList. We always append the * buffer to the tail of the list. */ pcur = &asock->sendBufList; if (*pcur != NULL) { if (!bufferListWasEmpty) { do { pcur = &((*pcur)->next); } while ((*pcur)->next != NULL); } if ((*pcur)->buf == buf) { free(*pcur); *pcur = NULL; asock->sendBufTail = pcur; } } return retVal; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketResolveAddr -- * * Resolves a hostname and port. * * Results: * Zero upon success. This returns whatever getaddrinfo() returns. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketResolveAddr(const char *hostname, // IN unsigned int port, // IN int family, // IN Bool passive, // IN struct sockaddr_storage *addr, // OUT socklen_t *addrLen, // OUT char **addrString) // OUT { struct addrinfo hints; struct addrinfo *aiTop = NULL; struct addrinfo *aiIterator = NULL; int getaddrinfoError = 0; char portString[PORT_STRING_LEN]; ASSERT(NULL != addr); if (port > MAX_UINT16) { Log(ASOCKPREFIX "port number requested (%d) is out of range.\n", port); return EAI_SERVICE; } Str_Sprintf(portString, sizeof(portString), "%d", port); memset(&hints, 0, sizeof(hints)); hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; if (passive) { hints.ai_flags = AI_PASSIVE; } getaddrinfoError = Posix_GetAddrInfo(hostname, portString, &hints, &aiTop); if (0 != getaddrinfoError) { Log(ASOCKPREFIX "getaddrinfo failed for host %s: %s\n", hostname, gai_strerror(getaddrinfoError)); goto bye; } for (aiIterator = aiTop; NULL != aiIterator ; aiIterator = aiIterator->ai_next) { if ((family == AF_UNSPEC && (aiIterator->ai_family == AF_INET || aiIterator->ai_family == AF_INET6)) || family == aiIterator->ai_family) { if (addrString != NULL) { char tempAddrString[ADDR_STRING_LEN]; static char unknownAddr[] = "(Unknown)"; #if defined(_WIN32) DWORD len = ARRAYSIZE(tempAddrString); if (WSAAddressToStringA(aiIterator->ai_addr, aiIterator->ai_addrlen, NULL, tempAddrString, &len)) { *addrString = Util_SafeStrdup(unknownAddr); } else { *addrString = Util_SafeStrdup(tempAddrString); } #else if (aiIterator->ai_family == AF_INET && !inet_ntop(aiIterator->ai_family, &(((struct sockaddr_in *)aiIterator->ai_addr)->sin_addr), tempAddrString, INET6_ADDRSTRLEN)) { *addrString = Util_SafeStrdup(unknownAddr); } else if (aiIterator->ai_family == AF_INET6 && !inet_ntop(aiIterator->ai_family, &(((struct sockaddr_in6 *)aiIterator->ai_addr)->sin6_addr), tempAddrString, INET6_ADDRSTRLEN)) { *addrString = Util_SafeStrdup(unknownAddr); } else { *addrString = Str_SafeAsprintf(NULL, aiIterator->ai_family == AF_INET6 ? "[%s]:%u" : "%s:%u", tempAddrString, port); } #endif } memcpy(addr, aiIterator->ai_addr, aiIterator->ai_addrlen); *addrLen = aiIterator->ai_addrlen; break; } } bye: if (NULL != aiTop) { Posix_FreeAddrInfo(aiTop); } return getaddrinfoError; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketFillRecvBuffer -- * * Called when an asock has data ready to be read via the poll callback. * * Results: * ASOCKERR_SUCCESS if everything worked, * ASOCKERR_REMOTE_DISCONNECT if peer closed connection gracefully, * ASOCKERR_CLOSED if trying to read from a closed socket. * ASOCKERR_GENERIC for other errors. * * Side effects: * Reads data, could fire recv completion or trigger socket destruction. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketFillRecvBuffer(AsyncTCPSocket *s) // IN { int recvd; int needed; int sysErr = 0; int result; int pending = 0; ASSERT(AsyncTCPSocketIsLocked(s)); ASSERT(AsyncTCPSocketGetState(s) == AsyncSocketConnected); /* * When a socket has received all its desired content and FillRecvBuffer is * called again for the same socket, just return ASOCKERR_SUCCESS. The * reason we need this hack is that if a client which registered a receive * callback asynchronously later changes its mind to do it synchronously, * (e.g. aioMgr wait function), then FillRecvBuffer can be potentially be * called twice for the same receive event. */ needed = s->base.recvLen - s->base.recvPos; if (!s->base.recvBuf && needed == 0) { return ASOCKERR_SUCCESS; } ASSERT(needed > 0); AsyncTCPSocketAddRef(s); /* * See comment in AsyncTCPSocket_Recv */ s->inRecvLoop = TRUE; do { /* * Try to read the remaining bytes to complete the current recv request. */ if (s->passFd.expected) { int fd; recvd = SSL_RecvDataAndFd(s->sslSock, (uint8 *) s->base.recvBuf + s->base.recvPos, needed, &fd); if (fd != -1) { s->passFd.fd = fd; s->passFd.expected = FALSE; } } else { recvd = SSL_Read(s->sslSock, (uint8 *) s->base.recvBuf + s->base.recvPos, needed); } TCPSOCKLOG(3, s, ("need\t%d\trecv\t%d\tremain\t%d\n", needed, recvd, needed - recvd)); if (recvd > 0) { s->sslConnected = TRUE; s->base.recvPos += recvd; if (AsyncSocketCheckAndDispatchRecv(&s->base, &result)) { goto exit; } } else if (recvd == 0) { TCPSOCKLG0(s, ("recv detected client closed connection\n")); /* * We treat this as an error so that the owner can detect closing * of connection by peer (via the error handler callback). */ result = ASOCKERR_REMOTE_DISCONNECT; goto exit; } else if ((sysErr = ASOCK_LASTERROR()) == ASOCK_EWOULDBLOCK) { TCPSOCKLOG(4, s, ("recv would block\n")); break; } else { TCPSOCKLG0(s, ("recv error %d: %s\n", sysErr, Err_Errno2String(sysErr))); s->genericErrno = sysErr; result = ASOCKERR_GENERIC; goto exit; } /* * At this point, s->recvFoo have been updated to point to the * next chained Recv buffer. By default we're done at this * point, but we may want to continue if the SSL socket has data * buffered in userspace already (SSL_Pending). */ needed = s->base.recvLen - s->base.recvPos; ASSERT(needed > 0); pending = SSL_Pending(s->sslSock); needed = MIN(needed, pending); } while (needed); /* * Reach this point only when previous SSL_Pending returns 0 or * error is ASOCK_EWOULDBLOCK */ ASSERT(pending == 0 || sysErr == ASOCK_EWOULDBLOCK); /* * Both a spurious wakeup and receiving any data even if it wasn't enough * to fire the callback are both success. We were ready and now * presumably we aren't ready anymore. */ result = ASOCKERR_SUCCESS; exit: s->inRecvLoop = FALSE; AsyncTCPSocketRelease(s); return result; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketDispatchSentBuffer -- * * Pop off the head of the send buffer list and call its callback. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketDispatchSentBuffer(AsyncTCPSocket *s) // IN { int result = ASOCKERR_SUCCESS; /* * We're done with the current buffer, so pop it off and nuke it. * We do the list management *first*, so that the list is in a * consistent state. */ SendBufList *head = s->sendBufList; SendBufList tmp = *head; s->sendBufList = head->next; if (s->sendBufList == NULL) { s->sendBufTail = &(s->sendBufList); } s->sendPos = 0; free(head); if (tmp.sendFn) { /* * Firing the send completion cannot trigger immediate * destruction of the socket because we hold a refCount across * this and all other application callbacks. If the socket is * closed, however, we need to bubble the information up to the * caller in the same way as we do in the Recv callback case. */ ASSERT(s->base.refCount > 1); tmp.sendFn(tmp.buf, tmp.len, BaseSocket(s), tmp.clientData); if (AsyncTCPSocketGetState(s) == AsyncSocketClosed) { TCPSOCKLG0(s, ("owner closed connection in send callback\n")); result = ASOCKERR_CLOSED; } } return result; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketWriteBuffers -- * * The meat of AsyncTCPSocket's sending functionality. This function * actually writes to the wire assuming there's space in the buffers * for the socket. * * Results: * ASOCKERR_SUCCESS if everything worked, else ASOCKERR_GENERIC. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketWriteBuffers(AsyncTCPSocket *s) // IN { int result; ASSERT(AsyncTCPSocketIsLocked(s)); if (s->sendBufList == NULL) { return ASOCKERR_SUCCESS; /* Vacuously true */ } if (AsyncTCPSocketGetState(s) != AsyncSocketConnected) { TCPSOCKWARN(s, ("write buffers on a disconnected socket!\n")); return ASOCKERR_GENERIC; } AsyncTCPSocketAddRef(s); while (s->sendBufList && AsyncTCPSocketGetState(s) == AsyncSocketConnected) { SendBufList *head = s->sendBufList; int error = 0; int sent = 0; int left = head->len - s->sendPos; int sizeToSend = head->len; sent = SSL_Write(s->sslSock, (uint8 *) head->buf + s->sendPos, left); TCPSOCKLOG(3, s, ("left\t%d\tsent\t%d\tremain\t%d\n", left, sent, left - sent)); if (sent > 0) { s->sendBufFull = FALSE; s->sslConnected = TRUE; if ((s->sendPos += sent) == sizeToSend) { result = AsyncTCPSocketDispatchSentBuffer(s); if (result != ASOCKERR_SUCCESS) { goto exit; } } } else if (sent == 0) { TCPSOCKLG0(s, ("socket write() should never return 0.\n")); NOT_REACHED(); } else if ((error = ASOCK_LASTERROR()) != ASOCK_EWOULDBLOCK) { TCPSOCKLG0(s, ("send error %d: %s\n", error, Err_Errno2String(error))); s->genericErrno = error; if (error == ASOCK_EPIPE || error == ASOCK_ECONNRESET) { result = ASOCKERR_REMOTE_DISCONNECT; } else { result = ASOCKERR_GENERIC; } goto exit; } else { /* * Ran out of space to send. This is actually successful completion * (our contract obligates us to send as much data as space allows * and we fulfilled that). * * Indicate send buffer is full. */ s->sendBufFull = TRUE; break; } } result = ASOCKERR_SUCCESS; exit: AsyncTCPSocketRelease(s); return result; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketAcceptInternal -- * * The meat of 'accept'. This function can be invoked either via a * poll callback or blocking. We call accept to get the new socket fd, * create a new asock, and call the newFn callback previously supplied * by the call to AsyncTCPSocket_Listen. * * Results: * ASOCKERR_SUCCESS if everything works, else an error code. * ASOCKERR_GENERIC is returned to hide accept() system call's * nitty-gritty, it implies that we should try accept() again and not * report error to client. * ASOCKERR_ACCEPT to report accept operation's error to client. * * Side effects: * Accepts on listening fd, creates new asock. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketAcceptInternal(AsyncTCPSocket *s) // IN { AsyncTCPSocket *newsock; int sysErr; int fd; struct sockaddr_storage remoteAddr; socklen_t remoteAddrLen = sizeof remoteAddr; ASSERT(AsyncTCPSocketIsLocked(s)); ASSERT(AsyncTCPSocketGetState(s) == AsyncSocketListening); if ((fd = accept(s->fd, (struct sockaddr *)&remoteAddr, &remoteAddrLen)) == -1) { sysErr = ASOCK_LASTERROR(); s->genericErrno = sysErr; if (sysErr == ASOCK_EWOULDBLOCK) { TCPSOCKWARN(s, ("spurious accept notification\n")); #if TARGET_OS_IPHONE /* * For iOS, while the app is suspended and device's screen is locked, * system will reclaim resources from underneath socket(see Apple * Technical Note TN2277), the callback function AsyncTCPSocketAcceptCallback() * will be invoked repeatedly, to deal with this issue, we need to * handle error EWOULDBLOCK. */ return ASOCKERR_ACCEPT; #else return ASOCKERR_GENERIC; #endif #ifndef _WIN32 /* * This sucks. Linux accept() can return ECONNABORTED for connections * that closed before we got to actually call accept(), but Windows * just ignores this case. So we have to special case for Linux here. * We return ASOCKERR_GENERIC here because we still want to continue * accepting new connections. */ } else if (sysErr == ECONNABORTED) { TCPSOCKLG0(s, ("accept: new connection was aborted\n")); return ASOCKERR_GENERIC; #endif } else { TCPSOCKWARN(s, ("accept failed on fd %d, error %d: %s\n", s->fd, sysErr, Err_Errno2String(sysErr))); return ASOCKERR_ACCEPT; } } if (remoteAddr.ss_family == AF_INET6 && AsyncTCPSocketOSVersionSupportsV4Mapped()) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&remoteAddr; /* * Remote address should not be a V4MAPPED address. Validate for the rare * case that IPV6_V6ONLY is not defined and V4MAPPED is enabled by * default when setting up socket listener. */ if (IN6_IS_ADDR_V4MAPPED(&(addr6->sin6_addr))) { TCPSOCKWARN(s, ("accept rejected on fd %d due to a IPv4-mapped IPv6 " "remote connection address.\n", s->fd)); SSLGeneric_close(fd); return ASOCKERR_ACCEPT; } } newsock = AsyncTCPSocketAttachToFd(fd, AsyncTCPSocketPollParams(s), NULL); if (!newsock) { SSLGeneric_close(fd); return ASOCKERR_ACCEPT; } newsock->remoteAddr = remoteAddr; newsock->remoteAddrLen = remoteAddrLen; AsyncTCPSocketSetState(newsock, AsyncSocketConnected); newsock->internalRecvFn = s->internalRecvFn; newsock->internalSendFn = s->internalSendFn; /* * Fire the connect callback: */ s->connectFn(BaseSocket(newsock), s->clientData); return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketConnectInternal -- * * The meat of connect. This function is invoked either via a poll * callback or the blocking API and verifies that connect() succeeded * or reports is failure. On success we call the registered 'new * connection' function. * * Results: * ASOCKERR_SUCCESS if it all worked out or ASOCKERR_GENERIC. * * Side effects: * Creates new asock, fires newFn callback. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketConnectInternal(AsyncTCPSocket *s) // IN { int optval = 0, optlen = sizeof optval, sysErr; ASSERT(AsyncTCPSocketIsLocked(s)); ASSERT(AsyncTCPSocketGetState(s) == AsyncSocketConnecting); /* Remove when bug 859728 is fixed */ if (vmx86_server && s->remoteAddr.ss_family == AF_UNIX) { goto done; } if (getsockopt(s->fd, SOL_SOCKET, SO_ERROR, (void *) &optval, (void *)&optlen) != 0) { sysErr = ASOCK_LASTERROR(); s->genericErrno = sysErr; Warning(ASOCKPREFIX "getsockopt for connect on fd %d failed with " "error %d : %s\n", s->fd, sysErr, Err_Errno2String(sysErr)); return ASOCKERR_GENERIC; } if (optval != 0) { s->genericErrno = optval; TCPSOCKLOG(1, s, ("connection SO_ERROR: %s\n", Err_Errno2String(optval))); return ASOCKERR_GENERIC; } s->localAddrLen = sizeof s->localAddr; if (getsockname(s->fd, (struct sockaddr *)&s->localAddr, &s->localAddrLen) != 0) { sysErr = ASOCK_LASTERROR(); s->genericErrno = sysErr; Warning(ASOCKPREFIX "getsockname for connect on fd %d failed with " "error %d: %s\n", s->fd, sysErr, Err_Errno2String(sysErr)); return ASOCKERR_GENERIC; } done: AsyncTCPSocketSetState(s, AsyncSocketConnected); s->connectFn(BaseSocket(s), s->clientData); return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetGenericErrno -- * * Used when an ASOCKERR_GENERIC is returned due to a system error. * The errno that was returned by the system is stored in the asock * struct and returned to the user in this function. * * XXX: This function is not thread-safe. The errno should be returned * in a parameter to any function that can return ASOCKERR_GENERIC. * * Results: * int error code * * Side effects: * None * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketGetGenericErrno(AsyncSocket *base) // IN: { AsyncTCPSocket *asock = TCPSocket(base); ASSERT(asock); return asock->genericErrno; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketWaitForConnection -- * * Spins a socket currently listening or connecting until the * connection completes or the allowed time elapses. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on failures, and * ASOCKERR_TIMEOUT if nothing happened in the allotted time. * * Side effects: * None. *---------------------------------------------------------------------------- */ static int AsyncTCPSocketWaitForConnection(AsyncSocket *base, // IN: int timeoutMS) // IN: { AsyncTCPSocket *s = TCPSocket(base); Bool read = FALSE; int error; VmTimeType now, done; Bool removed = FALSE; ASSERT(AsyncTCPSocketIsLocked(s)); if (AsyncTCPSocketGetState(s) == AsyncSocketConnected) { return ASOCKERR_SUCCESS; } if (AsyncTCPSocketGetState(s) != AsyncSocketListening && AsyncTCPSocketGetState(s) != AsyncSocketConnecting) { return ASOCKERR_GENERIC; } read = AsyncTCPSocketGetState(s) == AsyncSocketListening; /* * For listening sockets, unregister AsyncTCPSocketAcceptCallback before * starting polling and re-register before returning. * * ConnectCallback() is either registered as a device or rtime callback * depending on the prior return value of connect(). So we try to remove it * from both. */ if (read) { if (s->fd == -1) { if (s->listenAsock4) { ASSERT(AsyncTCPSocketIsLocked(s->listenAsock4)); AsyncTCPSocketCancelListenCb(s->listenAsock4); } if (s->listenAsock6) { ASSERT(AsyncTCPSocketIsLocked(s->listenAsock6)); AsyncTCPSocketCancelListenCb(s->listenAsock6); } } else { AsyncTCPSocketCancelListenCb(s); } removed = TRUE; } else { removed = (AsyncTCPSocketPollRemove(s, TRUE, POLL_FLAG_WRITE, AsyncTCPSocketConnectCallback) || AsyncTCPSocketPollRemove(s, FALSE, 0, AsyncTCPSocketConnectCallback)); ASSERT(removed); if (s->internalConnectFn) { removed = AsyncTCPSocketPollRemove(s, FALSE, POLL_FLAG_PERIODIC, AsyncTCPSocketConnectErrorCheck); ASSERT(removed); s->internalConnectFn = NULL; } } now = Hostinfo_SystemTimerUS() / 1000; done = now + timeoutMS; do { AsyncTCPSocket *asock = NULL; error = AsyncTCPSocketPoll(s, read, done - now, &asock); if (error != ASOCKERR_SUCCESS) { goto out; } now = Hostinfo_SystemTimerUS() / 1000; if (read) { if (AsyncTCPSocketAcceptInternal(asock) != ASOCKERR_SUCCESS) { TCPSOCKLG0(s, ("wait for connection: accept failed\n")); /* * Just fall through, we'll loop and try again as long as we still * have time remaining. */ } else { error = ASOCKERR_SUCCESS; goto out; } } else { error = AsyncTCPSocketConnectInternal(asock); goto out; } } while ((now < done && timeoutMS > 0) || (timeoutMS < 0)); error = ASOCKERR_TIMEOUT; out: if (read && removed) { if (s->fd == -1) { if (s->listenAsock4 && AsyncTCPSocketGetState(s->listenAsock4) != AsyncSocketClosed) { if (!AsyncTCPSocketAddListenCb(s->listenAsock4)) { error = ASOCKERR_POLL; } } if (s->listenAsock6 && AsyncTCPSocketGetState(s->listenAsock6) != AsyncSocketClosed) { if (!AsyncTCPSocketAddListenCb(s->listenAsock6)) { error = ASOCKERR_POLL; } } } else if (AsyncTCPSocketGetState(s) != AsyncSocketClosed) { if (!AsyncTCPSocketAddListenCb(s)) { error = ASOCKERR_POLL; } } } return error; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketDoOneMsg -- * * Spins a socket until the specified amount of time has elapsed or * data has arrived / been sent. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call * failures * ASOCKERR_TIMEOUT if nothing happened in the allotted time. * * Side effects: * None. *---------------------------------------------------------------------------- */ static int AsyncTCPSocketDoOneMsg(AsyncSocket *base, // IN Bool read, // IN int timeoutMS) // IN { AsyncTCPSocket *s = TCPSocket(base); AsyncTCPSocket *asock = NULL; int retVal; ASSERT(AsyncTCPSocketIsLocked(s)); ASSERT(AsyncTCPSocketGetState(s) == AsyncSocketConnected); if (read) { if (s->inRecvLoop) { /* * The recv loop would read the data if there is any and it is * not safe to proceed and race with the recv loop. */ TCPSOCKLG0(s, ("busy: another thread in recv loop\n")); return ASOCKERR_BUSY; } /* * Bug 158571: There could other threads polling on the same asyncsocket. * If two threads land up polling on the same socket at the same time, * the first thread to be scheduled reads the data from the socket, * while the second one blocks infinitely. This hangs the VM. To prevent * this, we temporarily remove the poll callback and then reinstate it * after reading the data. */ ASSERT(s->recvCb); /* We are supposed to call someone... */ AsyncTCPSocketAddRef(s); AsyncTCPSocketCancelRecvCb(s); s->recvCb = TRUE; /* We need to know if the callback cancel recv. */ s->inBlockingRecv++; retVal = AsyncTCPSocketPoll(s, read, timeoutMS, &asock); s->inBlockingRecv--; if (retVal != ASOCKERR_SUCCESS) { if (retVal == ASOCKERR_GENERIC) { TCPSOCKWARN(s, ("%s: failed to poll on the socket during read.\n", __FUNCTION__)); } } else { ASSERT(asock == s); s->inDoOneMsg = TRUE; retVal = AsyncTCPSocketFillRecvBuffer(s); s->inDoOneMsg = FALSE; } /* * If socket got closed in AsyncTCPSocketFillRecvBuffer, we * cannot add poll callback - AsyncSocket_Close() would remove * it if we would not remove it above. */ if (AsyncTCPSocketGetState(s) != AsyncSocketClosed && s->recvCb) { ASSERT(s->base.refCount > 1); /* We shouldn't be last user of socket. */ ASSERT(AsyncTCPSocketGetState(s) == AsyncSocketConnected); /* * If AsyncTCPSocketPoll or AsyncTCPSocketFillRecvBuffer fails, do not * add the recv callback as it may never fire. */ s->recvCb = FALSE; /* For re-registering the poll callback. */ if (retVal == ASOCKERR_SUCCESS || retVal == ASOCKERR_TIMEOUT) { retVal = AsyncTCPSocketRegisterRecvCb(s); } if (retVal != ASOCKERR_SUCCESS) { s->base.recvBuf = NULL; } } AsyncTCPSocketRelease(s); } else { AsyncTCPSocketAddRef(s); retVal = AsyncTCPSocketPoll(s, read, timeoutMS, &asock); if (retVal != ASOCKERR_SUCCESS) { if (retVal == ASOCKERR_GENERIC) { TCPSOCKWARN(s, ("%s: failed to poll on the socket during write.\n", __FUNCTION__)); } } else { ASSERT(asock == s); retVal = AsyncTCPSocketWriteBuffers(s); } AsyncTCPSocketRelease(s); } return retVal; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketFlush -- * * Try to send any pending out buffers until we run out of buffers, or * the timeout expires. * * Results: * ASOCKERR_SUCCESS if it worked, ASOCKERR_GENERIC on system call * failures, and ASOCKERR_TIMEOUT if we couldn't send enough data * before the timeout expired. * * Side effects: * None. *---------------------------------------------------------------------------- */ static int AsyncTCPSocketFlush(AsyncSocket *base, // IN int timeoutMS) // IN { AsyncTCPSocket *s = TCPSocket(base); VmTimeType now, done; int retVal; if (s == NULL) { Warning(ASOCKPREFIX "Flush called with invalid arguments!\n"); return ASOCKERR_INVAL; } ASSERT(AsyncTCPSocketIsLocked(s)); AsyncTCPSocketAddRef(s); if (AsyncTCPSocketGetState(s) != AsyncSocketConnected) { TCPSOCKWARN(s, ("flush called but state is not connected!\n")); retVal = ASOCKERR_INVAL; goto outHaveLock; } now = Hostinfo_SystemTimerUS() / 1000; done = now + timeoutMS; while (s->sendBufList) { AsyncTCPSocket *asock = NULL; retVal = AsyncTCPSocketPoll(s, FALSE, done - now, &asock); if (retVal != ASOCKERR_SUCCESS) { TCPSOCKWARN(s, ("flush failed\n")); goto outHaveLock; } ASSERT(asock == s); if ((retVal = AsyncTCPSocketWriteBuffers(s)) != ASOCKERR_SUCCESS) { goto outHaveLock; } ASSERT(AsyncTCPSocketGetState(s) == AsyncSocketConnected); /* Setting timeoutMS to -1 means never timeout. */ if (timeoutMS >= 0) { now = Hostinfo_SystemTimerUS() / 1000; /* Don't timeout if you've sent everything */ if (now > done && s->sendBufList) { TCPSOCKWARN(s, ("flush timed out\n")); retVal = ASOCKERR_TIMEOUT; goto outHaveLock; } } } retVal = ASOCKERR_SUCCESS; outHaveLock: AsyncTCPSocketRelease(s); return retVal; } /* *---------------------------------------------------------------------------- * * AsyncSocketCancelListenCbSocket -- * * Socket specific code for canceling callbacks for a listening socket. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketCancelListenCb(AsyncTCPSocket *asock) // IN: { Bool removed; ASSERT(AsyncTCPSocketIsLocked(asock)); removed = AsyncTCPSocketPollRemove(asock, TRUE, POLL_FLAG_READ | POLL_FLAG_PERIODIC, AsyncTCPSocketAcceptCallback); ASSERT(removed); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketAddListenCb -- * * Socket specific code for adding callbacks for a listening socket. * * Results: * TRUE if Poll callback successfully added. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static Bool AsyncTCPSocketAddListenCb(AsyncTCPSocket *asock) // IN: { VMwareStatus pollStatus; ASSERT(AsyncTCPSocketIsLocked(asock)); pollStatus = AsyncTCPSocketPollAdd(asock, TRUE, POLL_FLAG_READ | POLL_FLAG_PERIODIC, AsyncTCPSocketAcceptCallback); if (pollStatus != VMWARE_STATUS_SUCCESS) { TCPSOCKWARN(asock, ("failed to install listen accept callback!\n")); } return pollStatus == VMWARE_STATUS_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketCancelRecvCb -- * * Socket specific code for canceling callbacks when a receive * request is being canceled. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketCancelRecvCb(AsyncTCPSocket *asock) // IN: { ASSERT(AsyncTCPSocketIsLocked(asock)); if (asock->recvCbTimer) { AsyncTCPSocketPollRemove(asock, FALSE, 0, asock->internalRecvFn); asock->recvCbTimer = FALSE; } if (asock->recvCb) { Bool removed; TCPSOCKLOG(1, asock, ("Removing poll recv callback while cancelling recv.\n")); removed = AsyncTCPSocketPollRemove(asock, TRUE, POLL_FLAG_READ | POLL_FLAG_PERIODIC, asock->internalRecvFn); VERIFY(removed || AsyncTCPSocketPollParams(asock)->iPoll); asock->recvCb = FALSE; } } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketCancelCbForClose -- * * Cancel future asynchronous send and recv by unregistering * their Poll callbacks, and change the socket state to * AsyncTCPSocketCBCancelled if the socket state is AsyncTCPSocketConnected. * * The function can be called in a send/recv error handler before * actually closing the socket in a separate thread, to prevent other * code calling AsyncTCPSocket_Send/Recv from re-registering the * callbacks again. The next operation should be just AsyncSocket_Close(). * This helps to avoid unnecessary send/recv callbacks before the * socket is closed. * * Results: * ASOCKERR_*. * * Side effects: * Unregisters send/recv Poll callbacks, and fires the send * triggers for any remaining output buffers. May also change * the socket state. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketCancelCbForClose(AsyncSocket *base) // IN: { AsyncTCPSocket *asock = TCPSocket(base); Bool removed; ASSERT(AsyncTCPSocketIsLocked(asock)); if (AsyncTCPSocketGetState(asock) == AsyncSocketConnected) { AsyncTCPSocketSetState(asock, AsyncSocketCBCancelled); } /* * Remove the read and write poll callbacks. * * We could fire the current recv completion callback here, but in * practice clients won't want to know about partial reads since it just * complicates the common case (i.e. every read callback would need to * check the len parameter). * * For writes, however, we *do* fire all of the callbacks. The argument * here is that the common case for writes is "fire and forget", e.g. * send this buffer and free it. Firing the triggers at close time * simplifies client code, since the clients aren't forced to keep track * of send buffers themselves. Clients can figure out how much data was * actually transmitted (if they care) by checking the len parameter * passed to the send callback. * * A modification suggested by Jeremy is to pass a list of unsent * buffers and their completion callbacks to the error handler if one is * registered, and only fire the callbacks here if there was no error * handler invoked. */ ASSERT(!asock->base.recvBuf || asock->base.recvFn); if (asock->recvCbTimer) { AsyncTCPSocketPollRemove(asock, FALSE, 0, asock->internalRecvFn); asock->recvCbTimer = FALSE; } if (asock->recvCb) { TCPSOCKLOG(1, asock, ("recvCb is non-NULL, removing recv callback\n")); removed = AsyncTCPSocketPollRemove(asock, TRUE, POLL_FLAG_READ | POLL_FLAG_PERIODIC, asock->internalRecvFn); /* Callback might be temporarily removed in AsyncSocket_DoOneMsg. */ ASSERT_NOT_TESTED(removed || asock->inDoOneMsg || AsyncTCPSocketPollParams(asock)->iPoll); asock->recvCb = FALSE; asock->base.recvBuf = NULL; } if (asock->sendCb) { TCPSOCKLOG(1, asock, ("sendBufList is non-NULL, removing send callback\n")); /* * The send callback could be either a device or RTime callback, so * we check the latter if it wasn't the former. */ if (asock->sendCbTimer) { removed = AsyncTCPSocketPollRemove(asock, FALSE, 0, asock->internalSendFn); } else { removed = AsyncTCPSocketPollRemove(asock, TRUE, POLL_FLAG_WRITE, asock->internalSendFn); } ASSERT(removed || AsyncTCPSocketPollParams(asock)->iPoll); asock->sendCb = FALSE; asock->sendCbTimer = FALSE; } /* * Go through any send buffers on the list and fire their * callbacks, reflecting back how much of each buffer has been * submitted to the kernel. For the first buffer in the list that * may be non-zero, for subsequent buffers it will be zero. */ AsyncTCPSocketAddRef(asock); while (asock->sendBufList) { /* * Pop each remaining buffer and fire its completion callback. */ SendBufList *cur = asock->sendBufList; int pos = asock->sendPos; asock->sendBufList = asock->sendBufList->next; asock->sendPos = 0; if (cur->sendFn) { cur->sendFn(cur->buf, pos, BaseSocket(asock), cur->clientData); } free(cur); } AsyncTCPSocketRelease(asock); return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketCancelCbForConnectingClose -- * * Cancels outstanding connect requests for a socket that is going * away. * * Results: * TRUE on callback removed. FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static Bool AsyncTCPSocketCancelCbForConnectingClose(AsyncTCPSocket *asock) // IN { return (AsyncTCPSocketPollRemove(asock, TRUE, POLL_FLAG_WRITE, AsyncTCPSocketConnectCallback) || AsyncTCPSocketPollRemove(asock, FALSE, 0, AsyncTCPSocketConnectCallback)); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketSetCloseOptions -- * * Enables optional behavior for AsyncSocket_Close(): * * - If flushEnabledMaxWaitMsec is non-zero, the output stream * will be flushed synchronously before the socket is closed. * (default is zero: close socket right away without flushing) * * - If closeCb is set, the callback will be called asynchronously * when the socket is actually destroyed. * (default is NULL: no callback) * * Results: * ASOCKERR_*. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketSetCloseOptions(AsyncSocket *base, // IN int flushEnabledMaxWaitMsec, // IN AsyncSocketCloseFn closeCb) // IN { AsyncTCPSocket *asock = TCPSocket(base); asock->flushEnabledMaxWaitMsec = flushEnabledMaxWaitMsec; asock->closeCb = closeCb; VERIFY(closeCb == NULL); return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketClose -- * * AsyncTCPSocket destructor. The destructor should be safe to call at any * time. It's invoked automatically for I/O errors on slots that have no * error handler set, and should be called manually by the error handler * as necessary. It could also be called as part of the normal program * flow. * * Results: * ASOCKERR_*. * * Side effects: * Closes the socket fd, unregisters all Poll callbacks, and fires the * send triggers for any remaining output buffers. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketClose(AsyncSocket *base) // IN { AsyncTCPSocket *asock = TCPSocket(base); ASSERT(AsyncTCPSocketIsLocked(asock)); if (AsyncTCPSocketGetState(asock) == AsyncSocketClosed) { Warning("%s() called on already closed asock!\n", __FUNCTION__); return ASOCKERR_CLOSED; } if (asock->listenAsock4 || asock->listenAsock6) { if (asock->listenAsock4) { AsyncSocket_Close(BaseSocket(asock->listenAsock4)); } if (asock->listenAsock6) { AsyncSocket_Close(BaseSocket(asock->listenAsock6)); } } else { Bool removed; AsyncSocketState oldState; /* Flush output if requested via AsyncTCPSocket_SetCloseOptions(). */ if (asock->flushEnabledMaxWaitMsec && AsyncTCPSocketGetState(asock) == AsyncSocketConnected && !asock->base.errorSeen) { int ret = AsyncTCPSocketFlush(BaseSocket(asock), asock->flushEnabledMaxWaitMsec); if (ret != ASOCKERR_SUCCESS) { TCPSOCKWARN(asock, ("AsyncTCPSocket_Flush failed: %s. Closing now.\n", AsyncSocket_Err2String(ret))); } } /* * Set the new state to closed, and then check the old state and do the * right thing accordingly */ TCPSOCKLOG(1, asock, ("closing socket\n")); oldState = AsyncTCPSocketGetState(asock); AsyncTCPSocketSetState(asock, AsyncSocketClosed); switch(oldState) { case AsyncSocketListening: TCPSOCKLOG(1, asock, ("old state was listening, removing accept " "callback\n")); AsyncTCPSocketCancelListenCb(asock); break; case AsyncSocketConnecting: TCPSOCKLOG(1, asock, ("old state was connecting, removing connect " "callback\n")); removed = AsyncTCPSocketCancelCbForConnectingClose(asock); if (!removed) { TCPSOCKLOG(1, asock, ("connect callback is not present in the poll " "list.\n")); } break; case AsyncSocketConnected: TCPSOCKLOG(1, asock, ("old state was connected\n")); AsyncTCPSocketCancelCbForClose(BaseSocket(asock)); break; case AsyncSocketCBCancelled: TCPSOCKLOG(1, asock, ("old state was CB-cancelled\n")); break; default: NOT_REACHED(); } if (asock->internalConnectFn) { removed = AsyncTCPSocketPollRemove(asock, FALSE, POLL_FLAG_PERIODIC, AsyncTCPSocketConnectErrorCheck); ASSERT(removed); asock->internalConnectFn = NULL; } if (asock->sslConnectFn && asock->sslPollFlags > 0) { removed = AsyncTCPSocketPollRemove(asock, TRUE, asock->sslPollFlags, AsyncTCPSocketSslConnectCallback); ASSERT(removed); } if (asock->sslAcceptFn && asock->sslPollFlags > 0) { removed = AsyncTCPSocketPollRemove(asock, TRUE, asock->sslPollFlags, AsyncTCPSocketSslAcceptCallback); ASSERT(removed); } asock->sslPollFlags = 0; /* * Close the underlying SSL sockets. */ SSL_Shutdown(asock->sslSock); if (asock->passFd.fd != -1) { SSLGeneric_close(asock->passFd.fd); } } AsyncSocketTeardownSocket(base); return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketIsSendBufferFull -- * * Indicate if socket send buffer is full. Note that unless this is * called from a callback function, the return value should be treated * as transient. * * Results: * 0: send space probably available, * 1: send has reached maximum, * ASOCKERR_GENERIC: null socket. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketIsSendBufferFull(AsyncSocket *base) // IN { AsyncTCPSocket *asock = TCPSocket(base); return asock->sendBufFull; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketHasDataPending -- * * Determine if SSL has any pending/unread data. * * Results: * TRUE if this socket has pending data. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static Bool AsyncTCPSocketHasDataPending(AsyncTCPSocket *asock) // IN: { return SSL_Pending(asock->sslSock); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketMakeNonBlocking -- * * Make the specified socket non-blocking if it isn't already. * * Results: * ASOCKERR_SUCCESS if the operation succeeded, ASOCKERR_GENERIC otherwise. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketMakeNonBlocking(int fd) // IN { #ifdef _WIN32 int retval; u_long argp = 1; /* non-zero => enable non-blocking mode */ retval = ioctlsocket(fd, FIONBIO, &argp); if (retval != 0) { ASSERT(retval == SOCKET_ERROR); return ASOCKERR_GENERIC; } #elif defined(__APPLE__) int argp = 1; if (ioctl(fd, FIONBIO, &argp) < 0) { return ASOCKERR_GENERIC; } #else int flags; if ((flags = fcntl(fd, F_GETFL)) < 0) { return ASOCKERR_GENERIC; } if (!(flags & O_NONBLOCK) && (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)) { return ASOCKERR_GENERIC; } #endif return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncSocketAcceptCallback -- * * Poll callback for listening fd waiting to complete an accept * operation. We call accept to get the new socket fd, create a new * asock, and call the newFn callback previously supplied by the call to * AsyncTCPSocket_Listen. * * Results: * None. * * Side effects: * Accepts on listening fd, creates new asock. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketAcceptCallback(void *clientData) // IN { AsyncTCPSocket *asock = clientData; int retval; ASSERT(asock); ASSERT(AsyncTCPSocketPollParams(asock)->iPoll == NULL); ASSERT(AsyncTCPSocketIsLocked(asock)); AsyncTCPSocketAddRef(asock); retval = AsyncTCPSocketAcceptInternal(asock); /* * See comment for return value of AsyncTCPSocketAcceptInternal(). */ if (retval == ASOCKERR_ACCEPT) { AsyncTCPSocketHandleError(asock, retval); } AsyncTCPSocketRelease(asock); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketConnectCallback -- * * Poll callback for connecting fd. Calls through to * AsyncTCPSocketConnectInternal to do the real work. * * Results: * None. * * Side effects: * Creates new asock, fires newFn callback. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketConnectCallback(void *clientData) // IN { AsyncTCPSocket *asock = clientData; int retval; ASSERT(asock); ASSERT(AsyncTCPSocketPollParams(asock)->iPoll == NULL); ASSERT(AsyncTCPSocketIsLocked(asock)); AsyncTCPSocketAddRef(asock); retval = AsyncTCPSocketConnectInternal(asock); if (retval != ASOCKERR_SUCCESS) { ASSERT(retval == ASOCKERR_GENERIC); /* Only one we're expecting */ AsyncTCPSocketHandleError(asock, retval); } AsyncTCPSocketRelease(asock); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketRecvCallback -- * * Poll callback for input waiting on the socket. We try to pull off the * remaining data requested by the current receive function. * * Results: * None. * * Side effects: * Reads data, could fire recv completion or trigger socket destruction. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketRecvCallback(void *clientData) // IN { AsyncTCPSocket *asock = clientData; int error; ASSERT(asock); ASSERT(AsyncTCPSocketIsLocked(asock)); AsyncTCPSocketAddRef(asock); error = AsyncTCPSocketFillRecvBuffer(asock); if (error == ASOCKERR_GENERIC || error == ASOCKERR_REMOTE_DISCONNECT) { AsyncTCPSocketHandleError(asock, error); } AsyncTCPSocketRelease(asock); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketIPollRecvCallback -- * * Poll callback for input waiting on the socket. IVmdbPoll does not * handle callback locks, so this function first locks the asyncsocket * and verify that the recv callback has not been cancelled before * calling AsyncTCPSocketFillRecvBuffer to do the real work. * * Results: * None. * * Side effects: * Reads data, could fire recv completion or trigger socket destruction. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketIPollRecvCallback(void *clientData) // IN: { #ifdef VMX86_TOOLS NOT_IMPLEMENTED(); #else AsyncTCPSocket *asock = clientData; MXUserRecLock *lock; ASSERT(asock); ASSERT(AsyncTCPSocketPollParams(asock)->lock == NULL || !MXUser_IsCurThreadHoldingRecLock( AsyncTCPSocketPollParams(asock)->lock)); AsyncTCPSocketLock(asock); if (asock->recvCbTimer) { /* IVmdbPoll only has periodic callbacks. */ AsyncTCPSocketIPollRemove(asock, FALSE, 0, asock->internalRecvFn); asock->recvCbTimer = FALSE; } asock->inIPollCb |= IN_IPOLL_RECV; lock = AsyncTCPSocketPollParams(asock)->lock; if (asock->recvCb && asock->inBlockingRecv == 0) { /* * There is no need to take a reference here -- the fact that this * callback is running means AsyncsocketIPollRemove would not release a * reference if it is called. */ int error = AsyncTCPSocketFillRecvBuffer(asock); if (error == ASOCKERR_GENERIC || error == ASOCKERR_REMOTE_DISCONNECT) { AsyncTCPSocketHandleError(asock, error); } } asock->inIPollCb &= ~IN_IPOLL_RECV; if (asock->recvCb) { AsyncTCPSocketUnlock(asock); } else { /* * Callback has been unregistered. Per above, we need to release the * reference explicitly. */ AsyncTCPSocketRelease(asock); AsyncTCPSocketUnlock(asock); if (lock != NULL) { MXUser_DecRefRecLock(lock); } } #endif } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketSendCallback -- * * Poll callback for output socket buffer space available (socket is * writable). We iterate over all the remaining buffers in our queue, * writing as much as we can until we fill the socket buffer again. If we * don't finish, we register ourselves as a device write callback. * * Results: * None. * * Side effects: * Writes data, could trigger write completion or socket destruction. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketSendCallback(void *clientData) // IN { AsyncTCPSocket *s = clientData; int retval; ASSERT(s); ASSERT(AsyncTCPSocketIsLocked(s)); AsyncTCPSocketAddRef(s); s->sendCb = FALSE; /* AsyncTCPSocketSendCallback is never periodic */ s->sendCbTimer = FALSE; retval = AsyncTCPSocketWriteBuffers(s); if (retval != ASOCKERR_SUCCESS && retval != ASOCKERR_CLOSED) { AsyncTCPSocketHandleError(s, retval); } else if (s->sendBufList && !s->sendCb) { VMwareStatus pollStatus; /* * We didn't finish, so we need to reschedule the Poll callback (the * write callback is *not* periodic). */ #ifdef _WIN32 /* * If any data has been sent out or read in from the sslSock, * SSL has finished the handshaking. Otherwise, * we have to schedule a realtime callback for write. See bug 37147 */ if (!s->sslConnected) { pollStatus = AsyncTCPSocketPollAdd(s, FALSE, 0, s->internalSendFn, 100000); VERIFY(pollStatus == VMWARE_STATUS_SUCCESS); s->sendCbTimer = TRUE; } else #endif { pollStatus = AsyncTCPSocketPollAdd(s, TRUE, POLL_FLAG_WRITE, s->internalSendFn); VERIFY(pollStatus == VMWARE_STATUS_SUCCESS); } s->sendCb = TRUE; } AsyncTCPSocketRelease(s); } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketIPollSendCallback -- * * IVmdbPoll callback for output socket buffer space available. IVmdbPoll * does not handle callback locks, so this function first locks the * asyncsocket and verify that the send callback has not been cancelled. * IVmdbPoll only has periodic callbacks, so this function unregisters * itself before calling AsyncTCPSocketSendCallback to do the real work. * * Results: * None. * * Side effects: * Writes data, could trigger write completion or socket destruction. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketIPollSendCallback(void *clientData) // IN: { #ifdef VMX86_TOOLS NOT_IMPLEMENTED(); #else AsyncTCPSocket *s = clientData; MXUserRecLock *lock; ASSERT(s); AsyncTCPSocketLock(s); s->inIPollCb |= IN_IPOLL_SEND; lock = AsyncTCPSocketPollParams(s)->lock; if (s->sendCb) { /* * Unregister this callback as we want the non-periodic behavior. There * is no need to take a reference here -- the fact that this callback is * running means AsyncsocketIPollRemove would not release a reference. * We would release that reference at the end. */ if (s->sendCbTimer) { AsyncTCPSocketIPollRemove(s, FALSE, 0, AsyncTCPSocketIPollSendCallback); } else { AsyncTCPSocketIPollRemove(s, TRUE, POLL_FLAG_WRITE, AsyncTCPSocketIPollSendCallback); } AsyncTCPSocketSendCallback(s); } s->inIPollCb &= ~IN_IPOLL_SEND; AsyncTCPSocketRelease(s); AsyncTCPSocketUnlock(s); if (lock != NULL) { MXUser_DecRefRecLock(lock); } #endif } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketPollAdd -- * * Add a poll callback. Wrapper for Poll_Callback since we always call * it in one of two basic forms. * * If socket is FALSE, user has to pass in the timeout value * * Results: * VMwareStatus result code from Poll_Callback * * Side effects: * Only the obvious. * *----------------------------------------------------------------------------- */ static VMwareStatus AsyncTCPSocketPollAdd(AsyncTCPSocket *asock, // IN Bool socket, // IN int flags, // IN PollerFunction callback, // IN ...) // IN { int type, info; if (socket) { ASSERT(asock->fd != -1); type = POLL_DEVICE; flags |= POLL_FLAG_SOCKET; info = asock->fd; } else { va_list marker; va_start(marker, callback); type = POLL_REALTIME; info = va_arg(marker, int); va_end(marker); } if (AsyncTCPSocketPollParams(asock)->iPoll != NULL) { return AsyncTCPSocketIPollAdd(asock, socket, flags, callback, info); } return Poll_Callback(AsyncTCPSocketPollParams(asock)->pollClass, flags | AsyncTCPSocketPollParams(asock)->flags, callback, asock, type, info, AsyncTCPSocketPollParams(asock)->lock); } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketPollRemove -- * * Remove a poll callback. Wrapper for Poll_CallbackRemove since we * always call it in one of two basic forms. * * Results: * TRUE if removed, FALSE if not found. * * Side effects: * Only the obvious. * *----------------------------------------------------------------------------- */ static Bool AsyncTCPSocketPollRemove(AsyncTCPSocket *asock, // IN Bool socket, // IN int flags, // IN PollerFunction callback) // IN { int type; if (AsyncTCPSocketPollParams(asock)->iPoll != NULL) { return AsyncTCPSocketIPollRemove(asock, socket, flags, callback); } if (socket) { ASSERT(asock->fd != -1); type = POLL_DEVICE; flags |= POLL_FLAG_SOCKET; } else { type = POLL_REALTIME; } return Poll_CallbackRemove(AsyncTCPSocketPollParams(asock)->pollClass, flags | AsyncTCPSocketPollParams(asock)->flags, callback, asock, type); } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketIPollAdd -- * * Add a poll callback. Wrapper for IVmdbPoll.Register[Timer]. * * If socket is FALSE, user has to pass in the timeout value * * Results: * VMwareStatus result code. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static VMwareStatus AsyncTCPSocketIPollAdd(AsyncTCPSocket *asock, // IN Bool socket, // IN int flags, // IN PollerFunction callback, // IN int info) // IN { #ifdef VMX86_TOOLS return VMWARE_STATUS_ERROR; #else VMwareStatus status = VMWARE_STATUS_SUCCESS; VmdbRet ret; IVmdbPoll *poll; ASSERT(AsyncTCPSocketPollParams(asock)->iPoll); ASSERT(AsyncTCPSocketIsLocked(asock)); /* Protect asyncsocket and lock from disappearing */ AsyncTCPSocketAddRef(asock); if (AsyncTCPSocketPollParams(asock)->lock != NULL) { MXUser_IncRefRecLock(AsyncTCPSocketPollParams(asock)->lock); } poll = AsyncTCPSocketPollParams(asock)->iPoll; if (socket) { int pollFlags = (flags & POLL_FLAG_READ) != 0 ? VMDB_PRF_READ : VMDB_PRF_WRITE; ret = poll->Register(poll, pollFlags, callback, asock, info); } else { ret = poll->RegisterTimer(poll, callback, asock, info); } if (ret != VMDB_S_OK) { Log(ASOCKPREFIX "failed to register callback (%s %d): error %d\n", socket ? "socket" : "delay", info, ret); if (AsyncTCPSocketPollParams(asock)->lock != NULL) { MXUser_DecRefRecLock(AsyncTCPSocketPollParams(asock)->lock); } AsyncTCPSocketRelease(asock); status = VMWARE_STATUS_ERROR; } return status; #endif } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketIPollRemove -- * * Remove a poll callback. Wrapper for IVmdbPoll.Unregister[Timer]. * * Results: * TRUE if the callback was registered and has been cancelled successfully. * FALSE if the callback was not registered, or the callback is already * scheduled to fire (and is guaranteed to fire). * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool AsyncTCPSocketIPollRemove(AsyncTCPSocket *asock, // IN Bool socket, // IN int flags, // IN PollerFunction callback) // IN { #ifdef VMX86_TOOLS return FALSE; #else IVmdbPoll *poll; Bool ret; ASSERT(AsyncTCPSocketPollParams(asock)->iPoll); ASSERT(AsyncTCPSocketIsLocked(asock)); poll = AsyncTCPSocketPollParams(asock)->iPoll; if (socket) { int pollFlags = (flags & POLL_FLAG_READ) != 0 ? VMDB_PRF_READ : VMDB_PRF_WRITE; ret = poll->Unregister(poll, pollFlags, callback, asock); } else { ret = poll->UnregisterTimer(poll, callback, asock); } if (ret && !((asock->inIPollCb & IN_IPOLL_RECV) != 0 && callback == asock->internalRecvFn) && !((asock->inIPollCb & IN_IPOLL_SEND) != 0 && callback == asock->internalSendFn)) { MXUserRecLock *lock = AsyncTCPSocketPollParams(asock)->lock; /* * As the callback has been unregistered and we are not currently in * the callback being removed, we can safely release the reference taken * when registering the callback. */ AsyncTCPSocketRelease(asock); if (lock != NULL) { MXUser_DecRefRecLock(lock); } } return ret; #endif } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketCancelRecv -- * * Call this function if you know what you are doing. This should be * called if you want to synchronously receive the outstanding data on * the socket. It removes the recv poll callback. It also returns number of * partially read bytes (if any). A partially read response may exist as * AsyncTCPSocketRecvCallback calls the recv callback only when all the data * has been received. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_INVAL. * * Side effects: * Subsequent client call to AsyncTCPSocket_Recv can reinstate async behaviour. * *----------------------------------------------------------------------------- */ static int AsyncTCPSocketCancelRecv(AsyncSocket *base, // IN int *partialRecvd, // OUT void **recvBuf, // OUT void **recvFn, // OUT Bool cancelOnSend) // IN { AsyncTCPSocket *asock = TCPSocket(base); ASSERT(AsyncTCPSocketIsLocked(asock)); if (AsyncTCPSocketGetState(asock) != AsyncSocketConnected) { Warning(ASOCKPREFIX "Failed to cancel request on disconnected socket!\n"); return ASOCKERR_INVAL; } if (asock->inBlockingRecv) { Warning(ASOCKPREFIX "Cannot cancel request while a blocking recv is " "pending.\n"); return ASOCKERR_INVAL; } if (!cancelOnSend && (asock->sendBufList || asock->sendCb)) { Warning(ASOCKPREFIX "Can't cancel request as socket has send operation " "pending.\n"); return ASOCKERR_INVAL; } AsyncTCPSocketCancelRecvCb(asock); AsyncSocketCancelRecv(BaseSocket(asock), partialRecvd, recvBuf, recvFn); if (asock->passFd.fd != -1) { SSLGeneric_close(asock->passFd.fd); asock->passFd.fd = -1; } asock->passFd.expected = FALSE; return ASOCKERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketGetReceivedFd -- * * Retrieve received file descriptor from socket. * * Results: * File descriptor. Or -1 if none was received. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static int AsyncTCPSocketGetReceivedFd(AsyncSocket *base) // IN { AsyncTCPSocket *asock = TCPSocket(base); int fd; ASSERT(AsyncTCPSocketIsLocked(asock)); if (AsyncTCPSocketGetState(asock) != AsyncSocketConnected) { Warning(ASOCKPREFIX "Failed to receive fd on disconnected socket!\n"); return -1; } fd = asock->passFd.fd; asock->passFd.fd = -1; asock->passFd.expected = FALSE; return fd; } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketConnectSSL -- * * Initialize the socket's SSL object, by calling SSL_ConnectAndVerify. * NOTE: This call is blocking. * * Results: * TRUE if SSL_ConnectAndVerify succeeded, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool AsyncTCPSocketConnectSSL(AsyncSocket *base, // IN SSLVerifyParam *verifyParam, // IN/OPT void *sslContext) // IN/OPT { #ifndef USE_SSL_DIRECT AsyncTCPSocket *asock = TCPSocket(base); ASSERT(asock); if (sslContext == NULL) { sslContext = SSL_DefaultContext(); } return SSL_ConnectAndVerifyWithContext(asock->sslSock, verifyParam, sslContext); #else return FALSE; #endif } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketAcceptSSL -- * * Initialize the socket's SSL object, by calling SSL_Accept or * SSL_AcceptWithContext. * * Results: * TRUE if SSL_Accept/SSL_AcceptWithContext succeeded, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool AsyncTCPSocketAcceptSSL(AsyncSocket *base, // IN void *sslCtx) // IN: optional { #ifndef USE_SSL_DIRECT AsyncTCPSocket *asock = TCPSocket(base); ASSERT(asock); if (sslCtx) { return SSL_AcceptWithContext(asock->sslSock, sslCtx); } else { return SSL_Accept(asock->sslSock); } #else return FALSE; #endif } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketSslConnectCallback -- * * Poll callback to redrive an outstanding ssl connect operation. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketSslConnectCallback(void *clientData) // IN { #ifndef USE_SSL_DIRECT int sslOpCode; VMwareStatus pollStatus; AsyncTCPSocket *asock = clientData; ASSERT(asock); ASSERT(AsyncTCPSocketPollParams(asock)->iPoll == NULL); ASSERT(AsyncTCPSocketIsLocked(asock)); AsyncTCPSocketAddRef(asock); /* Only set if poll callback is registered */ asock->sslPollFlags = 0; sslOpCode = SSL_TryCompleteConnect(asock->sslSock); if (sslOpCode > 0) { (*asock->sslConnectFn)(TRUE, BaseSocket(asock), asock->clientData); } else if (sslOpCode < 0) { (*asock->sslConnectFn)(FALSE, BaseSocket(asock), asock->clientData); } else { asock->sslPollFlags = SSL_WantRead(asock->sslSock) ? POLL_FLAG_READ : POLL_FLAG_WRITE; /* register the poll callback to redrive the SSL connect */ pollStatus = AsyncTCPSocketPollAdd(asock, TRUE, asock->sslPollFlags, AsyncTCPSocketSslConnectCallback); if (pollStatus != VMWARE_STATUS_SUCCESS) { TCPSOCKWARN(asock, ("failed to reinstall ssl connect callback!\n")); asock->sslPollFlags = 0; (*asock->sslConnectFn)(FALSE, BaseSocket(asock), asock->clientData); } } AsyncTCPSocketRelease(asock); #else NOT_IMPLEMENTED(); #endif } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketStartSslConnect -- * * Start an asynchronous SSL connect operation. * * The supplied callback function is called when the operation is complete * or an error occurs. * * Note: The client callback could be invoked from this function or * from a poll callback. If there is any requirement to always * invoke the client callback from outside this function, consider * changing this code to use a poll timer callback with timeout * set to zero. * * Results: * ASOCKERR_SUCCESS or ASOCKERR_*. * Errors during async processing are reported using the callback supplied. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static int AsyncTCPSocketStartSslConnect(AsyncSocket *base, // IN SSLVerifyParam *verifyParam, // IN/OPT void *sslCtx, // IN AsyncSocketSslConnectFn sslConnectFn, // IN void *clientData) // IN { #ifndef USE_SSL_DIRECT AsyncTCPSocket *asock = TCPSocket(base); Bool ok; ASSERT(asock); ASSERT(sslConnectFn); ASSERT(AsyncTCPSocketIsLocked(asock)); if (asock->sslConnectFn || asock->sslAcceptFn) { TCPSOCKWARN(asock, ("An SSL operation was already initiated.\n")); return ASOCKERR_GENERIC; } ok = SSL_SetupConnectAndVerifyWithContext(asock->sslSock, verifyParam, sslCtx); if (!ok) { /* Something went wrong already */ (*sslConnectFn)(FALSE, BaseSocket(asock), clientData); return ASOCKERR_GENERIC; } asock->sslConnectFn = sslConnectFn; asock->clientData = clientData; AsyncTCPSocketSslConnectCallback(asock); return ASOCKERR_SUCCESS; #else return ASOCKERR_INVAL; #endif } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketSslAcceptCallback -- * * Poll callback for redrive an outstanding ssl accept operation * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void AsyncTCPSocketSslAcceptCallback(void *clientData) // IN { int sslOpCode; AsyncTCPSocket *asock = clientData; VMwareStatus pollStatus; ASSERT(asock); ASSERT(AsyncTCPSocketPollParams(asock)->iPoll == NULL); ASSERT(AsyncTCPSocketIsLocked(asock)); AsyncTCPSocketAddRef(asock); /* Only set if poll callback is registered */ asock->sslPollFlags = 0; sslOpCode = SSL_TryCompleteAccept(asock->sslSock); if (sslOpCode > 0) { (*asock->sslAcceptFn)(TRUE, BaseSocket(asock), asock->clientData); } else if (sslOpCode < 0) { (*asock->sslAcceptFn)(FALSE, BaseSocket(asock), asock->clientData); } else { asock->sslPollFlags = SSL_WantRead(asock->sslSock) ? POLL_FLAG_READ : POLL_FLAG_WRITE; /* register the poll callback to redrive the SSL accept */ pollStatus = AsyncTCPSocketPollAdd(asock, TRUE, asock->sslPollFlags, AsyncTCPSocketSslAcceptCallback); if (pollStatus != VMWARE_STATUS_SUCCESS) { TCPSOCKWARN(asock, ("failed to reinstall ssl accept callback!\n")); asock->sslPollFlags = 0; (*asock->sslAcceptFn)(FALSE, BaseSocket(asock), asock->clientData); } } AsyncTCPSocketRelease(asock); } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketStartSslAccept -- * * Start an asynchronous SSL accept operation. * * The supplied callback function is called when the operation is complete * or an error occurs. * * Note: The client callback could be invoked from this function or * from a poll callback. If there is any requirement to always * invoke the client callback from outside this function, consider * changing this code to use a poll timer callback with timeout * set to zero. * * Note: sslCtx is typed as void *, so that the async socket code does * not have to include the openssl header. This is in sync with * SSL_AcceptWithContext(), where the sslCtx param is typed as void * * Results: * ASOCKERR_SUCCESS or ASOCKERR_*. * Errors during async processing reported using the callback supplied. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static int AsyncTCPSocketStartSslAccept(AsyncSocket *base, // IN void *sslCtx, // IN AsyncSocketSslAcceptFn sslAcceptFn, // IN void *clientData) // IN { AsyncTCPSocket *asock = TCPSocket(base); Bool ok; ASSERT(asock); ASSERT(sslAcceptFn); ASSERT(AsyncTCPSocketIsLocked(asock)); if (asock->sslAcceptFn || asock->sslConnectFn) { TCPSOCKWARN(asock, ("An SSL operation was already initiated.\n")); return ASOCKERR_GENERIC; } ok = SSL_SetupAcceptWithContext(asock->sslSock, sslCtx); if (!ok) { /* Something went wrong already */ (*sslAcceptFn)(FALSE, BaseSocket(asock), clientData); return ASOCKERR_GENERIC; } asock->sslAcceptFn = sslAcceptFn; asock->clientData = clientData; AsyncTCPSocketSslAcceptCallback(asock); return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketSetOption -- * * This implementation of ->setOption() supports the following * options. Exact behavior of each cited optID is documented in the * comment header for that enum value declaration (for non-native options), * or `man setsockopt`/equivalent (for native options). * * - layer = SOL_SOCKET, optID = * SO_SNDBUF, SO_RCVBUF. * * - layer = IPPROTO_TCP, optID = * TCP_NODELAY, TCP_KEEPINTVL, TCP_KEEPIDLE, TCP_KEEPCNT. * * - layer = ASYNC_SOCKET_OPTS_LAYER_BASE, optID (type) = * ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE (Bool). * * Results: * ASOCKERR_SUCCESS on success, ASOCKERR_* otherwise. * Invalid option+layer yields ASOCKERR_INVAL. * Failure to set a native OS option yields ASOCKERR_GENERIC. * inBufLen being wrong (for the given option) yields undefined behavior. * * Side effects: * Depends on option. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketSetOption(AsyncSocket *asyncSocket, // IN/OUT AsyncSocketOpts_Layer layer, // IN AsyncSocketOpts_ID optID, // IN const void *valuePtr, // IN socklen_t inBufLen) // IN { /* Maintenance: Keep this in sync with ...GetOption(). */ AsyncTCPSocket *tcpSocket = TCPSocket(asyncSocket); Bool isSupported; switch ((int)layer) { case SOL_SOCKET: case IPPROTO_TCP: case ASYNC_SOCKET_OPTS_LAYER_BASE: break; default: TCPSOCKLG0(tcpSocket, ("%s: Option layer [%d] (option [%d]) is not " "supported for TCP socket.\n", __FUNCTION__, (int)layer, optID)); return ASOCKERR_INVAL; } /* * layer is supported. * Handle non-native options first. */ if ((layer == ASYNC_SOCKET_OPTS_LAYER_BASE) && (optID == ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE)) { ASSERT(inBufLen == sizeof(Bool)); tcpSocket->sendLowLatency = *((const Bool *)valuePtr); TCPSOCKLG0(tcpSocket, ("%s: sendLowLatencyMode set to [%d].\n", __FUNCTION__, (int)tcpSocket->sendLowLatency)); return ASOCKERR_SUCCESS; } /* * Handle native (setsockopt()) options from this point on. * * We need the level and option_name arguments for that call. * Our design dictates that, for native options, simply option_name=optID. * So just determine level from our layer enum (for native layers, the enum's * ordinal value is set to the corresponding int level value). Therefore, * level=layer. * * level and option_name are known. However, we only allow the setting of * certain specific options. Anything else is an error. */ isSupported = FALSE; if (layer == SOL_SOCKET) { switch (optID) { case SO_SNDBUF: case SO_RCVBUF: isSupported = TRUE; } } else { ASSERT((int)layer == IPPROTO_TCP); switch (optID) { /* * Note: All but TCP_KEEPIDLE are available in Mac OS X (at least * 10.11). iOS and Android are TBD. For now, let's keep it simple and * make all these available in the two known OS where all 3 exist * together, as they're typically often set as a group. * TODO: Possibly enable for other OS in more fine-grained fashion. */ #if defined(__linux__) || defined(VMX86_SERVER) case TCP_KEEPIDLE: case TCP_KEEPINTVL: case TCP_KEEPCNT: #endif case TCP_NODELAY: isSupported = TRUE; } } if (!isSupported) { TCPSOCKLG0(tcpSocket, ("%s: Option layer/level [%d], option/name [%d]: " "could not set OS option for TCP socket; " "option not supported.\n", __FUNCTION__, (int)layer, optID)); return ASOCKERR_INVAL; } /* All good. Ready to actually set the OS option. */ if (setsockopt(tcpSocket->fd, layer, optID, valuePtr, inBufLen) != 0) { tcpSocket->genericErrno = Err_Errno(); TCPSOCKLG0(tcpSocket, ("%s: Option layer/level [%d], option/name [%d]: " "could not set OS option for TCP socket; " "error [%d: %s].\n", __FUNCTION__, (int)layer, optID, tcpSocket->genericErrno, Err_Errno2String(tcpSocket->genericErrno))); return ASOCKERR_GENERIC; } TCPSOCKLG0(tcpSocket, ("%s: Option layer/level [%d], option/name [%d]: successfully " "set OS option for TCP socket.\n", __FUNCTION__, (int)layer, optID)); return ASOCKERR_SUCCESS; } /* *---------------------------------------------------------------------------- * * AsyncTCPSocketGetOption -- * * This is the reverse of AsyncTCPSocketSetOption(). * * Results: * ASOCKERR_SUCCESS on success, ASOCKERR_* otherwise. * Invalid option+layer yields ASOCKERR_INVAL. * Failure to get a native OS option yields ASOCKERR_GENERIC. * *outBufLen being wrong (for the given option) at entry to function * yields undefined behavior. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static int AsyncTCPSocketGetOption(AsyncSocket *asyncSocket, // IN/OUT AsyncSocketOpts_Layer layer, // IN AsyncSocketOpts_ID optID, // IN void *valuePtr, // OUT socklen_t *outBufLen) // IN/OUT { /* * Maintenance: Keep this in sync with ...GetOption(). * Substantive comments are kept light to avoid redundancy (refer to the * other function). */ AsyncTCPSocket *tcpSocket = TCPSocket(asyncSocket); Bool isSupported; switch ((int)layer) { case SOL_SOCKET: case IPPROTO_TCP: case ASYNC_SOCKET_OPTS_LAYER_BASE: break; default: TCPSOCKLG0(tcpSocket, ("%s: Option layer [%d] (option [%d]) is not " "supported for TCP socket.\n", __FUNCTION__, (int)layer, optID)); return ASOCKERR_INVAL; } if ((layer == ASYNC_SOCKET_OPTS_LAYER_BASE) && (optID == ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE)) { ASSERT(*outBufLen >= sizeof(Bool)); *outBufLen = sizeof(Bool); *((Bool *)valuePtr) = tcpSocket->sendLowLatency; TCPSOCKLG0(tcpSocket, ("%s: sendLowLatencyMode is [%d].\n", __FUNCTION__, (int)tcpSocket->sendLowLatency)); return ASOCKERR_SUCCESS; } isSupported = FALSE; if (layer == SOL_SOCKET) { switch (optID) { case SO_SNDBUF: case SO_RCVBUF: isSupported = TRUE; } } else { ASSERT((int)layer == IPPROTO_TCP); switch (optID) { #ifdef __linux__ case TCP_KEEPIDLE: case TCP_KEEPINTVL: case TCP_KEEPCNT: #endif case TCP_NODELAY: isSupported = TRUE; } } if (!isSupported) { TCPSOCKLG0(tcpSocket, ("%s: Option layer/level [%d], option/name [%d]: " "could not get OS option for TCP socket; " "option not supported.\n", __FUNCTION__, (int)layer, optID)); return ASOCKERR_INVAL; } if (getsockopt(tcpSocket->fd, layer, optID, valuePtr, outBufLen) != 0) { tcpSocket->genericErrno = Err_Errno(); TCPSOCKLG0(tcpSocket, ("%s: Option layer/level [%d], option/name [%d]: " "could not get OS option for TCP socket; " "error [%d: %s].\n", __FUNCTION__, (int)layer, optID, tcpSocket->genericErrno, Err_Errno2String(tcpSocket->genericErrno))); return ASOCKERR_GENERIC; } TCPSOCKLG0(tcpSocket, ("%s: Option layer/level [%d], option/name [%d]: successfully " "got OS option for TCP socket.\n", __FUNCTION__, (int)layer, optID)); return ASOCKERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * AsyncTCPSocketDestroy -- * * Free the AsyncTCPSocket struct and all of its child storage. * * Result * None * * Side-effects * Releases memory. * *----------------------------------------------------------------------------- */ static void AsyncTCPSocketDestroy(AsyncSocket *base) // IN/OUT { free(base); } #ifndef _WIN32 /* *----------------------------------------------------------------------------- * * AsyncSocket_ListenSocketUDS -- * * Listens on the specified unix domain socket, and accepts new * socket connections. Fires the connect callback with new * AsyncTCPSocket object for each connection. * * Results: * New AsyncTCPSocket in listening state or NULL on error * * Side effects: * Creates new Unix domain socket, binds and listens. * *----------------------------------------------------------------------------- */ AsyncSocket * AsyncSocket_ListenSocketUDS(const char *pipeName, // IN AsyncSocketConnectFn connectFn, // IN void *clientData, // IN AsyncSocketPollParams *pollParams, // IN int *outError) // OUT { struct sockaddr_un addr; AsyncTCPSocket *asock; memset(&addr, 0, sizeof addr); addr.sun_family = AF_UNIX; Str_Strcpy(addr.sun_path, pipeName, sizeof addr.sun_path); Log(ASOCKPREFIX "creating new socket listening on %s\n", pipeName); asock = AsyncTCPSocketListenImpl((struct sockaddr_storage *)&addr, sizeof addr, connectFn, clientData, pollParams, outError); return BaseSocket(asock); } #endif /* *----------------------------------------------------------------------------- * * AsyncTCPSocketListenerError -- * * Call the error handler from parent AsyncSocket object. The passed in * parameter clientData is the parent AsyncSocket object. * * Result * None * * Side-effects * None * *----------------------------------------------------------------------------- */ static void AsyncTCPSocketListenerError(int error, // IN AsyncSocket *asock, // IN void *clientData) // IN { AsyncSocket *s = clientData; ASSERT(s); AsyncSocketHandleError(s, error); } open-vm-tools-stable-10.2.0/open-vm-tools/lib/auth/000077500000000000000000000000001321503522500220055ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/auth/Makefile.am000066400000000000000000000017671321503522500240540ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libAuth.la libAuth_la_SOURCES = libAuth_la_SOURCES += authPosix.c AM_CFLAGS = @LIB_AUTH_CPPFLAGS@ open-vm-tools-stable-10.2.0/open-vm-tools/lib/auth/authPosix.c000066400000000000000000000304371321503522500241440ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #include #include #include #include // for access, crypt, etc. #if !defined USE_PAM && !defined __APPLE__ #include #endif #include "vmware.h" #include "vm_product.h" #include "codeset.h" #include "posix.h" #include "auth.h" #include "str.h" #include "log.h" #ifdef USE_PAM # include "file.h" # include "config.h" # include "localconfig.h" # include # include #endif #if defined(HAVE_CONFIG_H) || defined(sun) # include #endif #define LOGLEVEL_MODULE auth #include "loglevel_user.h" typedef struct { struct passwd pwd; /* must be first member */ size_t bufSize; uint8 buf[]; } AuthTokenInternal; #ifdef USE_PAM #if defined(sun) #define CURRENT_PAM_LIBRARY "libpam.so.1" #elif defined(__FreeBSD__) #define CURRENT_PAM_LIBRARY "libpam.so" #elif defined(__APPLE__) #define CURRENT_PAM_LIBRARY "libpam.dylib" #else #define CURRENT_PAM_LIBRARY "libpam.so.0" #endif static typeof(&pam_start) dlpam_start; static typeof(&pam_end) dlpam_end; static typeof(&pam_authenticate) dlpam_authenticate; static typeof(&pam_setcred) dlpam_setcred; static typeof(&pam_acct_mgmt) dlpam_acct_mgmt; static typeof(&pam_strerror) dlpam_strerror; #if 0 /* These three functions are not used yet */ static typeof(&pam_open_session) dlpam_open_session; static typeof(&pam_close_session) dlpam_close_session; static typeof(&pam_chauthtok) dlpam_chauthtok; #endif static struct { void **procaddr; const char *procname; } authPAMImported[] = { #define IMPORT_SYMBOL(x) { (void **)&dl##x, #x } IMPORT_SYMBOL(pam_start), IMPORT_SYMBOL(pam_end), IMPORT_SYMBOL(pam_authenticate), IMPORT_SYMBOL(pam_setcred), IMPORT_SYMBOL(pam_acct_mgmt), IMPORT_SYMBOL(pam_strerror), #undef IMPORT_SYMBOL }; static void *authPamLibraryHandle = NULL; /* *---------------------------------------------------------------------- * * AuthLoadPAM -- * * Attempt to load and initialize PAM library. * * Results: * FALSE if load and/or initialization failed. * TRUE if initialization succeeded. * * Side effects: * libpam loaded. We never unload - some libpam modules use * syslog() function, and glibc does not survive when arguments * specified to openlog() are freeed from memory. * *---------------------------------------------------------------------- */ static Bool AuthLoadPAM(void) { void *pam_library; int i; if (authPamLibraryHandle) { return TRUE; } pam_library = Posix_Dlopen(CURRENT_PAM_LIBRARY, RTLD_LAZY | RTLD_GLOBAL); if (!pam_library) { #if defined(VMX86_TOOLS) /* * XXX do we even try to configure the pam libraries? * potential nightmare on all the possible guest OSes */ Log("System PAM libraries are unusable: %s\n", dlerror()); return FALSE; #else char *liblocation; char *libdir; libdir = LocalConfig_GetPathName(DEFAULT_LIBDIRECTORY, CONFIG_VMWAREDIR); if (!libdir) { Log("System PAM library unusable and bundled one not found.\n"); return FALSE; } liblocation = Str_SafeAsprintf(NULL, "%s/lib/%s/%s", libdir, CURRENT_PAM_LIBRARY, CURRENT_PAM_LIBRARY); free(libdir); pam_library = Posix_Dlopen(liblocation, RTLD_LAZY | RTLD_GLOBAL); if (!pam_library) { Log("Neither system nor bundled (%s) PAM libraries usable: %s\n", liblocation, dlerror()); free(liblocation); return FALSE; } free(liblocation); #endif } for (i = 0; i < ARRAYSIZE(authPAMImported); i++) { void *symbol = dlsym(pam_library, authPAMImported[i].procname); if (!symbol) { Log("PAM library does not contain required function: %s\n", dlerror()); dlclose(pam_library); return FALSE; } *(authPAMImported[i].procaddr) = symbol; } authPamLibraryHandle = pam_library; Log("PAM up and running.\n"); return TRUE; } static const char *PAM_username; static const char *PAM_password; #if defined(sun) static int PAM_conv (int num_msg, // IN: struct pam_message **msg, // IN: struct pam_response **resp, // OUT: void *appdata_ptr) // IN: #else static int PAM_conv (int num_msg, // IN: const struct pam_message **msg, // IN: struct pam_response **resp, // OUT: void *appdata_ptr) // IN: #endif { int count; struct pam_response *reply = calloc(num_msg, sizeof *reply); if (!reply) { return PAM_CONV_ERR; } for (count = 0; count < num_msg; count++) { switch (msg[count]->msg_style) { case PAM_PROMPT_ECHO_ON: reply[count].resp_retcode = PAM_SUCCESS; reply[count].resp = PAM_username ? strdup(PAM_username) : NULL; /* PAM frees resp */ break; case PAM_PROMPT_ECHO_OFF: reply[count].resp_retcode = PAM_SUCCESS; reply[count].resp = PAM_password ? strdup(PAM_password) : NULL; /* PAM frees resp */ break; case PAM_TEXT_INFO: reply[count].resp_retcode = PAM_SUCCESS; reply[count].resp = NULL; /* ignore it... */ break; case PAM_ERROR_MSG: reply[count].resp_retcode = PAM_SUCCESS; reply[count].resp = NULL; /* Must be an error of some sort... */ default: while (--count >= 0) { free(reply[count].resp); } free(reply); return PAM_CONV_ERR; } } *resp = reply; return PAM_SUCCESS; } static struct pam_conv PAM_conversation = { &PAM_conv, NULL }; #endif /* USE_PAM */ /* *---------------------------------------------------------------------- * * AuthAllocateToken -- * * Allocates an AuthTokenInternal structure, plus helper buffer * large enough for the Posix_Get*_r calls. * * Side effects: * None. * * Results: * An AuthTokenInternal pointer. Free with Auth_CloseToken. * *---------------------------------------------------------------------- */ static AuthTokenInternal * AuthAllocateToken(void) { AuthTokenInternal *ati; size_t bufSize; /* * We need to get the maximum size buffer needed by getpwuid_r from * sysconf. Multiply by 4 to compensate for the conversion to UTF-8 * by the Posix_Get*_r() wrappers. */ bufSize = (size_t) sysconf(_SC_GETPW_R_SIZE_MAX) * 4; ati = Util_SafeMalloc(sizeof *ati + bufSize); ati->bufSize = bufSize; return ati; } /* *---------------------------------------------------------------------- * * Auth_GetPwnam -- * * Wrapper aroung Posix_Getpwnam_r. * * Side effects: * None. * * Results: * An AuthToken. Free with Auth_CloseToken. * *---------------------------------------------------------------------- */ AuthToken Auth_GetPwnam(const char *user) // IN { AuthTokenInternal *ati; int res; struct passwd *ppwd; ASSERT(user); ati = AuthAllocateToken(); res = Posix_Getpwnam_r(user, &ati->pwd, ati->buf, ati->bufSize, &ppwd); if ((0 != res) || (ppwd == NULL)) { Auth_CloseToken((AuthToken) ati); return NULL; } ASSERT(ppwd == &ati->pwd); return (AuthToken) ati; } /* *---------------------------------------------------------------------- * * Auth_AuthenticateSelf -- * * Authenticate as the current user. * * Side effects: * None. * * Results: * An AuthToken. Free with Auth_CloseToken. * *---------------------------------------------------------------------- */ AuthToken Auth_AuthenticateSelf(void) // IN { AuthTokenInternal *ati; int res; struct passwd *ppwd; ati = AuthAllocateToken(); res = Posix_Getpwuid_r(getuid(), &ati->pwd, ati->buf, ati->bufSize, &ppwd); if ((0 != res) || (ppwd == NULL)) { Auth_CloseToken((AuthToken) ati); return NULL; } ASSERT(ppwd == &ati->pwd); return (AuthToken) ati; } /* *---------------------------------------------------------------------- * * Auth_AuthenticateUser -- * * Accept username/password And verfiy it * * Side effects: * None. * * Results: * * The vmauthToken for the authenticated user, or NULL if * authentication failed. * *---------------------------------------------------------------------- */ AuthToken Auth_AuthenticateUser(const char *user, // IN: const char *pass) // IN: { #ifdef USE_PAM pam_handle_t *pamh; int pam_error; #endif Bool success = FALSE; AuthTokenInternal *ati = NULL; if (!CodeSet_Validate(user, strlen(user), "UTF-8")) { Log("User not in UTF-8\n"); goto exit; } if (!CodeSet_Validate(pass, strlen(pass), "UTF-8")) { Log("Password not in UTF-8\n"); goto exit; } #ifdef USE_PAM if (!AuthLoadPAM()) { goto exit; } /* * XXX PAM can blow away our syslog level settings so we need * to call Log_InitEx() again before doing any more Log()s */ #define PAM_BAIL if (pam_error != PAM_SUCCESS) { \ Log_Error("%s:%d: PAM failure - %s (%d)\n", \ __FUNCTION__, __LINE__, \ dlpam_strerror(pamh, pam_error), pam_error); \ dlpam_end(pamh, pam_error); \ goto exit; \ } PAM_username = user; PAM_password = pass; #if defined(VMX86_TOOLS) pam_error = dlpam_start("vmtoolsd", PAM_username, &PAM_conversation, &pamh); #else pam_error = dlpam_start("vmware-authd", PAM_username, &PAM_conversation, &pamh); #endif if (pam_error != PAM_SUCCESS) { Log("Failed to start PAM (error = %d).\n", pam_error); goto exit; } pam_error = dlpam_authenticate(pamh, 0); PAM_BAIL; pam_error = dlpam_acct_mgmt(pamh, 0); PAM_BAIL; pam_error = dlpam_setcred(pamh, PAM_ESTABLISH_CRED); PAM_BAIL; dlpam_end(pamh, PAM_SUCCESS); /* If this point is reached, the user has been authenticated. */ ati = (AuthTokenInternal *) Auth_GetPwnam(user); #else /* !USE_PAM */ /* All of the following issues are dealt with in the PAM configuration file, so put all authentication/priviledge checks before the corresponding #endif below. */ ati = (AuthTokenInternal *) Auth_GetPwnam(user); if (ati == NULL) { goto exit; } if (*ati->pwd.pw_passwd != '\0') { const char *pw = ati->pwd.pw_passwd; const char *namep; #if !defined __APPLE__ // support shadow passwords: if (strcmp(pw, "x") == 0) { struct spwd *sp = getspnam(user); if (sp) { pw = sp->sp_pwdp; } } #endif namep = crypt(pass, pw); if (namep == NULL || strcmp(namep, pw) != 0) { // Incorrect password goto exit; } // Clear out crypt()'s internal state, too. crypt("glurp", pw); } #endif /* !USE_PAM */ success = TRUE; exit: if (success) { return (AuthToken) ati; } else { Auth_CloseToken((AuthToken) ati); return NULL; } } /* *---------------------------------------------------------------------- * * Auth_CloseToken -- * * Free the token allocated in Auth_AuthenticateUser. * * Side effects: * None * * Results: * None * *---------------------------------------------------------------------- */ void Auth_CloseToken(AuthToken token) // IN (OPT): { free((void *) token); } open-vm-tools-stable-10.2.0/open-vm-tools/lib/backdoor/000077500000000000000000000000001321503522500226305ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/backdoor/Makefile.am000066400000000000000000000021431321503522500246640ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libBackdoor.la libBackdoor_la_SOURCES = libBackdoor_la_SOURCES += backdoor.c if THIRTY_TWO_BIT_USERSPACE libBackdoor_la_SOURCES += backdoorGcc32.c else libBackdoor_la_SOURCES += backdoorGcc64.c endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/backdoor/backdoor.c000066400000000000000000000173441321503522500245710ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1999-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * backdoor.c -- * * First layer of the internal communication channel between guest * applications and vmware * * This is the backdoor. By using special ports of the virtual I/O space, * and the virtual CPU registers, a guest application can send a * synchroneous basic request to vmware, and vmware can reply to it. */ #ifdef __cplusplus extern "C" { #endif #include "backdoor_def.h" #include "backdoor.h" #include "backdoorInt.h" #ifdef USE_VALGRIND /* * When running under valgrind, we need to ensure we have the correct register * state when poking the backdoor. The VALGRIND_NON_SIMD_CALLx macros are used * to escape from the valgrind emulated CPU to the physical CPU. */ #include "vm_valgrind.h" #endif #if defined(BACKDOOR_DEBUG) && defined(USERLEVEL) #if defined(__KERNEL__) || defined(_KERNEL) #else # include "debug.h" #endif # include # define BACKDOOR_LOG(args) Debug args # define BACKDOOR_LOG_PROTO_STRUCT(x) BackdoorPrintProtoStruct((x)) # define BACKDOOR_LOG_HB_PROTO_STRUCT(x) BackdoorPrintHbProtoStruct((x)) /* *---------------------------------------------------------------------------- * * BackdoorPrintProtoStruct -- * BackdoorPrintHbProtoStruct -- * * Print the contents of the specified backdoor protocol structure via * printf. * * Results: * None. * * Side effects: * Output to stdout. * *---------------------------------------------------------------------------- */ void BackdoorPrintProtoStruct(Backdoor_proto *myBp) { Debug("magic 0x%08x, command %d, size %"FMTSZ"u, port %d\n", myBp->in.ax.word, myBp->in.cx.halfs.low, myBp->in.size, myBp->in.dx.halfs.low); #ifndef VM_X86_64 Debug("ax %#x, " "bx %#x, " "cx %#x, " "dx %#x, " "si %#x, " "di %#x\n", myBp->out.ax.word, myBp->out.bx.word, myBp->out.cx.word, myBp->out.dx.word, myBp->out.si.word, myBp->out.di.word); #else Debug("ax %#"FMT64"x, " "bx %#"FMT64"x, " "cx %#"FMT64"x, " "dx %#"FMT64"x, " "si %#"FMT64"x, " "di %#"FMT64"x\n", myBp->out.ax.quad, myBp->out.bx.quad, myBp->out.cx.quad, myBp->out.dx.quad, myBp->out.si.quad, myBp->out.di.quad); #endif } void BackdoorPrintHbProtoStruct(Backdoor_proto_hb *myBp) { Debug("magic 0x%08x, command %d, size %"FMTSZ"u, port %d, " "srcAddr %"FMTSZ"u, dstAddr %"FMTSZ"u\n", myBp->in.ax.word, myBp->in.bx.halfs.low, myBp->in.size, myBp->in.dx.halfs.low, myBp->in.srcAddr, myBp->in.dstAddr); #ifndef VM_X86_64 Debug("ax %#x, " "bx %#x, " "cx %#x, " "dx %#x, " "si %#x, " "di %#x, " "bp %#x\n", myBp->out.ax.word, myBp->out.bx.word, myBp->out.cx.word, myBp->out.dx.word, myBp->out.si.word, myBp->out.di.word, myBp->out.bp.word); #else Debug("ax %#"FMT64"x, " "bx %#"FMT64"x, " "cx %#"FMT64"x, " "dx %#"FMT64"x, " "si %#"FMT64"x, " "di %#"FMT64"x, " "bp %#"FMT64"x\n", myBp->out.ax.quad, myBp->out.bx.quad, myBp->out.cx.quad, myBp->out.dx.quad, myBp->out.si.quad, myBp->out.di.quad, myBp->out.bp.quad); #endif } #else # define BACKDOOR_LOG(args) # define BACKDOOR_LOG_PROTO_STRUCT(x) # define BACKDOOR_LOG_HB_PROTO_STRUCT(x) #endif /* *----------------------------------------------------------------------------- * * Backdoor -- * * Send a low-bandwidth basic request (16 bytes) to vmware, and return its * reply (24 bytes). * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ #ifdef USE_VALGRIND static void Backdoor_InOutValgrind(uint16 tid, Backdoor_proto *myBp) { Backdoor_InOut(myBp); } #endif void Backdoor(Backdoor_proto *myBp) // IN/OUT { ASSERT(myBp); myBp->in.ax.word = BDOOR_MAGIC; myBp->in.dx.halfs.low = BDOOR_PORT; BACKDOOR_LOG(("Backdoor: before ")); BACKDOOR_LOG_PROTO_STRUCT(myBp); #ifdef USE_VALGRIND VALGRIND_NON_SIMD_CALL1(Backdoor_InOutValgrind, myBp); #else Backdoor_InOut(myBp); #endif BACKDOOR_LOG(("Backdoor: after ")); BACKDOOR_LOG_PROTO_STRUCT(myBp); } /* *----------------------------------------------------------------------------- * * Backdoor_HbOut -- * * Send a high-bandwidth basic request to vmware, and return its * reply. * * Result: * The host-side response is returned via the IN/OUT parameter. * * Side-effects: * Pokes the high-bandwidth backdoor. * *----------------------------------------------------------------------------- */ #ifdef USE_VALGRIND static void BackdoorHbOutValgrind(uint16 tid, Backdoor_proto_hb *myBp) { BackdoorHbOut(myBp); } #endif void Backdoor_HbOut(Backdoor_proto_hb *myBp) // IN/OUT { ASSERT(myBp); myBp->in.ax.word = BDOOR_MAGIC; myBp->in.dx.halfs.low = BDOORHB_PORT; BACKDOOR_LOG(("Backdoor_HbOut: before ")); BACKDOOR_LOG_HB_PROTO_STRUCT(myBp); #ifdef USE_VALGRIND VALGRIND_NON_SIMD_CALL1(BackdoorHbOutValgrind, myBp); #else BackdoorHbOut(myBp); #endif BACKDOOR_LOG(("Backdoor_HbOut: after ")); BACKDOOR_LOG_HB_PROTO_STRUCT(myBp); } /* *----------------------------------------------------------------------------- * * Backdoor_HbIn -- * * Send a basic request to vmware, and return its high-bandwidth * reply * * Result: * Host-side response returned via the IN/OUT parameter. * * Side-effects: * Pokes the high-bandwidth backdoor. * *----------------------------------------------------------------------------- */ #ifdef USE_VALGRIND static void BackdoorHbInValgrind(uint16 tid, Backdoor_proto_hb *myBp) { BackdoorHbIn(myBp); } #endif void Backdoor_HbIn(Backdoor_proto_hb *myBp) // IN/OUT { ASSERT(myBp); myBp->in.ax.word = BDOOR_MAGIC; myBp->in.dx.halfs.low = BDOORHB_PORT; BACKDOOR_LOG(("Backdoor_HbIn: before ")); BACKDOOR_LOG_HB_PROTO_STRUCT(myBp); #ifdef USE_VALGRIND VALGRIND_NON_SIMD_CALL1(BackdoorHbInValgrind, myBp); #else BackdoorHbIn(myBp); #endif BACKDOOR_LOG(("Backdoor_HbIn: after ")); BACKDOOR_LOG_HB_PROTO_STRUCT(myBp); } #ifdef __cplusplus } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/backdoor/backdoorGcc32.c000066400000000000000000000151561321503522500253520ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * backdoorGcc32.c -- * * Implements the real work for guest-side backdoor for GCC, 32-bit * target (supports inline ASM, GAS syntax). The asm sections are marked * volatile since vmware can change the registers content without the * compiler knowing it. * * XXX * I tried to write this more cleanly, but: * - There is no way to specify an "ebp" constraint * - "ebp" is ignored when specified as cloberred register * - gas barfs when there is more than 10 operands * - gas 2.7.2.3, depending on the order of the operands, can * mis-assemble without any warning * --hpreg * * Note that the problems with gas noted above might longer be relevant * now that we've upgraded most of our compiler versions. * --rrdharan */ #ifdef __cplusplus extern "C" { #endif #include "backdoor.h" #include "backdoorInt.h" /* *---------------------------------------------------------------------------- * * Backdoor_InOut -- * * Send a low-bandwidth basic request (16 bytes) to vmware, and return its * reply (24 bytes). * * Results: * Host-side response returned in bp IN/OUT parameter. * * Side effects: * Pokes the backdoor. * *---------------------------------------------------------------------------- */ void Backdoor_InOut(Backdoor_proto *myBp) // IN/OUT { uint32 dummy; __asm__ __volatile__( #ifdef __PIC__ "pushl %%ebx" "\n\t" #endif "pushl %%eax" "\n\t" "movl 20(%%eax), %%edi" "\n\t" "movl 16(%%eax), %%esi" "\n\t" "movl 12(%%eax), %%edx" "\n\t" "movl 8(%%eax), %%ecx" "\n\t" "movl 4(%%eax), %%ebx" "\n\t" "movl (%%eax), %%eax" "\n\t" "inl %%dx, %%eax" "\n\t" "xchgl %%eax, (%%esp)" "\n\t" "movl %%edi, 20(%%eax)" "\n\t" "movl %%esi, 16(%%eax)" "\n\t" "movl %%edx, 12(%%eax)" "\n\t" "movl %%ecx, 8(%%eax)" "\n\t" "movl %%ebx, 4(%%eax)" "\n\t" "popl (%%eax)" "\n\t" #ifdef __PIC__ "popl %%ebx" "\n\t" #endif : "=a" (dummy) : "0" (myBp) /* * vmware can modify the whole VM state without the compiler knowing * it. So far it does not modify EFLAGS. --hpreg */ : #ifndef __PIC__ "ebx", #endif "ecx", "edx", "esi", "edi", "memory" ); } /* *----------------------------------------------------------------------------- * * BackdoorHbIn -- * BackdoorHbOut -- * * Send a high-bandwidth basic request to vmware, and return its * reply. * * Results: * Host-side response returned in bp IN/OUT parameter. * * Side-effects: * Pokes the high-bandwidth backdoor port. * *----------------------------------------------------------------------------- */ void BackdoorHbIn(Backdoor_proto_hb *myBp) // IN/OUT { uint32 dummy; __asm__ __volatile__( #ifdef __PIC__ "pushl %%ebx" "\n\t" #endif "pushl %%ebp" "\n\t" "pushl %%eax" "\n\t" "movl 24(%%eax), %%ebp" "\n\t" "movl 20(%%eax), %%edi" "\n\t" "movl 16(%%eax), %%esi" "\n\t" "movl 12(%%eax), %%edx" "\n\t" "movl 8(%%eax), %%ecx" "\n\t" "movl 4(%%eax), %%ebx" "\n\t" "movl (%%eax), %%eax" "\n\t" "cld" "\n\t" "rep; insb" "\n\t" "xchgl %%eax, (%%esp)" "\n\t" "movl %%ebp, 24(%%eax)" "\n\t" "movl %%edi, 20(%%eax)" "\n\t" "movl %%esi, 16(%%eax)" "\n\t" "movl %%edx, 12(%%eax)" "\n\t" "movl %%ecx, 8(%%eax)" "\n\t" "movl %%ebx, 4(%%eax)" "\n\t" "popl (%%eax)" "\n\t" "popl %%ebp" "\n\t" #ifdef __PIC__ "popl %%ebx" "\n\t" #endif : "=a" (dummy) : "0" (myBp) /* * vmware can modify the whole VM state without the compiler knowing * it. --hpreg */ : #ifndef __PIC__ "ebx", #endif "ecx", "edx", "esi", "edi", "memory", "cc" ); } void BackdoorHbOut(Backdoor_proto_hb *myBp) // IN/OUT { uint32 dummy; __asm__ __volatile__( #ifdef __PIC__ "pushl %%ebx" "\n\t" #endif "pushl %%ebp" "\n\t" "pushl %%eax" "\n\t" "movl 24(%%eax), %%ebp" "\n\t" "movl 20(%%eax), %%edi" "\n\t" "movl 16(%%eax), %%esi" "\n\t" "movl 12(%%eax), %%edx" "\n\t" "movl 8(%%eax), %%ecx" "\n\t" "movl 4(%%eax), %%ebx" "\n\t" "movl (%%eax), %%eax" "\n\t" "cld" "\n\t" "rep; outsb" "\n\t" "xchgl %%eax, (%%esp)" "\n\t" "movl %%ebp, 24(%%eax)" "\n\t" "movl %%edi, 20(%%eax)" "\n\t" "movl %%esi, 16(%%eax)" "\n\t" "movl %%edx, 12(%%eax)" "\n\t" "movl %%ecx, 8(%%eax)" "\n\t" "movl %%ebx, 4(%%eax)" "\n\t" "popl (%%eax)" "\n\t" "popl %%ebp" "\n\t" #ifdef __PIC__ "popl %%ebx" "\n\t" #endif : "=a" (dummy) : "0" (myBp) : #ifndef __PIC__ "ebx", #endif "ecx", "edx", "esi", "edi", "memory", "cc" ); } #ifdef __cplusplus } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/backdoor/backdoorGcc64.c000066400000000000000000000164241321503522500253560ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * backdoorGcc64.c -- * * Implements the real work for guest-side backdoor for GCC, 64-bit * target (supports inline ASM, GAS syntax). The asm sections are marked * volatile since vmware can change the registers content without the * compiler knowing it. * * See backdoorGCC32.c (from which this code was mostly copied) for * details on why the ASM is written this way. Also note that it might be * possible to write the asm blocks using the symbolic operand specifiers * in such a way that the same asm would generate correct code for both * 32-bit and 64-bit targets, but I'm too lazy to figure it all out. * --rrdharan */ #ifdef __cplusplus extern "C" { #endif #include "backdoor.h" #include "backdoorInt.h" /* *---------------------------------------------------------------------------- * * Backdoor_InOut -- * * Send a low-bandwidth basic request (16 bytes) to vmware, and return its * reply (24 bytes). * * Results: * Host-side response returned in bp IN/OUT parameter. * * Side effects: * Pokes the backdoor. * *---------------------------------------------------------------------------- */ void Backdoor_InOut(Backdoor_proto *myBp) // IN/OUT { uint64 dummy; __asm__ __volatile__( #ifdef __APPLE__ /* * Save %rbx on the stack because the Mac OS GCC doesn't want us to * clobber it - it erroneously thinks %rbx is the PIC register. * (Radar bug 7304232) */ "pushq %%rbx" "\n\t" #endif "pushq %%rax" "\n\t" "movq 40(%%rax), %%rdi" "\n\t" "movq 32(%%rax), %%rsi" "\n\t" "movq 24(%%rax), %%rdx" "\n\t" "movq 16(%%rax), %%rcx" "\n\t" "movq 8(%%rax), %%rbx" "\n\t" "movq (%%rax), %%rax" "\n\t" "inl %%dx, %%eax" "\n\t" /* NB: There is no inq instruction */ "xchgq %%rax, (%%rsp)" "\n\t" "movq %%rdi, 40(%%rax)" "\n\t" "movq %%rsi, 32(%%rax)" "\n\t" "movq %%rdx, 24(%%rax)" "\n\t" "movq %%rcx, 16(%%rax)" "\n\t" "movq %%rbx, 8(%%rax)" "\n\t" "popq (%%rax)" "\n\t" #ifdef __APPLE__ "popq %%rbx" "\n\t" #endif : "=a" (dummy) : "0" (myBp) /* * vmware can modify the whole VM state without the compiler knowing * it. So far it does not modify EFLAGS. --hpreg */ : #ifndef __APPLE__ /* %rbx is unchanged at the end of the function on Mac OS. */ "rbx", #endif "rcx", "rdx", "rsi", "rdi", "memory" ); } /* *----------------------------------------------------------------------------- * * BackdoorHbIn -- * BackdoorHbOut -- * * Send a high-bandwidth basic request to vmware, and return its * reply. * * Results: * Host-side response returned in bp IN/OUT parameter. * * Side-effects: * Pokes the high-bandwidth backdoor port. * *----------------------------------------------------------------------------- */ void BackdoorHbIn(Backdoor_proto_hb *myBp) // IN/OUT { uint64 dummy; __asm__ __volatile__( "pushq %%rbp" "\n\t" #ifdef __APPLE__ /* * Save %rbx on the stack because the Mac OS GCC doesn't want us to * clobber it - it erroneously thinks %rbx is the PIC register. * (Radar bug 7304232) */ "pushq %%rbx" "\n\t" #endif "pushq %%rax" "\n\t" "movq 48(%%rax), %%rbp" "\n\t" "movq 40(%%rax), %%rdi" "\n\t" "movq 32(%%rax), %%rsi" "\n\t" "movq 24(%%rax), %%rdx" "\n\t" "movq 16(%%rax), %%rcx" "\n\t" "movq 8(%%rax), %%rbx" "\n\t" "movq (%%rax), %%rax" "\n\t" "cld" "\n\t" "rep; insb" "\n\t" "xchgq %%rax, (%%rsp)" "\n\t" "movq %%rbp, 48(%%rax)" "\n\t" "movq %%rdi, 40(%%rax)" "\n\t" "movq %%rsi, 32(%%rax)" "\n\t" "movq %%rdx, 24(%%rax)" "\n\t" "movq %%rcx, 16(%%rax)" "\n\t" "movq %%rbx, 8(%%rax)" "\n\t" "popq (%%rax)" "\n\t" #ifdef __APPLE__ "popq %%rbx" "\n\t" #endif "popq %%rbp" : "=a" (dummy) : "0" (myBp) /* * vmware can modify the whole VM state without the compiler knowing * it. --hpreg */ : #ifndef __APPLE__ /* %rbx is unchanged at the end of the function on Mac OS. */ "rbx", #endif "rcx", "rdx", "rsi", "rdi", "memory", "cc" ); } void BackdoorHbOut(Backdoor_proto_hb *myBp) // IN/OUT { uint64 dummy; __asm__ __volatile__( "pushq %%rbp" "\n\t" #ifdef __APPLE__ /* * Save %rbx on the stack because the Mac OS GCC doesn't want us to * clobber it - it erroneously thinks %rbx is the PIC register. * (Radar bug 7304232) */ "pushq %%rbx" "\n\t" #endif "pushq %%rax" "\n\t" "movq 48(%%rax), %%rbp" "\n\t" "movq 40(%%rax), %%rdi" "\n\t" "movq 32(%%rax), %%rsi" "\n\t" "movq 24(%%rax), %%rdx" "\n\t" "movq 16(%%rax), %%rcx" "\n\t" "movq 8(%%rax), %%rbx" "\n\t" "movq (%%rax), %%rax" "\n\t" "cld" "\n\t" "rep; outsb" "\n\t" "xchgq %%rax, (%%rsp)" "\n\t" "movq %%rbp, 48(%%rax)" "\n\t" "movq %%rdi, 40(%%rax)" "\n\t" "movq %%rsi, 32(%%rax)" "\n\t" "movq %%rdx, 24(%%rax)" "\n\t" "movq %%rcx, 16(%%rax)" "\n\t" "movq %%rbx, 8(%%rax)" "\n\t" "popq (%%rax)" "\n\t" #ifdef __APPLE__ "popq %%rbx" "\n\t" #endif "popq %%rbp" : "=a" (dummy) : "0" (myBp) : #ifndef __APPLE__ /* %rbx is unchanged at the end of the function on Mac OS. */ "rbx", #endif "rcx", "rdx", "rsi", "rdi", "memory", "cc" ); } #ifdef __cplusplus } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/backdoor/backdoorInt.h000066400000000000000000000031301321503522500252350ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * backdoorInt.h -- * * Internal function prototypes for the real backdoor work. */ void BackdoorHbIn(Backdoor_proto_hb *bp); void BackdoorHbOut(Backdoor_proto_hb *bp); open-vm-tools-stable-10.2.0/open-vm-tools/lib/dataMap/000077500000000000000000000000001321503522500224135ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/dataMap/Makefile.am000066400000000000000000000017351321503522500244550ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2013-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libDataMap.la libDataMap_la_SOURCES = libDataMap_la_SOURCES += dataMap.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/dataMap/dataMap.c000066400000000000000000001741041321503522500241350ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2012-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #include #include #include #ifdef _WIN32 #include #else #include #endif #include "vm_basic_types.h" #include "str.h" #include "dataMap.h" #include "vm_ctype.h" /* * A union for all kinds of data fields types. */ typedef union { struct { int64 val; } number; struct { int32 length; char *str; } string; struct { int32 length; int64 *numbers; } numList; struct { char **strings; /* a list of string pointers, the last elment is NULL */ int32 *lengths; /* a list of lengths for strings in strings. */ } strList; } DMFieldValue; typedef struct { DMFieldType type; DMFieldValue value; } DataMapEntry; /* structure used in hashMap iteration callback */ typedef struct { DataMap *map; ErrorCode result; /* store the previous callback function result value */ /* the followings are used during serialization, deserialization and * pretty print. */ char *buffer; uint32 buffLen; /* available buffer size */ uint32 maxNumElems; /* this limits the number of elements for list print. */ uint32 maxStrLen; /* max number of bytes to print for each string */ FieldIdNameEntry *fieldIdList; /* array for field ID to name mapping */ uint32 fieldIdListLen; /* fieldIdList size */ } ClientData; static const uint64 magic_cookie = 0x4d41474943ULL; /* 'MAGIC' */ /* *----------------------------------------------------------------------------- * * AddEntry_Int64 -- * * - low level helper function to add a numeric type entry to the map * * Result: * 0 on success * error code otherwise * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode AddEntry_Int64(DataMap *that, // IN/OUT DMKeyType key, // IN int64 value) // IN { DataMapEntry *entry = (DataMapEntry *)malloc(sizeof(DataMapEntry)); if (entry == NULL) { return DMERR_INSUFFICIENT_MEM; } entry->type = DMFIELDTYPE_INT64; entry->value.number.val = value; if (!HashMap_Put(that->map, &key, &entry)) { return DMERR_INSUFFICIENT_MEM; } return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * AddEntry_String -- * * Low level helper function to add a string type entry to the map. * - 'str': ownership of the str pointer is passed to the map on success. * * Result: * 0 on success * error code otherwise * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode AddEntry_String(DataMap *that, // IN/OUT DMKeyType key, // IN char *str, // IN int32 strLen) // IN { DataMapEntry *entry = (DataMapEntry *)malloc(sizeof(DataMapEntry)); if (entry == NULL) { return DMERR_INSUFFICIENT_MEM; } entry->type = DMFIELDTYPE_STRING; entry->value.string.str = str; entry->value.string.length = strLen; if (!HashMap_Put(that->map, &key, &entry)) { return DMERR_INSUFFICIENT_MEM; } return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * AddEntry_Int64List -- * * Low level helper function to add a list of numbers to the map * - 'numbers': ownership of this pointer is passed to the map on success. * - 'listLen': the number of integers in the list of 'numbers'. * * Result: * 0 on success * error code otherwise * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode AddEntry_Int64List(DataMap *that, // IN/OUT DMKeyType key, // IN int64 *numbers, // IN int32 listLen) // IN { DataMapEntry *entry = (DataMapEntry *)malloc(sizeof(DataMapEntry)); if (entry == NULL) { return DMERR_INSUFFICIENT_MEM; } entry->type = DMFIELDTYPE_INT64LIST; entry->value.numList.numbers = numbers; entry->value.numList.length = listLen; if (!HashMap_Put(that->map, &key, &entry)) { return DMERR_INSUFFICIENT_MEM; } return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * AddEntry_StringList -- * * Low level helper function to add a list of trings to the map * - 'strList': this pointer points to an array of pointers which points to * strings. Upon success, the ownership of this array is passed to the * map, no copy of strings is made. The last element in this array * pointer must be NULL. * - 'strLens': this is an array of integers which indicating the length of * cooresponding string in strList. the ownership is passed to the map * as well on success. * * Result: * 0 on success * error code otherwise * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode AddEntry_StringList(DataMap *that, // IN/OUT DMKeyType key, // IN char **strList, // IN int32 *strLens) // IN { DataMapEntry *entry = (DataMapEntry *)malloc(sizeof(DataMapEntry)); if (entry == NULL) { return DMERR_INSUFFICIENT_MEM; } entry->type = DMFIELDTYPE_STRINGLIST; entry->value.strList.strings = strList; entry->value.strList.lengths = strLens; if (!HashMap_Put(that->map, &key, &entry)) { return DMERR_INSUFFICIENT_MEM; } return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * FreeStringList -- * * Low level helper function to free a list of strings. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void FreeStringList(char **strList, // IN int32 *strLens) // IN { if (*strList != NULL) { char **ptr; for (ptr = strList; *ptr != NULL; ptr++) { free(*ptr); } } free(strLens); free(strList); } /* *----------------------------------------------------------------------------- * * FreeEntryPayload -- * * - low level helper function to free entry payload only * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void FreeEntryPayload(DataMapEntry *entry) // IN { if (entry == NULL) { return; } switch(entry->type) { case DMFIELDTYPE_INT64: break; case DMFIELDTYPE_STRING: free(entry->value.string.str); break; case DMFIELDTYPE_INT64LIST: free(entry->value.numList.numbers); break; case DMFIELDTYPE_STRINGLIST: FreeStringList(entry->value.strList.strings, entry->value.strList.lengths); break; default: ASSERT(0); /* we do not expect this to happen */ } } /* *----------------------------------------------------------------------------- * * EncodeInt32 -- * * Low level helper function to encode an int32 into a byte buffer. * - 'buf': *buf points to the output buffer, *buf is advanced properly. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void EncodeInt32(char **buf, // IN/OUT int32 num) // IN { uint32 netVal = htonl((uint32)num); *((uint32 *)(*buf)) = netVal; (*buf) += sizeof(int32); } /* *----------------------------------------------------------------------------- * * DecodeInt32 -- * * Low level helper function to decode an int32 from a byte buffer * - 'buf': *buf points to the input buffer. *buf is advanced accordingly * on success. * - 'left': indicates number of bytes left in the input buffer, *left is * updated accordingly on success. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode DecodeInt32(char **buf, // IN/OUT int32 *left, // IN/OUT int32 *num) // OUT { uint32 val; if (*left < sizeof(int32)) { return DMERR_TRUNCATED_DATA; } val = ntohl(*((uint32 *)(*buf))); *num = (int32) val; *buf += sizeof(int32); *left -= sizeof(int32); return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * EncodeInt64 -- * * Low level helper function to encode an int64 into a byte buffer * - 'buf': *buf points to the output buffer, *buf is advanced properly. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void EncodeInt64(char **buf, // IN/OUT int64 num) // IN { EncodeInt32(buf, (uint32)num); EncodeInt32(buf, (uint32)(num >> 32)); } /* *----------------------------------------------------------------------------- * * DecodeInt64 -- * * Low level helper function to decode an int64 from a byte buffer * - 'buf': *buf points to the input buffer. *buf is advanced accordingly * on success. * - 'left': indicates number of bytes left in the input buffer, *left is * updated accordingly on success. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode DecodeInt64(char **buf, // IN/OUT int32 *left, // IN/OUT int64 *num) // OUT { ErrorCode res; uint32 low; uint32 high; res = DecodeInt32(buf, left, &low); if (res == DMERR_SUCCESS) { res = DecodeInt32(buf, left, &high); if (res == DMERR_SUCCESS) { *num = (int64)(((((uint64)high)<< 32) | low)); } } return res; } /* *----------------------------------------------------------------------------- * * EncodeString -- * * Low level helper function to encode a string into a byte buffer * - 'buf': *buf points to the output buffer, *buf is advanced properly. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void EncodeString(char **buf, // IN/OUT const char *str, // IN int32 strLen) // IN { EncodeInt32(buf, strLen); memcpy(*buf, str, strLen); (*buf) += strLen; } /* *----------------------------------------------------------------------------- * * DecodeString -- * * - low level helper function to decode a string from a byte buffer * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode DecodeString(char **buf, // IN/OUT int32 *left, // IN/OUT char **str, // OUT int32 *strLen) // OUT { ErrorCode res; res = DecodeInt32(buf, left, strLen); if (res != DMERR_SUCCESS) { return res; } if (*strLen <= 0) { return DMERR_BAD_DATA; } if (*left < *strLen) { return DMERR_TRUNCATED_DATA; } *str = (char *)malloc(*strLen); if (*str == NULL) { return DMERR_INSUFFICIENT_MEM; } memcpy(*str, *buf, *strLen); *buf += *strLen; *left -= *strLen; return res; } /* *----------------------------------------------------------------------------- * * EncodeInt64List -- * * Low level helper function to encode an int64 list into a byte buffer * - 'buf': *buf points to the output buffer, *buf is advanced properly. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void EncodeInt64List(char **buf, // IN/OUT int64 *numList, // IN int32 listLen) // IN { int32 i; EncodeInt32(buf, (uint32)listLen); for(i = 0; i< listLen; i++) { EncodeInt64(buf, numList[i]); } } /* *----------------------------------------------------------------------------- * * DecodeInt64List -- * * Low level helper function to decode an int64 list from a byte buffer * - 'buf': *buf points to the input buffer. *buf is advanced accordingly * on success. * - 'left': indicates number of bytes left in the input buffer, *left is * updated accordingly on success. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode DecodeInt64List(char **buf, // IN/OUT int32 *left, // IN/OUT DMKeyType fieldId, // IN DataMap *that) // OUT { int32 listLen; int64 *numList = NULL; ErrorCode res; int32 i; res = DecodeInt32(buf, left, &listLen); if (res != DMERR_SUCCESS) { return res; } if (listLen < 0 || listLen > *left / sizeof(int64)) { /* listLen can be zero to support an empty list */ return DMERR_BAD_DATA; } if (listLen) { numList = (int64 *)malloc(sizeof(int64) * listLen); if (numList == NULL) { return DMERR_INSUFFICIENT_MEM; } for(i = 0; i< listLen; i++) { res = DecodeInt64(buf, left, numList + i); if (res != DMERR_SUCCESS) { break; } } } if (res == DMERR_SUCCESS) { res = AddEntry_Int64List(that, fieldId, numList, listLen); } if (res != DMERR_SUCCESS) { /* clean up memory */ free(numList); } return res; } /* *----------------------------------------------------------------------------- * * FreeEntry -- * * - low level helper function to free an entry. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void FreeEntry(DataMapEntry *entry) // IN { FreeEntryPayload(entry); free(entry); } /* *----------------------------------------------------------------------------- * * LookupEntry -- * * - helper function to lookup an entry in the data map. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static DataMapEntry * LookupEntry(const DataMap *that, // IN DMKeyType fieldId) // IN { if ((that != NULL) && (that->map != NULL)) { void *rv = HashMap_Get(that->map, &fieldId); if (rv == NULL) { return NULL; /* key not found */ } return *((DataMapEntry **)rv); } else { return NULL; } } /* *----------------------------------------------------------------------------- * * DataMap_GetType -- * * Get the value type for a given fieldID. * * Result: * - DMFIELDTYPE_EMPTY is returned if entry does not exist. * - One of other values in DMFieldType otherwise. * * * Side-effects: * None * *----------------------------------------------------------------------------- */ DMFieldType DataMap_GetType(const DataMap *that, // IN DMKeyType fieldId) // IN { DataMapEntry *entry; ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { return DMFIELDTYPE_EMPTY; } else { return entry->type; } } /* *----------------------------------------------------------------------------- * * DataMap_Create -- * * - Initialize an Empty DataMap using the DataMap storage pointed * by that. * - The memory pointed by that may be allocated from heap or stack. * - This function may allocate additional memory from the heap to * initialize the DataMap object. * * Result: * 0(DMERR_SUCCESS) on success. * error code on failures. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_Create(DataMap *that) // IN/OUT { if (that == NULL) { return DMERR_INVALID_ARGS; } that->map = HashMap_AllocMap(16, sizeof(DMKeyType), sizeof(DataMapEntry *)); if (that->map != NULL) { that->cookie = magic_cookie; return DMERR_SUCCESS; } return DMERR_INSUFFICIENT_MEM; } /* *----------------------------------------------------------------------------- * * ToBufferUpdate -- * * Update result, advance buffer pointer, and adjust buffer left size etc * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void ToBufferUpdate(ClientData *clientData, // IN/OUT uint32 len) { if (len >= clientData->buffLen) { clientData->result = DMERR_BUFFER_TOO_SMALL; clientData->buffer += clientData->buffLen; clientData->buffLen = 0; } else { clientData->buffer += len; clientData->buffLen -= len; } } /* *----------------------------------------------------------------------------- * * ToBufferString -- * * Copy a string to a buffer. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void ToBufferString(ClientData *clientData, // IN/OUT const char *str) // IN { int32 len; if (clientData->result != DMERR_SUCCESS) { /* an error occurred already, so stop. */ return; } ASSERT(clientData->buffLen > 0); len = snprintf(clientData->buffer, clientData->buffLen, "%s", str); ToBufferUpdate(clientData, len); } /* *----------------------------------------------------------------------------- * * ToBufferStringN -- * * Copy N bytes from a string to a buffer. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void ToBufferStringN(ClientData *clientData, // IN/OUT const char *str, // IN uint32 len) // IN { uint32 copyLen = len; if (clientData->result != DMERR_SUCCESS) { /* an error occurred already, so stop. */ return; } ASSERT(clientData->buffLen > 0); if (copyLen >= clientData->buffLen) { copyLen = clientData->buffLen - 1; } memcpy(clientData->buffer, str, copyLen); clientData->buffer[copyLen] = '\0'; ToBufferUpdate(clientData, len); } /* *----------------------------------------------------------------------------- * * GetLimit -- * * Get the limit from the given max and actual length. * * Result: * Returns the limit * * Side-effects: * None * *----------------------------------------------------------------------------- */ static int32 GetLimit(int32 max, // IN: -1 means no limit int32 length) // IN { if (max < 0) { return length; } return max < length ? max : length; } /* *----------------------------------------------------------------------------- * * ToBufferInt64 -- * * Copy an int64 to a buffer. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void ToBufferInt64(ClientData *clientData, // IN/OUT int64 num) // IN { uint32 len; if (clientData->result != DMERR_SUCCESS) { /* an error occurred already, so stop. */ return; } ASSERT(clientData->buffLen > 0); len = snprintf(clientData->buffer, clientData->buffLen, "%"FMT64"d", num); ToBufferUpdate(clientData, len); } /* *----------------------------------------------------------------------------- * * ToBufferIdType -- * * Convert the ID, name and type to a string. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void ToBufferIdType(ClientData *clientData, // IN/OUT const char *idName, // IN DMKeyType fieldId, // IN const char *type) // IN { uint32 len; if (clientData->result != DMERR_SUCCESS) { /* an error occurred already, so stop. */ return; } ASSERT(clientData->buffLen > 0); len = snprintf(clientData->buffer, clientData->buffLen, "--> FIELD_%s(%d, %s): [", idName, fieldId, type); ToBufferUpdate(clientData, len); } /* *----------------------------------------------------------------------------- * * ToBufferEndLine -- * * Print to end the current line * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void ToBufferEndLine(ClientData *clientData) // IN/OUT { ToBufferString(clientData, "]\n"); } /* *----------------------------------------------------------------------------- * * IsPrintable -- * * Check is a string is printable or not. * - 'len': if printable, *len is the printable length, '\0' is excluded. * * Result: * TRUE if yes, FALSE otherwise * * Side-effects: * None * *----------------------------------------------------------------------------- */ static Bool IsPrintable(const char *str, // IN int32 strLen, // IN int32 *len) // OUT { Bool printable = TRUE; int32 cc; for (cc = 0; cc < strLen; cc ++) { /* isprint crashes with negative value in windows debug mode */ if ((!CType_IsPrint(str[cc])) && (!CType_IsSpace(str[cc]))) { printable = FALSE; break; } } if (printable) { *len = strLen; } else { /* if only the last char is not printable and is '\0', * make it printable */ if ((cc == strLen - 1) && (str[cc] == '\0')) { printable = TRUE; *len = strLen - 1; } } return printable; } /* *----------------------------------------------------------------------------- * * ToBufferHexString -- * * Print a string into a buffer, the string may be in binary format. * - 'strLen': is the length of str. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void ToBufferHexString(ClientData *clientData, // IN/OUT const char *str, // IN uint32 strLen) // IN { Bool printable; int32 len; /* the number of printable chars */ int32 maxLen = clientData->maxStrLen; /* -1 means no limit */ if (clientData->result != DMERR_SUCCESS) { /* an error occurred already, so stop. */ return; } ASSERT(clientData->buffLen > 0); maxLen = GetLimit(maxLen, strLen); printable = IsPrintable(str, maxLen, &len); if (printable) { ToBufferString(clientData, "\""); ToBufferStringN(clientData, str, len); if (maxLen < strLen) { ToBufferString(clientData, "..."); /* to indicate partial print */ } ToBufferString(clientData, "\""); } else { int i; /* print the string in hex */ ToBufferString(clientData, "("); for (i = 0; i < maxLen; i++) { char hexStr[3]; if (i) { ToBufferString(clientData, ","); /* separator */ } snprintf(hexStr, sizeof(hexStr), "%02x", (unsigned char)(str[i])); ToBufferString(clientData, hexStr); if (clientData->result != DMERR_SUCCESS) { break; } } if (maxLen < strLen) { /* "..." to indicate partial print*/ ToBufferString(clientData, ",..."); } ToBufferString(clientData, ")"); } } /* *----------------------------------------------------------------------------- * * HashMapToStringEntryCb -- * * Convert to an entry to a string. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void HashMapToStringEntryCb(void *key, // IN void *data, // IN void *userData) // IN/OUT { DataMapEntry *entry = *((DataMapEntry **)data); ClientData *clientData = (ClientData *)userData; DMKeyType fieldId = *((DMKeyType *)key); const char *idName = NULL; /* field ID name */ if (clientData->result != DMERR_SUCCESS) { /* A previous error has occurred, so stop. */ return; } if (clientData->fieldIdList!= NULL) { int32 cc; for (cc = 0; cc < clientData->fieldIdListLen; cc ++) { if (fieldId == clientData->fieldIdList[cc].fieldId) { idName = clientData->fieldIdList[cc].fieldName; break; } } } if (idName == NULL) { idName = ""; } switch(entry->type) { case DMFIELDTYPE_INT64: { ToBufferIdType(clientData, idName, fieldId, "int64"); ToBufferInt64(clientData, entry->value.number.val); ToBufferEndLine(clientData); break; } case DMFIELDTYPE_STRING: { ToBufferIdType(clientData, idName, fieldId, "string"); ToBufferHexString(clientData, entry->value.string.str, entry->value.string.length); ToBufferEndLine(clientData); break; } case DMFIELDTYPE_INT64LIST: { int32 cc; int32 max = GetLimit(clientData->maxNumElems, entry->value.numList.length); ToBufferIdType(clientData, idName, fieldId, "int64List"); for (cc = 0; cc < max; cc++) { if (cc != 0) { ToBufferString(clientData, ","); /* add a separator */ } ToBufferInt64(clientData, entry->value.numList.numbers[cc]); } if (max < entry->value.numList.length) { /* to indicate partial print*/ ToBufferString(clientData, ",..."); } ToBufferEndLine(clientData); break; } case DMFIELDTYPE_STRINGLIST: { char **strPtr = entry->value.strList.strings; int32 *lenPtr = entry->value.strList.lengths; int32 cc = 0; int32 max = clientData->maxNumElems; ToBufferIdType(clientData, idName, fieldId, "stringList"); for (; *strPtr != NULL; strPtr++, lenPtr++, cc++) { if ((max >= 0) && (cc >= max)) { break; } if (cc > 0) { ToBufferString(clientData, ","); /* add a separator */ } ToBufferHexString(clientData, *strPtr, *lenPtr); if (clientData->result != DMERR_SUCCESS) { return; } } if (*strPtr != NULL) { /* to indicate partial print*/ ToBufferString(clientData, ",..."); } ToBufferEndLine(clientData); break; } default: { clientData->result = DMERR_UNKNOWN_TYPE; return; } } } /* *----------------------------------------------------------------------------- * * HashMapCalcEntrySizeCb -- * * - calculate how much space is needed to encode an entry * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void HashMapCalcEntrySizeCb(void *key, // IN void *data, // IN void *userData) // IN/OUT { DataMapEntry *entry = *((DataMapEntry **)data); ClientData *clientData = (ClientData *)userData; uint32 oldLen = clientData->buffLen; uint32 *buffLen = &(clientData->buffLen); if (clientData->result != DMERR_SUCCESS) { /* a previous error has occurred, so stop. */ return; } switch(entry->type) { case DMFIELDTYPE_INT64: { *buffLen += sizeof(int32); /* type */ *buffLen += sizeof(DMKeyType); /* fieldId */ *buffLen += sizeof(int64); /* int value */ break; } case DMFIELDTYPE_STRING: { *buffLen += sizeof(int32); /* type */ *buffLen += sizeof(DMKeyType); /* fieldId */ *buffLen += sizeof(int32); /* string length */ *buffLen += entry->value.string.length; /* string payload */ break; } case DMFIELDTYPE_INT64LIST: { *buffLen += sizeof(int32); /* type */ *buffLen += sizeof(DMKeyType); /* fieldId */ *buffLen += sizeof(int32); /* list size */ *buffLen += sizeof(int64) * entry->value.numList.length; break; } case DMFIELDTYPE_STRINGLIST: { char **strPtr = entry->value.strList.strings; int32 *lenPtr = entry->value.strList.lengths; *buffLen += sizeof(int32); /* type */ *buffLen += sizeof(DMKeyType); /* fieldId */ *buffLen += sizeof(int32); /* list size */ for (; *strPtr != NULL; strPtr++, lenPtr++) { if (*buffLen < oldLen) { clientData->result = DMERR_INTEGER_OVERFLOW; return; } *buffLen += sizeof(int32); /* string length */ *buffLen += *lenPtr; /* string payload */ } break; } default: { clientData->result = DMERR_UNKNOWN_TYPE; return; } } if (*buffLen < oldLen) { clientData->result = DMERR_INTEGER_OVERFLOW; return; } } /* *----------------------------------------------------------------------------- * * HashMapSerializeEntryCb -- * * - serialize each entry into a byte buffer * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void HashMapSerializeEntryCb(void *key, // IN void *data, // IN void *userData) // OUT { DataMapEntry *entry = *((DataMapEntry **)data); ClientData *clientData = (ClientData *)userData; char **buffPtr = &(clientData->buffer); char *buffPtrOrig = clientData->buffer; EncodeInt32(buffPtr, entry->type); /* encode type */ EncodeInt32(buffPtr, *((DMKeyType *)key)); /* encode field id*/ switch(entry->type) { case DMFIELDTYPE_INT64: EncodeInt64(buffPtr, entry->value.number.val); break; case DMFIELDTYPE_STRING: EncodeString(buffPtr, entry->value.string.str, entry->value.string.length); break; case DMFIELDTYPE_INT64LIST: EncodeInt64List(buffPtr, entry->value.numList.numbers, entry->value.numList.length); break; case DMFIELDTYPE_STRINGLIST: { char **strPtr = entry->value.strList.strings; int32 *lenPtr = entry->value.strList.lengths; int32 listSize = 0; char *listSizePtr = *buffPtr; /*reserve the space for list size, we will update later*/ *buffPtr += sizeof(int32); for (; *strPtr != NULL; strPtr++, lenPtr++) { EncodeString(buffPtr, *strPtr, *lenPtr); listSize ++; } EncodeInt32(&listSizePtr, listSize); /* now update the list size */ break; } default: ASSERT(0); /* we do not expect this to happen */ } /* Update left buffer size so we can do a sanity check at the end */ clientData->buffLen -= (clientData->buffer - buffPtrOrig); } /* *----------------------------------------------------------------------------- * * DecodeStringList -- * * Decode a string list entry and add to the dataMap * - 'buf': *buf points to the input buffer. *buf is advanced accordingly * on success. * - 'left': indicates number of bytes left in the input buffer, *left is * updated accordingly on success. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode DecodeStringList(char **buf, // IN int32 *left, // IN DMKeyType fieldId, // IN DataMap *that) // OUT { ErrorCode res; int32 listSize; char **strList; int32 *strLens; int32 i; res = DecodeInt32(buf, left, &listSize); if (res != DMERR_SUCCESS) { return res; } if (listSize < 0 || listSize > *left / sizeof(int32)) { /* listSize can be zero to support an empty list */ return DMERR_BAD_DATA; } strList = (char **)calloc(listSize + 1, sizeof(char *)); if (strList == NULL) { return DMERR_INSUFFICIENT_MEM; } if (listSize) { strLens = (int32 *)malloc(sizeof(int32) * listSize); if (strLens == NULL) { FreeStringList(strList, strLens); return DMERR_INSUFFICIENT_MEM; } } else { strLens = NULL; } for (i = 0; i < listSize; i++) { res = DecodeString(buf, left, &strList[i], &strLens[i]); if (res != DMERR_SUCCESS) { break; } } if (res == DMERR_SUCCESS) { res = AddEntry_StringList(that, fieldId, strList, strLens); } if (res != DMERR_SUCCESS) { FreeStringList(strList, strLens); } return res; } /* *----------------------------------------------------------------------------- * * CopyStringList -- * * - copy string list entry into another map * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static ErrorCode CopyStringListEntry(DMKeyType fieldId, // IN const DataMapEntry *entry, // IN DataMap *dst) // OUT { char **oldList = entry->value.strList.strings; int32 *lenPtr = entry->value.strList.lengths; char **newList; int32 *newLens; int32 listSize = 0; char **ptr = oldList; ErrorCode res = DMERR_SUCCESS; int32 i; /* get the list Size */ for (; *ptr != NULL; ptr++) { listSize ++; } newList = (char **)calloc(listSize + 1, sizeof(char *)); newLens = (int32 *)malloc(sizeof(int32) * listSize); if (newList == NULL || newLens == NULL) { FreeStringList(newList, newLens); return DMERR_INSUFFICIENT_MEM; } /* copy the length vector */ memcpy(newLens, lenPtr, listSize * sizeof(int32)); /* copy string one by one */ for (i = 0; i < listSize; i++) { newList[i] = (char *)malloc(newLens[i]); if (newList[i] == NULL) { res = DMERR_INSUFFICIENT_MEM; break; } memcpy(newList[i], oldList[i], newLens[i]); } if (res == DMERR_SUCCESS) { res = AddEntry_StringList(dst, fieldId, newList, newLens); } if (res != DMERR_SUCCESS) { FreeStringList(newList, newLens); } return res; } /* *----------------------------------------------------------------------------- * * HashMapCopyEntryCb -- * * - Call back function to copy a dataMap entry. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void HashMapCopyEntryCb(void *key, // IN void *data, // IN void *userData) // IN/OUT { DMKeyType fieldId = *((DMKeyType *)key); DataMapEntry *entry = *((DataMapEntry **)data); ClientData *clientData = (ClientData *)userData; DataMap *dst = clientData->map; ErrorCode res = DMERR_SUCCESS; if (clientData->result != DMERR_SUCCESS) { /* previous calls have encountered error, so stop */ return; } switch(entry->type) { case DMFIELDTYPE_INT64: res = AddEntry_Int64(dst, fieldId, entry->value.number.val); break; case DMFIELDTYPE_STRING: { char *str = (char *)malloc(entry->value.string.length); if (str == NULL) { res = DMERR_INSUFFICIENT_MEM; break; } memcpy(str, entry->value.string.str, entry->value.string.length); res = AddEntry_String(dst, fieldId, str, entry->value.string.length); if (res != DMERR_SUCCESS) { free(str); } break; } case DMFIELDTYPE_INT64LIST: { int64 *numList; numList = (int64 *)malloc(sizeof(int64) * (entry->value.numList.length)); if (numList == NULL) { res = DMERR_INSUFFICIENT_MEM; } else { res = AddEntry_Int64List(dst, fieldId, numList, entry->value.numList.length); if (res != DMERR_SUCCESS) { free(numList); } } break; } case DMFIELDTYPE_STRINGLIST: res = CopyStringListEntry(fieldId, entry, dst); break; default: ASSERT(0); /* we do not expect this to happen */ break; } clientData->result = res; } /* *----------------------------------------------------------------------------- * * HashMapFreeEntryCb -- * * - call back function is called to free all entries in the hashMap. * * Result: * None * * Side-effects: * None * *----------------------------------------------------------------------------- */ static void HashMapFreeEntryCb(void *key, void *data, void *userData) { DataMapEntry *entry = *((DataMapEntry **)data); FreeEntry(entry); } /* *----------------------------------------------------------------------------- * * DataMap_Destroy -- * * Destroy the DataMap object pointed by that. Frees all the internal * pointers in the object. However the memory pointed by that is not * freed. * * Result: * 0 on success. * error code on failures. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_Destroy(DataMap *that) // IN/OUT { if (that == NULL) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); HashMap_Iterate(that->map, HashMapFreeEntryCb, TRUE, NULL); HashMap_DestroyMap(that->map); that->map = NULL; that->cookie = 0; return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * DataMap_Copy -- * * Copy a DataMap, a deep copy. * - 'dst': dst should *NOT* be initialized via DataMap_Create. * the caller *MUST* call DataMap_Destroy to detroy dst upon success. * * Result: * 0 on success. * error code on failures. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_Copy(const DataMap *src, // IN DataMap *dst) // OUT { ClientData clientData; ErrorCode res; ASSERT(src->map != NULL); ASSERT(src->cookie == magic_cookie); if (src == NULL || dst == NULL) { return DMERR_INVALID_ARGS; } /* init dst map */ res = DataMap_Create(dst); if (res != DMERR_SUCCESS) { return res; } clientData.map = dst; clientData.result = DMERR_SUCCESS; HashMap_Iterate(src->map, HashMapCopyEntryCb, FALSE, &clientData); if (clientData.result != DMERR_SUCCESS) { DataMap_Destroy(dst); } return clientData.result; } /* *----------------------------------------------------------------------------- * * DataMap_Serialize -- * * Serialize a DataMap to a buffer. * - 'buf': on success, this points to the allocated serialize buffer. * The caller *MUST* free this buffer to avoid memory leak. * - 'bufLen': on success, this indicates the length of the allocated * buffer. * * Result: * 0 on success * error code on failures. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_Serialize(const DataMap *that, // IN char **buf, // OUT uint32 *bufLen) // OUT { ClientData clientData; if (that == NULL || buf == NULL || bufLen == NULL) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); /* get the buffer size first */ memset(&clientData, 0, sizeof clientData); HashMap_Iterate(that->map, HashMapCalcEntrySizeCb, FALSE, &clientData); if (clientData.result != DMERR_SUCCESS) { return clientData.result; } /* 4 bytes is payload length */ *bufLen = clientData.buffLen + sizeof(uint32); if (*bufLen < clientData.buffLen) { return DMERR_INTEGER_OVERFLOW; } *buf = (char *)malloc(*bufLen); if (*buf == NULL) { return DMERR_INSUFFICIENT_MEM; } /* now serialize the map into the buffer */ clientData.map = (DataMap *)that; clientData.result = DMERR_SUCCESS; clientData.buffer = *buf; /* Encode the payload size */ EncodeInt32(&(clientData.buffer), clientData.buffLen); HashMap_Iterate(that->map, HashMapSerializeEntryCb, FALSE, &clientData); /* sanity check, make sure the buffer size is just used up*/ ASSERT(clientData.buffLen == 0); if (clientData.result != DMERR_SUCCESS) { free(*buf); *buf = NULL; *bufLen = 0; } return clientData.result; } /* *----------------------------------------------------------------------------- * * DataMap_Deserialize -- * * Initialize an empty DataMap from a buffer. * - 'that': the given map should *NOT* be initialized by the caller. * On success, the caller needs to call DataMap_Destropy on 'that' to * avoid any memory leak. * * Result: * - 0 on success * - error code on failures. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_Deserialize(const char *bufIn , // IN const int32 bufLen, // IN DataMap *that) // OUT { ErrorCode res; int32 left = bufLen; /* number of bytes undecoded */ int32 len; char *buf = (char *)bufIn; if (that == NULL || bufIn == NULL || bufLen < 0) { return DMERR_INVALID_ARGS; } /* decode the encoded buffer length */ res = DecodeInt32(&buf, &left, &len); if (res != DMERR_SUCCESS) { return res; } if (len > bufLen - sizeof(int32)) { return DMERR_TRUNCATED_DATA; } left = len; return DataMap_DeserializeContent(buf, left, that); } /* *----------------------------------------------------------------------------- * * DataMap_DeserializeContent -- * * Initialize an empty DataMap from the content of the data map buffer * - 'that': the given map should *NOT* be initialized by the caller. * On success, the caller needs to call DataMap_Destropy on 'that' to * avoid any memory leak. * * Result: * - 0 on success * - error code on failures. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_DeserializeContent(const char *content, // IN const int32 contentLen, // IN DataMap *that) // OUT { ErrorCode res; int32 left = contentLen; /* number of bytes undecoded */ char *buf = (char *)content; res = DataMap_Create(that); /* init the map */ if (res != DMERR_SUCCESS) { return res; } while ((left> 0) && (res == DMERR_SUCCESS)) { DMFieldType type; DMKeyType fieldId; int32 val; res = DecodeInt32(&buf, &left, &val); /* decode entry type */ if (res != DMERR_SUCCESS) { goto out; } if (val >= DMFIELDTYPE_MAX) { res = DMERR_UNKNOWN_TYPE; goto out; } type = (DMFieldType)val; res = DecodeInt32(&buf, &left, &fieldId); /* decode filedID */ if (res != DMERR_SUCCESS) { goto out; } if (LookupEntry(that, fieldId) != NULL) { res = DMERR_DUPLICATED_FIELD_IDS; goto out; } /* decode individual entry */ switch(type) { case DMFIELDTYPE_INT64: { int64 val; res = DecodeInt64(&buf, &left, &val); if (res != DMERR_SUCCESS) { goto out; } res = AddEntry_Int64(that, fieldId, val); break; } case DMFIELDTYPE_STRING: { char *str; int32 strLen; res = DecodeString(&buf, &left, &str, &strLen); if (res != DMERR_SUCCESS) { goto out; } res = AddEntry_String(that, fieldId, str, strLen); if (res != DMERR_SUCCESS) { /* clean up memory */ free(str); } break; } case DMFIELDTYPE_INT64LIST: { res = DecodeInt64List(&buf, &left, fieldId, that); break; } case DMFIELDTYPE_STRINGLIST: { res = DecodeStringList(&buf, &left, fieldId, that); break; } default: res = DMERR_UNKNOWN_TYPE; break; } } if (res != DMERR_SUCCESS) { goto out; } return DMERR_SUCCESS; out: DataMap_Destroy(that); return res; } /* *----------------------------------------------------------------------------- * * DataMap_SetInt64 -- * * Set an integer value to the map by given field id. * - 'replace': when an entry with the same fieldID exists, if replace is * true, error will be returned, otherwise, the existing entry will be * replaced. * * Result: * 0 on success * Otherwise, corresponding error code is returned. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_SetInt64(DataMap *that, // IN/OUT DMKeyType fieldId, // IN int64 value, // IN Bool replace) // IN { DataMapEntry *entry; if (that == NULL) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { /* need to add a new entry */ return AddEntry_Int64(that, fieldId, value); } else if (!replace){ return DMERR_ALREADY_EXIST; } else { if ((entry->type != DMFIELDTYPE_INT64)) { FreeEntryPayload(entry); entry->type = DMFIELDTYPE_INT64; } /* simple update */ entry->value.number.val = value; return DMERR_SUCCESS; } } /* *----------------------------------------------------------------------------- * * DataMap_SetString -- * * Set a string field to a map. * - 'str': the ownership of buffer pointed by str is passed to the map * on success. * - 'strLen': length of str, -1 means str is null terminated. * - 'replace': when an entry with the same fieldID exists, if replace is * true, error will be returned, otherwise, the existing entry will be * replaced. * * Result: * 0 on success * error code otherwise. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_SetString(DataMap *that, // IN/OUT DMKeyType fieldId, // IN char *str, // IN int32 strLen, // IN Bool replace) // IN { DataMapEntry *entry; if (that == NULL || str == NULL || (strLen < 0 && strLen != -1)) { return DMERR_INVALID_ARGS; } if (strLen == -1) { strLen = strlen(str); } ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { return AddEntry_String(that, fieldId, str, strLen); } else if (!replace){ return DMERR_ALREADY_EXIST; } else { FreeEntryPayload(entry); entry->type = DMFIELDTYPE_STRING; entry->value.string.str = str; entry->value.string.length = strLen; return DMERR_SUCCESS; } } /* *----------------------------------------------------------------------------- * * DataMap_SetInt64List -- * * Set an integer value array to the map by given field id. * - 'numList': the ownership of this list will be passed to the map on * success, no copy of the list numbers is made. * - 'replace': when an entry with the same fieldID exists, if replace is * true, error will be returned, otherwise, the existing entry will be * replaced. * * Result: * 0 on success * Otherwise, corresponding error code is returned. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_SetInt64List(DataMap *that, // IN/OUT DMKeyType fieldId, // IN int64 *numList, // IN int32 listLen, // IN Bool replace) // IN { DataMapEntry *entry; if (that == NULL || numList == NULL || listLen < 0) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { /* need to add a new entry */ return AddEntry_Int64List(that, fieldId, numList, listLen); } else if (!replace){ return DMERR_ALREADY_EXIST; } else { FreeEntryPayload(entry); entry->type = DMFIELDTYPE_INT64LIST; entry->value.numList.numbers = numList; entry->value.numList.length = listLen; return DMERR_SUCCESS; } } /* *----------------------------------------------------------------------------- * * DataMap_SetStringList -- * * Set a string list field to a map. * - 'strList': this pointer points to an array of string pointers. * Upon success, the ownership of this array is passed to the * map, no copy of strings is made. The last element in this array * pointer must be NULL. * - 'strLens': this is an array of integers which indicating the length of * cooresponding string in strList. the ownership is passed to the map * as well on success. * - 'replace': when an entry with the same fieldID exists, if replace is * true, error will be returned, otherwise, the existing entry will be * replaced. * * Result: * 0 on success * error code otherwise. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_SetStringList(DataMap *that, // IN/OUT DMKeyType fieldId, // IN char **strList, // IN int32 *strLens, // IN Bool replace) // IN { DataMapEntry *entry; if (that == NULL || strList == NULL || strLens == NULL) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { /* need to add a new entry */ return AddEntry_StringList(that, fieldId, strList, strLens); } else if (!replace){ return DMERR_ALREADY_EXIST; } else { FreeEntryPayload(entry); entry->type = DMFIELDTYPE_STRINGLIST; entry->value.strList.strings = strList; entry->value.strList.lengths = strLens; return DMERR_SUCCESS; } } /* *----------------------------------------------------------------------------- * * DataMap_GetInt64 -- * * - Get an integer value from the map by given field id. * * Result: * - DMERR_SUCCESS: *value has the value. * - DMERR_NOT_FOUND: no data is found * - DMERR_TYPE_MISMATCH: the entry in the map has other type. * - Otherwise, corresponding error code is returned. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_GetInt64(const DataMap *that, // IN DMKeyType fieldId, // IN int64 *value) // OUT { DataMapEntry *entry; if (that == NULL || value == NULL) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { return DMERR_NOT_FOUND; } if (entry->type != DMFIELDTYPE_INT64) { return DMERR_TYPE_MISMATCH; } *value = entry->value.number.val; return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * DataMap_GetString -- * * Get a string value from the map by given fieldId. * - 'str': upon success, *str is a string pointer which points to internal * map structures, and should not be modified. * - 'strLen': upon success, *strLen indicates the length of str. * * Result: * - DMERR_SUCCESS: *str points to the string field in the map, *strLen has * the string length. * - DMERR_NOT_FOUND: no data is found * - DMERR_TYPE_MISMATCH: the entry in the map has other type. * - Otherwise, corresponding error code is returned. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_GetString(const DataMap *that, // IN DMKeyType fieldId, // IN char **str, // OUT int32 *strLen) // OUT { DataMapEntry *entry; if (that == NULL || str == NULL || strLen == NULL) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { return DMERR_NOT_FOUND; } if (entry->type != DMFIELDTYPE_STRING) { return DMERR_TYPE_MISMATCH; } *str = entry->value.string.str; *strLen = entry->value.string.length; return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * DataMap_GetInt64List -- * * Get an integer value list from the map by given field id. * - 'numList': on success, *numList points data structures in the map, * and should not be modified. *numList is an array of int64. * - 'listLen': on success, *listLen indicates number of elements in * numList. * * Result: * - DMERR_SUCCESS: *numbers points to the list of numbers in the map, * *listLen has the list length. * - DMERR_NOT_FOUND: no data is found * - DMERR_TYPE_MISMATCH: the entry in the map has other type. * - Otherwise, corresponding error code is returned. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_GetInt64List(const DataMap *that, // IN DMKeyType fieldId, // IN int64 **numList, // OUT int32 *listLen) // OUT { DataMapEntry *entry; if (that == NULL || numList == NULL || listLen == NULL) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { return DMERR_NOT_FOUND; } if (entry->type != DMFIELDTYPE_INT64LIST) { return DMERR_TYPE_MISMATCH; } *numList = entry->value.numList.numbers; *listLen = entry->value.numList.length; return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * DataMap_GetStringList -- * * Get a string list from the map by given fieldId. * - 'strList': on success, *strList points to an array of strings which * is owned by the map, and should not be modified. * The last element in the array is NULL. * - 'strLen': on success, *strLen is an array of numbers indicates the * length of corresponding string in strList. * This should not be modified either. * * Result: * - DMERR_SUCCESS: *strList points to the list of strings in the map, * *strLens has the length for each string. * - DMERR_NOT_FOUND: no data is found * - DMERR_TYPE_MISMATCH: the entry in the map has other type. * - Otherwise, corresponding error code is returned. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_GetStringList(const DataMap *that, // IN DMKeyType fieldId, // IN char ***strList, // OUT int32 **strLens) // OUT { DataMapEntry *entry; if (that == NULL || strList == NULL || strLens == NULL) { return DMERR_INVALID_ARGS; } ASSERT(that->cookie == magic_cookie); entry = LookupEntry(that, fieldId); if (entry == NULL) { return DMERR_NOT_FOUND; } if (entry->type != DMFIELDTYPE_STRINGLIST) { return DMERR_TYPE_MISMATCH; } *strList = entry->value.strList.strings; *strLens = entry->value.strList.lengths; return DMERR_SUCCESS; } /* *----------------------------------------------------------------------------- * * DataMap_ToString -- * * Dump the content of the whole map into a user supplied buffer. * - 'fieldIdList': this is an array of FieldIdNameEntry. * - 'fieldIdListLen': the size of of feildIdList array. * - 'maxNumElements': for list elements, this is the max number of * elemenents we print. -1 means no limit. * - 'maxStrLen': max number of bytes to print for a string, -1 no limit. * - 'buf': *buf is a null terminated output string buffer, the caller * *MUST* free this buffer later to avoid memory leak. * * Result: * DMERR_SUCCESS on success. * error code on failures. * * Side-effects: * None * *----------------------------------------------------------------------------- */ ErrorCode DataMap_ToString(const DataMap *that, // IN FieldIdNameEntry *fieldIdList, // IN int32 fieldIdListLen, // IN int32 maxNumElements, // IN int32 maxStrLen, // IN char **buf) // OUT { ClientData clientData; char *buffPtr; const char *truncStr = " DATA TRUNCATED!!!\n"; /* This API is for debugging only, so we use hard coded buffer size */ const int32 maxBuffSize = 10 * 1024; if (that == NULL || buf == NULL || (maxNumElements < 0 && maxNumElements != -1) || (maxStrLen < 0 && maxStrLen != -1)) { return DMERR_INVALID_ARGS; } *buf = NULL; ASSERT(that->cookie == magic_cookie); /* get the buffer size first */ memset(&clientData, 0, sizeof clientData); clientData.map = (DataMap *)that; clientData.fieldIdList = fieldIdList; clientData.fieldIdListLen = fieldIdListLen; clientData.maxNumElems = maxNumElements; clientData.maxStrLen = maxStrLen; clientData.buffLen = maxBuffSize; buffPtr = (char *)malloc(maxBuffSize); if (buffPtr == NULL) { return DMERR_INSUFFICIENT_MEM; } *buf = buffPtr; clientData.buffer = buffPtr; ToBufferString(&clientData, "--> Begin\n"); /* output each entry in the map */ HashMap_Iterate(that->map, HashMapToStringEntryCb, FALSE, &clientData); ToBufferString(&clientData, "--> End.\n"); /* sanity check, make sure the buffer is not overflown. */ ASSERT(clientData.buffLen >= 0); ASSERT(buffPtr + maxBuffSize >= clientData.buffer); if (clientData.result == DMERR_BUFFER_TOO_SMALL) { ASSERT(maxBuffSize > strlen(truncStr)); Str_Strcpy(buffPtr + maxBuffSize - strlen(truncStr) - 1, truncStr, strlen(truncStr) + 1); return DMERR_SUCCESS; } else if (clientData.result != DMERR_SUCCESS) { *buf = NULL; free(buffPtr); return clientData.result; } else { clientData.buffer[0] = '\0'; return DMERR_SUCCESS; } } open-vm-tools-stable-10.2.0/open-vm-tools/lib/dict/000077500000000000000000000000001321503522500217675ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/dict/Makefile.am000066400000000000000000000017231321503522500240260ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libDict.la libDict_la_SOURCES = libDict_la_SOURCES += dictll.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/dict/dictll.c000066400000000000000000000367221321503522500234200ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * dictll.c -- * * Low-level dictionary format --hpreg */ #include #include #include #include #include "vmware.h" #include "vmstdio.h" #include "escape.h" #include "dictll.h" #include "util.h" #define UTF8_BOM "\xEF\xBB\xBF" /* Duplicate a buffer --hpreg. The result is NUL-terminated */ static void * BufDup(void const * const bufIn, // IN: buffer to duplicate unsigned int const sizeIn) // IN: buffer size in bytes { char *bufOut; ASSERT(bufIn); bufOut = Util_SafeMalloc(sizeIn + 1); memcpy(bufOut, bufIn, sizeIn); bufOut[sizeIn] = '\0'; return bufOut; } /* *----------------------------------------------------------------------------- * * Walk -- * * While 'bufIn' points to a byte in 'sentinel', increment it --hpreg * * Note: * If your 'bufIn' is a NUL-terminated C string, you should rather make sure * that the NUL byte is not in your 'sentinel' * * Results: * The new 'buf' * * Side effects: * None * *----------------------------------------------------------------------------- */ static void const * Walk(void const * const bufIn, // IN int const * const sentinel) // IN { char const *buf; buf = (char const *)bufIn; ASSERT(buf); /* Unsigned does matter --hpreg */ while (sentinel[(unsigned char)*buf]) { buf++; } return buf; } /* * XXX Document the escaping/unescaping process: rationale for which chars we * escape, and how we escape --hpreg * * The dictionary line format: * * = * or * = " " * or * = (Implied value of empty string) * or * * * where * does not contain any whitespace or = or # * does not contain any double-quote or # * does not contain any double-quote * begins with # and ends at the end of the line * is a sequence spaces and/or tabs * and are optional */ /* *----------------------------------------------------------------------------- * * DictLL_UnmarshalLine -- * * Reads a line from the bufSize-byte buffer buf, which holds one or more * new-line delimited lines. The buffer is not necessarily * NUL-terminated. * * Results: * The beginning of the next line if a line was successfully parsed. In * that case, '*line' is the allocated line. If the line is well-formed, * then '*name' and '*value' are allocated strings. Otherwise they are * both NULL. * * A null pointer at the end of the buffer, in which case *line, *name, * and *value are set to null pointers. * * Side effects: * Advances *buf to the beginning of the next line. * *----------------------------------------------------------------------------- */ const char * DictLL_UnmarshalLine(const char *buf, // IN: buffer to parse size_t bufSize, // IN: buffer size in bytes char **line, // OUT: malloc()'d entire line char **name, // OUT: malloc()'d name or NULL char **value) // OUT: malloc()'d value or NULL { /* Space and tab --hpreg */ static int const ws_in[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* Everything but NUL, space, tab and pound --hpreg */ static int const wsp_out[] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; /* Everything but NUL, space, tab, pound and equal --hpreg */ static int const wspe_out[] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; /* Everything but NUL and double quote --hpreg */ static int const q_out[] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; char const *nBegin; char const *nEnd; char const *vBegin; char const *vEnd; char const *tmp; char *myLine; char *myName; char *myValue; const char *lineEnd; const char *nextLine; ASSERT(buf); ASSERT(line); ASSERT(name); ASSERT(value); /* Check for end of buffer. */ if (bufSize == 0) { *line = NULL; *name = NULL; *value = NULL; return NULL; } /* Find end of this line, beginning of next. */ lineEnd = memchr(buf, '\n', bufSize); if (lineEnd != NULL) { nextLine = lineEnd + 1; } else { nextLine = lineEnd = buf + bufSize; } /* Make local copy of line. */ myLine = BufDup(buf, lineEnd - buf); /* Check if the line is well-formed --hpreg */ nBegin = Walk(myLine, ws_in); nEnd = Walk(nBegin, wspe_out); tmp = Walk(nEnd, ws_in); if (nBegin == nEnd || *tmp != '=') { goto weird; } tmp++; tmp = Walk(tmp, ws_in); if (*tmp == '"') { tmp++; vBegin = tmp; vEnd = Walk(vBegin, q_out); tmp = vEnd; if (*tmp != '"') { goto weird; } tmp++; } else { vBegin = tmp; vEnd = Walk(vBegin, wsp_out); tmp = vEnd; } tmp = Walk(tmp, ws_in); if (*tmp != '\0' && *tmp != '#') { goto weird; } /* The line is well-formed. Extract the name and value --hpreg */ myName = BufDup(nBegin, nEnd - nBegin); myValue = Escape_Undo('|', vBegin, vEnd - vBegin, NULL); VERIFY(myValue); *line = myLine; *name = myName; *value = myValue; return nextLine; weird: /* The line is not well-formed. Let the upper layers handle it --hpreg */ *line = myLine; *name = NULL; *value = NULL; return nextLine; } /* *----------------------------------------------------------------------------- * * DictLL_ReadLine -- * * Read the next line from a dictionary file --hpreg * * Results: * 2 on success: '*line' is the allocated line * If the line is well-formed, then '*name' and '*value' are * allocated strings. Otherwise they are both NULL. * 1 if there is no next line (end of stream) * 0 on failure: errno is set accordingly * * Side effects: * None * *----------------------------------------------------------------------------- */ int DictLL_ReadLine(FILE *stream, // IN: stream to read char **line, // OUT: malloc()'d line or null pointer char **name, // OUT: malloc()'d name or null pointer char **value) // OUT: malloc()'d value or null pointer { char *myLine; size_t myLineLen; ASSERT(stream); ASSERT(line); ASSERT(name); ASSERT(value); *line = NULL; *name = NULL; *value = NULL; switch (StdIO_ReadNextLine(stream, &myLine, 0, &myLineLen)) { case StdIO_Error: return 0; case StdIO_EOF: return 1; case StdIO_Success: if (DictLL_UnmarshalLine(myLine, myLineLen, line, name, value) == NULL) { *line = BufDup("", 0); } free(myLine); return 2; default: NOT_IMPLEMENTED(); } NOT_REACHED(); } /* *----------------------------------------------------------------------------- * * DictLL_MarshalLine -- * * Marshals a line, appending the data to a DynBuf. If 'name' is NULL, * '*value' contains the whole line to write verbatim. Otherwise a proper * name/value pair is written. * * Results: * TRUE on success, FALSE on failure (caused by memory allocation failure). * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool DictLL_MarshalLine(DynBuf *output, // IN/OUT: output buffer char const *name, // IN/OPT: name to marshal char const *value) // IN: value to marshal { size_t size; if (name) { /* * Double quote, pipe, 0x7F, and all control characters but * tab --hpreg * 0x80 to 0xff are unescaped so characters in encodings * like UTF-8 will be displayed normally. */ static int const toEscape[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; char *evalue; /* Write a well-formed line --hpreg */ evalue = Escape_Do('|', toEscape, value, (uint32)strlen(value), &size); if ( !DynBuf_Append(output, name, (uint32)strlen(name)) || !DynBuf_Append(output, " = \"", 4) || (size && !DynBuf_Append(output, evalue, size)) || !DynBuf_Append(output, "\"", 1)) { free(evalue); return FALSE; } free(evalue); } else { /* Write the line as passed from the upper layers --hpreg */ size = (uint32)strlen(value); if (size && !DynBuf_Append(output, value, size)) { return FALSE; } } /* * Win32 takes care of adding the \r (XXX this assumes that the stream * is opened in ascii mode) --hpreg */ if (!DynBuf_Append(output, "\n", 1)) { return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * DictLL_WriteLine -- * * Marshals a line, writing the data to a file. If 'name' is NULL, '*value' * contains the whole line to write verbatim. Otherwise a proper name/value * pair is written. * * Results: * TRUE on success * FALSE on failure: errno is set accordingly * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool DictLL_WriteLine(FILE *stream, // IN: stream to write char const *name, // IN: name to write char const *value) // IN: value to write { DynBuf buf; DynBuf_Init(&buf); if (!DictLL_MarshalLine(&buf, name, value)) { DynBuf_Destroy(&buf); errno = ENOMEM; return FALSE; } if (fwrite(DynBuf_Get(&buf), DynBuf_GetSize(&buf), 1, stream) != 1) { DynBuf_Destroy(&buf); return FALSE; } DynBuf_Destroy(&buf); return TRUE; } /* *----------------------------------------------------------------------------- * * DictLL_ReadUTF8BOM -- * * Reads a UTF-8 BOM from a file. * * Results: * If successful, returns TRUE and updates the file position. * Returns FALSE if a UTF-8 BOM was not found. * * Side effects: * Might clears the error indicator of the file stream. * *----------------------------------------------------------------------------- */ Bool DictLL_ReadUTF8BOM(FILE *file) // IN/OUT { Bool found; // sizeof on a string literal counts NUL. Exclude it. char buf[sizeof UTF8_BOM - 1] = { 0 }; if (file == stdin) { return FALSE; } found = fread(buf, sizeof buf, 1, file) == 1 && memcmp(UTF8_BOM, buf, sizeof buf) == 0; if (!found) { rewind(file); } return found; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/dynxdr/000077500000000000000000000000001321503522500223545ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/dynxdr/Makefile.am000066400000000000000000000017751321503522500244220ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2008-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libDynxdr.la libDynxdr_la_SOURCES = libDynxdr_la_SOURCES += dynxdr.c libDynxdr_la_SOURCES += xdrutil.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/dynxdr/dynxdr.c000066400000000000000000000266341321503522500240430ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #include #if defined(_WIN32) # include #else # include # include # include # include #endif #include "dynxdr.h" #include "dynbuf.h" #include "util.h" /* * dynxdr.c -- * * Implements an XDR stream backed by a DynBuf. */ typedef struct DynXdrData { DynBuf data; Bool freeMe; } DynXdrData; /* * FreeBSD < 5.0 and Solaris do not declare some parameters as "const". */ #if defined(sun) || (defined(__FreeBSD__) && __FreeBSD_version < 500000) # define DYNXDR_CONST #else # define DYNXDR_CONST const #endif /* * Mac OS X, FreeBSD and Solaris don't take a const parameter to the * "x_getpostn" function. */ #if defined(__APPLE__) || defined(__FreeBSD__) || defined(sun) # define DYNXDR_GETPOS_CONST #else # define DYNXDR_GETPOS_CONST const #endif /* * Solaris defines the parameter to "x_putbytes" as an int. */ #if defined(sun) # define DYNXDR_SIZE_T int #else # define DYNXDR_SIZE_T u_int #endif /* * Mac OS 64-bit defines the parameter to "x_putlong" as an int. */ #if defined __APPLE__ && defined __LP64__ # define DYNXDR_LONG int #else # define DYNXDR_LONG long #endif #if defined(sun) # define DYNXDR_INLINE_T rpc_inline_t # define DYNXDR_INLINE_LEN_T int #else # define DYNXDR_INLINE_T int32_t # define DYNXDR_INLINE_LEN_T u_int #endif /* *----------------------------------------------------------------------------- * * DynXdrPutBytes -- * * Writes a byte array into the XDR stream. * * Results: * TRUE: all ok * FALSE: failed to add data do dynbuf. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static bool_t DynXdrPutBytes(XDR *xdrs, // IN/OUT DYNXDR_CONST char *data, // IN DYNXDR_SIZE_T len) // IN { DynXdrData *priv = (DynXdrData *) xdrs->x_private; return DynBuf_Append(&priv->data, data, len); } /* *----------------------------------------------------------------------------- * * DynXdrGetPos -- * * Returns the current position of the buffer, which is the same as * the current buffer size. * * XXX: The Mac OS X headers don't expect a "const" argument. * * Results: * The size of the underlying buffer. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static u_int DynXdrGetPos(DYNXDR_GETPOS_CONST XDR *xdrs) // IN { DynXdrData *priv = (DynXdrData *) xdrs->x_private; return (u_int) DynBuf_GetSize(&priv->data); } /* *----------------------------------------------------------------------------- * * DynXdrSetPos -- * * Sets the position of the XDR stream. The current data in the buffer is * not affected, just the pointer to the current position. * * Results: * TRUE if pos is within the bounds of the backing buffer. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static bool_t DynXdrSetPos(XDR *xdrs, // IN u_int pos) // IN { DynXdrData *priv = (DynXdrData *) xdrs->x_private; if (pos <= DynBuf_GetAllocatedSize(&priv->data)) { DynBuf_SetSize(&priv->data, (size_t) pos); return TRUE; } return FALSE; } #if defined(__GLIBC__) || (defined(sun) && (defined(_LP64) || defined(_KERNEL))) /* *----------------------------------------------------------------------------- * * DynXdrPutInt32 -- * * Writes a 32-bit int to the XDR stream. * * XXX: This seems to be a glibc-only extenstion. It's present since at * least glibc 2.1, according to their CVS. * * XXX: Investigate this further. This XDR operation exists in Solaris * since at least Solaris 9. * * Results: * TRUE: all ok * FALSE: failed to add data do dynbuf. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static bool_t DynXdrPutInt32(XDR *xdrs, // IN/OUT DYNXDR_CONST int32_t *ip) // IN { int32_t out = htonl(*ip); DynXdrData *priv = (DynXdrData *) xdrs->x_private; return DynBuf_Append(&priv->data, &out, sizeof out); } #endif /* *----------------------------------------------------------------------------- * * DynXdrPutLong -- * * Writes a 32-bit int to the XDR stream. * * Results: * TRUE: all ok * FALSE: failed to add data do dynbuf. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static bool_t DynXdrPutLong(XDR *xdrs, // IN/OUT DYNXDR_CONST DYNXDR_LONG *lp) // IN { int32 out; DynXdrData *priv = (DynXdrData *) xdrs->x_private; #ifdef __APPLE__ ASSERT_ON_COMPILE(sizeof *lp <= sizeof (int32)); #endif out = htonl((int32)*lp); return DynBuf_Append(&priv->data, &out, sizeof out); } /* *----------------------------------------------------------------------------- * * DynXdrInline -- * * Return a pointer to a contiguous buffer of len bytes. On XDR_ENCODE, * is used to preallocate chunks of the backing buffer such that the caller * may set bulk 4-byte members w/o reallocating each time. * * Results: * Valid pointer on success, NULL on failure. * * Side effects: * Backing DynBuf may be enlarged. * *----------------------------------------------------------------------------- */ static DYNXDR_INLINE_T * DynXdrInline(XDR *xdrs, // IN/OUT DYNXDR_INLINE_LEN_T len) // IN { DynXdrData *priv = (DynXdrData *)xdrs->x_private; DynBuf *buf = &priv->data; DYNXDR_INLINE_T *retAddr; ASSERT(len >= 0); ASSERT(xdrs->x_op == XDR_ENCODE); if (len == 0) { return (DYNXDR_INLINE_T *)&buf->data[buf->size]; } if (buf->allocated - buf->size < len) { /* DynBuf too small. Grow it. */ if (!DynBuf_Enlarge(buf, buf->size + len)) { return NULL; } } retAddr = (DYNXDR_INLINE_T *)&buf->data[buf->size]; buf->size += len; return retAddr; } /* *----------------------------------------------------------------------------- * * DynXdr_Create -- * * Creates a new XDR struct backed by a DynBuf. The XDR stream is created * in XDR_ENCODE mode. The "in" argument is optional - if NULL, a new XDR * structure will be allocated. * * Results: * The XDR struct, or NULL on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ XDR * DynXdr_Create(XDR *in) // IN { static struct xdr_ops dynXdrOps = { /* * Yes, these macros are a little redundant, but I figure it helps with * readability to group the sun/_KERNEL bits together. */ #if !defined(sun) || (defined(sun) && !defined(_KERNEL)) NULL, /* x_getlong */ DynXdrPutLong, /* x_putlong */ #endif NULL, /* x_getbytes */ DynXdrPutBytes, /* x_putbytes */ DynXdrGetPos, /* x_getpostn */ DynXdrSetPos, /* x_setpostn */ DynXdrInline, /* x_inline */ NULL, /* x_destroy */ #if defined(__GLIBC__) NULL, /* x_getint32 */ DynXdrPutInt32, /* x_putint32 */ #elif defined(__APPLE__) NULL, /* x_control */ #elif defined(sun) && (defined(_LP64) || defined(_KERNEL)) NULL, /* x_control */ NULL, /* x_getint32 */ DynXdrPutInt32, /* x_putint32 */ #endif }; XDR *ret; DynXdrData *priv; if (in == NULL) { ret = malloc(sizeof *ret); if (ret == NULL) { goto error; } } else { ret = in; } priv = malloc(sizeof *priv); if (priv == NULL) { goto error; } priv->freeMe = (in == NULL); DynBuf_Init(&priv->data); ret->x_op = XDR_ENCODE; ret->x_public = NULL; ret->x_private = (char *) priv; ret->x_base = 0; ret->x_ops = &dynXdrOps; return ret; error: if (in == NULL) { free(ret); } return NULL; } /* *----------------------------------------------------------------------------- * * DynXdr_AppendRaw -- * * Appends some raw bytes to the XDR stream's internal dynbuf. This is * useful when non-XDR data may need to be added to the buffer, avoiding * the need to create another buffer and copying the existing data. * * Results: * Whether appending the data was successful. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool DynXdr_AppendRaw(XDR *xdrs, // IN const void *buf, // IN size_t len) // IN { DynBuf *intbuf = &((DynXdrData *) xdrs->x_private)->data; return DynBuf_Append(intbuf, buf, len); } /* *----------------------------------------------------------------------------- * * DynXdr_GetData -- * * Returns a copy of the current data in the XDR buffer. Caller is * responsible for freeing the data. * * Results: * The current data in the buffer, or NULL if there's no data, or failed * to allocate data. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void * DynXdr_AllocGet(XDR *xdrs) // IN { DynBuf *buf = &((DynXdrData *) xdrs->x_private)->data; return Util_Memdup(DynBuf_Get(buf), DynBuf_GetSize(buf)); } /* *----------------------------------------------------------------------------- * * DynXdr_Get -- * * Returns the current data in the XDR buffer. * * Results: * The current data in the buffer, or NULL if there's no data. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void * DynXdr_Get(XDR *xdrs) // IN { DynBuf *buf = &((DynXdrData *) xdrs->x_private)->data; return DynBuf_Get(buf); } /* *----------------------------------------------------------------------------- * * DynXdr_Destroy -- * * Frees data in the XDR stream, optionally destroying the underlying * DynBuf (if "release" is TRUE). If the XDR stream was dynamically * allocated by DynXdr_Create(), it will be freed. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void DynXdr_Destroy(XDR *xdrs, // IN Bool release) // IN { if (xdrs) { DynXdrData *priv = (DynXdrData *) xdrs->x_private; if (release) { DynBuf_Destroy(&priv->data); } if (priv->freeMe) { free(xdrs); } free(priv); } } open-vm-tools-stable-10.2.0/open-vm-tools/lib/dynxdr/xdrutil.c000066400000000000000000000057461321503522500242270ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * xdrutil.c -- * * Utility functions for code that uses XDR to encode/decode data. */ #include #include #include "vm_assert.h" #include "vmxrpc.h" #include "xdrutil.h" /* *----------------------------------------------------------------------------- * * XdrUtil_ArrayAppend -- * * Appends 'cnt' new elements of size 'sz' at the end of the given array. * If successful, len will contain the count of elements in the new * array. * * The newly allocated memory is zeroed out. * * Results: * NULL on allocation failure, pointer to the first new element otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void * XdrUtil_ArrayAppend(void **array, // IN/OUT u_int *arrayLen, // IN/OUT size_t elemSz, // IN u_int elemCnt) // IN { void *ret = NULL; void *newarray; newarray = realloc(*array, (*arrayLen + elemCnt) * elemSz); if (newarray != NULL) { ret = &((char *)newarray)[*arrayLen * elemSz]; memset(ret, 0, elemSz * elemCnt); *array = newarray; *arrayLen = *arrayLen + elemCnt; } return ret; } /* *----------------------------------------------------------------------------- * * XdrUtil_Deserialize -- * * Deserializes the given data into the provided destination, using the * given XDR function. * * Results: * Whether deserialization was successful. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool XdrUtil_Deserialize(const void *data, // IN size_t dataLen, // IN void *xdrProc, // IN void *dest) // IN { Bool ret; xdrproc_t proc = xdrProc; XDR xdrs; ASSERT(data != NULL); ASSERT(xdrProc != NULL); ASSERT(dest != NULL); xdrmem_create(&xdrs, (char *) data, dataLen, XDR_DECODE); ret = (Bool) proc(&xdrs, dest, 0); xdr_destroy(&xdrs); if (!ret) { VMX_XDR_FREE(proc, dest); } return ret; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/err/000077500000000000000000000000001321503522500216345ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/err/Makefile.am000066400000000000000000000017551321503522500237000ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libErr.la libErr_la_SOURCES = libErr_la_SOURCES += err.c libErr_la_SOURCES += errPosix.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/err/err.c000066400000000000000000000164471321503522500226040ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * err.c -- * * General error handling library * */ #include "vmware.h" #include "errInt.h" #include "str.h" #include "vm_atomic.h" #include "hashTable.h" #include "util.h" #include "codeset.h" /* * Constants */ #define HASHTABLE_SIZE 2048 /* * Types */ typedef struct ErrInfo { Err_Number number; char *string; } ErrInfo; /* * Variables */ /* * We statically link lib/err in several libraries. This means that a * single binary may have several copies of lib/err. These pointers are * not static so that we have one copy across the entire binary. */ Atomic_Ptr errNumTable; Atomic_Ptr errPtrTable; #if defined VMX86_DEBUG && defined __linux__ Atomic_Ptr errStrTable; #endif #define NUMTABLE() HashTable_AllocOnce(&errNumTable, HASHTABLE_SIZE, \ HASH_INT_KEY | HASH_FLAG_ATOMIC, NULL) #define PTRTABLE() HashTable_AllocOnce(&errPtrTable, HASHTABLE_SIZE, \ HASH_INT_KEY | HASH_FLAG_ATOMIC, NULL) #if defined VMX86_DEBUG && defined __linux__ #define STRTABLE() HashTable_AllocOnce(&errStrTable, HASHTABLE_SIZE, \ HASH_STRING_KEY | HASH_FLAG_ATOMIC, \ NULL) #endif /* *---------------------------------------------------------------------- * * Err_ErrString -- * * Returns a string that corresponds to the last error message. * The error number used is that which is native to the platform, * errno on POSIXen and GetLastError on Windows. * * Results: * Error message string. * * Side effects: * None. * Current error number is preserved. * *---------------------------------------------------------------------- */ const char * Err_ErrString(void) { return Err_Errno2String(Err_Errno()); } /* *---------------------------------------------------------------------- * * Err_Errno2String -- * * Return a string that corresponds to the passed error number. * The error number used is that which is native to the platform, * errno on POSIXen and GetLastError on Windows. * * The string is in English in UTF-8, has indefinite lifetime, * and need not be freed. * * Results: * Error message string in UTF-8. * * Side effects: * None. * Current error number is preserved. * *---------------------------------------------------------------------- */ const char * Err_Errno2String(Err_Number errorNumber) // IN { HashTable *numTable; HashTable *ptrTable; ErrInfo *info; ErrInfo *oldInfo; Err_Number oldErrno = Err_Errno(); ASSERT(errorNumber != ERR_INVALID); /* * Look up the error in numTable. * Or insert it if it's not there. */ numTable = NUMTABLE(); if (!HashTable_Lookup(numTable, (void *) (uintptr_t) errorNumber, (void **) &info)) { char buf[2048]; const char *p; size_t n; /* * Convert number to string and build the info structure. */ p = ErrErrno2String(errorNumber, buf, sizeof buf); info = Util_SafeMalloc(sizeof *info); info->number = errorNumber; info->string = Util_SafeStrdup(p); /* * To be safe, make sure the end of the string is at * a UTF-8 boundary, but we can only do this when the * string is in our buffer (it may not be). */ n = strlen(info->string); n = CodeSet_Utf8FindCodePointBoundary(info->string, n); info->string[n] = '\0'; /* * Try to insert new info into numTable. * If that fails, then we must have lost out to someone else. * Use theirs in that case. */ oldInfo = HashTable_LookupOrInsert(numTable, (void *) (uintptr_t) errorNumber, info); if (oldInfo != info) { ASSERT(oldInfo->number == info->number); ASSERT(Str_Strcmp(oldInfo->string, info->string) == 0); free(info->string); free(info); info = oldInfo; } } /* * Try to insert info into ptrTable. * We need to do it even if we didn't create this entry, * because we may get here before the other guy (who created * the entry and inserted it into numTable). */ ptrTable = PTRTABLE(); oldInfo = HashTable_LookupOrInsert(ptrTable, info->string, info); ASSERT(oldInfo == info); #if defined VMX86_DEBUG && defined __linux__ { HashTable *strTable = STRTABLE(); ErrInfo *i = HashTable_LookupOrInsert(strTable, info->string, info); ASSERT(i == info); } #endif Err_SetErrno(oldErrno); return info->string; } /* *---------------------------------------------------------------------- * * Err_String2Errno -- * * Return an error number that corresponds to the passed string. * The error number used is that which is native to the platform, * errno on POSIXen and GetLastError on Windows. * * To be recognized, the string must be one previously returned * by Err_Errno2String. Any other string (even a copy of * a valid error string) returns ERR_INVALID. * * Results: * Error number or ERR_INVALID. * * Side effects: * None. * *---------------------------------------------------------------------- */ Err_Number Err_String2Errno(const char *string) // IN { HashTable *ptrTable = PTRTABLE(); ErrInfo *info; if (!HashTable_Lookup(ptrTable, string, (void **) &info)) { return ERR_INVALID; } ASSERT(info->string == string); ASSERT(info->number != ERR_INVALID); return info->number; } #ifdef VMX86_DEBUG /* *---------------------------------------------------------------------- * * Err_String2ErrnoDebug -- * * Return an error number that corresponds to the passed string. * * This is the debug version that uses the whole string as key, * instead of just the address. * * Results: * Error number or ERR_INVALID. * * Side effects: * None. * *---------------------------------------------------------------------- */ Err_Number Err_String2ErrnoDebug(const char *string) // IN { #ifdef __linux__ HashTable *strTable = STRTABLE(); ErrInfo *info; if (!HashTable_Lookup(strTable, string, (void **) &info)) { return ERR_INVALID; } ASSERT(Str_Strcmp(info->string, string) == 0); ASSERT(info->number != ERR_INVALID); if (info->string != string) { Log("%s: errno %d, string \"%s\" at %p, originally at %p.\n", __FUNCTION__, info->number, string, string, info->string); } return info->number; #else return ERR_INVALID; #endif } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/err/errInt.h000066400000000000000000000023171321503522500232530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * errInt.h -- * * Internal definitions for the Err module. */ #ifndef _ERRINT_H_ #define _ERRINT_H_ #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #include "err.h" const char *ErrErrno2String(Err_Number errorNumber, char *buf, size_t bufSize); #endif // ifndef _ERRINT_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/err/errPosix.c000066400000000000000000000036271321503522500236230ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * errPosix.c -- * * Posix error handling library * */ #if defined __linux__ /* Force GNU strerror_r prototype instead of Posix prototype */ # define _GNU_SOURCE #endif #include #include #include #include "vmware.h" #include "errInt.h" #include "util.h" #include "str.h" /* *---------------------------------------------------------------------- * * ErrErrno2String -- * * Convert an error number to a string in English. * The returned string may use the supplied buffer or may be * a static string. * * Results: * The error string. * * Side effects: * None. * *---------------------------------------------------------------------- */ const char * ErrErrno2String(Err_Number errorNumber, // IN char *buf, // OUT: return buffer size_t bufSize) // IN: size of buffer { char *p; #if defined(__linux__) && !defined(__ANDROID__) p = strerror_r(errorNumber, buf, bufSize); #else p = strerror(errorNumber); #endif ASSERT(p != NULL); return p; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/000077500000000000000000000000001321503522500217635ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/Makefile.am000066400000000000000000000023651321503522500240250ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libFile.la libFile_la_SOURCES = libFile_la_SOURCES += file.c libFile_la_SOURCES += fileStandAlone.c libFile_la_SOURCES += filePosix.c libFile_la_SOURCES += fileIO.c libFile_la_SOURCES += fileIOPosix.c libFile_la_SOURCES += fileLockPrimitive.c libFile_la_SOURCES += fileLockPosix.c libFile_la_SOURCES += fileTempPosix.c libFile_la_SOURCES += fileTemp.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/file.c000066400000000000000000002016061321503522500230530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * file.c -- * * Interface to host file system. See also filePosix.c, * fileWin32.c, etc. * * If a function can be implemented such that it has no dependencies * outside of lib/misc, place the function in fileStandAlone.c, NOT * here. */ #if defined(_WIN32) #include #endif #include #include #include #include #include "safetime.h" #if defined(_WIN32) #include #define S_IXUSR 0100 #define S_IWUSR 0200 #else #include #endif #include #include #include #include "vmware.h" #include "util.h" #include "str.h" #include "msg.h" #include "log.h" #include "random.h" #include "uuid.h" #include "config.h" #include "posix.h" #include "file.h" #include "fileIO.h" #include "util.h" #include "fileInt.h" #include "dynbuf.h" #include "base64.h" #include "timeutil.h" #include "hostinfo.h" #include "hostType.h" #include "vm_atomic.h" #include "fileLock.h" #include "userlock.h" #include "unicodeOperations.h" /* *---------------------------------------------------------------------- * * File_Exists -- * * Check if a file is accessible with the process' real user ID * * XXX - This function invokes access(), which uses the real uid, * not the effective uid, so it probably does not do what you * expect. Instead it should use Posix_EuidAccess(), which * uses the effective uid, but it's too risky to fix right now. * See PR 459242. * * Results: * TRUE file is accessible with the process' real uid * FALSE file doesn't exist or an error occured * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_Exists(const char *pathName) // IN: May be NULL. { return FileIO_IsSuccess(FileIO_Access(pathName, FILEIO_ACCESS_EXISTS)); } /* *---------------------------------------------------------------------- * * File_UnlinkIfExists -- * * If the given file exists, unlink it. * * Results: * Return 0 if the unlink is successful or if the file did not exist. * Otherwise return -1. * * Side effects: * May unlink the file. * *---------------------------------------------------------------------- */ int File_UnlinkIfExists(const char *pathName) // IN: { int ret = FileDeletion(pathName, TRUE); if (ret != 0) { ret = (ret == ENOENT) ? 0 : -1; } return ret; } /* *----------------------------------------------------------------------------- * * File_SupportsMandatoryLock -- * * Determines if the underlying filesystem for a particular location * can support mandatory locking. Mandatory locking is used within * FileLock to make the advisory FileLock self-cleaning in the event * of host failure. * * Results: * TRUE if FILEIO_OPEN_EXCLUSIVE_LOCK will work, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool File_SupportsMandatoryLock(const char *pathName) // IN: file to be locked { /* * For now, "know" that all ESX filesystems support mandatory locks * and no non-ESX filesystems support mandatory locks. */ return HostType_OSIsVMK(); } /* *---------------------------------------------------------------------- * * File_IsDirectory -- * * Check if specified file is a directory or not. * * Results: * TRUE is a directory * FALSE is not a directory or an error occured * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_IsDirectory(const char *pathName) // IN: { FileData fileData; return (FileAttributes(pathName, &fileData) == 0) && (fileData.fileType == FILE_TYPE_DIRECTORY); } /* *----------------------------------------------------------------------------- * * File_GetFilePermissions -- * * Return the read / write / execute permissions of a file. * * Results: * TRUE if success, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool File_GetFilePermissions(const char *pathName, // IN: int *mode) // OUT: file mode { FileData fileData; ASSERT(mode != NULL); if (FileAttributes(pathName, &fileData) != 0) { return FALSE; } *mode = fileData.fileMode; #if defined(_WIN32) /* * On Win32 implementation of FileAttributes does not return execution * bit. */ if (FileIO_Access(pathName, FILEIO_ACCESS_EXEC) == FILEIO_SUCCESS) { *mode |= S_IXUSR; } #endif return TRUE; } /* *---------------------------------------------------------------------- * * File_Unlink -- * * Unlink the file. * * POSIX: If name is a symbolic link, then unlink the the file the link * refers to as well as the link itself. Only one level of links are * followed. * WINDOWS: No symbolic links so no link following. * * Results: * Return 0 if the unlink is successful. Otherwise, returns -1. * * Side effects: * The file is removed. * *---------------------------------------------------------------------- */ int File_Unlink(const char *pathName) // IN: { return (FileDeletion(pathName, TRUE) == 0) ? 0 : -1; } /* *---------------------------------------------------------------------- * * File_UnlinkNoFollow -- * * Unlink the file (do not follow symbolic links). * On Windows, there are no symbolic links so this is the same as * File_Unlink * * Results: * Return 0 if the unlink is successful. Otherwise, returns -1. * * Side effects: * The file is removed. * *---------------------------------------------------------------------- */ int File_UnlinkNoFollow(const char *pathName) // IN: { return (FileDeletion(pathName, FALSE) == 0) ? 0 : -1; } /* *---------------------------------------------------------------------- * * File_UnlinkRetry -- * * Unlink the file, retrying on EBUSY on ESX, up to given timeout. * * Results: * Return 0 if the unlink is successful. Otherwise, return -1. * * Side effects: * The file is removed. * *---------------------------------------------------------------------- */ int File_UnlinkRetry(const char *pathName, // IN: uint32 maxWaitTimeMilliSec) // IN: { int ret; if (vmx86_server) { uint32 const unlinkWait = 300; uint32 waitMilliSec = 0; do { ret = FileDeletion(pathName, TRUE); if (ret != EBUSY || waitMilliSec >= maxWaitTimeMilliSec) { break; } Log(LGPFX" %s: %s after %u ms\n", __FUNCTION__, pathName, unlinkWait); Util_Usleep(unlinkWait * 1000); waitMilliSec += unlinkWait; } while (TRUE); } else { ret = FileDeletion(pathName, TRUE); } return ret == 0 ? 0 : -1; } /* *---------------------------------------------------------------------- * * FileCreateDirectoryEx -- * * Creates the specified directory with the specified permissions. * * Results: * True if the directory is successfully created, false otherwise. * * Side effects: * Creates the directory on disk. * *---------------------------------------------------------------------- */ static int FileCreateDirectoryEx(const char *pathName, // IN: int mask) // IN: { int err = FileCreateDirectory(pathName, mask); if (err != 0) { Log(LGPFX" %s: Failed to create %s. Error = %d\n", __FUNCTION__, pathName, err); } return err; } /* *---------------------------------------------------------------------- * * File_CreateDirectoryEx -- * * Creates the specified directory with the specified permissions. * * Results: * True if the directory is successfully created, false otherwise. * * Side effects: * Creates the directory on disk. * *---------------------------------------------------------------------- */ Bool File_CreateDirectoryEx(const char *pathName, // IN: int mask) // IN: { int err = FileCreateDirectoryEx(pathName, mask); return err == 0; } /* *---------------------------------------------------------------------- * * File_CreateDirectory -- * * Creates the specified directory with 0777 permissions. * * Results: * True if the directory is successfully created, false otherwise. * * Side effects: * Creates the directory on disk. * *---------------------------------------------------------------------- */ Bool File_CreateDirectory(const char *pathName) // IN: { return File_CreateDirectoryEx(pathName, 0777); } /* *---------------------------------------------------------------------- * * File_EnsureDirectoryEx -- * * If the directory doesn't exist, creates it. If the directory * already exists, do nothing and succeed. * * Results: * See above. * * Side effects: * May create a directory on disk. * *---------------------------------------------------------------------- */ Bool File_EnsureDirectoryEx(const char *pathName, // IN: int mask) // IN: { int err = FileCreateDirectory(pathName, mask); Bool success = ((err == 0) || (err == EEXIST)); if (!success) { Log(LGPFX" %s: Failed to create %s. Error = %d\n", __FUNCTION__, pathName, err); } return success; } /* *---------------------------------------------------------------------- * * File_EnsureDirectory -- * * If the directory doesn't exist, creates it. If the directory * already exists, do nothing and succeed. * * Results: * See above. * * Side effects: * May create a directory on disk. * *---------------------------------------------------------------------- */ Bool File_EnsureDirectory(const char *pathName) // IN: { return File_EnsureDirectoryEx(pathName, 0777); } /* *---------------------------------------------------------------------- * * File_DeleteEmptyDirectory -- * * Deletes the specified directory if it is empty. * * Results: * True if the directory is successfully deleted, false otherwise. * * Side effects: * Deletes the directory from disk. * *---------------------------------------------------------------------- */ Bool File_DeleteEmptyDirectory(const char *pathName) // IN: { Bool returnValue = TRUE; if (FileRemoveDirectory(pathName) != 0) { #if defined(_WIN32) /* * Directory may have read-only bit set. Unset the * read-only bit and try deleting one more time. */ if (File_SetFilePermissions(pathName, S_IWUSR)) { if (FileRemoveDirectory(pathName) != 0) { returnValue = FALSE; } } else { returnValue = FALSE; } #else returnValue = FALSE; #endif } return returnValue; } /* *---------------------------------------------------------------------- * * GetOldMachineID -- * * Return the old machineID, the one based on Hostinfo_MachineID. * * Results: * The machineID is returned. It should not be freed. * * Side effects: * Memory allocated for the machineID is never freed, however the * memory is cached - there is no memory leak. * *---------------------------------------------------------------------- */ static const char * GetOldMachineID(void) { static Atomic_Ptr atomic; /* Implicitly initialized to NULL. --mbellon */ const char *machineID; machineID = Atomic_ReadPtr(&atomic); if (machineID == NULL) { char *p; uint32 hashValue; uint64 hardwareID; char encodedMachineID[16 + 1]; char rawMachineID[sizeof hashValue + sizeof hardwareID]; Hostinfo_MachineID(&hashValue, &hardwareID); /* Build the raw machineID */ memcpy(rawMachineID, &hashValue, sizeof hashValue); memcpy(&rawMachineID[sizeof hashValue], &hardwareID, sizeof hardwareID); /* Base 64 encode the binary data to obtain printable characters */ Base64_Encode(rawMachineID, sizeof rawMachineID, encodedMachineID, sizeof encodedMachineID, NULL); /* remove '/' from the encoding; no problem using it for a file name */ for (p = encodedMachineID; *p; p++) { if (*p == '/') { *p = '-'; } } p = Util_SafeStrdup(encodedMachineID); if (Atomic_ReadIfEqualWritePtr(&atomic, NULL, p)) { Posix_Free(p); } machineID = Atomic_ReadPtr(&atomic); ASSERT(machineID != NULL); } return machineID; } /* *---------------------------------------------------------------------- * * FileLockGetMachineID -- * * Return the machineID, a "universally unique" identification of * of the system that calls this routine. * * An attempt is first made to use the host machine's UUID. If that * fails drop back to the older machineID method. * * Results: * The machineID is returned. It should not be freed. * * Side effects: * Memory allocated for the machineID is never freed, however the * memory is cached - there is no memory leak. * *---------------------------------------------------------------------- */ const char * FileLockGetMachineID(void) { static Atomic_Ptr atomic; /* Implicitly initialized to NULL. --mbellon */ const char *machineID; machineID = Atomic_ReadPtr(&atomic); if (machineID == NULL) { char *p; char *q; /* * UUID_GetHostRealUUID is fine on Windows. * * UUID_GetHostUUID is fine on Macs because the UUID can't be found * in /dev/mem even if it can be accessed. Macs always use the MAC * address from en0 to provide a UUID. * * UUID_GetHostUUID is problematic on Linux so it is not acceptable for * locking purposes - it accesses /dev/mem to obtain the SMBIOS UUID * and that can fail when the calling process is not priviledged. * */ #if defined(_WIN32) q = UUID_GetRealHostUUID(); #elif defined(__APPLE__) || defined(VMX86_SERVER) q = UUID_GetHostUUID(); #else q = NULL; #endif if (q == NULL) { p = Util_SafeStrdup(GetOldMachineID()); } else { p = Str_SafeAsprintf(NULL, "uuid=%s", q); Posix_Free(q); /* Surpress any whitespace. */ for (q = p; *q; q++) { if (isspace((int) *q)) { *q = '-'; } } } if (Atomic_ReadIfEqualWritePtr(&atomic, NULL, p)) { Posix_Free(p); } machineID = Atomic_ReadPtr(&atomic); ASSERT(machineID != NULL); } return machineID; } /* *----------------------------------------------------------------------------- * * OldMachineIDMatch -- * * Do the old-style MachineIDs match? * * Results: * TRUE Yes * FALSE No * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool OldMachineIDMatch(const char *first, // IN: const char *second) // IN: { #if defined(__APPLE__) || defined(__linux__) /* Ignore the host name hash */ char *p; char *q; size_t len; Bool result; uint8 rawMachineID_1[12]; uint8 rawMachineID_2[12]; for (p = Util_SafeStrdup(first), q = p; *p; p++) { if (*p == '-') { *p = '/'; } } result = Base64_Decode(q, rawMachineID_1, sizeof rawMachineID_1, &len); Posix_Free(q); if ((result == FALSE) || (len != 12)) { Warning("%s: unexpected decode problem #1 (%s)\n", __FUNCTION__, first); return FALSE; } for (p = Util_SafeStrdup(second), q = p; *p; p++) { if (*p == '-') { *p = '/'; } } result = Base64_Decode(q, rawMachineID_2, sizeof rawMachineID_2, &len); Posix_Free(q); if ((result == FALSE) || (len != 12)) { Warning("%s: unexpected decode problem #2 (%s)\n", __FUNCTION__, second); return FALSE; } return memcmp(&rawMachineID_1[4], &rawMachineID_2[4], 8) == 0 ? TRUE : FALSE; #else return strcmp(first, second) == 0 ? TRUE : FALSE; #endif } /* *----------------------------------------------------------------------------- * * FileLockMachineIDMatch -- * * Do the MachineIDs match? * * Results: * TRUE Yes * FALSE No * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool FileLockMachineIDMatch(const char *hostMachineID, // IN: const char *otherMachineID) // IN: { if (strncmp(hostMachineID, "uuid=", 5) == 0) { if (strncmp(otherMachineID, "uuid=", 5) == 0) { return strcmp(hostMachineID + 5, otherMachineID + 5) == 0 ? TRUE : FALSE; } else { return OldMachineIDMatch(GetOldMachineID(), otherMachineID); } } else { if (strncmp(otherMachineID, "uuid=", 5) == 0) { return FALSE; } else { return strcmp(hostMachineID, otherMachineID) == 0 ? TRUE : FALSE; } } } /* *---------------------------------------------------------------------------- * * File_IsEmptyDirectory -- * * Check if specified file is a directory and contains no files. * * Results: * Bool - TRUE -> is an empty directory, FALSE -> not an empty directory * * Side effects: * None * *---------------------------------------------------------------------------- */ Bool File_IsEmptyDirectory(const char *pathName) // IN: { int numFiles; if (!File_IsDirectory(pathName)) { return FALSE; } numFiles = File_ListDirectory(pathName, NULL); if (numFiles < 0) { return FALSE; } return numFiles == 0; } /* *---------------------------------------------------------------------------- * * File_IsOsfsVolumeEmpty -- * * Check if specified OSFS volume contains no files. * This method ignore hidden .sf files. *.sf files are VMFS * metadata files. * * OSFS based volumes are considered empty even if they * contain vmfs metadata files. This emptiness can not be * checked by File_IsEmptyDirectory API (PR 1050328). * * Results: * Bool - TRUE -> is vmfs empty directory, FALSE -> not an vmfs * empty directory * * Side effects: * None * *---------------------------------------------------------------------------- */ Bool File_IsOsfsVolumeEmpty(const char *pathName) // IN: { int i, numFiles; char **fileList = NULL; static const char vmfsSystemFilesuffix[] = ".sf"; Bool onlyVmfsSystemFilesFound = TRUE; numFiles = File_ListDirectory(pathName, &fileList); if (numFiles == -1) { return FALSE; } for (i = 0; i < numFiles; i++) { if (!Unicode_EndsWith(fileList[i], vmfsSystemFilesuffix)) { onlyVmfsSystemFilesFound = FALSE; break; } } Util_FreeStringList(fileList, numFiles); return onlyVmfsSystemFilesFound; } /* *---------------------------------------------------------------------- * * File_IsFile -- * * Check if specified file is a regular file. * * Results: * TRUE is a regular file * FALSE is not a regular file or an error occured. * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_IsFile(const char *pathName) // IN: { FileData fileData; return (FileAttributes(pathName, &fileData) == 0) && (fileData.fileType == FILE_TYPE_REGULAR); } /* *---------------------------------------------------------------------- * * File_CopyFromFdToFd -- * * Write all data between the current position in the 'src' file and the * end of the 'src' file to the current position in the 'dst' file * * Results: * TRUE success * FALSE failure * * Side effects: * The current position in the 'src' file and the 'dst' file are modified * *---------------------------------------------------------------------- */ Bool File_CopyFromFdToFd(FileIODescriptor src, // IN: FileIODescriptor dst) // IN: { Err_Number err; FileIOResult fretR; do { unsigned char buf[8 * 1024]; size_t actual; FileIOResult fretW; fretR = FileIO_Read(&src, buf, sizeof buf, &actual); if (!FileIO_IsSuccess(fretR) && (fretR != FILEIO_READ_ERROR_EOF)) { err = Err_Errno(); Msg_Append(MSGID(File.CopyFromFdToFd.read.failure) "Read error: %s.\n\n", FileIO_MsgError(fretR)); Err_SetErrno(err); return FALSE; } fretW = FileIO_Write(&dst, buf, actual, NULL); if (!FileIO_IsSuccess(fretW)) { err = Err_Errno(); Msg_Append(MSGID(File.CopyFromFdToFd.write.failure) "Write error: %s.\n\n", FileIO_MsgError(fretW)); Err_SetErrno(err); return FALSE; } } while (fretR != FILEIO_READ_ERROR_EOF); return TRUE; } /* *----------------------------------------------------------------------------- * * FileCopyTree -- * * Recursively copies all files from a source path to a destination, * optionally overwriting any files. This does the actual work * for File_CopyTree. * * Results: * TRUE on success * FALSE on failure: Error messages are appended. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool FileCopyTree(const char *srcName, // IN: const char *dstName, // IN: Bool overwriteExisting, // IN: Bool followSymlinks) // IN: { int err; Bool success = TRUE; int numFiles; int i; char **fileList = NULL; numFiles = File_ListDirectory(srcName, &fileList); if (numFiles == -1) { err = Err_Errno(); Msg_Append(MSGID(File.CopyTree.walk.failure) "Unable to access '%s' when copying files.\n\n", srcName); Err_SetErrno(err); return FALSE; } File_EnsureDirectory(dstName); for (i = 0; i < numFiles && success; i++) { struct stat sb; char *srcFilename; srcFilename = File_PathJoin(srcName, fileList[i]); if (followSymlinks) { success = (Posix_Stat(srcFilename, &sb) == 0); } else { success = (Posix_Lstat(srcFilename, &sb) == 0); } if (success) { char *dstFilename = File_PathJoin(dstName, fileList[i]); switch (sb.st_mode & S_IFMT) { case S_IFDIR: success = FileCopyTree(srcFilename, dstFilename, overwriteExisting, followSymlinks); break; #if !defined(_WIN32) case S_IFLNK: if (Posix_Symlink(Posix_ReadLink(srcFilename), dstFilename) != 0) { err = Err_Errno(); Msg_Append(MSGID(File.CopyTree.symlink.failure) "Unable to symlink '%s' to '%s': %s\n\n", Posix_ReadLink(srcFilename), dstFilename, Err_Errno2String(err)); Err_SetErrno(err); success = FALSE; } break; #endif default: if (!File_Copy(srcFilename, dstFilename, overwriteExisting)) { err = Err_Errno(); Msg_Append(MSGID(File.CopyTree.copy.failure) "Unable to copy '%s' to '%s': %s\n\n", srcFilename, dstFilename, Err_Errno2String(err)); Err_SetErrno(err); success = FALSE; } break; } Posix_Free(dstFilename); } else { err = Err_Errno(); Msg_Append(MSGID(File.CopyTree.stat.failure) "Unable to get information on '%s' when copying files.\n\n", srcFilename); Err_SetErrno(err); } Posix_Free(srcFilename); } Util_FreeStringList(fileList, numFiles); return success; } /* *----------------------------------------------------------------------------- * * File_CopyTree -- * * Recursively copies all files from a source path to a destination, * optionally overwriting any files. * * Results: * TRUE on success * FALSE on failure: Error messages are appended. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool File_CopyTree(const char *srcName, // IN: const char *dstName, // IN: Bool overwriteExisting, // IN: Bool followSymlinks) // IN: { int err; ASSERT(srcName != NULL); ASSERT(dstName != NULL); if (!File_IsDirectory(srcName)) { err = Err_Errno(); Msg_Append(MSGID(File.CopyTree.source.notDirectory) "Source path '%s' is not a directory.", srcName); Err_SetErrno(err); return FALSE; } if (!File_IsDirectory(dstName)) { err = Err_Errno(); Msg_Append(MSGID(File.CopyTree.dest.notDirectory) "Destination path '%s' is not a directory.", dstName); Err_SetErrno(err); return FALSE; } return FileCopyTree(srcName, dstName, overwriteExisting, followSymlinks); } /* *---------------------------------------------------------------------- * * File_CopyFromFd -- * * Copy the 'src' file to 'dstName'. * If the 'dstName' file already exists, 'overwriteExisting' * decides whether to overwrite the existing file or not. * * Results: * TRUE on success * FALSE on failure: Messages are appended * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_CopyFromFd(FileIODescriptor src, // IN: const char *dstName, // IN: Bool overwriteExisting) // IN: { Bool success; Err_Number err; FileIOResult fret; FileIODescriptor dst; FileIOOpenAction action; ASSERT(dstName != NULL); FileIO_Invalidate(&dst); action = overwriteExisting ? FILEIO_OPEN_CREATE_EMPTY : FILEIO_OPEN_CREATE_SAFE; fret = FileIO_Open(&dst, dstName, FILEIO_OPEN_ACCESS_WRITE, action); if (!FileIO_IsSuccess(fret)) { err = Err_Errno(); Msg_Append(MSGID(File.CopyFromFdToName.create.failure) "Unable to create a new '%s' file: %s.\n\n", dstName, FileIO_MsgError(fret)); Err_SetErrno(err); return FALSE; } success = File_CopyFromFdToFd(src, dst); err = Err_Errno(); if (!FileIO_IsSuccess(FileIO_Close(&dst))) { if (success) { // Report close failure when there isn't another error err = Err_Errno(); } Msg_Append(MSGID(File.CopyFromFdToName.close.failure) "Unable to close the '%s' file: %s.\n\n", dstName, Msg_ErrString()); success = FALSE; } if (!success) { /* The copy failed: ensure the destination file is removed */ File_Unlink(dstName); } Err_SetErrno(err); return success; } /* *---------------------------------------------------------------------- * * File_Copy -- * * Copy the 'srcName' file to 'dstName'. * If 'srcName' doesn't exist, an error is reported * If the 'dstName' file already exists, 'overwriteExisting' * decides whether to overwrite the existing file or not. * * Results: * TRUE on success * FALSE on failure: Messages are appended * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_Copy(const char *srcName, // IN: const char *dstName, // IN: Bool overwriteExisting) // IN: { Bool success; Err_Number err; FileIOResult fret; FileIODescriptor src; ASSERT(srcName != NULL); ASSERT(dstName != NULL); FileIO_Invalidate(&src); fret = FileIO_Open(&src, srcName, FILEIO_OPEN_ACCESS_READ, FILEIO_OPEN); if (!FileIO_IsSuccess(fret)) { err = Err_Errno(); Msg_Append(MSGID(File.Copy.open.failure) "Unable to open the '%s' file for read access: %s.\n\n", srcName, FileIO_MsgError(fret)); Err_SetErrno(err); return FALSE; } success = File_CopyFromFd(src, dstName, overwriteExisting); err = Err_Errno(); if (!FileIO_IsSuccess(FileIO_Close(&src))) { if (success) { // Report close failure when there isn't another error err = Err_Errno(); } Msg_Append(MSGID(File.Copy.close.failure) "Unable to close the '%s' file: %s.\n\n", srcName, Msg_ErrString()); success = FALSE; } Err_SetErrno(err); return success; } /* *---------------------------------------------------------------------- * * File_Move -- * * Moves a file from one place to the other as efficiently as possible. * This can be used to rename a file but, since file copying may be * necessary, there is no assurance of atomicity. For efficiency * purposes copying only results if the native rename ability fails. * * Results: * TRUE succeeded * FALSE otherwise * * Side effects: * src file is no more, but dst file exists * *---------------------------------------------------------------------- */ Bool File_Move(const char *oldFile, // IN: const char *newFile, // IN: Bool *asRename) // OUT/OPT: result occurred due to rename/copy { Bool ret; Bool duringRename; if (File_Rename(oldFile, newFile) == 0) { duringRename = TRUE; ret = TRUE; Err_SetErrno(0); } else { duringRename = FALSE; if (File_Copy(oldFile, newFile, TRUE)) { // Allow overwrite File_Unlink(oldFile); // Explicitly ignore errors ret = TRUE; Err_SetErrno(0); } else { ret = FALSE; } } if (asRename) { *asRename = duringRename; } return ret; } /* *----------------------------------------------------------------------------- * * File_MoveTree -- * * Moves a directory from one place to the other. * - If dstName indicates a path that does not exist a directory will be * created with that path filled with the contents from srcName. * - If dstName is an existing directory then the contents will be moved * into that directory. * - If dstName indicates a file then File_MoveTree fails. * * First we'll attempt to rename the directory, failing that we copy the * contents from src->destination and unlink the src. If the copy is * succesful then we will report success even if the unlink fails for some * reason. In that event we will append error messages. * * Results: * TRUE - on success * FALSE - on failure with error messages appended * * Side effects: * - Deletes the originating directory * - In the event of a failed copy we'll leave the new directory in a state * *----------------------------------------------------------------------------- */ Bool File_MoveTree(const char *srcName, // IN: const char *dstName, // IN: Bool overwriteExisting, // IN: Bool *asMove) // OUT/OPT: { Bool ret = FALSE; Bool createdDir = FALSE; ASSERT(srcName != NULL); ASSERT(dstName != NULL); if (asMove) { *asMove = FALSE; } if (!File_IsDirectory(srcName)) { Msg_Append(MSGID(File.MoveTree.source.notDirectory) "Source path '%s' is not a directory.", srcName); return FALSE; } if (File_Rename(srcName, dstName) == 0) { if (asMove) { *asMove = TRUE; } ret = TRUE; } else { struct stat statbuf; if (Posix_Stat(dstName, &statbuf) == -1) { int err = Err_Errno(); if (err == ENOENT) { if (!File_CreateDirectoryHierarchy(dstName, NULL)) { Msg_Append(MSGID(File.MoveTree.dst.couldntCreate) "Could not create '%s'.\n\n", dstName); return FALSE; } createdDir = TRUE; } else { Msg_Append(MSGID(File.MoveTree.statFailed) "%d:Failed to stat destination '%s'.\n\n", err, dstName); return FALSE; } } else { if (!File_IsDirectory(dstName)) { Msg_Append(MSGID(File.MoveTree.dest.notDirectory) "The destination path '%s' is not a directory.\n\n", dstName); return FALSE; } } #if !defined(__FreeBSD__) && !defined(sun) /* * File_GetFreeSpace is not defined for FreeBSD */ if (createdDir) { /* * Check for free space on destination filesystem. * We only check for free space if the destination directory * did not exist. In this case, we will not be overwriting any existing * paths, so we need as much space as srcName. */ int64 srcSize; int64 freeSpace; srcSize = File_GetSizeEx(srcName); freeSpace = File_GetFreeSpace(dstName, TRUE); if (freeSpace < srcSize) { char *spaceStr = Msg_FormatSizeInBytes(srcSize); Msg_Append(MSGID(File.MoveTree.dst.insufficientSpace) "There is not enough space in the file system to " "move the directory tree. Free %s and try again.", spaceStr); Posix_Free(spaceStr); return FALSE; } } #endif if (File_CopyTree(srcName, dstName, overwriteExisting, FALSE)) { ret = TRUE; if (!File_DeleteDirectoryTree(srcName)) { Msg_Append(MSGID(File.MoveTree.cleanupFailed) "Forced to copy '%s' into '%s' but unable to remove " "source directory.\n\n", srcName, dstName); } } else { ret = FALSE; Msg_Append(MSGID(File.MoveTree.copyFailed) "Could not rename and failed to copy source directory " "'%s'.\n\n", srcName); if (createdDir) { /* * Only clean up if we created the directory. Not attempting to * clean up partial failures. */ File_DeleteDirectoryTree(dstName); } } } return ret; } /* *---------------------------------------------------------------------- * * File_GetModTimeString -- * * Returns a human-readable string denoting the last modification * time of a file. * ctime() returns string terminated with newline, which we replace * with a '\0'. * * Results: * Last modification time string on success, NULL on error. * * Side effects: * None. * *---------------------------------------------------------------------- */ char * File_GetModTimeString(const char *pathName) // IN: { int64 modTime; modTime = File_GetModTime(pathName); return (modTime == -1) ? NULL : TimeUtil_GetTimeFormat(modTime, TRUE, TRUE); } /* *---------------------------------------------------------------------------- * * File_GetSize -- * * Get size of file. Try File_GetSizeEx to get size of directory/symlink. * * Results: * Size of file or -1. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int64 File_GetSize(const char *pathName) // IN: { int64 ret; if (pathName == NULL) { ret = -1; } else { FileIODescriptor fd; FileIOResult res; FileIO_Invalidate(&fd); res = FileIO_Open(&fd, pathName, FILEIO_OPEN_ACCESS_READ, FILEIO_OPEN); if (FileIO_IsSuccess(res)) { ret = FileIO_GetSize(&fd); FileIO_Close(&fd); } else { ret = -1; } } return ret; } /* *---------------------------------------------------------------------- * * File_SupportsLargeFiles -- * * Check if the given file is on an FS that supports 4GB files. * Require 4GB support so we rule out FAT filesystems, which * support 4GB-1 on both Linux and Windows. * * Results: * TRUE if FS supports files over 4GB. * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_SupportsLargeFiles(const char *pathName) // IN: { return File_SupportsFileSize(pathName, CONST64U(0x100000000)); } /* *---------------------------------------------------------------------------- * * File_GetSizeEx -- * * Get size of file or directory or symlink. File_GetSize can only get * size of file. * * Results: * Size of file/directory/symlink or -1. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int64 File_GetSizeEx(const char *pathName) // IN: { int i; int numFiles; int64 totalSize = 0; char **fileList = NULL; if (pathName == NULL) { return -1; } if (!File_IsDirectory(pathName)) { return File_GetSize(pathName); } numFiles = File_ListDirectory(pathName, &fileList); if (numFiles == -1) { return -1; } for (i = 0; i < numFiles; i++) { char *fileName = File_PathJoin(pathName, fileList[i]); int64 fileSize = File_GetSizeEx(fileName); Posix_Free(fileName); if (fileSize != -1) { totalSize += fileSize; } } Util_FreeStringList(fileList, numFiles); return totalSize; } /* *---------------------------------------------------------------------------- * * File_GetSizeByPath -- * * Get size of a file without opening it. * * Results: * Size of file or -1. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int64 File_GetSizeByPath(const char *pathName) // IN: { return (pathName == NULL) ? -1 : FileIO_GetSizeByPath(pathName); } /* *---------------------------------------------------------------------- * * FileFirstSlashIndex -- * * Finds the first pathname slash index in a path (both slashes count * for Win32, only forward slash for Unix). * * Results: * As described. * * Side effects: * None. * *---------------------------------------------------------------------- */ static UnicodeIndex FileFirstSlashIndex(const char *pathName, // IN: UnicodeIndex startIndex) // IN: { UnicodeIndex firstFS; #if defined(_WIN32) UnicodeIndex firstBS; #endif ASSERT(pathName); firstFS = Unicode_FindSubstrInRange(pathName, startIndex, -1, "/", 0, 1); #if defined(_WIN32) firstBS = Unicode_FindSubstrInRange(pathName, startIndex, -1, "\\", 0, 1); if ((firstFS != UNICODE_INDEX_NOT_FOUND) && (firstBS != UNICODE_INDEX_NOT_FOUND)) { return MIN(firstFS, firstBS); } else { return (firstFS == UNICODE_INDEX_NOT_FOUND) ? firstBS : firstFS; } #else return firstFS; #endif } /* *----------------------------------------------------------------------------- * * File_CreateDirectoryHierarchyEx -- * * Create a directory including any parents that don't already exist. * All the created directories are tagged with the specified permission. * Returns the topmost directory which was created, to allow calling code * to remove it after in case later operations fail. * * Results: * TRUE on success, FALSE on failure. * * If topmostCreated is not NULL, it returns the result of the hierarchy * creation. If no directory was created, *topmostCreated is set to NULL. * Otherwise *topmostCreated is set to the topmost directory which was * created. *topmostCreated is set even in case of failure. * * The caller most free the resulting string. * * Side effects: * Only the obvious. * *----------------------------------------------------------------------------- */ Bool File_CreateDirectoryHierarchyEx(const char *pathName, // IN: int mask, // IN: char **topmostCreated) // OUT/OPT: { char *volume; UnicodeIndex index; UnicodeIndex length; if (topmostCreated != NULL) { *topmostCreated = NULL; } if (pathName == NULL) { return TRUE; } length = Unicode_LengthInCodePoints(pathName); if (length == 0) { return TRUE; } /* * Skip past any volume/share. */ File_SplitName(pathName, &volume, NULL, NULL); index = Unicode_LengthInCodePoints(volume); Posix_Free(volume); if (index >= length) { return File_IsDirectory(pathName); } /* * Iterate parent directories, splitting on appropriate dir separators. */ while (TRUE) { int err; char *temp; index = FileFirstSlashIndex(pathName, index + 1); temp = Unicode_Substr(pathName, 0, (index == UNICODE_INDEX_NOT_FOUND) ? -1 : index); /* * If we check if the directory already exists and then we create it, * there is a race between these two operations - that might cause this * operation to fail with no reason. * This is why we reverse the attempt and the check. */ err = FileCreateDirectoryEx(temp, mask); if (err == 0) { if (topmostCreated != NULL && *topmostCreated == NULL) { *topmostCreated = temp; temp = NULL; } } else { FileData fileData; if (err == EEXIST) { err = FileAttributes(temp, &fileData); if (err == 0) { if (fileData.fileType != FILE_TYPE_DIRECTORY) { err = ENOTDIR; errno = err; #if defined(_WIN32) SetLastError(ERROR_DIRECTORY); #endif } } } } Posix_Free(temp); if (err != 0) { return FALSE; } if (index == UNICODE_INDEX_NOT_FOUND) { break; } } return TRUE; } /* *----------------------------------------------------------------------------- * * File_CreateDirectoryHierarchy -- * * Create a directory including any parents that don't already exist. * All the created directories are tagged with 0777 permissions. * Returns the topmost directory which was created, to allow calling code * to remove it after in case later operations fail. * * Results: * TRUE on success, FALSE on failure. * * If topmostCreated is not NULL, it returns the result of the hierarchy * creation. If no directory was created, *topmostCreated is set to NULL. * Otherwise *topmostCreated is set to the topmost directory which was * created. *topmostCreated is set even in case of failure. * * The caller most free the resulting string. * * Side effects: * Only the obvious. * *----------------------------------------------------------------------------- */ Bool File_CreateDirectoryHierarchy(const char *pathName, // IN: char **topmostCreated) // OUT/OPT: { return File_CreateDirectoryHierarchyEx(pathName, 0777, topmostCreated); } /* *---------------------------------------------------------------------- * * FileDeleteDirectoryTree -- * * Deletes the specified directory tree. If filesystem errors are * encountered along the way, the function will continue to delete what * it can but will return FALSE. If contentOnly is TRUE it does not * delete the directory itself. * * Results: * TRUE the entire tree was deleted or didn't exist * FALSE otherwise. * * Side effects: * Deletes the directory tree from disk. * *---------------------------------------------------------------------- */ static INLINE Bool FileDeleteDirectoryTree(const char *pathName, // IN: directory to delete Bool contentOnly) // IN: Content only or not { int i; int numFiles; int err = 0; char *base; char **fileList = NULL; Bool sawFileError = FALSE; if (Posix_EuidAccess(pathName, F_OK) != 0) { /* * If Posix_EuidAccess failed with errno == ENOSYS, then fall back * to FileAttributes. */ if (errno == ENOSYS) { /* FileAttributes returns the error code instead of setting errno. */ err = FileAttributes(pathName, NULL); } else { /* Use the error value that was set by Posix_EuidAccess. */ err = errno; } } switch (err) { case ENOENT: case ENOTDIR: /* path does not exist or is inaccessible */ return TRUE; default: break; } /* get list of files in current directory */ numFiles = File_ListDirectory(pathName, &fileList); if (numFiles == -1) { return FALSE; } /* delete everything in the directory */ base = Unicode_Append(pathName, DIRSEPS); for (i = 0; i < numFiles; i++) { char *curPath; struct stat statbuf; curPath = Unicode_Append(base, fileList[i]); if (Posix_Lstat(curPath, &statbuf) == 0) { switch (statbuf.st_mode & S_IFMT) { case S_IFDIR: /* Directory, recurse */ if (!FileDeleteDirectoryTree(curPath, FALSE)) { sawFileError = TRUE; } break; #if !defined(_WIN32) case S_IFLNK: /* Delete symlink, not what it points to */ if (FileDeletion(curPath, FALSE) != 0) { sawFileError = TRUE; } break; #endif default: if (FileDeletion(curPath, FALSE) != 0) { #if defined(_WIN32) if (File_SetFilePermissions(curPath, S_IWUSR)) { if (FileDeletion(curPath, FALSE) != 0) { sawFileError = TRUE; } } else { sawFileError = TRUE; } #else sawFileError = TRUE; #endif } break; } } else { sawFileError = TRUE; } Posix_Free(curPath); } Posix_Free(base); if (!contentOnly) { /* * Call File_DeleteEmptyDirectory() only if there is no prior error * while deleting the children. */ if (!sawFileError && !File_DeleteEmptyDirectory(pathName)) { sawFileError = TRUE; } } Util_FreeStringList(fileList, numFiles); return !sawFileError; } /* *---------------------------------------------------------------------- * * File_DeleteDirectoryContent -- * * Deletes the specified directory content. If filesystem errors are * encountered along the way, the function will continue to delete what * it can but will return FALSE. * * Results: * TRUE the entire content was deleted or there were no files and the * directoy was empty * FALSE otherwise. * * Side effects: * Deletes the directory content from disk. * *---------------------------------------------------------------------- */ Bool File_DeleteDirectoryContent(const char *pathName) // IN: directory to delete { return FileDeleteDirectoryTree(pathName, TRUE); } /* *---------------------------------------------------------------------- * * File_DeleteDirectoryTree -- * * Deletes the specified directory tree. If filesystem errors are * encountered along the way, the function will continue to delete what * it can but will return FALSE. * * Results: * TRUE the entire tree was deleted or didn't exist * FALSE otherwise. * * Side effects: * Deletes the directory tree from disk. * *---------------------------------------------------------------------- */ Bool File_DeleteDirectoryTree(const char *pathName) // IN: directory to delete { return FileDeleteDirectoryTree(pathName, FALSE); } /* *----------------------------------------------------------------------------- * * File_FindFileInSearchPath -- * * Search all the directories in searchPath for a filename. * If searchPath has a relative path take it with respect to cwd. * searchPath must be ';' delimited. * * Results: * TRUE if a file is found. FALSE otherwise. * * Side effects: * If result is non Null allocate a string for the filename found. * *----------------------------------------------------------------------------- */ Bool File_FindFileInSearchPath(const char *fileIn, // IN: const char *searchPath, // IN: const char *cwd, // IN: char **result) // OUT/OPT: { char *cur; char *tok; Bool found; Bool full; char *saveptr = NULL; char *sp = NULL; char *dir = NULL; char *file = NULL; ASSERT(fileIn != NULL); ASSERT(searchPath != NULL); ASSERT(cwd != NULL); /* * First check the usual places - the fullpath or the cwd. */ full = File_IsFullPath(fileIn); if (full) { cur = Util_SafeStrdup(fileIn); } else { cur = Str_SafeAsprintf(NULL, "%s%s%s", cwd, DIRSEPS, fileIn); } if (Posix_EuidAccess(cur, F_OK) == 0) { goto done; } if (errno == ENOSYS && FileAttributes(cur, NULL) == 0) { goto done; } Posix_Free(cur); cur = NULL; if (full) { goto done; } File_GetPathName(fileIn, &dir, &file); /* * Search path applies only if filename is simple basename. */ if (Unicode_LengthInCodePoints(dir) != 0) { goto done; } /* * Didn't find it in the usual places so strip it to its bare minimum and * start searching. */ sp = Util_SafeStrdup(searchPath); tok = strtok_r(sp, FILE_SEARCHPATHTOKEN, &saveptr); while (tok) { if (File_IsFullPath(tok)) { /* Fully Qualified Path. Use it. */ cur = Str_SafeAsprintf(NULL, "%s%s%s", tok, DIRSEPS, file); } else { /* Relative Path. Prepend the cwd. */ if (Str_Strcasecmp(tok, ".") == 0) { /* Don't append "." */ cur = Str_SafeAsprintf(NULL, "%s%s%s", cwd, DIRSEPS, file); } else { cur = Str_SafeAsprintf(NULL, "%s%s%s%s%s", cwd, DIRSEPS, tok, DIRSEPS, file); } } if (Posix_EuidAccess(cur, F_OK) == 0) { break; } if ((errno == ENOSYS) && (FileAttributes(cur, NULL) == 0)) { break; } Posix_Free(cur); cur = NULL; tok = strtok_r(NULL, FILE_SEARCHPATHTOKEN, &saveptr); } done: if (cur) { found = TRUE; if (result) { *result = File_FullPath(cur); if (*result == NULL) { found = FALSE; } } Posix_Free(cur); } else { found = FALSE; } Posix_Free(sp); Posix_Free(dir); Posix_Free(file); return found; } /* *---------------------------------------------------------------------- * * File_ExpandAndCheckDir -- * * Expand any environment variables in the given path and check that * the named directory is writeable. * * Results: * NULL if error, the expanded path otherwise. * * Side effects: * The result is allocated. * *---------------------------------------------------------------------- */ char * File_ExpandAndCheckDir(const char *dirName) // IN: { if (dirName != NULL) { char *edirName = Util_ExpandString(dirName); if ((edirName != NULL) && FileIsWritableDir(edirName)) { size_t len = strlen(edirName) - 1; if (edirName[len] == DIRSEPC) { edirName[len] = '\0'; } return edirName; } } return NULL; } /* *----------------------------------------------------------------------------- * * FileSimpleRandom -- * * Return a random number in the range of 0 and 2^32-1. * * Results: * Random number is returned. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ uint32 FileSimpleRandom(void) { static Atomic_Ptr lckStorage; static rqContext *context = NULL; uint32 result; MXUserExclLock *lck = MXUser_CreateSingletonExclLock(&lckStorage, "fileSimpleRandomLock", RANK_LEAF); MXUser_AcquireExclLock(lck); if (UNLIKELY(context == NULL)) { uint32 value; #if defined(_WIN32) value = GetCurrentProcessId(); #else value = getpid(); #endif context = Random_QuickSeed(value); ASSERT(context != NULL); } result = Random_Quick(context); MXUser_ReleaseExclLock(lck); return result; } /* *---------------------------------------------------------------------- * * FileSleeper * * Sleep for a random amount of time, no less than the specified minimum * and no more than the specified maximum sleep time values. This often * proves useful to "jitter" retries such that multiple threads don't * easily get into resonance performing necessary actions. * * Results: * Somnambulistic behavior; the amount of time slept is returned. * * Side effects: * None * *---------------------------------------------------------------------- */ uint32 FileSleeper(uint32 minSleepTimeMsec, // IN: uint32 maxSleepTimeMsec) // IN: { uint32 variance; uint32 actualSleepTimeMsec; #if defined(_WIN32) uint32 totalSleepTimeMsec; #endif ASSERT(minSleepTimeMsec <= maxSleepTimeMsec); variance = maxSleepTimeMsec - minSleepTimeMsec; if (variance == 0) { actualSleepTimeMsec = minSleepTimeMsec; } else { float fpRand = ((float) FileSimpleRandom()) / ((float) ~((uint32) 0)); actualSleepTimeMsec = minSleepTimeMsec + (uint32) (fpRand * variance); } #if defined(_WIN32) /* Clamp individual sleeps to avoid Windows issues */ totalSleepTimeMsec = actualSleepTimeMsec; while (totalSleepTimeMsec > 0) { uint32 sleepTimeMsec = (totalSleepTimeMsec > 900) ? 900 : totalSleepTimeMsec; Util_Usleep(1000 * sleepTimeMsec); totalSleepTimeMsec -= sleepTimeMsec; } #else Util_Usleep(1000 * actualSleepTimeMsec); #endif return actualSleepTimeMsec; } /* *---------------------------------------------------------------------- * * FileRotateByRename -- * * The oldest indexed file should be removed so that the consequent * rename succeeds. * * The last dst is 'fileName' and should not be deleted. * * Results: * If newFileName is non-NULL: the new path is returned to *newFileName * if the rotation succeeded, otherwise NULL is returned in *newFileName. * The caller is responsible for freeing the string returned in * *newFileName. * * Side effects: * Rename backup old files kept so far. * *---------------------------------------------------------------------- */ static void FileRotateByRename(const char *fileName, // IN: full path to file const char *baseName, // IN: filename w/o extension. const char *ext, // IN: extension int n, // IN: number of old files to keep char **newFileName) // OUT/OPT: new path to file { char *src = NULL; char *dst = NULL; int i; int result; if (newFileName != NULL) { *newFileName = NULL; } for (i = n; i >= 0; i--) { src = (i == 0) ? (char *) fileName : Str_SafeAsprintf(NULL, "%s-%d%s", baseName, i - 1, ext); if (dst == NULL) { result = File_UnlinkIfExists(src); if (result == -1) { Log(LGPFX" %s: failed to remove %s: %s\n", __FUNCTION__, src, Msg_ErrString()); } } else { result = Posix_Rename(src, dst); if (result == -1) { int error = Err_Errno(); if (error != ENOENT) { Log(LGPFX" %s: failed to rename %s -> %s: %s\n", src, dst, __FUNCTION__, Err_Errno2String(error)); } } } if ((src == fileName) && (newFileName != NULL) && (result == 0)) { *newFileName = Util_SafeStrdup(dst); } ASSERT(dst != fileName); Posix_Free(dst); dst = src; } } /* *---------------------------------------------------------------------- * * FileNumberCompare -- * * Helper function for comparing the contents of two * uint32 pointers a and b, suitable for use by qsort * to order an array of file numbers. * * Results: * The contents of 'a' minus the contents of 'b'. * * Side effects: * None. */ static int FileNumberCompare(const void *a, // IN: const void *b) // IN: { return *(uint32 *) a - *(uint32 *) b; } /* *---------------------------------------------------------------------- * * FileRotateByRenumber -- * * File rotation scheme optimized for vmfs: * 1) find highest numbered file (maxNr) * 2) rename . to -. * 3) delete (nFound - numToKeep) lowest numbered files. * * Wrap around is handled incorrectly. * * Results: * If newFilePath is non-NULL: the new path is returned to *newFilePath * if the rotation succeeded, otherwise NULL is returned in *newFilePath. * The caller is responsible for freeing the string returned in * *newFilePath. * * Side effects: * Files renamed / deleted. * *---------------------------------------------------------------------- */ static void FileRotateByRenumber(const char *filePath, // IN: full path to file const char *filePathNoExt, // IN: filename w/o extension. const char *ext, // IN: extension int n, // IN: number old files to keep char **newFilePath) // OUT/OPT: new path to file { char *baseDir = NULL, *fmtString = NULL, *baseName = NULL, *tmp; char *fullPathNoExt = NULL; uint32 maxNr = 0; int i, nrFiles, nFound = 0; char **fileList = NULL; uint32 *fileNumbers = NULL; int result; if (newFilePath != NULL) { *newFilePath = NULL; } fullPathNoExt = File_FullPath(filePathNoExt); if (fullPathNoExt == NULL) { Log(LGPFX" %s: failed to get full path for '%s'.\n", __FUNCTION__, filePathNoExt); goto cleanup; } File_GetPathName(fullPathNoExt, &baseDir, &baseName); if ((baseDir == NULL) || (*baseDir == '\0')) { baseDir = Unicode_Duplicate(DIRSEPS); } if ((baseName == NULL) || (*baseName == '\0')) { Log(LGPFX" %s: failed to get base name for path '%s'.\n", __FUNCTION__, filePathNoExt); goto cleanup; } fmtString = Str_SafeAsprintf(NULL, "%s-%%d%s%%n", baseName, ext); nrFiles = File_ListDirectory(baseDir, &fileList); if (nrFiles == -1) { Log(LGPFX" %s: failed to read the directory '%s'.\n", __FUNCTION__, baseDir); goto cleanup; } fileNumbers = Util_SafeCalloc(nrFiles, sizeof(uint32)); for (i = 0; i < nrFiles; i++) { uint32 curNr; int bytesProcessed = 0; /* * Make sure the whole file name matched what we expect for the file. */ if ((sscanf(fileList[i], fmtString, &curNr, &bytesProcessed) >= 1) && (bytesProcessed == strlen(fileList[i]))) { fileNumbers[nFound++] = curNr; } Posix_Free(fileList[i]); } if (nFound > 0) { qsort(fileNumbers, nFound, sizeof(uint32), FileNumberCompare); maxNr = fileNumbers[nFound - 1]; } /* rename the existing file to the next number */ tmp = Str_SafeAsprintf(NULL, "%s/%s-%d%s", baseDir, baseName, maxNr + 1, ext); result = Posix_Rename(filePath, tmp); if (result == -1) { int error = Err_Errno(); if (error != ENOENT) { Log(LGPFX" %s: failed to rename %s -> %s failed: %s\n", __FUNCTION__, filePath, tmp, Err_Errno2String(error)); } } if (newFilePath == NULL || result == -1) { Posix_Free(tmp); } else { *newFilePath = tmp; } if (nFound >= n) { /* Delete the extra files. */ for (i = 0; i <= nFound - n; i++) { tmp = Str_SafeAsprintf(NULL, "%s/%s-%d%s", baseDir, baseName, fileNumbers[i], ext); if (Posix_Unlink(tmp) == -1) { Log(LGPFX" %s: failed to remove %s: %s\n", __FUNCTION__, tmp, Msg_ErrString()); } Posix_Free(tmp); } } cleanup: Posix_Free(fileNumbers); Posix_Free(fileList); Posix_Free(fmtString); Posix_Free(baseDir); Posix_Free(baseName); Posix_Free(fullPathNoExt); } /* *---------------------------------------------------------------------- * * File_Rotate -- * * Rotate old files. The 'noRename' option is useful for filesystems * where rename is hideously expensive (*cough* vmfs). * * Results: * If newFileName is non-NULL: the new path is returned to * *newFileName if the rotation succeeded, otherwise NULL * is returned in *newFileName. The caller is responsible * for freeing the string returned in *newFileName. * * Side effects: * Files are renamed / deleted. * *---------------------------------------------------------------------- */ void File_Rotate(const char *fileName, // IN: original file int n, // IN: number of backup files Bool noRename, // IN: don't rename all files char **newFileName) // OUT/OPT: new path to file { const char *ext; size_t baseLen; char *baseName; ASSERT(fileName != NULL); if ((ext = Str_Strrchr(fileName, '.')) == NULL) { ext = fileName + strlen(fileName); } baseLen = ext - fileName; /* * Backup base of file name. * * Since the Str_Asprintf(...) doesn't like format of %.*s and crashes * in Windows 2000. (Daniel Liu) */ baseName = Util_SafeStrdup(fileName); baseName[baseLen] = '\0'; if (noRename) { FileRotateByRenumber(fileName, baseName, ext, n, newFileName); } else { FileRotateByRename(fileName, baseName, ext, n, newFileName); } Posix_Free(baseName); } /* *----------------------------------------------------------------------------- * * File_GetFSMountInfo -- * * Platform-independent wrapper around File_GetVMFSMountInfo * * Results: * On failure return -1. Otherwise, return fsType, version, * remoteIP, remoteMountPoint, and localMountPoint. * * Side effects: * None * *----------------------------------------------------------------------------- */ int File_GetFSMountInfo(const char *pathName, char **fsType, uint32 *version, char **remoteIP, char **remoteMountPoint, char **localMountPoint) { #if defined VMX86_SERVER return File_GetVMFSMountInfo(pathName, fsType, version, remoteIP, remoteMountPoint, localMountPoint); #else return -1; #endif } /* *---------------------------------------------------------------------- * * File_ContainSymLink -- * * Check if the specified file path contains symbolic link. * * Results: * return TRUE if pathName contains a symlink, * return FALSE if pathName is not a symlink or error. * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_ContainSymLink(const char *pathName) // IN: { char *path = NULL; char *base = NULL; Bool retValue = FALSE; if (File_IsSymLink(pathName)) { return TRUE; } File_GetPathName(pathName, &path, &base); if ((path != NULL) && (base != NULL) && (strcmp(path, "") != 0) && (strcmp(base, "") != 0)) { if (File_ContainSymLink(path)) { retValue = TRUE; } } Posix_Free(path); Posix_Free(base); return retValue; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/fileIO.c000066400000000000000000000661301321503522500233040ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * fileIO.c -- * * Basic (non internationalized) implementation of error messages for the * Files library. * * File locking/unlocking routines. * */ #include #include #include #include "vmware.h" #include "util.h" #include "fileIO.h" #include "fileLock.h" #include "fileInt.h" #include "msg.h" #include "unicodeOperations.h" #include "hostType.h" #if defined(_WIN32) #include #else #include #include #include #include #include #endif #if defined(VMX86_SERVER) #include "fs_public.h" #endif /* *---------------------------------------------------------------------- * * FileIO_ErrorEnglish -- * * Return the message associated with a status code * * Results: * The message * * Side effects: * None * *---------------------------------------------------------------------- */ const char * FileIO_ErrorEnglish(FileIOResult status) // IN: { return Msg_StripMSGID(FileIO_MsgError(status)); } /* *---------------------------------------------------------------------- * * FileIO_MsgError -- * * Return the message associated with a status code * * Results: * The message. * * Side effects: * None. * *---------------------------------------------------------------------- */ const char * FileIO_MsgError(FileIOResult status) // IN: { const char *result = NULL; switch (status) { case FILEIO_SUCCESS: /* * Most of the time, you don't call this function with this value * because there is no error */ result = MSGID(fileio.success) "Success"; break; case FILEIO_CANCELLED: /* * Most of the time, you don't call this function with this value * because you don't want to display error messages after a user has * cancelled an operation. */ result = MSGID(fileio.cancel) "The operation was cancelled by the user"; break; case FILEIO_ERROR: /* * Most of the time, you don't call this function with this value * because you can call your native function to retrieve a more * accurate message. */ result = MSGID(fileio.generic) "Error"; break; case FILEIO_OPEN_ERROR_EXIST: result = MSGID(fileio.exists) "The file already exists"; break; case FILEIO_LOCK_FAILED: result = MSGID(fileio.lock) "Failed to lock the file"; break; case FILEIO_READ_ERROR_EOF: result = MSGID(fileio.eof) "Tried to read beyond the end of the file"; break; case FILEIO_FILE_NOT_FOUND: result = MSGID(fileio.notfound) "Could not find the file"; break; case FILEIO_NO_PERMISSION: result = MSGID(fileio.noPerm) "Insufficient permission to access the file"; break; case FILEIO_FILE_NAME_TOO_LONG: result = MSGID(fileio.namelong) "The file name is too long"; break; case FILEIO_WRITE_ERROR_FBIG: result = MSGID(fileio.fBig) "The file is too large"; break; case FILEIO_WRITE_ERROR_NOSPC: result = MSGID(fileio.noSpc) "There is no space left on the device"; break; case FILEIO_WRITE_ERROR_DQUOT: result = MSGID(fileio.dQuot) "There is no space left on the device"; break; case FILEIO_ERROR_LAST: NOT_IMPLEMENTED(); break; /* * We do not provide a default case on purpose, so that the compiler can * detect changes in the error set and reminds us to implement the * associated messages --hpreg */ } if (!result) { Warning("%s: bad code %d\n", __FUNCTION__, status); ASSERT(0); result = MSGID(fileio.unknown) "Unknown error"; } return result; } /* *---------------------------------------------------------------------- * * FileIO_Init -- * * Initialize invalid FileIODescriptor. Expects that caller * prepared structure with FileIO_Invalidate. * * Results: * None. * * Side effects: * None * *---------------------------------------------------------------------- */ void FileIO_Init(FileIODescriptor *fd, // IN/OUT: const char *pathName) // IN: { ASSERT(fd != NULL); ASSERT(pathName != NULL); fd->fileName = Unicode_Duplicate(pathName); } /* *---------------------------------------------------------------------- * * FileIO_Cleanup -- * * Undo resource allocation done by FileIO_Init. You do not want to * call this function directly, you most probably want FileIO_Close. * * Results: * None. * * Side effects: * None * *---------------------------------------------------------------------- */ void FileIO_Cleanup(FileIODescriptor *fd) // IN/OUT: { ASSERT(fd != NULL); if (fd->fileName) { Posix_Free(fd->fileName); fd->fileName = NULL; } } /* *---------------------------------------------------------------------- * * FileIOResolveLockBits -- * * Resolve the multitude of lock bits from historical public names * to newer internal names. * * Input flags: FILEIO_OPEN_LOCKED a.k.a. FILEIO_OPEN_LOCK_BEST, * FILEIO_OPEN_EXCLUSIVE_LOCK * Output flags: FILEIO_OPEN_LOCK_MANDATORY, FILEIO_OPEN_LOCK_ADVISORY * * Results: * None * * Side effects: * Only output flags are set in *access. * *---------------------------------------------------------------------- */ void FileIOResolveLockBits(int *access) // IN/OUT: FILEIO_OPEN_* bits { /* * Lock types: * none: no locking at all * advisory: open() ignores lock, FileIO_ respects lock. * mandatory: open() and FileIO_ respect lock. * "best": downgrades to advisory or mandatory based on OS support */ if ((*access & FILEIO_OPEN_EXCLUSIVE_LOCK) != 0) { *access &= ~FILEIO_OPEN_EXCLUSIVE_LOCK; *access |= FILEIO_OPEN_LOCK_MANDATORY; } if ((*access & FILEIO_OPEN_LOCK_BEST) != 0) { /* "Best effort" bit: mandatory if OS supports, advisory otherwise */ *access &= ~FILEIO_OPEN_LOCK_BEST; if (HostType_OSIsVMK()) { *access |= FILEIO_OPEN_LOCK_MANDATORY; } else { *access |= FILEIO_OPEN_LOCK_ADVISORY; } } /* Only one lock type (or none at all) allowed */ ASSERT(((*access & FILEIO_OPEN_LOCK_ADVISORY) == 0) || ((*access & FILEIO_OPEN_LOCK_MANDATORY) == 0)); } /* *---------------------------------------------------------------------- * * FileIO_Lock -- * * Call the FileLock module to lock the given file. * * Results: * FILEIO_ERROR A serious error occured. * FILEIO_SUCCESS All is well * FILEIO_LOCK_FAILED Requested lock on file was not acquired * FILEIO_FILE_NOT_FOUND Unable to find the specified file * FILEIO_NO_PERMISSION Permissions issues * FILEIO_FILE_NAME_TOO_LONG The path name is too long * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Lock(FileIODescriptor *file, // IN/OUT: int access) // IN: { FileIOResult ret = FILEIO_SUCCESS; /* * Lock the file if necessary. */ ASSERT(file != NULL); ASSERT(file->lockToken == NULL); FileIOResolveLockBits(&access); ASSERT((access & FILEIO_OPEN_LOCKED) == 0); #if !defined(__FreeBSD__) && !defined(sun) if ((access & FILEIO_OPEN_LOCK_MANDATORY) != 0) { /* Mandatory file locks are available only when opening a file */ ret = FILEIO_LOCK_FAILED; } else if ((access & FILEIO_OPEN_LOCK_ADVISORY) != 0) { int err = 0; file->lockToken = FileLock_Lock(file->fileName, (access & FILEIO_OPEN_ACCESS_WRITE) == 0, FILELOCK_DEFAULT_WAIT, &err, NULL); if (file->lockToken == NULL) { /* Describe the lock not acquired situation in detail */ Warning(LGPFX" %s on '%s' failed: %s\n", __FUNCTION__, file->fileName, (err == 0) ? "Lock timed out" : Err_Errno2String(err)); /* Return a serious failure status if the locking code did */ switch (err) { case 0: // File is currently locked case EROFS: // Attempt to lock for write on RO FS ret = FILEIO_LOCK_FAILED; break; case ENAMETOOLONG: // Path is too long ret = FILEIO_FILE_NAME_TOO_LONG; break; case ENOENT: // No such file or directory ret = FILEIO_FILE_NOT_FOUND; break; case EACCES: // Permissions issues ret = FILEIO_NO_PERMISSION; break; default: // Some sort of locking error ret = FILEIO_ERROR; } } } #endif // !__FreeBSD__ && !sun return ret; } /* *---------------------------------------------------------------------- * * FileIO_UnLock -- * * Call the FileLock module to unlock the given file. * * Results: * FILEIO_SUCCESS All is well * FILEIO_ERROR A serious error occured. * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Unlock(FileIODescriptor *file) // IN/OUT: { FileIOResult ret = FILEIO_SUCCESS; ASSERT(file != NULL); #if !defined(__FreeBSD__) && !defined(sun) if (file->lockToken != NULL) { int err = 0; if (!FileLock_Unlock(file->lockToken, &err, NULL)) { Warning(LGPFX" %s on '%s' failed: %s\n", __FUNCTION__, file->fileName, Err_Errno2String(err)); ret = FILEIO_ERROR; } file->lockToken = NULL; } #else ASSERT(file->lockToken == NULL); #endif // !__FreeBSD__ && !sun return ret; } /* *---------------------------------------------------------------------- * * FileIO_GetSize -- * * Get size of file. * * Results: * Size of file or -1. * * Side effects: * errno is set on error. * *---------------------------------------------------------------------- */ int64 FileIO_GetSize(const FileIODescriptor *fd) // IN: { int64 logicalBytes; return (FileIO_GetAllocSize(fd, &logicalBytes, NULL) != FILEIO_SUCCESS) ? -1 : logicalBytes; } /* *---------------------------------------------------------------------- * * FileIO_GetSizeByPath -- * * Get size of a file specified by path. * * Results: * Size of file or -1. * * Side effects: * errno is set on error * *---------------------------------------------------------------------- */ int64 FileIO_GetSizeByPath(const char *pathName) // IN: { int64 logicalBytes; return (FileIO_GetAllocSizeByPath(pathName, &logicalBytes, NULL) != FILEIO_SUCCESS) ? -1 : logicalBytes; } /* *---------------------------------------------------------------------- * * FileIO_Filename -- * * Returns the filename that was used to open a FileIODescriptor * * Results: * Filename. You DON'T own the memory - use Unicode_Duplicate if * you want to keep it for yourself. In particular, if the file * gets closed the string will almost certainly become invalid. * * Side effects: * None. * *---------------------------------------------------------------------- */ const char * FileIO_Filename(FileIODescriptor *fd) // IN: { ASSERT(fd != NULL); return fd->fileName; } /* *---------------------------------------------------------------------- * * FileIO_CloseAndUnlink * * Closes and unlinks the file associated with a FileIODescriptor. * * Results: * FILEIO_SUCCESS: The file was closed and unlinked. The FileIODescriptor * is no longer valid. * FILEIO_ERROR: An error occurred. * * Side effects: * File is probably closed and unlinked. * *---------------------------------------------------------------------- */ FileIOResult FileIO_CloseAndUnlink(FileIODescriptor *fd) // IN: { char *path; FileIOResult ret; ASSERT(fd != NULL); ASSERT(FileIO_IsValid(fd)); path = Unicode_Duplicate(fd->fileName); ret = FileIO_Close(fd); if (FileIO_IsSuccess(ret)) { if (File_UnlinkIfExists(path) == -1) { ret = FILEIO_ERROR; } } Posix_Free(path); return ret; } #if defined(_WIN32) || defined(__linux__) || defined(__APPLE__) || \ defined(__FreeBSD__) || defined(sun) /* *---------------------------------------------------------------------- * * FileIO_Pread -- * * Reads from a file starting at a specified offset. * * Note: This function may update the file pointer so you will need to * call FileIO_Seek before calling FileIO_Read/Write afterwards. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Pread(FileIODescriptor *fd, // IN: File descriptor void *buf, // IN: Buffer to read into size_t len, // IN: Length of the buffer uint64 offset) // IN: Offset to start reading { struct iovec iov; ASSERT(fd != NULL); iov.iov_base = buf; iov.iov_len = len; return FileIO_Preadv(fd, &iov, 1, offset, len, NULL); } /* *---------------------------------------------------------------------- * * FileIO_Pwrite -- * * Writes to a file starting at a specified offset. * * Note: This function may update the file pointer so you will need to * call FileIO_Seek before calling FileIO_Read/Write afterwards. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Pwrite(FileIODescriptor *fd, // IN: File descriptor void const *buf, // IN: Buffer to write from size_t len, // IN: Length of the buffer uint64 offset) // IN: Offset to start writing { struct iovec iov; ASSERT(fd != NULL); /* The cast is safe because FileIO_Pwritev() will not write to '*buf'. */ iov.iov_base = (void *)buf; iov.iov_len = len; return FileIO_Pwritev(fd, &iov, 1, offset, len, NULL); } #endif #if defined(sun) && __GNUC__ < 3 /* *----------------------------------------------------------------------------- * * FileIO_IsSuccess -- * * XXX: See comment in fileIO.h. For reasonable compilers, this * function is implemented as "static inline" in fileIO.h; for * unreasonable compilers, it can't be static so we implement it here. * * Results: * TRUE if the input indicates success. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool FileIO_IsSuccess(FileIOResult res) // IN: { return res == FILEIO_SUCCESS; } #endif /* *----------------------------------------------------------------------------- * * FileIO_AtomicTempPath * * Return a temp path name in the same directory as the argument path. * The path is the full path of the source file with a '~' appended. * The caller must free the path when done. * * Results: * UTF8 path if successful, NULL on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ char * FileIO_AtomicTempPath(const char *path) // IN: { char *srcPath; char *retPath; srcPath = File_FullPath(path); if (srcPath == NULL) { Log("%s: File_FullPath of '%s' failed.\n", __FUNCTION__, path); return NULL; } retPath = Unicode_Join(srcPath, "~", NULL); Posix_Free(srcPath); return retPath; } /* *----------------------------------------------------------------------------- * * FileIO_AtomicTempFile * * Create a temp file in the same directory as the argument file. * On non-Windows attempts to create the temp file with the same * permissions and owner/group as the argument file. * * Results: * FileIOResult of call that failed or FILEIO_SUCCESS * * Side effects: * Creates a new file. * *----------------------------------------------------------------------------- */ FileIOResult FileIO_AtomicTempFile(FileIODescriptor *fileFD, // IN: FileIODescriptor *tempFD) // OUT: { char *tempPath = NULL; int permissions; FileIOResult status; #if !defined(_WIN32) int ret; struct stat stbuf; #endif ASSERT(FileIO_IsValid(fileFD)); ASSERT(tempFD && !FileIO_IsValid(tempFD)); tempPath = FileIO_AtomicTempPath(FileIO_Filename(fileFD)); if (tempPath == NULL) { status = FILEIO_ERROR; goto bail; } #if defined(_WIN32) permissions = 0; File_UnlinkIfExists(tempPath); #else if (fstat(fileFD->posix, &stbuf)) { Log("%s: Failed to fstat '%s', errno: %d.\n", __FUNCTION__, FileIO_Filename(fileFD), errno); status = FILEIO_ERROR; goto bail; } permissions = stbuf.st_mode; /* Clean up a previously created temp file; if one exists. */ ret = Posix_Unlink(tempPath); if (ret != 0 && errno != ENOENT) { Log("%s: Failed to unlink temporary file, errno: %d\n", __FUNCTION__, errno); /* Fall through; FileIO_Create will report the actual error. */ } #endif status = FileIO_Create(tempFD, tempPath, FILEIO_ACCESS_READ | FILEIO_ACCESS_WRITE, FILEIO_OPEN_CREATE_SAFE, permissions); if (!FileIO_IsSuccess(status)) { Log("%s: Failed to create temporary file, %s (%d). errno: %d\n", __FUNCTION__, FileIO_ErrorEnglish(status), status, Err_Errno()); goto bail; } #if !defined(_WIN32) /* * On ESX we always use the vmkernel atomic file swap primitive, so * there's no need to set the permissions and owner of the temp file. * * XXX this comment is not true for NFS on ESX -- we use rename rather * than "vmkernel atomic file swap primitive" -- but we do not care * because files are always owned by root. Sigh. Bug 839283. */ if (!HostType_OSIsVMK()) { if (fchmod(tempFD->posix, stbuf.st_mode)) { Log("%s: Failed to chmod temporary file, errno: %d\n", __FUNCTION__, errno); status = FILEIO_ERROR; goto bail; } if (fchown(tempFD->posix, stbuf.st_uid, stbuf.st_gid)) { Log("%s: Failed to chown temporary file, errno: %d\n", __FUNCTION__, errno); status = FILEIO_ERROR; goto bail; } } #endif Posix_Free(tempPath); return FILEIO_SUCCESS; bail: ASSERT(!FileIO_IsSuccess(status)); if (FileIO_IsValid(tempFD)) { FileIO_Close(tempFD); #if defined(_WIN32) File_UnlinkIfExists(tempPath); #else ret = Posix_Unlink(tempPath); if (ret != 0) { Log("%s: Failed to clean up temporary file, errno: %d\n", __FUNCTION__, errno); } ASSERT(ret == 0); #endif } Posix_Free(tempPath); return status; } /* *----------------------------------------------------------------------------- * * FileIO_AtomicUpdateEx -- * * On ESX when the target files reside on vmfs, exchanges the contents * of two files using code modeled from VmkfsLib_SwapFiles. Both "curr" * and "new" are left open. * * On hosted products, uses rename to swap files, so "new" becomes "curr", * and path to "new" no longer exists on success. * * On ESX on NFS: * * If renameOnNFS is TRUE, use rename, like on hosted. * * If renameOnNFS is FALSE, returns -1 rather than trying to use * rename, to avoid various bugs in the vmkernel client... (PR * 839283, PR 1671787, etc). * * On success the caller must call FileIO_IsValid on newFD to verify it * is still open before using it again. * * Results: * 1 if successful, 0 on failure, -1 if not supported on this filesystem. * errno is preserved. * * Side effects: * Disk I/O. * *----------------------------------------------------------------------------- */ int FileIO_AtomicUpdateEx(FileIODescriptor *newFD, // IN/OUT: file IO descriptor FileIODescriptor *currFD, // IN/OUT: file IO descriptor Bool renameOnNFS) // IN: fall back to rename on NFS { char *currPath = NULL; char *newPath = NULL; #if defined(_WIN32) uint32 currAccess; uint32 newAccess; FileIOResult status; FileIODescriptor tmpFD; #else int fd; #endif int savedErrno = 0; int ret = 0; ASSERT(FileIO_IsValid(newFD)); ASSERT(FileIO_IsValid(currFD)); if (HostType_OSIsVMK()) { #if defined(VMX86_SERVER) FS_SwapFilesArgsUW *args = NULL; char *dirName = NULL; char *fileName = NULL; char *dstDirName = NULL; char *dstFileName = NULL; currPath = File_FullPath(FileIO_Filename(currFD)); if (currPath == NULL) { savedErrno = errno; Log("%s: File_FullPath of '%s' failed.\n", __FUNCTION__, FileIO_Filename(currFD)); goto swapdone; } newPath = File_FullPath(FileIO_Filename(newFD)); if (newPath == NULL) { savedErrno = errno; Log("%s: File_FullPath of '%s' failed.\n", __FUNCTION__, FileIO_Filename(newFD)); goto swapdone; } File_GetPathName(newPath, &dirName, &fileName); File_GetPathName(currPath, &dstDirName, &dstFileName); ASSERT(dirName != NULL); ASSERT(fileName && *fileName); ASSERT(dstDirName != NULL); ASSERT(dstFileName && *dstFileName); ASSERT(File_IsSameFile(dirName, dstDirName)); args = Util_SafeCalloc(1, sizeof *args); args->fd = currFD->posix; if (ioctl(newFD->posix, IOCTLCMD_VMFS_SWAP_FILES, args) != 0) { savedErrno = errno; if (errno != ENOSYS && errno != ENOTTY) { Log("%s: ioctl failed %d.\n", __FUNCTION__, errno); ASSERT(errno != EBUSY); /* #615124. */ } } else { ret = 1; } /* * Did we fail because we are on a file system that does not * support the IOCTLCMD_VMFS_SWAP_FILES ioctl? If so fallback to * using rename. * * Check for both ENOSYS and ENOTTY. PR 957695 */ if (savedErrno == ENOSYS || savedErrno == ENOTTY) { if (renameOnNFS) { /* * NFS allows renames of locked files, even if both files * are locked. The file lock follows the file handle, not * the name, so after the rename we can swap the underlying * file descriptors instead of closing and reopening the * target file. * * This is different than the hosted path below because * ESX uses native file locks and hosted does not. * * We assume that all ESX file systems that support rename * have the same file lock semantics as NFS. */ if (File_Rename(newPath, currPath)) { Log("%s: rename of '%s' to '%s' failed %d.\n", __FUNCTION__, newPath, currPath, errno); savedErrno = errno; goto swapdone; } ret = 1; fd = newFD->posix; newFD->posix = currFD->posix; currFD->posix = fd; FileIO_Close(newFD); } else { ret = -1; } } swapdone: Posix_Free(args); Posix_Free(dirName); Posix_Free(fileName); Posix_Free(dstDirName); Posix_Free(dstFileName); Posix_Free(currPath); Posix_Free(newPath); errno = savedErrno; return ret; #else NOT_REACHED(); #endif } #if defined(_WIN32) currPath = Unicode_Duplicate(FileIO_Filename(currFD)); newPath = Unicode_Duplicate(FileIO_Filename(newFD)); newAccess = newFD->flags; currAccess = currFD->flags; FileIO_Close(newFD); /* * The current file needs to be closed and reopened, * but we don't want to drop the file lock by calling * FileIO_Close() on it. Instead, use native close primitives. * We'll reopen it later with FileIO_Open. Set the * descriptor/handle to an invalid value while we're in the * middle of transferring ownership. */ CloseHandle(currFD->win32); currFD->win32 = INVALID_HANDLE_VALUE; if (File_RenameRetry(newPath, currPath, 10) == 0) { ret = TRUE; } else { savedErrno = errno; ASSERT(!ret); } FileIO_Invalidate(&tmpFD); /* * Clear the locking bits from the requested access so that reopening * the file ignores the advisory lock. */ ASSERT((currAccess & FILEIO_OPEN_LOCK_MANDATORY) == 0); currAccess &= ~(FILEIO_OPEN_LOCK_MANDATORY | FILEIO_OPEN_LOCK_ADVISORY | FILEIO_OPEN_LOCK_BEST | FILEIO_OPEN_LOCKED); status = FileIO_Open(&tmpFD, currPath, currAccess, FILEIO_OPEN); if (!FileIO_IsSuccess(status)) { Panic("Failed to reopen dictionary after renaming " "\"%s\" to \"%s\": %s (%d)\n", newPath, currPath, FileIO_ErrorEnglish(status), status); } ASSERT(tmpFD.lockToken == NULL); currFD->win32 = tmpFD.win32; FileIO_Cleanup(&tmpFD); Posix_Free(currPath); Posix_Free(newPath); errno = savedErrno; return ret; #else currPath = (char *)FileIO_Filename(currFD); newPath = (char *)FileIO_Filename(newFD); if (File_Rename(newPath, currPath)) { Log("%s: rename of '%s' to '%s' failed %d.\n", __FUNCTION__, newPath, currPath, errno); savedErrno = errno; } else { ret = TRUE; fd = newFD->posix; newFD->posix = currFD->posix; currFD->posix = fd; FileIO_Close(newFD); } errno = savedErrno; return ret; #endif } /* *----------------------------------------------------------------------------- * * FileIO_AtomicUpdate -- * * Wrapper around FileIO_AtomicUpdateEx that derfaults 'renameOnNFS' to * TRUE. * * Results: * TRUE if successful, FALSE otherwise. * * Side effects: * See FileIO_AtomicUpdateEx. * *----------------------------------------------------------------------------- */ Bool FileIO_AtomicUpdate(FileIODescriptor *newFD, // IN/OUT: file IO descriptor FileIODescriptor *currFD) // IN/OUT: file IO descriptor { return FileIO_AtomicUpdateEx(newFD, currFD, TRUE) == 1; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/fileIOPosix.c000066400000000000000000002363151321503522500243330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * fileIOPosix.c -- * * Implementation of the file library host specific functions for linux. */ #if defined(__linux__) # if !defined(VMX86_TOOLS) && !defined(__ANDROID__) # define FILEIO_SUPPORT_ODIRECT # define _GNU_SOURCE # endif # include #endif #include #include #include #include #if defined __ANDROID__ #include // for __NR_SYSCALL_BASE #endif #include #include #include #include #if defined(__linux__) #ifdef __ANDROID__ # include #else # include #endif #endif #include #include "su.h" #if defined(__APPLE__) #include #include #include #include #include #include #include #include #include #include #include #include #else #if defined(__FreeBSD__) #include #include #else #include #if !defined(__sun__) #include #include #endif #endif #endif /* Check for non-matching prototypes */ #include "vmware.h" #include "str.h" #include "err.h" #include "posix.h" #include "file.h" #include "fileIO.h" #include "fileInt.h" #include "config.h" #include "util.h" #include "iovector.h" #include "hostType.h" #include "unicodeOperations.h" #include "memaligned.h" #include "userlock.h" #include "hostinfo.h" #if defined(__APPLE__) #include #include #endif /* * fallocate() is only supported since the glibc-2.8 and * linux kernel-2.6.23. Presently the glibc in our toolchain is 2.3. */ #if defined(__linux__) #if !defined(SYS_fallocate) #if defined(__i386__) #define SYS_fallocate 324 #elif __x86_64__ #define SYS_fallocate 285 #elif __arm__ #define SYS_fallocate (__NR_SYSCALL_BASE+352) // newer glibc value #endif #endif #if !defined(FALLOC_FL_KEEP_SIZE) #define FALLOC_FL_KEEP_SIZE 1 #endif #endif static const unsigned int FileIO_SeekOrigins[] = { SEEK_SET, SEEK_CUR, SEEK_END, }; static const int FileIO_OpenActions[] = { 0, O_TRUNC, O_CREAT, O_CREAT | O_EXCL, O_CREAT | O_TRUNC, }; /* * Options for FileCoalescing performance optimization */ typedef struct FilePosixOptions { Bool initialized; Bool aligned; Bool enabled; int countThreshold; int sizeThreshold; int aioNumThreads; ssize_t maxIOVec; } FilePosixOptions; static FilePosixOptions filePosixOptions; /* * Data structures for FileIOAligned_* functions; only used on * hosted (see fileInt.h for rationale). */ #if !defined(VMX86_TOOLS) && !defined(VMX86_SERVER) #define ALIGNEDPOOL_FREELIST_SIZE 30 #define ALIGNEDPOOL_BUFSZ (1024 * 1024) #define ALIGNEDPOOL_OLD_AGE ((VmTimeType)1000 * 1000 * 1000) /* nanoseconds */ typedef struct AlignedPool { MXUserExclLock *lock; /* * list: Array of allocated buffers. * 0 .. numBusy-1 : busy buffers (in use by a caller). * numBusy .. numAlloc-1 : allocated but not busy. * numAlloc .. SIZE-1 : unused. */ void *list[ALIGNEDPOOL_FREELIST_SIZE]; /* * timestamp: Array of release timestamps. * 0 .. numBusy-1 : unused. * numBusy .. numAlloc-1 : last time we had N buffers outstanding. * numAlloc .. SIZE-1 : unused. */ VmTimeType timestamp[ALIGNEDPOOL_FREELIST_SIZE]; /* invariant: 0 <= numBusy <= numAlloc <= ALIGNEDPOOL_FREELIST_SIZE */ unsigned numAlloc; unsigned numBusy; } AlignedPool; static Atomic_Ptr alignedPoolLockStorage; static AlignedPool alignedPool; #endif /* * Although, support for preadv()/pwrite() first appeared in Linux 2.6.30, * library support was added in glibc 2.10. Hence these functions * are not available in any header file. */ #if defined(__linux__) && !defined(__ANDROID__) #if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64) /* * We want preadv/pwritev. But due to FOB=64, the symbols are -64. * TODO: when the baseline bumps to XOPEN=700, link directly to * the symbols (and anyone building XOPEN<700 gets nothing). */ extern ssize_t preadv64(int fd, const struct iovec *iov, int iovcnt, __off64_t offset) __attribute__ ((weak)); extern ssize_t pwritev64(int fd, const struct iovec *iov, int iovcnt, __off64_t offset) __attribute__ ((weak)); #else #error "Large file support unavailable. Aborting." #endif #endif /* defined(__linux__) */ /* *----------------------------------------------------------------------------- * * FileIOErrno2Result -- * * Convert a POSIX errno to a FileIOResult code. * * Results: * The FileIOResult corresponding to the errno, FILEIO_ERROR by default. * * Side effects: * None * *----------------------------------------------------------------------------- */ static FileIOResult FileIOErrno2Result(int error) // IN: errno to convert { switch (error) { case EIO: return FILEIO_ERROR; case EEXIST: return FILEIO_OPEN_ERROR_EXIST; case ENOENT: return FILEIO_FILE_NOT_FOUND; case EACCES: return FILEIO_NO_PERMISSION; case ENAMETOOLONG: return FILEIO_FILE_NAME_TOO_LONG; case ENOSPC: return FILEIO_WRITE_ERROR_NOSPC; case EFBIG: return FILEIO_WRITE_ERROR_FBIG; #if defined(VMX86_SERVER) case EBUSY: return FILEIO_LOCK_FAILED; #endif #if defined(EDQUOT) case EDQUOT: return FILEIO_WRITE_ERROR_DQUOT; #endif default: return FILEIO_ERROR; } } /* *---------------------------------------------------------------------- * * FileIO_OptionalSafeInitialize -- * * Initialize global state. If this module is called from a * thread other than the VMX or VCPU threads, like an aioGeneric worker * thread, then we cannot do things like call config. Do that sort * of initialization here, which is called from a safe thread. * * This routine is OPTIONAL if you do not call this module from a * worker thread. The same initialization can be done lazily when * a read/write routine is called. * * Results: * None * * Side effects: * None * *---------------------------------------------------------------------- */ INLINE void FileIO_OptionalSafeInitialize(void) { if (!filePosixOptions.initialized) { filePosixOptions.enabled = Config_GetBool(TRUE, "filePosix.coalesce.enable"); /* * Aligned malloc starts failing to allocate memory during heavy I/O on * Linux. We're not sure why -- maybe we are running out of mmaps? * Turn it off by default for now. */ filePosixOptions.aligned = Config_GetBool(FALSE, "filePosix.coalesce.aligned"); filePosixOptions.countThreshold = Config_GetLong(5, "filePosix.coalesce.count"); filePosixOptions.sizeThreshold = Config_GetLong(16*1024, "filePosix.coalesce.size"); filePosixOptions.aioNumThreads = Config_GetLong(0, "aiomgr.numThreads"); #if defined(__linux__) filePosixOptions.maxIOVec = sysconf(_SC_IOV_MAX); /* Assume unlimited unless sysconf says otherwise. */ if (filePosixOptions.maxIOVec < 0) { filePosixOptions.maxIOVec = MAX_INT32; } #elif defined(__APPLE__) /* * There appears to be no way to determine the iovec size limit at * runtime. If Apple ever changes this, we lose binary compatibility. * On the bright side, Apple has not changed this value for at least as * long as they've produced Intel Macs. */ filePosixOptions.maxIOVec = 1024; #else filePosixOptions.maxIOVec = MAX_INT32; #endif filePosixOptions.initialized = TRUE; FileIOAligned_PoolInit(); } } /* *---------------------------------------------------------------------- * * FileIO_Invalidate -- * * Initialize a FileIODescriptor with an invalid value * * Results: * None * * Side effects: * None * *---------------------------------------------------------------------- */ void FileIO_Invalidate(FileIODescriptor *fd) // OUT: { ASSERT(fd != NULL); (memset)(fd, 0, sizeof *fd); fd->posix = -1; } /* *---------------------------------------------------------------------- * * FileIO_IsValid -- * * Check whether a FileIODescriptor is valid. * * Results: * True if valid. * * Side effects: * None * *---------------------------------------------------------------------- */ Bool FileIO_IsValid(const FileIODescriptor *fd) // IN: { ASSERT(fd != NULL); return fd->posix != -1; } /* *---------------------------------------------------------------------- * * FileIO_CreateFDPosix -- * * This function is for specific needs: for example, when you need * to create a FileIODescriptor from an already open fd. Use only * FileIO_* library functions on the FileIODescriptor from that point on. * * Because FileIODescriptor struct is different on two platforms, * this function is the only one in the file library that's * platform-specific. * * Results: * FileIODescriptor * * Side effects: * None * *---------------------------------------------------------------------- */ FileIODescriptor FileIO_CreateFDPosix(int posix, // IN: UNIX file descriptor int flags) // IN: UNIX access flags { FileIODescriptor fd; FileIO_Invalidate(&fd); switch (flags & O_ACCMODE) { case O_RDWR: fd.flags |= (FILEIO_OPEN_ACCESS_READ | FILEIO_OPEN_ACCESS_WRITE); break; case O_WRONLY: fd.flags |= FILEIO_OPEN_ACCESS_WRITE; break; default: ASSERT(FALSE); /* FALLTHRU */ case O_RDONLY: fd.flags |= FILEIO_OPEN_ACCESS_READ; break; } #if defined(O_SYNC) // Not available in FreeBSD tools build if (flags & O_SYNC) { fd.flags |= FILEIO_OPEN_SYNC; } #endif if (flags & O_APPEND) { fd.flags |= FILEIO_OPEN_APPEND; } #if defined(__linux__) && defined(O_CLOEXEC) if (flags & O_CLOEXEC) { fd.flags |= FILEIO_OPEN_CLOSE_ON_EXEC; } #endif fd.posix = posix; return fd; } #if defined(__APPLE__) /* *---------------------------------------------------------------------- * * ProxySendResults -- * * Send the results of a open from the proxy. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static void ProxySendResults(int sock_fd, // IN: int send_fd, // IN: int send_errno) // IN: { struct iovec iov; struct msghdr msg; char cmsgBuf[CMSG_SPACE(sizeof send_fd)]; iov.iov_base = &send_errno; iov.iov_len = sizeof send_errno; if (send_fd == -1) { msg.msg_control = NULL; msg.msg_controllen = 0; } else { struct cmsghdr *cmsg; msg.msg_control = cmsgBuf; msg.msg_controllen = sizeof cmsgBuf; cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_len = CMSG_LEN(sizeof send_fd); cmsg->cmsg_type = SCM_RIGHTS; (*(int *) CMSG_DATA(cmsg)) = send_fd; msg.msg_controllen = cmsg->cmsg_len; } msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_flags = 0; sendmsg(sock_fd, &msg, 0); } /* *---------------------------------------------------------------------- * * ProxyReceiveResults -- * * Receive the results of an open from the proxy. * * Results: * None * * Side effects: * None * *---------------------------------------------------------------------- */ static void ProxyReceiveResults(int sock_fd, // IN: int *recv_fd, // OUT: int *recv_errno) // OUT: { int err; struct iovec iov; struct msghdr msg; struct cmsghdr *cmsg; uint8_t cmsgBuf[CMSG_SPACE(sizeof(int))]; iov.iov_base = recv_errno; iov.iov_len = sizeof *recv_errno; msg.msg_control = cmsgBuf; msg.msg_controllen = sizeof cmsgBuf; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_iov = &iov; msg.msg_iovlen = 1; err = recvmsg(sock_fd, &msg, 0); if (err <= 0) { *recv_fd = -1; *recv_errno = (err == 0) ? EIO : errno; return; } if (msg.msg_controllen == 0) { *recv_fd = -1; } else { cmsg = CMSG_FIRSTHDR(&msg); if ((cmsg->cmsg_level == SOL_SOCKET) && (cmsg->cmsg_type == SCM_RIGHTS)) { *recv_fd = *((int *) CMSG_DATA(cmsg)); } else { *recv_fd = -1; *recv_errno = EIO; } } } /* *---------------------------------------------------------------------- * * ProxyOpen -- * * Open a file via a proxy. * * Results: * -1 on error * >= 0 on success * * Side effects: * errno is set on error * *---------------------------------------------------------------------- */ static int ProxyOpen(const char *pathName, // IN: int flags, // IN: int mode) // IN: { int err; pid_t pid; int fds[2]; int proxyFD; int saveErrno = 0; if (pathName == NULL) { errno = EFAULT; return -1; } err = socketpair(AF_UNIX, SOCK_DGRAM, 0, fds); if (err == -1) { errno = ENOMEM; // Out of resources... return err; } pid = fork(); if (pid == -1) { proxyFD = -1; saveErrno = ENOMEM; // Out of resources... goto bail; } if (pid == 0) { /* child: use fd[0] */ proxyFD = Posix_Open(pathName, flags, mode); ProxySendResults(fds[0], proxyFD, errno); _exit(0); } else { /* parent: use fd[1] */ ProxyReceiveResults(fds[1], &proxyFD, &saveErrno); waitpid(pid, &err, 0); } bail: close(fds[0]); close(fds[1]); errno = saveErrno; return proxyFD; } /* *---------------------------------------------------------------------- * * ProxyUse -- * * Determine is the open proxy is to be used. * * Results: * 0 Success, useProxy is set * > 0 Failure (errno value); useProxy is undefined * * Side effects: * None * *---------------------------------------------------------------------- */ static int ProxyUse(const char *pathName, // IN: Bool *useProxy) // IN: { char *path; UnicodeIndex index; struct statfs sfbuf; struct stat statbuf; if (pathName == NULL) { errno = EFAULT; return -1; } if ((Posix_Lstat(pathName, &statbuf) == 0) && S_ISLNK(statbuf.st_mode)) { *useProxy = TRUE; return 0; } /* * Construct the path to the directory that contains the filePath. */ index = Unicode_FindLast(pathName, "/"); if (index == UNICODE_INDEX_NOT_FOUND) { path = Unicode_Duplicate("."); } else { char *temp; temp = Unicode_Substr(pathName, 0, index + 1); path = Unicode_Append(temp, "."); Posix_Free(temp); } /* * Attempt to obtain information about the testPath (directory * containing filePath). */ if (Posix_Statfs(path, &sfbuf) == 0) { /* * The testPath exists; determine proxy usage explicitely. */ *useProxy = strcmp(sfbuf.f_fstypename, "nfs") == 0 ? TRUE : FALSE; } else { /* * A statfs error of some sort; Err on the side of caution. */ *useProxy = TRUE; } Posix_Free(path); return 0; } /* *---------------------------------------------------------------------- * * PosixFileOpener -- * * Open a file. Use a proxy when creating a file or on NFS. * * Why a proxy? The Mac OS X 10.4.* NFS client interacts with our * use of settid() and doesn't send the proper credentials on opens. * This leads to files being written without error but containing no * data. The proxy avoids all of this unhappiness. * * Results: * -1 on error * >= 0 on success * * Side effects: * errno is set * *---------------------------------------------------------------------- */ int PosixFileOpener(const char *pathName, // IN: int flags, // IN: mode_t mode) // IN: { Bool useProxy; if ((flags & O_ACCMODE) || (flags & O_CREAT)) { int err; /* * Open for write and/or O_CREAT. Determine proxy usage. */ err = ProxyUse(pathName, &useProxy); if (err != 0) { errno = err; return -1; } } else { /* * No write access, no need for a proxy. */ useProxy = FALSE; } return useProxy ? ProxyOpen(pathName, flags, mode) : Posix_Open(pathName, flags, mode); } #endif /* *---------------------------------------------------------------------- * * FileIOCreateRetry -- * * Open/create a file; specify creation mode * May perform retries to deal with certain OS conditions * * Results: * FILEIO_SUCCESS on success: 'file' is set * FILEIO_OPEN_ERROR_EXIST if the file already exists * FILEIO_FILE_NOT_FOUND if the file is not present * FILEIO_ERROR for other errors * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIOCreateRetry(FileIODescriptor *file, // OUT: const char *pathName, // IN: int access, // IN: FileIOOpenAction action, // IN: int mode, // IN: mode_t for creation uint32 maxWaitTimeMsec) // IN: Ignored { uid_t uid = -1; int fd = -1; int flags = 0; int error; FileIOResult ret; ASSERT(file != NULL); if (pathName == NULL) { errno = EFAULT; return FILEIO_ERROR; } ASSERT(!FileIO_IsValid(file)); ASSERT(file->lockToken == NULL); ASSERT_ON_COMPILE(FILEIO_ERROR_LAST < 16); /* See comment in fileIO.h */ FileIOResolveLockBits(&access); ASSERT((access & FILEIO_OPEN_LOCKED) == 0 && (access & FILEIO_OPEN_EXCLUSIVE_LOCK) == 0); /* Only ESX implements mandatory locking */ ASSERT((access & FILEIO_OPEN_LOCK_MANDATORY) == 0 || File_SupportsMandatoryLock(pathName)); #if defined(__APPLE__) if (access & FILEIO_OPEN_EXCLUSIVE_LOCK_MACOS) { flags |= O_EXLOCK; } #elif defined(__linux__) if (HostType_OSIsVMK()) { if ((access & FILEIO_OPEN_SWMR_LOCK) != 0) { flags |= O_SWMR_LOCK; } else if ((access & FILEIO_OPEN_MULTIWRITER_LOCK) != 0) { flags |= O_MULTIWRITER_LOCK; } else if ((access & FILEIO_OPEN_LOCK_MANDATORY) != 0) { flags |= O_EXCLUSIVE_LOCK; } else if ((access & FILEIO_OPEN_OPTIMISTIC_LOCK) != 0) { flags |= O_OPTIMISTIC_LOCK; } } #endif /* * Locking implementation note: this can be recursive. On ESX: * FileIOCreateRetry("foo", ...ADVISORY...) * -> FileIO_Lock("foo", ...ADVISORY...) * -> FileLock_Lock("foo", ...ADVISORY...) * -> FileIOCreateRetry("foo.lck", ...MANDATORY...) * -> open("foo.lck", ...O_EXCLUSIVE_LOCK...) */ FileIO_Init(file, pathName); /* Mandatory file locks are only available at open() itself */ if ((access & FILEIO_OPEN_LOCK_ADVISORY) != 0) { ret = FileIO_Lock(file, access); if (!FileIO_IsSuccess(ret)) { goto error; } } if ((access & (FILEIO_OPEN_ACCESS_READ | FILEIO_OPEN_ACCESS_WRITE)) == (FILEIO_OPEN_ACCESS_READ | FILEIO_OPEN_ACCESS_WRITE)) { flags |= O_RDWR; } else if (access & FILEIO_OPEN_ACCESS_WRITE) { flags |= O_WRONLY; } else if (access & FILEIO_OPEN_ACCESS_READ) { flags |= O_RDONLY; } if (access & FILEIO_OPEN_EXCLUSIVE_READ && access & FILEIO_OPEN_EXCLUSIVE_WRITE) { flags |= O_EXCL; } if (access & FILEIO_OPEN_UNBUFFERED) { #if defined(FILEIO_SUPPORT_ODIRECT) flags |= O_DIRECT; #elif !defined(__APPLE__) // Mac hosts need this access flag after opening. access &= ~FILEIO_OPEN_UNBUFFERED; LOG_ONCE((LGPFX" %s reverting to buffered IO on %s.\n", __FUNCTION__, pathName)); #endif } if (access & FILEIO_OPEN_NONBLOCK) { flags |= O_NONBLOCK; } if (access & FILEIO_OPEN_APPEND) { flags |= O_APPEND; } #if defined(O_NOFOLLOW) if (access & FILEIO_OPEN_ACCESS_NOFOLLOW) { flags |= O_NOFOLLOW; } #endif #if defined(__linux__) if (access & FILEIO_OPEN_SYNC) { flags |= O_SYNC; } #endif #if defined(O_NOFOLLOW) if (access & FILEIO_OPEN_ACCESS_NOFOLLOW) { flags |= O_NOFOLLOW; } #endif #if defined(__linux__) && defined(O_CLOEXEC) if (flags & FILEIO_OPEN_CLOSE_ON_EXEC) { flags |= O_CLOEXEC; } #endif flags |= FileIO_OpenActions[action]; file->flags = access; if (access & FILEIO_OPEN_PRIVILEGED) { uid = Id_BeginSuperUser(); } fd = PosixFileOpener(pathName, flags, mode); error = errno; if (access & FILEIO_OPEN_PRIVILEGED) { Id_EndSuperUser(uid); } errno = error; if (fd == -1) { ret = FileIOErrno2Result(errno); if (ret == FILEIO_ERROR) { Log(LGPFX "open error on %s: %s\n", pathName, Err_Errno2String(errno)); } goto error; } #if defined(__APPLE__) if (access & (FILEIO_OPEN_UNBUFFERED | FILEIO_OPEN_SYNC)) { error = fcntl(fd, F_NOCACHE, 1); if (error == -1) { ret = FileIOErrno2Result(errno); if (ret == FILEIO_ERROR) { Log(LGPFX "fcntl error on %s: %s\n", pathName, Err_Errno2String(errno)); } goto error; } if (!(access & FILEIO_OPEN_SYNC)) { error = fcntl(fd, F_NODIRECT, 1); if (error == -1) { ret = FileIOErrno2Result(errno); if (ret == FILEIO_ERROR) { Log(LGPFX "fcntl error on %s: %s\n", pathName, Err_Errno2String(errno)); } goto error; } } } #endif if (access & FILEIO_OPEN_DELETE_ASAP) { /* * Remove the name from the name space. The file remains laid out on the * disk and accessible through the file descriptor until it is closed. */ if (Posix_Unlink(pathName) == -1) { ret = FileIOErrno2Result(errno); if (ret == FILEIO_ERROR) { Log(LGPFX "unlink error on %s: %s\n", pathName, Err_Errno2String(errno)); } goto error; } } file->posix = fd; return FILEIO_SUCCESS; error: error = errno; if (fd != -1) { close(fd); } FileIO_Unlock(file); FileIO_Cleanup(file); FileIO_Invalidate(file); errno = error; return ret; } /* *---------------------------------------------------------------------- * * FileIO_CreateRetry -- * * Open/create a file; specify creation mode * * Results: * FILEIO_SUCCESS on success: 'file' is set * FILEIO_OPEN_ERROR_EXIST if the file already exists * FILEIO_FILE_NOT_FOUND if the file is not present * FILEIO_ERROR for other errors * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_CreateRetry(FileIODescriptor *file, // OUT: const char *pathName, // IN: int access, // IN: FileIOOpenAction action, // IN: int mode, // IN: mode_t for creation uint32 maxWaitTimeMsec) // IN: { return FileIOCreateRetry(file, pathName, access, action, mode, maxWaitTimeMsec); } /* *---------------------------------------------------------------------- * * FileIO_Create -- * * Open/create a file; specify creation mode * * Results: * FILEIO_SUCCESS on success: 'file' is set * FILEIO_OPEN_ERROR_EXIST if the file already exists * FILEIO_FILE_NOT_FOUND if the file is not present * FILEIO_ERROR for other errors * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Create(FileIODescriptor *file, // OUT: const char *pathName, // IN: int access, // IN: FileIOOpenAction action, // IN: int mode) // IN: mode_t for creation { return FileIOCreateRetry(file, pathName, access, action, mode, 0); } /* *---------------------------------------------------------------------- * * FileIO_OpenRetry -- * * Open/create a file. * May perform retries to deal with certain OS conditions. * * Results: * FILEIO_SUCCESS on success: 'file' is set * FILEIO_OPEN_ERROR_EXIST if the file already exists * FILEIO_FILE_NOT_FOUND if the file is not present * FILEIO_ERROR for other errors * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_OpenRetry(FileIODescriptor *file, // OUT: const char *pathName, // IN: int access, // IN: FileIOOpenAction action, // IN: uint32 maxWaitTimeMsec) // IN: { #if defined(VMX86_SERVER) FileIOResult res; uint32 waitTimeMsec = 0; uint32 maxLoopTimeMsec = 3000; // 3 seconds /* * Workaround the ESX NFS client bug as seen in PR 1341775. * Since ESX NFS client can sometimes *wrongly* return ESTALE for a * legitimate file open case, we retry for some time in hopes that the * problem will resolve itself. */ while (TRUE) { res = FileIOCreateRetry(file, pathName, access, action, S_IRUSR | S_IWUSR, maxWaitTimeMsec); if (res == FILEIO_ERROR && Err_Errno() == ESTALE && waitTimeMsec < maxLoopTimeMsec) { Log(LGPFX "FileIOCreateRetry (%s) failed with ESTALE, retrying.\n", pathName); waitTimeMsec += FileSleeper(100, 300); } else { break; } } return res; #else return FileIOCreateRetry(file, pathName, access, action, S_IRUSR | S_IWUSR, maxWaitTimeMsec); #endif } /* *---------------------------------------------------------------------- * * FileIO_Open -- * * Open/create a file. * * Results: * FILEIO_SUCCESS on success: 'file' is set * FILEIO_OPEN_ERROR_EXIST if the file already exists * FILEIO_FILE_NOT_FOUND if the file is not present * FILEIO_ERROR for other errors * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Open(FileIODescriptor *file, // OUT: const char *pathName, // IN: int access, // IN: FileIOOpenAction action) // IN: { return FileIO_OpenRetry(file, pathName, access, action, 0); } /* *---------------------------------------------------------------------- * * FileIO_Seek -- * * Change the current position in a file * * Results: * On success: the new current position in bytes from the beginning of * the file * * On failure: -1 * * Side effects: * None * *---------------------------------------------------------------------- */ uint64 FileIO_Seek(const FileIODescriptor *file, // IN: int64 distance, // IN: FileIOSeekOrigin origin) // IN: { ASSERT(file != NULL); #if defined(__ANDROID__) /* * Android doesn't implement _FILE_OFFSET_BITS=64, but always has lseek64. */ return lseek64(file->posix, distance, FileIO_SeekOrigins[origin]); #else /* * Require 64-bit file API support via _FILE_OFFSET_BITS=64 or * operating system default. */ ASSERT_ON_COMPILE(sizeof(off_t) == 8); return lseek(file->posix, distance, FileIO_SeekOrigins[origin]); #endif } /* *---------------------------------------------------------------------- * * FileIO_Write -- * * Write to a file * * Results: * FILEIO_SUCCESS on success: '*actual_count' = 'requested' bytes have * been written. * FILEIO_WRITE_ERROR_FBIG for the attempt to write file that exceeds * maximum file size. * FILEIO_WRITE_ERROR_NOSPC when the device containing the file has no * room for the data. * FILEIO_WRITE_ERROR_DQUOT for attempts to write file that exceeds * user's disk quota. * FILEIO_ERROR for other errors: only '*actual_count' bytes have been * written for sure. * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Write(FileIODescriptor *fd, // IN: const void *bufIn, // IN: size_t requested, // IN: size_t *actual) // OUT: { const uint8 *buf = (const uint8 *)bufIn; size_t initial_requested; FileIOResult fret = FILEIO_SUCCESS; ASSERT(fd != NULL); VERIFY(requested < 0x80000000); initial_requested = requested; while (requested > 0) { ssize_t res; res = write(fd->posix, buf, requested); if (res == -1) { int error = errno; if (error == EINTR) { continue; } fret = FileIOErrno2Result(error); break; } buf += res; requested -= res; } if (actual) { *actual = initial_requested - requested; } return fret; } /* *---------------------------------------------------------------------- * * FileIO_Read -- * * Read from a file * * Results: * FILEIO_SUCCESS on success: '*actual_count' = 'requested' bytes have * been read. * FILEIO_READ_ERROR_EOF if the end of the file was reached: only * '*actual_count' bytes have been read for sure. * FILEIO_ERROR for other errors: only '*actual_count' bytes have been * read for sure. * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Read(FileIODescriptor *fd, // IN: void *bufIn, // OUT: size_t requested, // IN: size_t *actual) // OUT: { uint8 *buf = (uint8 *) bufIn; size_t initial_requested; FileIOResult fret = FILEIO_SUCCESS; ASSERT(fd != NULL); VERIFY(requested < 0x80000000); initial_requested = requested; while (requested > 0) { ssize_t res; res = read(fd->posix, buf, requested); if (res == -1) { if (errno == EINTR) { continue; } fret = FileIOErrno2Result(errno); break; } if (res == 0) { fret = FILEIO_READ_ERROR_EOF; break; } buf += res; requested -= res; } if (actual) { *actual = initial_requested - requested; } return fret; } /* *---------------------------------------------------------------------- * * FileIO_Truncate -- * * Truncates file to a given length * * Results: * Bool - TRUE on success, FALSE on failure * * Side effects: * None * *---------------------------------------------------------------------- */ Bool FileIO_Truncate(FileIODescriptor *file, // IN: uint64 newLength) // IN: { ASSERT(file != NULL); return ftruncate(file->posix, newLength) == 0; } /* *---------------------------------------------------------------------- * * FileIO_Close -- * * Close a file * * Results: * FILEIO_SUCCESS: The file was closed and unlinked. The FileIODescriptor * is no longer valid. * FILEIO_ERROR: An error occurred. * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Close(FileIODescriptor *file) // IN: { int err; ASSERT(file != NULL); err = (close(file->posix) == -1) ? errno : 0; /* Unlock the file if it was locked */ FileIO_Unlock(file); FileIO_Cleanup(file); FileIO_Invalidate(file); if (err) { errno = err; } return (err == 0) ? FILEIO_SUCCESS : FILEIO_ERROR; } /* *---------------------------------------------------------------------- * * FileIO_Sync -- * * Synchronize the disk state of a file with its memory state * * Results: * On success: FILEIO_SUCCESS * On failure: FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Sync(const FileIODescriptor *file) // IN: { ASSERT(file != NULL); return (fsync(file->posix) == -1) ? FILEIO_ERROR : FILEIO_SUCCESS; } /* *----------------------------------------------------------------------------- * * FileIOCoalesce -- * * Linux 2.2 does a fairly braindead thing with ioVec's. It simply issues * reads and writes internal to the kernel in serial * (linux/fs/read_write.c:do_readv_writev()). We optimize here for the * case of many small chunks. The cost of the extra copy in this case * is made up for by the decreased number of separate I/Os the kernel * issues internally. Note that linux 2.4 seems to be smarter with respect * to this problem. * * Results: * Bool - Whether or not coalescing was done. If it was done, * FileIODecoalesce *MUST* be called. * * Side effects: * FileIOCoalesce will malloc *outVec if coalescing is performed * *----------------------------------------------------------------------------- */ static Bool FileIOCoalesce( struct iovec const *inVec, // IN: Vector to coalesce from int inCount, // IN: count for inVec size_t inTotalSize, // IN: totalSize (bytes) in inVec Bool isWrite, // IN: coalesce for writing (or reading) Bool forceCoalesce, // IN: if TRUE always coalesce int flags, // IN: fileIO open flags struct iovec *outVec) // OUT: Coalesced (1-entry) iovec { uint8 *cBuf; ASSERT(inVec != NULL); ASSERT(outVec != NULL); FileIO_OptionalSafeInitialize(); /* simple case: no need to coalesce */ if (inCount == 1) { return FALSE; } /* * Only coalesce when the number of entries is above our count threshold * and the average size of an entry is less than our size threshold */ if (!forceCoalesce && (!filePosixOptions.enabled || inCount <= filePosixOptions.countThreshold || inTotalSize / inCount >= filePosixOptions.sizeThreshold)) { return FALSE; } // XXX: Wouldn't it be nice if we could log from here! //LOG(5, ("FILE: Coalescing %s of %d elements and %d size\n", // isWrite ? "write" : "read", inCount, inTotalSize)); if (filePosixOptions.aligned || flags & FILEIO_OPEN_UNBUFFERED) { cBuf = FileIOAligned_Malloc(sizeof(uint8) * inTotalSize); } else { cBuf = Util_SafeMalloc(sizeof(uint8) * inTotalSize); } if (!cBuf) { return FALSE; } if (isWrite) { IOV_WriteIovToBuf(inVec, inCount, cBuf, inTotalSize); } outVec->iov_base = cBuf; outVec->iov_len = inTotalSize; return TRUE; } /* *----------------------------------------------------------------------------- * * FileIODecoalesce -- * * Inverse of the coalesce optimization. For writes, its a NOOP, but * for reads, it copies the data back into the original buffer. * It also frees the memory allocated by FileIOCoalesce. * * Results: * void * * Side effects: * None * *----------------------------------------------------------------------------- */ static void FileIODecoalesce( struct iovec *coVec, // IN: Coalesced (1-entry) vector struct iovec const *origVec, // IN: Original vector int origVecCount, // IN: count for origVec size_t actualSize, // IN: # bytes to transfer back to origVec Bool isWrite, // IN: decoalesce for writing (or reading) int flags) // IN: fileIO open flags { ASSERT(coVec != NULL); ASSERT(origVec != NULL); ASSERT(actualSize <= coVec->iov_len); ASSERT_NOT_TESTED(actualSize == coVec->iov_len); if (!isWrite) { IOV_WriteBufToIov(coVec->iov_base, actualSize, origVec, origVecCount); } if (filePosixOptions.aligned || flags & FILEIO_OPEN_UNBUFFERED) { FileIOAligned_Free(coVec->iov_base); } else { Posix_Free(coVec->iov_base); } } /* *---------------------------------------------------------------------- * * FileIO_Readv -- * * Wrapper for readv. In linux, we can issue a readv directly. * But the readv is not atomic, i.e, the read can succeed * on the first N vectors, and return a positive value in spite * of the fact that there was an error on the N+1st vector. There * is no way to query the exact error that happened. So, we retry * in a loop (for a max of MAX_RWV_RETRIES). * XXX: If we retried MAX_RWV_RETRIES times and gave up, we will * return FILEIO_ERROR even if errno is undefined. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR, FILEIO_READ_ERROR_EOF * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Readv(FileIODescriptor *fd, // IN: struct iovec const *v, // IN: int numEntries, // IN: size_t totalSize, // IN: size_t *actual) // OUT: { size_t bytesRead = 0, sum = 0; FileIOResult fret = FILEIO_ERROR; int nRetries = 0, maxRetries = numEntries; struct iovec coV; struct iovec const *vPtr; Bool didCoalesce; int numVec; ASSERT(fd != NULL); didCoalesce = FileIOCoalesce(v, numEntries, totalSize, FALSE, FALSE, fd->flags, &coV); VERIFY(totalSize < 0x80000000); numVec = didCoalesce ? 1 : numEntries; vPtr = didCoalesce ? &coV : v; while (nRetries < maxRetries) { ssize_t retval; int tempVec = MIN(filePosixOptions.maxIOVec, numVec); ASSERT(tempVec > 0); retval = readv(fd->posix, vPtr, tempVec); if (retval == -1) { if (errno == EINTR) { continue; } fret = FileIOErrno2Result(errno); break; } bytesRead += retval; if (bytesRead == totalSize) { fret = FILEIO_SUCCESS; break; } if (retval == 0) { fret = FILEIO_READ_ERROR_EOF; break; } /* * Ambigous case. Stupid Linux. If the bytesRead matches an * exact iovector boundary, we need to retry from the next * iovec. 2) If it does not match, EOF is the only error possible. * NOTE: If Linux Readv implementation changes, this * ambiguity handling may need to change. * --Ganesh, 08/15/2001. */ for (; sum < bytesRead; vPtr++, numVec--) { sum += vPtr->iov_len; /* * In each syscall, we will process atleast one iovec * or get an error back. We will therefore retry atmost * count times. If multiple iovecs were processed before * an error hit, we will retry a lesser number of times. */ nRetries++; } if (sum > bytesRead) { // A partially filled iovec can ONLY mean EOF fret = FILEIO_READ_ERROR_EOF; break; } } if (didCoalesce) { FileIODecoalesce(&coV, v, numEntries, bytesRead, FALSE, fd->flags); } if (actual) { *actual = bytesRead; } return fret; } /* *---------------------------------------------------------------------- * * FileIO_Writev -- * * Wrapper for writev. In linux, we can issue a writev directly. * But the writev is not atomic, i.e, the write can succeed * on the first N vectors, and return a positive value in spite * of the fact that there was an error on the N+1st vector. There * is no way to query the exact error that happened. So, we retry * in a loop (for a max of MAX_RWV_RETRIES). * XXX: If we retried MAX_RWV_RETRIES times and gave up, we will * return FILEIO_ERROR even if errno is undefined. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Writev(FileIODescriptor *fd, // IN: struct iovec const *v, // IN: int numEntries, // IN: size_t totalSize, // IN: size_t *actual) // OUT: { size_t bytesWritten = 0, sum = 0; FileIOResult fret = FILEIO_ERROR; int nRetries = 0, maxRetries = numEntries; struct iovec coV; struct iovec const *vPtr; Bool didCoalesce; int numVec; ASSERT(fd != NULL); didCoalesce = FileIOCoalesce(v, numEntries, totalSize, TRUE, FALSE, fd->flags, &coV); VERIFY(totalSize < 0x80000000); numVec = didCoalesce ? 1 : numEntries; vPtr = didCoalesce ? &coV : v; while (nRetries < maxRetries) { ssize_t retval; int tempVec = MIN(filePosixOptions.maxIOVec, numVec); ASSERT(tempVec > 0); retval = writev(fd->posix, vPtr, tempVec); if (retval == -1) { if (errno == EINTR) { continue; } fret = FileIOErrno2Result(errno); break; } bytesWritten += retval; if (bytesWritten == totalSize) { fret = FILEIO_SUCCESS; break; } for (; sum < bytesWritten; vPtr++, numVec--) { sum += vPtr->iov_len; nRetries++; } /* * writev only seems to produce a partial iovec when the disk is * out of space. Just call it an error. --probin */ if (sum != bytesWritten) { fret = FILEIO_WRITE_ERROR_NOSPC; break; } } if (didCoalesce) { FileIODecoalesce(&coV, v, numEntries, bytesWritten, TRUE, fd->flags); } if (actual) { *actual = bytesWritten; } return fret; } #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) ||\ defined(__sun__) /* *---------------------------------------------------------------------- * * FileIOPreadvCoalesced -- * * This function implements vector pread for platforms that do not * support the preadv system call. The incoming vectors are * coalesced to a single buffer to issue only one pread() * system call which reads from a specified offset. The * vectors are then decoalesced before return. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ static FileIOResult FileIOPreadvCoalesced( FileIODescriptor *fd, // IN: File descriptor struct iovec const *entries, // IN: Vector to read into int numEntries, // IN: Number of vector entries uint64 offset, // IN: Offset to start reading size_t totalSize, // IN: totalSize(bytes) in entries size_t *actual) // OUT: number of bytes read { struct iovec const *vPtr; struct iovec coV; int count; uint64 fileOffset; FileIOResult fret; Bool didCoalesce; size_t sum = 0; didCoalesce = FileIOCoalesce(entries, numEntries, totalSize, FALSE, TRUE /* force coalescing */, fd->flags, &coV); count = didCoalesce ? 1 : numEntries; vPtr = didCoalesce ? &coV : entries; fileOffset = offset; while (count > 0) { size_t leftToRead = vPtr->iov_len; uint8 *buf = (uint8 *) vPtr->iov_base; while (leftToRead > 0) { ssize_t retval = pread(fd->posix, buf, leftToRead, fileOffset); if (retval == -1) { if (errno == EINTR) { continue; } fret = FileIOErrno2Result(errno); goto exit; } if (retval == 0) { fret = FILEIO_READ_ERROR_EOF; goto exit; } buf += retval; leftToRead -= retval; sum += retval; fileOffset += retval; } count--; vPtr++; } fret = FILEIO_SUCCESS; exit: if (didCoalesce) { FileIODecoalesce(&coV, entries, numEntries, sum, FALSE, fd->flags); } if (actual) { *actual = sum; } return fret; } /* *---------------------------------------------------------------------- * * FileIOPwritevCoalesced -- * * This function implements vector pwrite for platforms that do not * support the pwritev system call. The incoming vectors are * coalesced to a single buffer to issue only one pwrite() * system call which writes from a specified offset. The * vectors are then decoalesced before return. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ static FileIOResult FileIOPwritevCoalesced( FileIODescriptor *fd, // IN: File descriptor struct iovec const *entries, // IN: Vector to write from int numEntries, // IN: Number of vector entries uint64 offset, // IN: Offset to start writing size_t totalSize, // IN: Total size(bytes) size_t *actual) // OUT: number of bytes written { struct iovec coV; Bool didCoalesce; struct iovec const *vPtr; int count; uint64 fileOffset; FileIOResult fret; size_t sum = 0; didCoalesce = FileIOCoalesce(entries, numEntries, totalSize, TRUE, TRUE /* force coalescing */, fd->flags, &coV); count = didCoalesce ? 1 : numEntries; vPtr = didCoalesce ? &coV : entries; fileOffset = offset; while (count > 0) { size_t leftToWrite = vPtr->iov_len; uint8 *buf = (uint8 *)vPtr->iov_base; while (leftToWrite > 0) { ssize_t retval = pwrite(fd->posix, buf, leftToWrite, fileOffset); if (retval == -1) { if (errno == EINTR) { continue; } fret = FileIOErrno2Result(errno); goto exit; } if (retval == 0) { NOT_TESTED(); fret = FILEIO_WRITE_ERROR_NOSPC; goto exit; } if (retval < leftToWrite) { /* * Using %zd on Android generated a warning about * expecting a "signed size_t" argument; casting retval to * "signed size_t" generated an error, though. We've * already checked for retval == -1 above, so the cast * below should be OK. Refer to bug 817761. */ LOG_ONCE((LGPFX" %s wrote %"FMTSZ"u out of %"FMTSZ"u bytes.\n", __FUNCTION__, (size_t)retval, leftToWrite)); } buf += retval; leftToWrite -= retval; sum += retval; fileOffset += retval; } count--; vPtr++; } fret = FILEIO_SUCCESS; exit: if (didCoalesce) { FileIODecoalesce(&coV, entries, numEntries, sum, TRUE, fd->flags); } if (actual) { *actual = sum; } return fret; } #endif /* defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__sun__) */ #if defined(__linux__) && !defined(__ANDROID__) /* *---------------------------------------------------------------------- * * FileIOPreadvInternal -- * * This function implements vector pread for linux builds. Although, * support for preadv() first appeared in Linux 2.6.30, * library support was added in glibc 2.10. * Hence using weak linkage technique, we try to call the more * optimized preadv system call. If the system does not support * this, we fall back to earlier unoptimized technique. * * Note that in linux, preadv can succeed on the first N vectors, * and return a positive value in spite of the fact that there was * an error on the N+1st vector. There is no way to query the exact * error that happened. So, we retry in a loop (for a max of * MAX_RWV_RETRIES), same as FileIO_Readv(). * * XXX: If we retried MAX_RWV_RETRIES times and gave up, we will * return FILEIO_ERROR even if errno is undefined. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ static FileIOResult FileIOPreadvInternal( FileIODescriptor *fd, // IN: File descriptor struct iovec const *entries, // IN: Vector to read into int numEntries, // IN: Number of vector entries uint64 offset, // IN: Offset to start reading size_t totalSize, // IN: totalSize(bytes) in entries size_t *actual) // OUT: number of bytes read { struct iovec const *vPtr; int numVec; size_t partialBytes = 0; size_t bytesRead = 0; size_t sum = 0; int nRetries = 0; int maxRetries = numEntries; FileIOResult fret = FILEIO_ERROR; FileIO_OptionalSafeInitialize(); numVec = numEntries; vPtr = entries; while (nRetries < maxRetries) { ssize_t retval = 0; ASSERT(numVec > 0); if (preadv64 == NULL) { fret = FileIOPreadvCoalesced(fd, entries, numEntries, offset, totalSize, &bytesRead); break; } else { int tempVec = MIN(filePosixOptions.maxIOVec, numVec); retval = preadv64(fd->posix, vPtr, tempVec, offset); } if (retval == -1) { if (errno == EINTR) { continue; } if (errno == ENOSYS || errno == EINVAL || errno == ENOMEM) { /* * ENOSYS is returned when the kernel does not support preadv and * will be returned the first time we ever call preadv. So, we * can assume that we are not reading partial requests here. * ENOMEM can be due to system call failure and EINVAL is when file * was opened with the O_DIRECT flag and memory is not suitably * aligned. Let's try to read the remaining vectors using the * unoptimized function and hope we don't encounter another error. */ size_t remSize = totalSize - bytesRead; uint64 tempOffset = offset + bytesRead; partialBytes = 0; fret = FileIOPreadvCoalesced(fd, vPtr, numVec, tempOffset, remSize, &partialBytes); break; } fret = FileIOErrno2Result(errno); break; } bytesRead += retval; if (bytesRead == totalSize) { fret = FILEIO_SUCCESS; break; } if (retval == 0) { fret = FILEIO_READ_ERROR_EOF; break; } /* * This is an ambiguous case in linux preadv implementation. * If the bytesRead matches an exact iovector boundary, we need * to retry from the next iovec. However, if it does not match, * EOF is the only error possible. Linux 3.4.4 continues to have * this behaviour. * NOTE: If Linux preadv implementation changes, this * ambiguity handling may need to change. */ for (; sum < bytesRead; vPtr++, numVec--) { sum += vPtr->iov_len; offset += vPtr->iov_len; /* * In each syscall, we will process atleast one iovec * or get an error back. We will therefore retry at most * count times. If multiple iovecs were processed before * an error hit, we will retry a lesser number of times. */ nRetries++; } if (sum > bytesRead) { // A partially filled iovec can ONLY mean EOF fret = FILEIO_READ_ERROR_EOF; break; } } if (actual) { *actual = bytesRead + partialBytes; } return fret; } /* *---------------------------------------------------------------------- * * FileIOPwritevInternal -- * * This function implements vector pwrite for linux builds. Although, * support for pwritev() first appeared in Linux 2.6.30, library * support was added in glibc 2.10. * Hence using weak linkage technique, we try to call the more * optimized pwritev system call. If the system does not support * this, we fall back to earlier unoptimized technique. * * Note that in linux, pwritev can succeed on the first N vectors, * and return a positive value in spite of the fact that there was * an error on the N+1st vector. There is no way to query the exact * error that happened. So, we retry in a loop (for a max of * MAX_RWV_RETRIES), same as FileIO_Writev(). * * XXX: If we retried MAX_RWV_RETRIES times and gave up, we will * return FILEIO_ERROR even if errno is undefined. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ static FileIOResult FileIOPwritevInternal( FileIODescriptor *fd, // IN: File descriptor struct iovec const *entries, // IN: Vector to write from int numEntries, // IN: Number of vector entries uint64 offset, // IN: Offset to start writing size_t totalSize, // IN: Total size(bytes)in entries size_t *actual) // OUT: number of bytes written { struct iovec const *vPtr; int numVec; size_t partialBytes = 0; size_t bytesWritten = 0; size_t sum = 0; int nRetries = 0; int maxRetries = numEntries; FileIOResult fret = FILEIO_ERROR; FileIO_OptionalSafeInitialize(); numVec = numEntries; vPtr = entries; while (nRetries < maxRetries) { ssize_t retval = 0; ASSERT(numVec > 0); if (pwritev64 == NULL) { fret = FileIOPwritevCoalesced(fd, entries, numEntries, offset, totalSize, &bytesWritten); break; } else { int tempVec = MIN(filePosixOptions.maxIOVec, numVec); retval = pwritev64(fd->posix, vPtr, tempVec, offset); } if (retval == -1) { if (errno == EINTR) { continue; } if (errno == ENOSYS || errno == EINVAL || errno == ENOMEM) { /* * ENOSYS is returned when the kernel does not support pwritev and * will be returned the first time we ever call pwritev. So, we * can assume that we are not writing partial requests here. * ENOMEM can be due to system call failure and EINVAL is when file * was opened with the O_DIRECT flag and memory is not suitably * aligned. Let's try writing the remaining vectors using the * unoptimized function and hope we don't encounter another error. */ size_t remSize = totalSize - bytesWritten; uint64 tempOffset = offset + bytesWritten; partialBytes = 0; fret = FileIOPwritevCoalesced(fd, vPtr, numVec, tempOffset, remSize, &partialBytes); break; } fret = FileIOErrno2Result(errno); break; } bytesWritten += retval; if (bytesWritten == totalSize) { fret = FILEIO_SUCCESS; break; } for (; sum < bytesWritten; vPtr++, numVec--) { sum += vPtr->iov_len; offset += vPtr->iov_len; nRetries++; } /* * pwritev produces a partial iovec when the disk is * out of space. Just call it an error. */ if (sum != bytesWritten) { fret = FILEIO_WRITE_ERROR_NOSPC; break; } } if (actual) { *actual = bytesWritten + partialBytes; } return fret; } #endif /* defined(__linux__) && !defined(__ANDROID__) */ #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) ||\ defined(__sun__) /* *---------------------------------------------------------------------- * * FileIO_Preadv -- * * Implementation of vector pread. The function checks for the support * of system call preadv with the version of glibc and calls the * optimized system call. If the system call is not supported, * we fall back to the earlier technique of coalescing the vectors * and calling a single pread and decoalescing again. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Preadv(FileIODescriptor *fd, // IN: File descriptor struct iovec const *entries, // IN: Vector to read into int numEntries, // IN: Number of vector entries uint64 offset, // IN: Offset to start reading size_t totalSize, // IN: totalSize (bytes) in entries size_t *actual) // OUT: number of bytes read { FileIOResult fret; ASSERT(fd != NULL); ASSERT(entries != NULL); ASSERT(!(fd->flags & FILEIO_ASYNCHRONOUS)); VERIFY(totalSize < 0x80000000); #if defined(__linux__) && !defined(__ANDROID__) fret = FileIOPreadvInternal(fd, entries, numEntries, offset, totalSize, actual); #else fret = FileIOPreadvCoalesced(fd, entries, numEntries, offset, totalSize, actual); #endif /* defined(__linux__ ) && !defined(__ANDROID__) */ return fret; } /* *---------------------------------------------------------------------- * * FileIO_Pwritev -- * * Implementation of vector pwrite. The function checks for the support * of system call pwritev with the version of glibc and calls the * optimized system call. If the system call is not supported, * we fall back to the earlier technique of coalescing the vectors and * calling a single pread and decoalescing again. * * Results: * FILEIO_SUCCESS, FILEIO_ERROR * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_Pwritev(FileIODescriptor *fd, // IN: File descriptor struct iovec const *entries, // IN: Vector to write from int numEntries, // IN: Number of vector entries uint64 offset, // IN: Offset to start writing size_t totalSize, // IN: Total size (bytes) in entries size_t *actual) // OUT: number of bytes written { FileIOResult fret; ASSERT(fd != NULL); ASSERT(entries != NULL); ASSERT(!(fd->flags & FILEIO_ASYNCHRONOUS)); VERIFY(totalSize < 0x80000000); #if defined(__linux__) && !defined(__ANDROID__) fret = FileIOPwritevInternal(fd, entries, numEntries, offset, totalSize, actual); #else fret = FileIOPwritevCoalesced(fd, entries, numEntries, offset, totalSize, actual); #endif /* defined(__linux__ ) && !defined(__ANDROID__) */ return fret; } #endif /* defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__sun__) */ /* *---------------------------------------------------------------------- * * FileIO_GetAllocSize -- * * Get logcial and alloced size of a file. * * Results: * FileIOResult. * * Side effects: * None * *---------------------------------------------------------------------- */ FileIOResult FileIO_GetAllocSize(const FileIODescriptor *fd, // IN: uint64 *logicalBytes, // OUT: uint64 *allocedBytes) // OUT: { struct stat statBuf; ASSERT(fd != NULL); if (fstat(fd->posix, &statBuf) == -1) { return FileIOErrno2Result(errno); } if (logicalBytes) { *logicalBytes = statBuf.st_size; } if (allocedBytes) { /* * If you don't like the magic number 512, yell at the people * who wrote sys/stat.h and tell them to add a #define for it. */ *allocedBytes = statBuf.st_blocks * 512; } return FILEIO_SUCCESS; } /* *---------------------------------------------------------------------- * * FileIO_SetAllocSize -- * * Set allocated size of file, allocating new blocks if needed. * It is an error for size to be less than the current size. * * Results: * TRUE on success. Sets errno on failure. * * Side effects: * None. * *---------------------------------------------------------------------- */ Bool FileIO_SetAllocSize(const FileIODescriptor *fd, // IN: uint64 size) // IN: { #if defined(__APPLE__) || defined(__linux__) FileIOResult fret; uint64 curSize; uint64 preallocLen; #if defined(__APPLE__) fstore_t prealloc; #endif fret = FileIO_GetAllocSize(fd, NULL, &curSize); if (!FileIO_IsSuccess(fret)) { return FALSE; } if (curSize > size) { errno = EINVAL; return FALSE; } preallocLen = size - curSize; #if defined(__APPLE__) prealloc.fst_flags = 0; prealloc.fst_posmode = F_PEOFPOSMODE; prealloc.fst_offset = 0; prealloc.fst_length = preallocLen; prealloc.fst_bytesalloc = 0; return fcntl(fd->posix, F_PREALLOCATE, &prealloc) != -1; #elif __linux__ return syscall(SYS_fallocate, fd->posix, FALLOC_FL_KEEP_SIZE, curSize, preallocLen) == 0; #endif #else errno = ENOSYS; return FALSE; #endif } /* *---------------------------------------------------------------------- * * FileIO_GetAllocSizeByPath -- * * Get the logcial and alloced size of a file specified by path. * * Results: * FileIOResult. * * Side effects: * errno is set on error * *---------------------------------------------------------------------- */ FileIOResult FileIO_GetAllocSizeByPath(const char *pathName, // IN: uint64 *logicalBytes, // OUT: uint64 *allocedBytes) // OUT: { struct stat statBuf; if (Posix_Stat(pathName, &statBuf) == -1) { return FileIOErrno2Result(errno); } if (logicalBytes) { *logicalBytes = statBuf.st_size; } if (allocedBytes) { /* * If you don't like the magic number 512, yell at the people * who wrote sys/stat.h and tell them to add a #define for it. */ *allocedBytes = statBuf.st_blocks * 512; } return FILEIO_SUCCESS; } /* *---------------------------------------------------------------------- * * FileIO_Access -- * * Wrapper for access syscall. We return FILEIO_SUCCESS if the file * is accessible with the specified mode. If not, we will return * FILEIO_ERROR. * * Results: * FILEIO_SUCCESS or FILEIO_ERROR. * * Side effects: * errno is set on error * *---------------------------------------------------------------------- */ FileIOResult FileIO_Access(const char *pathName, // IN: Path name. May be NULL. int accessMode) // IN: Access modes to be asserted { int mode = 0; if (pathName == NULL) { errno = EFAULT; return FILEIO_ERROR; } if (accessMode & FILEIO_ACCESS_READ) { mode |= R_OK; } if (accessMode & FILEIO_ACCESS_WRITE) { mode |= W_OK; } if (accessMode & FILEIO_ACCESS_EXEC) { mode |= X_OK; } if (accessMode & FILEIO_ACCESS_EXISTS) { mode |= F_OK; } return (Posix_Access(pathName, mode) == -1) ? FILEIO_ERROR : FILEIO_SUCCESS; } /* *---------------------------------------------------------------------- * * FileIO_GetFlags -- * * Accessor for fd->flags; * * Results: * fd->flags * * Side Effects: * None * *---------------------------------------------------------------------- */ uint32 FileIO_GetFlags(FileIODescriptor *fd) // IN: { ASSERT(fd != NULL); ASSERT(FileIO_IsValid(fd)); return fd->flags; } /* *---------------------------------------------------------------------- * * FileIO_SupportsFileSize -- * * Test whether underlying filesystem supports specified file size. * * Results: * Return TRUE if such file size is supported, FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------- */ Bool FileIO_SupportsFileSize(const FileIODescriptor *fd, // IN: uint64 requestedSize) // IN: { #if defined(__linux__) /* * Linux makes test on seek(), so we can do simple non-intrusive test. * Verified to work on 2.2.x, 2.4.x and 2.6.x, with ext2, ext3, smbfs, * cifs, nfs and ncpfs. Always got some reasonable value. */ Bool supported = FALSE; uint64 oldPos; ASSERT(FileIO_IsValid(fd)); oldPos = FileIO_Seek(fd, 0, FILEIO_SEEK_CURRENT); if (oldPos != (uint64)-1) { uint64 newPos; if (FileIO_Seek(fd, requestedSize, FILEIO_SEEK_BEGIN) == requestedSize) { supported = TRUE; } newPos = FileIO_Seek(fd, oldPos, FILEIO_SEEK_BEGIN); VERIFY(oldPos == newPos); } return supported; #elif defined(__APPLE__) struct statfs buf; if (fstatfs(fd->posix, &buf) == -1) { Log(LGPFX" %s fstatfs failure: %s\n", __FUNCTION__, Err_Errno2String(errno)); /* Be optimistic despite failure */ return TRUE; } /* Check for FAT and UFS file systems */ if ((Str_Strcasecmp(buf.f_fstypename, "msdos") == 0) || (Str_Strcasecmp(buf.f_fstypename, "ufs") == 0)) { /* 4 GB limit */ return requestedSize > CONST64U(0xFFFFFFFF) ? FALSE : TRUE; } /* Be optimistic... */ return TRUE; #else /* Be optimistic on FreeBSD and Solaris... */ return TRUE; #endif } /* *---------------------------------------------------------------------- * * FileIO_GetModTime -- * * Retrieve last modification time. * * Results: * Return POSIX epoch time or -1 on error. * * Side effects: * None. * *---------------------------------------------------------------------- */ int64 FileIO_GetModTime(const FileIODescriptor *fd) // IN: { struct stat statbuf; if (fstat(fd->posix, &statbuf) == 0) { return statbuf.st_mtime; } else { return -1; } } /* *---------------------------------------------------------------------- * * FileIO_PrivilegedPosixOpen -- * * Opens file with elevated privileges. * * Results: * Opened file descriptor, or -1 on failure (errno contains error code). * * Side effects: * None. * *---------------------------------------------------------------------- */ int FileIO_PrivilegedPosixOpen(const char *pathName, // IN: int flags) // IN: { int fd; Bool suDone; uid_t uid = -1; if (pathName == NULL) { errno = EFAULT; return -1; } /* * I've said *opens*. I want you really think twice before creating files * with elevated privileges, so for them you have to use Id_BeginSuperUser() * yourself. */ ASSERT((flags & (O_CREAT | O_TRUNC)) == 0); if (Id_IsSuperUser()) { suDone = FALSE; } else { uid = Id_BeginSuperUser(); suDone = TRUE; } fd = Posix_Open(pathName, flags, 0); if (suDone) { int error = errno; Id_EndSuperUser(uid); errno = error; } return fd; } /* *----------------------------------------------------------------------------- * * FileIO_DescriptorToStream * * Return a FILE * stream equivalent to the given FileIODescriptor. * This is the logical equivalent of Posix dup() then fdopen(). * * Caller should fclose the returned descriptor when finished. * * Results: * !NULL A FILE * associated with the file associated with the fd * NULL Failure * * Side effects: * New fd allocated. * *----------------------------------------------------------------------------- */ FILE * FileIO_DescriptorToStream(FileIODescriptor *fdesc, // IN: Bool textMode) // IN: unused { int dupFD; const char *mode; int tmpFlags; FILE *stream; dupFD = dup(fdesc->posix); if (dupFD == -1) { return NULL; } /* The file you pass us should be valid and opened for *something* */ ASSERT(FileIO_IsValid(fdesc)); ASSERT((fdesc->flags & (FILEIO_OPEN_ACCESS_READ | FILEIO_OPEN_ACCESS_WRITE)) != 0); tmpFlags = fdesc->flags & (FILEIO_OPEN_ACCESS_READ | FILEIO_OPEN_ACCESS_WRITE); if (tmpFlags == (FILEIO_OPEN_ACCESS_READ | FILEIO_OPEN_ACCESS_WRITE)) { mode = "r+"; } else if (tmpFlags == FILEIO_OPEN_ACCESS_WRITE) { mode = "w"; } else { /* therefore (tmpFlags == FILEIO_OPEN_ACCESS_READ) */ mode = "r"; } stream = fdopen(dupFD, mode); if (stream == NULL) { close(dupFD); } return stream; } #if defined(__APPLE__) /* *---------------------------------------------------------------------- * * HostSupportsPrealloc -- * * Returns TRUE if the host OS is new enough to support F_PREALLOCATE * without data loss bugs. On OSX, this has been verified fixed * on 10.6 build with kern.osrelease 10.0.0d6. * * Results: * TRUE if the current host OS is new enough. * FALSE if it is not or we can't tell because of an error. * * Side effects: * None. * *---------------------------------------------------------------------- */ static Bool HostSupportsPrealloc(void) { static Atomic_uint32 supported = { 0 }; enum { PREALLOC_UNKNOWN = 0, PREALLOC_YES, PREALLOC_NO } val; char curRel[32]; char type; unsigned static const int req[] = { 10, 0, 0, 6 }; unsigned int cur[4], i; int num; size_t len = sizeof curRel; Bool ret = FALSE; val = Atomic_Read(&supported); if (val != PREALLOC_UNKNOWN) { return val == PREALLOC_YES; } if (sysctlbyname("kern.osrelease", (void *) &curRel, &len, NULL, 0) == -1) { goto exit; } curRel[31] = '\0'; Log("Current OS Release is %s\n", curRel); /* * Apple's osversion is in the format X.Y.Z which maps to the public * OSX version 10.X-4.Y, and Z is incremented for each publicly * released build. The Z part is of the form AB, where a and * B are version numbers and is either d (devel), a (alpha), * b (beta), rc, or fc. If the B is missing, then its a GA build. * * Since we're checking for 10.0.0d6, we can just say anything without * a type or with a type other than d is higher. For d, we compare * the last number. */ num = sscanf(curRel, "%u.%u.%u%c%u", &cur[0], &cur[1], &cur[2], &type, &cur[3]); if (num < 3) { goto exit; } for (i = 0; i < 3; i++) { if (req[i] > cur[i]) { goto exit; } else if (req[i] < cur[i]) { ret = TRUE; goto exit; } } if (num == 5 && type == 'd') { ret = req[3] <= cur[3]; goto exit; } /* * If we get a type with no letter (num == 4), thats odd. * Consider it mal-formatted and fail. */ ret = num != 4; exit: if (!ret && filePosixOptions.initialized && filePosixOptions.aioNumThreads == 1) { ret = TRUE; } Atomic_Write(&supported, ret ? PREALLOC_YES : PREALLOC_NO); return ret; } #else /* *---------------------------------------------------------------------- * * HostSupportsPrealloc -- * * fallocate() is supported for ext4 and xfs since 2.6.23 kernels * * Results: * TRUE if the current host is linux and kernel is >= 2.6.23. * FALSE if it is not . * * Side effects: * None. * *---------------------------------------------------------------------- */ static Bool HostSupportsPrealloc(void) { #if (defined(__linux__ ) && !defined(VMX86_SERVER)) if (Hostinfo_OSVersion(0) >=2 && Hostinfo_OSVersion(1) >=6 && Hostinfo_OSVersion(2) >=23) { return TRUE; } #endif return FALSE; } #endif /* *---------------------------------------------------------------------------- * * FileIO_SupportsPrealloc -- * * Checks if the HostOS/filesystem supports preallocation. * * Results: * TRUE if supported by the Host OS/filesystem. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool FileIO_SupportsPrealloc(const char *pathName, // IN: Bool fsCheck) // IN: { Bool ret = TRUE; if (!HostSupportsPrealloc()) { return FALSE; } if (!fsCheck) { return ret; } #if (defined( __linux__) && !defined(VMX86_SERVER)) { struct statfs statBuf; char *fullPath; ret = FALSE; if (!pathName) { return ret; } fullPath = File_FullPath(pathName); if (!fullPath) { return ret; } if (Posix_Statfs(fullPath, &statBuf) == 0 && statBuf.f_type == EXT4_SUPER_MAGIC) { ret = TRUE; } Posix_Free(fullPath); } #endif return ret; } /* * The FileIOAligned_* functions are only used on * hosted (see fileInt.h for rationale). */ #if !defined(VMX86_TOOLS) && !defined(VMX86_SERVER) /* *--------------------------------------------------------------------------- * * FileIOAligned_PoolInit -- * * Initialize alignedPool. Must be called before FileIOAligned_PoolMalloc. * * Result: * None. * * Side effects: * None. * *--------------------------------------------------------------------------- */ void FileIOAligned_PoolInit(void) { alignedPool.lock = MXUser_CreateSingletonExclLock(&alignedPoolLockStorage, "alignedPoolLock", RANK_LEAF); } /* *--------------------------------------------------------------------------- * * FileIOAligned_PoolExit -- * * Tear down alignedPool. Afterwards, PoolInit can be called again if * desired. * * Result: * None. * * Side effects: * None. * *--------------------------------------------------------------------------- */ void FileIOAligned_PoolExit(void) { if (!alignedPool.lock) { LOG_ONCE(("%s called without FileIOAligned_Pool lock\n", __FUNCTION__)); return; } MXUser_AcquireExclLock(alignedPool.lock); if (alignedPool.numBusy > 0) { LOG_ONCE(("%s: %d busy buffers! Proceeding with trepidation.\n", __FUNCTION__, alignedPool.numBusy)); } while (alignedPool.numAlloc > 0) { alignedPool.numAlloc--; Aligned_Free(alignedPool.list[alignedPool.numAlloc]); } MXUser_ReleaseExclLock(alignedPool.lock); MXUser_DestroyExclLock(alignedPool.lock); memset(&alignedPool, 0, sizeof alignedPool); } /* *--------------------------------------------------------------------------- * * FileIOAligned_PoolMalloc -- * * Alloc a chunk of memory aligned on a page boundary using a memory * pool. Result needs to be freed with FileIOAligned_PoolFree. Returns * NULL if the pool is full or the requested size cannot be satisfied from * the pool. * * Result: * A pointer. NULL if requested size is too large, or on out of memory * condition. * * Side effects: * None. * *--------------------------------------------------------------------------- */ void * FileIOAligned_PoolMalloc(size_t size) // IN: { void *buf = NULL; if (!alignedPool.lock) { LOG_ONCE(("%s called without FileIOAligned_Pool lock\n", __FUNCTION__)); return NULL; } if (size > ALIGNEDPOOL_BUFSZ) { return NULL; } MXUser_AcquireExclLock(alignedPool.lock); ASSERT(alignedPool.numBusy <= ARRAYSIZE(alignedPool.list)); ASSERT(alignedPool.numAlloc <= ARRAYSIZE(alignedPool.list)); ASSERT(alignedPool.numBusy <= alignedPool.numAlloc); if (alignedPool.numBusy == ARRAYSIZE(alignedPool.list)) { goto done; } if (alignedPool.numBusy == alignedPool.numAlloc) { buf = Aligned_UnsafeMalloc(ALIGNEDPOOL_BUFSZ); /* If allocation fails, just bail. */ if (buf) { alignedPool.list[alignedPool.numAlloc] = buf; alignedPool.numBusy = ++alignedPool.numAlloc; } goto done; } buf = alignedPool.list[alignedPool.numBusy]; alignedPool.numBusy++; done: MXUser_ReleaseExclLock(alignedPool.lock); return buf; } /* *--------------------------------------------------------------------------- * * FileIOAligned_PoolFree -- * * Test if a pointer was allocated from alignedPool, and if so, free it. * * Result: * TRUE if ptr was allocated from alignedPool. ptr is returned to pool. * FALSE otherwise. * * Side effects: * Might Aligned_Free() some entries from alignedPool if the timestamp[] * entries indicate that we have not needed them for a while. * *--------------------------------------------------------------------------- */ Bool FileIOAligned_PoolFree(void *ptr) // IN: { unsigned i; Bool ret = FALSE; VmTimeType now; if (!alignedPool.lock) { LOG_ONCE(("%s called without FileIOAligned_Pool lock\n", __FUNCTION__)); return FALSE; } MXUser_AcquireExclLock(alignedPool.lock); ASSERT(alignedPool.numBusy <= ARRAYSIZE(alignedPool.list)); ASSERT(alignedPool.numAlloc <= ARRAYSIZE(alignedPool.list)); ASSERT(alignedPool.numBusy <= alignedPool.numAlloc); for (i = 0; i < alignedPool.numBusy; i++) { if (alignedPool.list[i] == ptr) { break; } } if (i == alignedPool.numBusy) { /* The pointer wasn't allocated from our pool. */ goto done; } alignedPool.numBusy--; /* * At this point either i points to the "top" busy item, or i points to an * earlier busy item. If i points to the top, we're done, and the following * "swap" is a noop. If i points somewhere further down the busy list, we * can simply move the newly freed item to the top of the free list by * swapping its place with the not-freed item at list[numBusy]. */ alignedPool.list[i] = alignedPool.list[alignedPool.numBusy]; alignedPool.list[alignedPool.numBusy] = ptr; now = Hostinfo_SystemTimerNS(); alignedPool.timestamp[alignedPool.numBusy] = now; while (alignedPool.numAlloc > alignedPool.numBusy && now - alignedPool.timestamp[alignedPool.numAlloc - 1] > ALIGNEDPOOL_OLD_AGE) { alignedPool.numAlloc--; Aligned_Free(alignedPool.list[alignedPool.numAlloc]); alignedPool.list[alignedPool.numAlloc] = NULL; } ret = TRUE; done: MXUser_ReleaseExclLock(alignedPool.lock); return ret; } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/fileInt.h000066400000000000000000000231741321503522500235350ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * fileInt.h -- * * Things internal to the file library. */ #if !defined(__FILE_INTERNAL_H__) #define __FILE_INTERNAL_H__ #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #include "err.h" #include "posix.h" #include "file.h" #include "fileIO.h" #include "fileLock.h" #include "unicodeTypes.h" #include "memaligned.h" /* * Max supported file size is 64 TB. */ #define MAX_SUPPORTED_FILE_SIZE CONST64U(0x400000000000) #if defined __linux__ /* * These magic constants are used only for parsing Linux statfs data. * So they make sense only for Linux build. If you need them on other OSes, * think once more. */ #define ADFS_SUPER_MAGIC 0xadf5 #define AFFS_SUPER_MAGIC 0xADFF #define EXT_SUPER_MAGIC 0x137D #define EXT2_OLD_SUPER_MAGIC 0xEF51 #define EXT2_SUPER_MAGIC 0xEF53 #define EXT3_SUPER_MAGIC 0xEF53 #define EXT4_SUPER_MAGIC 0xEF53 #define HFSPLUS_SUPER_MAGIC 0x482B #define NFS_SUPER_MAGIC 0x6969 #define SMB_SUPER_MAGIC 0x517B #define ISOFS_SUPER_MAGIC 0x9660 #define JFFS2_SUPER_MAGIC 0x72b6 #define PROC_SUPER_MAGIC 0x9fa0 #define OPENPROM_SUPER_MAGIC 0x9fa1 #define USBDEVICE_SUPER_MAGIC 0x9fa2 #define AUTOFS_SUPER_MAGIC 0x0187 #if !defined(MSDOS_SUPER_MAGIC) #define MSDOS_SUPER_MAGIC 0x4D44 #endif #define XENIX_SUPER_MAGIC 0x012FF7B4 #define SYSV4_SUPER_MAGIC 0x012FF7B5 #define SYSV2_SUPER_MAGIC 0x012FF7B6 #define COH_SUPER_MAGIC 0x012FF7B7 #define UFS_SUPER_MAGIC 0x00011954 #define XFS_SUPER_MAGIC 0x58465342 #define VMFS_SUPER_MAGIC 0x2fABF15E #define TMPFS_SUPER_MAGIC 0x01021994 #define JFS_SUPER_MAGIC 0x3153464a #define AFS_SUPER_MAGIC 0x5346414F #define CIFS_SUPER_MAGIC 0xFF534D42 #if !defined(REISERFS_SUPER_MAGIC) #define REISERFS_SUPER_MAGIC 0x52654973 #endif #endif // linux #define LGPFX "FILE:" #define FILE_TYPE_REGULAR 0 #define FILE_TYPE_DIRECTORY 1 #define FILE_TYPE_BLOCKDEVICE 2 #define FILE_TYPE_CHARDEVICE 3 #define FILE_TYPE_SYMLINK 4 #define FILE_TYPE_FIFO 5 #define FILE_TYPE_SOCKET 6 #define FILE_TYPE_UNCERTAIN 7 typedef struct FileData { uint64 fileAccessTime; uint64 fileCreationTime; uint64 fileModificationTime; uint64 fileSize; int fileType; int fileMode; int fileOwner; int fileGroup; } FileData; #define FILE_MAX_WAIT_TIME_MS 2000 // maximum wait time in milliseconds void FileIOResolveLockBits(int *access); #if defined(_WIN32) int FileMapErrorToErrno(const char *functionName, Err_Number status); Bool FileRetryThisError(DWORD error, uint32 numCodes, DWORD *codes); int FileAttributesRetry(const char *pathName, uint32 maxWaitTimeMsec, FileData *fileData); int FileDeletionRetry(const char *pathName, Bool handleLink, uint32 maxWaitTimeMsec); int FileCreateDirectoryRetry(const char *pathName, int mask, uint32 maxWaitTimeMsec); int FileRemoveDirectoryRetry(const char *pathName, uint32 maxWaitTimeMsec); int FileListDirectoryRetry(const char *pathName, uint32 maxWaitTimeMsec, char ***ids); #define FileAttributes(a, b) FileAttributesRetry((a), 0, (b)) #define FileDeletion(a, b) FileDeletionRetry((a), (b), 0) #define FileCreateDirectory(a, b) FileCreateDirectoryRetry((a), (b), 0) #define FileRemoveDirectory(a) FileRemoveDirectoryRetry((a), 0) #define FileListDirectoryRobust(a, b) \ FileListDirectoryRetry((a), FILE_MAX_WAIT_TIME_MS, (b)) #define FileAttributesRobust(a, b) \ FileAttributesRetry((a), FILE_MAX_WAIT_TIME_MS, (b)) #define FileRenameRobust(a, b) \ File_RenameRetry((a), (b), FILE_MAX_WAIT_TIME_MS) #define FileDeletionRobust(a, b) \ FileDeletionRetry((a), (b), FILE_MAX_WAIT_TIME_MS) #define FileCreateDirectoryRobust(a, b) \ FileCreateDirectoryRetry((a), (b), FILE_MAX_WAIT_TIME_MS) #define FileRemoveDirectoryRobust(a) \ FileRemoveDirectoryRetry((a), FILE_MAX_WAIT_TIME_MS) #else static INLINE int FileMapErrorToErrno(const char *functionName, Err_Number status) { return status; } char *FilePosixGetBlockDevice(char const *path); int FileAttributes(const char *pathName, FileData *fileData); int FileDeletion(const char *pathName, Bool handleLink); int FileCreateDirectory(const char *pathName, int mask); int FileRemoveDirectory(const char *pathName); #define FileListDirectoryRobust(a, b) File_ListDirectory((a), (b)) #define FileAttributesRobust(a, b) FileAttributes((a), (b)) #define FileRenameRobust(a, b) File_Rename((a), (b)) #define FileDeletionRobust(a, b) FileDeletion((a), (b)) #define FileCreateDirectoryRobust(a, b) FileCreateDirectory((a), (b)) #define FileRemoveDirectoryRobust(a) FileRemoveDirectory((a)) #endif typedef struct active_lock { struct active_lock *next; uint32 age; Bool marked; char *dirName; } ActiveLock; typedef struct lock_values { char *machineID; char *executionID; char *lockType; char *locationChecksum; char *memberName; unsigned int lamportNumber; Bool exclusivity; VmTimeType startTimeMsec; uint32 maxWaitTimeMsec; ActiveLock *lockList; } LockValues; #include "file_extensions.h" #define FILELOCK_SUFFIX "." LOCK_FILE_EXTENSION #define FILELOCK_DATA_SIZE 512 uint32 FileSleeper(uint32 minSleepTimeMsec, uint32 maxSleepTimeMsec); uint32 FileSimpleRandom(void); const char *FileLockGetMachineID(void); char *FileLockGetExecutionID(void); Bool FileLockMachineIDMatch(const char *host, const char *second); int FileLockMemberValues(const char *lockDir, const char *fileName, char *buffer, size_t size, LockValues *memberValues); FileLockToken *FileLockIntrinsic(const char *filePathName, Bool exclusivity, uint32 maxWaitTimeMsec, int *err); int FileUnlockIntrinsic(FileLockToken *tokenPtr); Bool FileLockIsLocked(const char *filePath, int *err); Bool FileLockValidExecutionID(const char *executionID); Bool FileLockValidName(const char *fileName); void FileLockAppendMessage(MsgList **msgs, int err); Bool FileIsWritableDir(const char *dirName); FileIOResult FileIOCreateRetry(FileIODescriptor *fd, const char *pathName, int access, FileIOOpenAction action, int mode, uint32 maxWaitTimeMsec); /* * FileIOAligned_* are useful on hosted platforms where malloc/memalign/valloc * for "large buffers" (in the range 64 KiB - 1 MiB) will generally fall * through to mmap/munmap, which is expensive due to page table modifications * and the attendant TLB flushing (which requires IPIs and possibly world * switches) on other threads running in the same address space. In particular, * on Mac OS 10.6.6 on a Westmere-class Mac Pro, mmap + memcpy + munmap adds * around a millisecond of CPU time and a hundred IPIs to a 512 KiB write. See * PR#685845. * * This isn't applicable to ESX because * 1. we don't use this path for disk IO * 2. we don't want to do extra large allocations * 3. we don't have the same alignment constraints * so simply define it away to nothing. * * Tools is another case, we can use this path for IO but we don't want to add * MXUserExclLock dependencies. */ #if defined(VMX86_TOOLS) || defined(VMX86_SERVER) #define FileIOAligned_PoolInit() /* nothing */ #define FileIOAligned_PoolExit() /* nothing */ #define FileIOAligned_PoolMalloc(sz) NULL #define FileIOAligned_PoolFree(ptr) FALSE #else void FileIOAligned_PoolInit(void); void FileIOAligned_PoolExit(void); void *FileIOAligned_PoolMalloc(size_t); Bool FileIOAligned_PoolFree(void *); #endif static INLINE void * FileIOAligned_Malloc(size_t sz) // IN: { void *buf = FileIOAligned_PoolMalloc(sz); if (!buf) { buf = Aligned_Malloc(sz); } return buf; } static INLINE void FileIOAligned_Free(void *ptr) // IN: { if (!FileIOAligned_PoolFree(ptr)) { Aligned_Free(ptr); } } #if defined(__APPLE__) int PosixFileOpener(const char *pathName, int flags, mode_t mode); #else #define PosixFileOpener(a, b, c) Posix_Open(a, b, c); #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/fileLockPosix.c000066400000000000000000000735451321503522500247200ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * fileLockPosix.c -- * * Interface to host-specific locking function for Posix hosts. */ #include #include #include #include /* Needed before sys/vfs.h with glibc 2.0 --hpreg */ #if !defined(__FreeBSD__) #if defined(__APPLE__) #include #include #include #include #else #include #endif #endif #include #include #include #include #include #include #include "vmware.h" #include "posix.h" #include "file.h" #include "fileIO.h" #include "fileLock.h" #include "fileInt.h" #include "util.h" #include "str.h" #include "err.h" #include "localconfig.h" #include "hostinfo.h" #include "su.h" #include "hostType.h" #include "unicodeOperations.h" #define LOGLEVEL_MODULE main #include "loglevel_user.h" #define DEVICE_LOCK_DIR "/var/lock" #define LOG_MAX_PROC_NAME 64 /* * XXX * Most of these warnings must be turned back into Msg_Appends, or the * equivalent. They were changed from Msg_Appends to Warnings to facilitate * integration in the disklib library, but many of the warnings are very * important, and should be presented directly to the user, not go silently * into the log file. */ #if !defined(__FreeBSD__) && !defined(sun) /* *---------------------------------------------------------------------- * * IsLinkingAvailable -- * * Check if linking is supported in the filesystem where we create * the lock file. * * Results: * TRUE is we're sure it's supported. FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------- */ static Bool IsLinkingAvailable(const char *fileName) // IN: { struct statfs buf; int status; ASSERT(fileName != NULL); /* * Don't use linking on ESX/VMFS... the overheads are expensive and this * path really isn't used. */ if (HostType_OSIsVMK()) { return FALSE; } status = statfs(fileName, &buf); if (status == -1) { Log(LGPFX" Bad statfs using %s (%s).\n", fileName, Err_Errno2String(errno)); return FALSE; } #if defined(__APPLE__) if ((Str_Strcasecmp(buf.f_fstypename, "hfs") == 0) || (Str_Strcasecmp(buf.f_fstypename, "nfs") == 0) || (Str_Strcasecmp(buf.f_fstypename, "ufs") == 0)) { return TRUE; } if ((Str_Strcasecmp(buf.f_fstypename, "smbfs") != 0) && (Str_Strcasecmp(buf.f_fstypename, "afpfs") != 0)) { Log(LGPFX" Unknown filesystem '%s'. Using non-linking file locking.\n", buf.f_fstypename); } #else /* consult "table" of known filesystem types */ switch (buf.f_type) { case AFFS_SUPER_MAGIC: case EXT_SUPER_MAGIC: case EXT2_OLD_SUPER_MAGIC: case EXT2_SUPER_MAGIC: // EXT3_SUPER_MAGIC is EXT2_SUPER_MAGIC case HFSPLUS_SUPER_MAGIC: case NFS_SUPER_MAGIC: case XENIX_SUPER_MAGIC: case SYSV4_SUPER_MAGIC: case SYSV2_SUPER_MAGIC: case COH_SUPER_MAGIC: case UFS_SUPER_MAGIC: case REISERFS_SUPER_MAGIC: case XFS_SUPER_MAGIC: case TMPFS_SUPER_MAGIC: case JFS_SUPER_MAGIC: return TRUE; // these are known to work case SMB_SUPER_MAGIC: case MSDOS_SUPER_MAGIC: return FALSE; } /* * Nothing is known about this filesystem. Play it safe and use * non-link based locking. */ Warning(LGPFX" Unknown filesystem 0x%x. Using non-linking locking.\n", (unsigned int) buf.f_type); #endif return FALSE; } /* *---------------------------------------------------------------------- * * RemoveStaleLockFile -- * * Remove a stale lock file. * * Results: * TRUE on success. * * Side effects: * Unlink file. * *---------------------------------------------------------------------- */ static Bool RemoveStaleLockFile(const char *lockFileName) // IN: { uid_t uid; int ret; int saveErrno; ASSERT(lockFileName != NULL); /* stale lock */ Log(LGPFX" Found a previous instance of lock file '%s'. " "It will be removed automatically.\n", lockFileName); uid = Id_BeginSuperUser(); ret = unlink(lockFileName); saveErrno = errno; Id_EndSuperUser(uid); if (ret < 0) { Warning(LGPFX" Failed to remove stale lock file %s (%s).\n", lockFileName, Err_Errno2String(saveErrno)); return FALSE; } return TRUE; } /* *---------------------------------------------------------------------- * * GetLockFileValues -- * * Get host name and PID of locking process. * * Results: * 1 on success, 0 if file doesn't exist, -1 for all other errors. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int GetLockFileValues(const char *lockFileName, // IN: int *pid, // OUT: char *hostID) // OUT: { char *p; int saveErrno; FILE *lockFile; char line[1000]; Bool deleteLockFile; uid_t uid; int status; ASSERT(lockFileName != NULL); ASSERT(pid != NULL); ASSERT(hostID != NULL); uid = Id_BeginSuperUser(); lockFile = Posix_Fopen(lockFileName, "r"); saveErrno = errno; Id_EndSuperUser(uid); if (lockFile == NULL) { Warning(LGPFX" Failed to open existing lock file %s (%s).\n", lockFileName, Err_Errno2String(saveErrno)); return (saveErrno == ENOENT) ? 0 : -1; } p = fgets(line, sizeof line, lockFile); saveErrno = errno; fclose(lockFile); if (p == NULL) { Warning(LGPFX" Failed to read line from lock file %s (%s).\n", lockFileName, Err_Errno2String(saveErrno)); deleteLockFile = TRUE; } else { switch (sscanf(line, "%d %999s", pid, hostID)) { case 2: // Everything is OK deleteLockFile = FALSE; break; case 1: default: Warning(LGPFX" Badly formatted lock file %s.\n", lockFileName); deleteLockFile = TRUE; } } status = 1; if (deleteLockFile) { status = 0; // we're going to delete the file if (!RemoveStaleLockFile(lockFileName)) { status = -1; } } return status; } /* *---------------------------------------------------------------------- * * FileLockIsValidProcess -- * * Determine if the process, via its pid, is valid (alive). * * Results: * TRUE Yes * FALSE No * * Side effects: * None. * *---------------------------------------------------------------------- */ static Bool FileLockIsValidProcess(int pid) // IN: { HostinfoProcessQuery value = Hostinfo_QueryProcessExistence(pid); if (value == HOSTINFO_PROCESS_QUERY_UNKNOWN) { return TRUE; // Err on the side of caution } return (value == HOSTINFO_PROCESS_QUERY_ALIVE) ? TRUE : FALSE; } /* *---------------------------------------------------------------------- * * FileLockCreateLockFile -- * * Create a new lock file, either via a O_EXCL creat() call or * through the linking method. * * Results: * 1 if we created our lock file successfully. * 0 if we should retry the creation. * -1 if the process failed. * * Side effects: * Change the host file system. * *---------------------------------------------------------------------- */ static int FileLockCreateLockFile(const char *lockFileName, // IN: const char *lockFileLink, // IN: const char *uniqueID) // IN: { int err; int lockFD; int status = 1; int saveErrno; Bool useLinking = IsLinkingAvailable(lockFileName); uid_t uid; if (useLinking) { uid = Id_BeginSuperUser(); lockFD = creat(lockFileLink, 0444); saveErrno = errno; Id_EndSuperUser(uid); if (lockFD == -1) { Log(LGPFX" Failed to create new lock file %s (%s).\n", lockFileLink, Err_Errno2String(saveErrno)); return (saveErrno == EEXIST) ? 0 : -1; } } else { /* * XXX * Note that this option is racy, at least for SMB and FAT32 file * systems. It appears, however, that by using a temporary lock * file before getting the real, persistent lock file, the race * can be eliminated. -- johnh */ uid = Id_BeginSuperUser(); lockFD = Posix_Open(lockFileName, O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); saveErrno = errno; Id_EndSuperUser(uid); if (lockFD == -1) { Log(LGPFX" Failed to create new lock file %s (%s).\n", lockFileName, Err_Errno2String(saveErrno)); return (saveErrno == EEXIST) ? 0 : -1; } } err = write(lockFD, uniqueID, strlen(uniqueID)); saveErrno = errno; close(lockFD); if (err != strlen(uniqueID)) { Warning(LGPFX" Failed to write to new lock file %s (%s).\n", lockFileName, Err_Errno2String(saveErrno)); status = -1; goto exit; } uid = Id_BeginSuperUser(); if (useLinking && (link(lockFileLink, lockFileName) < 0)) { status = (errno == EEXIST) ? 0 : -1; } Id_EndSuperUser(uid); exit: if (useLinking) { uid = Id_BeginSuperUser(); err = unlink(lockFileLink); Id_EndSuperUser(uid); if (err < 0) { Warning(LGPFX" Failed to remove temporary lock file %s (%s).\n", lockFileLink, Err_Errno2String(errno)); } } return status; } /* *---------------------------------------------------------------------- * * FileLock_LockDevice -- * * Lock with a file. Detect and remove stale locks * when possible. * * Results: * 1 if got the lock, 0 if not, -1 for errors. * * Side effects: * Change the host file system. * * Note: * This locking method remains due to "minicom" and similar * programs that use this locking method for access serialization * of serial ports. * *---------------------------------------------------------------------- */ int FileLock_LockDevice(const char *deviceName) // IN: { const char *hostID; char uniqueID[1000]; char *lockFileName; char *lockFileLink; int status = -1; ASSERT(deviceName != NULL); lockFileName = Str_SafeAsprintf(NULL, "%s/LCK..%s", DEVICE_LOCK_DIR, deviceName); lockFileLink = Str_SafeAsprintf(NULL, "%s/LTMP..%s.t%05d", DEVICE_LOCK_DIR, deviceName, getpid()); LOG(1, ("Requesting lock %s (temp = %s).\n", lockFileName, lockFileLink)); hostID = FileLockGetMachineID(); Str_Sprintf(uniqueID, sizeof uniqueID, "%d %s\n", getpid(), hostID); while ((status = FileLockCreateLockFile(lockFileName, lockFileLink, uniqueID)) == 0) { int pid; char fileID[1000]; /* * The lock file already exists. See if it is a stale lock. * * We retry the link if the file is gone now (0 return). */ switch (GetLockFileValues(lockFileName, &pid, fileID)) { case 1: break; case 0: continue; case -1: status = -1; goto exit; default: NOT_REACHED(); } if (strcmp(hostID, fileID) != 0) { /* Lock was acquired by a different host. */ status = 0; goto exit; } if (FileLockIsValidProcess(pid)) { status = 0; goto exit; } /* stale lock */ if (!RemoveStaleLockFile(lockFileName)) { status = -1; goto exit; } /* TRY AGAIN */ } exit: Posix_Free(lockFileName); Posix_Free(lockFileLink); return status; } /* *---------------------------------------------------------------------- * * FileLock_UnlockDevice -- * * Unlock a lock obtained by FileLock_LockDevice. * * Results: * True if successful, FALSE otherwise. * * Side effects: * Change the host file system. * *---------------------------------------------------------------------- */ Bool FileLock_UnlockDevice(const char *deviceName) // IN: { uid_t uid; int ret; int saveErrno; char *path; ASSERT(deviceName != NULL); path = Str_SafeAsprintf(NULL, "%s/LCK..%s", DEVICE_LOCK_DIR, deviceName); LOG(1, ("Releasing lock %s.\n", path)); uid = Id_BeginSuperUser(); ret = unlink(path); saveErrno = errno; Id_EndSuperUser(uid); if (ret < 0) { Log(LGPFX" Cannot remove lock file %s (%s).\n", path, Err_Errno2String(saveErrno)); Posix_Free(path); return FALSE; } Posix_Free(path); return TRUE; } /* *---------------------------------------------------------------------- * * FileLockAppendMessage -- * * Append a detailed error message to the MsgList. * * Results: * As above * * Side effects: * Memory is allocated * *---------------------------------------------------------------------- */ void FileLockAppendMessage(MsgList **msgs, // IN/OUT/OPT: int err) // IN: errno { #if defined(VMX86_TOOLS) Log(LGPFX "A file locking error (%d) has occurred: %s.", err, Err_Errno2String(err)); #else MsgList_Append(msgs, MSGID(fileLock.posix) "A file locking error (%d) has occurred: %s.", err, Err_Errno2String(err)); #endif } #if defined(__linux__) /* *---------------------------------------------------------------------- * * FileReadSlashProc -- * * Read the data in a /proc file * * Results: * 0 Data is available * !0 Error (errno) * * Side effects: * None. * *---------------------------------------------------------------------- */ static int FileReadSlashProc(const char *procPath, // IN: char *buffer, // OUT: size_t bufferSize) // IN: { int fd; int err; char *p; size_t len; ASSERT(procPath != NULL); ASSERT(buffer != NULL); ASSERT(bufferSize > 0); fd = Posix_Open(procPath, O_RDONLY, 0); if (fd == -1) { return errno; } len = read(fd, buffer, bufferSize - 1); err = errno; close(fd); if (len == -1) { return err; } buffer[len] = '\0'; p = strchr(buffer, '\n'); if (p != NULL) { *p = '\0'; } return 0; } /* *--------------------------------------------------------------------------- * * FileLockProcessDescriptor -- * * Returns the process descriptor of the specified process. * * The format of a process descriptor is as follows: * * processID-processCreationTime(processName) * * where the processName and processCreationTime information * may be independently optional. * * Results: * NULL The process does not exist. * !NULL The process descriptor is returned. It is the callers * responsibility to free the dynamically allocated memory. * * Side Effects: * None * *--------------------------------------------------------------------------- */ static char * FileLockProcessDescriptor(pid_t pid) // IN: { char path[64]; char buffer[1024]; char *descriptor = NULL; if (!FileLockIsValidProcess(pid)) { return NULL; } Str_Sprintf(path, sizeof path, "/proc/%d/stat", pid); if (FileReadSlashProc(path, buffer, sizeof buffer) == 0) { char *p; char *q; char *rest; uint32 argc; char *argv[22]; char *savePtr = NULL; /* * You are in a maze of twisty little fields, (virtually) all alike... * * The process creation time, in 64-bit jiffies is "out there". * * A "man 5 proc" will provide illumination concerning all of the * fields found on this line of text. We code for the worst case * and ensure that file names containing spaces or parens are * properly handled. */ p = strchr(buffer, '('); if ((p == NULL) || (p == buffer) || (*(p - 1) != ' ')) { goto bail; } *(p - 1) = '\0'; q = strrchr(p + 1, ')'); if (q == NULL) { goto bail; } rest = q + 1; if (*rest != ' ') { goto bail; } *rest++ = '\0'; argv[0] = strtok_r(buffer, " ", &savePtr); // ensure no trailing spaces argv[1] = p; /* Map spaces in the process name to something benign */ q = p; while ((q = strchr(q, ' ')) != NULL) { *q = '_'; } if (strlen(p) > LOG_MAX_PROC_NAME) { p[LOG_MAX_PROC_NAME - 1] = ')'; p[LOG_MAX_PROC_NAME] = '\0'; } for (argc = 2; argc < 22; argc++) { argv[argc] = strtok_r((argc == 2) ? rest : NULL, " ", &savePtr); if (argv[argc] == NULL) { break; } } if (argc == 22) { descriptor = Str_SafeAsprintf(NULL, "%s-%s%s", argv[0], argv[21], argv[1]); } } bail: if (descriptor == NULL) { /* * Accessing /proc failed in some way. Emit a valid string that also * provides a clue that there is/was a problem. */ descriptor = Str_SafeAsprintf(NULL, "%d-0", pid); } return descriptor; } #elif defined(__APPLE__) /* *--------------------------------------------------------------------------- * * FileLockProcessCreationTime -- * * Returns the process creation time of the specified process. * * Results: * TRUE Done! * FALSE Process doesn't exist * * Side effects: * None * *--------------------------------------------------------------------------- */ static Bool FileLockProcessCreationTime(pid_t pid, // IN: uint64 *procCreationTime) // OUT: { int err; size_t size; struct kinfo_proc info; int mib[4]; ASSERT(procCreationTime != NULL); /* Request information about the specified process */ mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = pid; memset(&info, 0, sizeof info); size = sizeof info; err = sysctl(mib, ARRAYSIZE(mib), &info, &size, NULL, 0); if (err == -1) { return FALSE; } *procCreationTime = (info.kp_proc.p_starttime.tv_sec * CONST64U(1000000)) + info.kp_proc.p_starttime.tv_usec; return TRUE; } /* *--------------------------------------------------------------------------- * * FileLockProcessDescriptor -- * * Returns the process descriptor of the specified process. * * The format of a process descriptor is as follows: * * processID-processCreationTime(processName) * * where the processName and processCreationTime information * may be independently optional. * * Results: * NULL The process does not exist. * !NULL The process descriptor is returned. It is the callers * responsibility to free the dynamically allocated memory. * * Side effects: * None * *--------------------------------------------------------------------------- */ static char * FileLockProcessDescriptor(pid_t pid) // IN: { uint64 procCreationTime; if (!FileLockIsValidProcess(pid)) { return NULL; } if (!FileLockProcessCreationTime(pid, &procCreationTime)) { return NULL; } return Str_SafeAsprintf(NULL, "%d-%"FMT64"u", pid, procCreationTime); } #else /* *--------------------------------------------------------------------------- * * FileLockProcessDescriptor -- * * Returns the process descriptor of the specified process. * * The format of a process descriptor is as follows: * * processID-processCreationTime(processName) * * where the processName and processCreationTime information * may be independently optional. * * Results: * NULL The process does not exist. * !NULL The process descriptor is returned. It is the callers * responsibility to free the dynamically allocated memory. * * Side effects: * None * *--------------------------------------------------------------------------- */ static char * FileLockProcessDescriptor(pid_t pid) // IN: { return FileLockIsValidProcess(pid) ? Str_SafeAsprintf(NULL, "%d-0", pid) : NULL; } #endif /* *--------------------------------------------------------------------------- * * FileLockGetExecutionID -- * * Returns the executionID of the caller. * * Results: * The executionID of the caller. This is a dynamically allocated string; * the caller is responsible for its disposal. * * Side effects: * The executionID of the caller is not thread safe. Locking is currently * done at the process level - all threads of a process are treated * identically. * *--------------------------------------------------------------------------- */ char * FileLockGetExecutionID(void) { char *descriptor = FileLockProcessDescriptor(getpid()); ASSERT(descriptor != NULL); // Must be able to describe ourselves! return descriptor; } /* *--------------------------------------------------------------------------- * * FileLockParseProcessDescriptor -- * * Attempt to parse the specified process descriptor. Return the * pieces requested. * * Results: * TRUE Process descriptor is valid. * FALSE Process descriptor is invalid. * * Side effects: * None * *--------------------------------------------------------------------------- */ static Bool FileLockParseProcessDescriptor(const char *procDescriptor, // IN: pid_t *pid, // OUT: uint64 *procCreationTime) // OUT: { ASSERT(procDescriptor != NULL); ASSERT(pid != NULL); ASSERT(procCreationTime != NULL); if (sscanf(procDescriptor, "%d-%"FMT64"u", pid, procCreationTime) != 2) { if (sscanf(procDescriptor, "%d", pid) == 1) { *procCreationTime = 0ULL; } else { return FALSE; } } return *pid >= 0; } /* *---------------------------------------------------------------------- * * FileLockValidExecutionID -- * * Validate the execution ID. * * Results: * TRUE Yes * FALSE No * * Side effects: * None. * *---------------------------------------------------------------------- */ Bool FileLockValidExecutionID(const char *executionID) // IN: { pid_t filePID; pid_t procPID; Bool gotFileData; Bool gotProcData; char *procDescriptor; uint64 fileCreationTime; uint64 procCreationTime; gotFileData = FileLockParseProcessDescriptor(executionID, &filePID, &fileCreationTime); if (!gotFileData) { Warning(LGPFX" %s parse error on '%s'. Assuming valid.\n", __FUNCTION__, executionID); return TRUE; // Assume TRUE - preserve a lock - on parse error } procDescriptor = FileLockProcessDescriptor(filePID); if (procDescriptor == NULL) { return FALSE; // process doesn't exist } gotProcData = FileLockParseProcessDescriptor(procDescriptor, &procPID, &procCreationTime); ASSERT(gotProcData); // We built it; it had better be good ASSERT(procPID == filePID); // This better match what we started with... Posix_Free(procDescriptor); if ((fileCreationTime != 0) && (procCreationTime != 0) && (fileCreationTime != procCreationTime)) { return FALSE; // The process no longer exists } else { return TRUE; // Looks valid... } } /* *--------------------------------------------------------------------------- * * FileLockNormalizePath * * Normalize the path of the file being locked. Locking a symbolic * link should place the lock next to the link, not where the link * points to. * * Results: * The normalized path or NULL on error * * Side effects: * None * *--------------------------------------------------------------------------- */ static char * FileLockNormalizePath(const char *filePath) // IN: { char *result; char *dirName = NULL; char *fileName = NULL; /* * If the file to be locked is a symbolic link the lock file belongs next * to the symbolic link, not "off" where the symbolic link points to. * Translation: Don't "full path" the entire path of the file to be locked; * "full path" the dirName of the path, leaving the fileName alone. */ File_GetPathName(filePath, &dirName, &fileName); /* * Handle filePath - "xxx", "./xxx", "/xxx", and "/a/b/c". */ if (*dirName == '\0') { if (File_IsFullPath(filePath)) { result = Unicode_Join(DIRSEPS, fileName, NULL); } else { result = Unicode_Join(".", DIRSEPS, fileName, NULL); } } else { char *fullPath = File_FullPath(dirName); result = (fullPath == NULL) ? NULL : Unicode_Join(fullPath, DIRSEPS, fileName, NULL); Posix_Free(fullPath); } Posix_Free(dirName); Posix_Free(fileName); return result; } /* *---------------------------------------------------------------------- * * FileLock_Lock -- * * Obtain a lock on a file; shared or exclusive access. Also specify * how long to wait on lock acquisition - maxWaitTimeMsec * * maxWaitTimeMsec specifies the maximum amount of time, in * milliseconds, to wait for the lock before returning the "not * acquired" status. A value of FILELOCK_TRYLOCK_WAIT is the * equivalent of a "try lock" - the lock will be acquired only if * there is no contention. A value of FILELOCK_INFINITE_WAIT * specifies "waiting forever" to acquire the lock. * * Results: * NULL Lock not acquired * errno to *err, msg to **msgs - when appropriate * !NULL Lock Acquired. This is the "lockToken" for an unlock. * * Side effects: * Changes the host file system. * *---------------------------------------------------------------------- */ FileLockToken * FileLock_Lock(const char *filePath, // IN: const Bool readOnly, // IN: const uint32 maxWaitTimeMsec, // IN: int *err, // OUT/OPT: returns errno MsgList **msgs) // IN/OUT/OPT: add error message { int res = 0; char *normalizedPath; FileLockToken *tokenPtr; ASSERT(filePath != NULL); ASSERT(err != NULL); normalizedPath = FileLockNormalizePath(filePath); if (normalizedPath == NULL) { res = EINVAL; tokenPtr = NULL; } else { tokenPtr = FileLockIntrinsic(normalizedPath, !readOnly, maxWaitTimeMsec, &res); Posix_Free(normalizedPath); } if (err != NULL) { *err = res; } if (tokenPtr == NULL) { int errnoValue; if (res == 0) { errnoValue = EAGAIN; // Thank you for playing; try again /* Failed to acquire the lock; another has possession of it */ } else { errnoValue = res; } FileLockAppendMessage(msgs, errnoValue); } return tokenPtr; } /* *---------------------------------------------------------------------- * * FileLock_IsLocked -- * * Is a file currently locked (at the time of the call)? * * Results: * TRUE YES * FALSE Failure (errno to *err, msg to **msgs - when appropriate) * *---------------------------------------------------------------------- */ Bool FileLock_IsLocked(const char *filePath, // IN: int *err, // OUT/OPT: returns errno MsgList **msgs) // IN/OUT/OPT: add error message { int res = 0; Bool isLocked; char *normalizedPath; ASSERT(filePath != NULL); normalizedPath = FileLockNormalizePath(filePath); if (normalizedPath == NULL) { res = EINVAL; isLocked = FALSE; } else { isLocked = FileLockIsLocked(normalizedPath, &res); Posix_Free(normalizedPath); } if (err != NULL) { *err = res; } if (res != 0) { FileLockAppendMessage(msgs, res); } return isLocked; } /* *---------------------------------------------------------------------- * * FileLock_Unlock -- * * Release the lock held on the specified file. * * Results: * TRUE Success * FALSE Failure (errno to *err, msg to **msgs - when appropriate) * * Side effects: * Changes the host file system. * *---------------------------------------------------------------------- */ Bool FileLock_Unlock(const FileLockToken *lockToken, // IN: int *err, // OUT/OPT: returns errno MsgList **msgs) // IN/OUT/OPT: error messages { int res; ASSERT(lockToken != NULL); res = FileUnlockIntrinsic((FileLockToken *) lockToken); if (err != NULL) { *err = res; } if (res != 0) { FileLockAppendMessage(msgs, res); } return (res == 0); } #else char * FileLockGetExecutionID(void) { NOT_IMPLEMENTED(); } Bool FileLockValidExecutionID(const char *executionID) // IN: { NOT_IMPLEMENTED(); } #endif /* !__FreeBSD__ && !sun */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/fileLockPrimitive.c000066400000000000000000001561241321503522500255610ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * fileLockPrimitive.c -- * * Portable file locking via Lamport's Bakery algorithm. * * This implementation relies upon a remove directory operation failing * if the directory contains any files. */ #define _GNU_SOURCE /* For O_NOFOLLOW */ #include #include #include #include #include #include #include #if defined(_WIN32) #include #include #include #else #include #include #endif #include "vmware.h" #include "hostinfo.h" #include "util.h" #include "err.h" #include "log.h" #include "str.h" #include "fileIO.h" #include "fileLock.h" #include "fileInt.h" #include "random.h" #include "vm_atomic.h" #include "util.h" #include "hostType.h" #include "unicodeOperations.h" #define LOGLEVEL_MODULE main #include "loglevel_user.h" #define LOCK_SHARED "S" #define LOCK_EXCLUSIVE "X" #define FILELOCK_PROGRESS_DEARTH 8000 // Dearth of progress time in milliseconds #define FILELOCK_PROGRESS_SAMPLE 200 // Progress sampling time in milliseconds static char implicitReadToken; #define PARSE_TABLE_UINT 0 #define PARSE_TABLE_STRING 1 typedef struct parse_table { int type; char *name; void *valuePtr; } ParseTable; /* * The lock token. This is returned by the lock operation and must be sent * to the unlock operation. */ #define FILELOCK_TOKEN_SIGNATURE 0x4B434C46 // 'FLCK' in memory struct FileLockToken { uint32 signature; Bool portable; char *pathName; union { struct { FileIODescriptor lockFd; } mandatory; struct { char *lockFilePath; // &implicitReadToken for implicit read locks } portable; } u; }; /* *----------------------------------------------------------------------------- * * FileLockSleeper -- * * Have the calling thread sleep "for a while". The duration of the * sleep is determined by the count that is passed in. Checks are * also done for exceeding the maximum wait time. * * Results: * 0 slept * EAGAIN maximum sleep time exceeded * * Side effects: * None. * *----------------------------------------------------------------------------- */ static int FileLockSleeper(LockValues *myValues) // IN/OUT: { VmTimeType ageMsec; uint32 maxSleepTimeMsec; if (myValues->maxWaitTimeMsec == FILELOCK_TRYLOCK_WAIT) { return EAGAIN; } ageMsec = Hostinfo_SystemTimerMS() - myValues->startTimeMsec; if ((myValues->maxWaitTimeMsec != FILELOCK_INFINITE_WAIT) && (ageMsec >= myValues->maxWaitTimeMsec)) { return EAGAIN; } if (ageMsec <= 2000) { /* Most locks are "short" */ maxSleepTimeMsec = 100; } else { /* * The lock has been around a while; use a continuously increasing back * off with an upper bound. */ maxSleepTimeMsec = MIN(ageMsec / 10, 2000); } /* * Randomize the time slept. This will prevent any potential cadence issues * (thundering herds). */ (void) FileSleeper(maxSleepTimeMsec / 2, maxSleepTimeMsec); return 0; } /* *----------------------------------------------------------------------------- * * FileLockRemoveLockingFile -- * * Remove the specified file. * * Results: * 0 success * > 0 failure (errno) * * Side effects: * None. * *----------------------------------------------------------------------------- */ static int FileLockRemoveLockingFile(const char *lockDir, // IN: const char *fileName) // IN: { int err; char *path; ASSERT(lockDir != NULL); ASSERT(fileName != NULL); path = Unicode_Join(lockDir, DIRSEPS, fileName, NULL); err = FileDeletionRobust(path, FALSE); if (err != 0) { if (err == ENOENT) { /* Not there anymore; locker unlocked or timed out */ err = 0; } else { Warning(LGPFX" %s of '%s' failed: %s\n", __FUNCTION__, path, Err_Errno2String(err)); } } Posix_Free(path); return err; } /* *----------------------------------------------------------------------------- * * FileLockParseArgs -- * * Parse the property list arguments of a lock file. The ParseTable * contains names of properies that are interesting to the caller; * only those values associated with the interesting names will be * extracted, the others will be ignored. * * Results: * TRUE An error was detected * FALSE All is well * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool FileLockParseArgs(char *argv[], // IN: uint32 argCount, // IN: ParseTable *table, // IN: uint32 tableSize) // IN: { uint32 argPos = 5; // The property list always starts with this argument while (argCount) { uint32 i; char *p = strchr(argv[argPos], '='); /* Validate the "name=value" form */ if ((p == NULL) || (p == argv[argPos]) || (p[1] == '\0')) { return TRUE; } *p = '\0'; /* Unknown names are ignored without error */ for (i = 0; i < tableSize; i++) { if (strcmp(argv[argPos], table[i].name) == 0) { switch (table[i].type) { case PARSE_TABLE_UINT: if (sscanf(&p[1], "%u", (uint32 *) table[i].valuePtr) != 1) { return TRUE; } break; case PARSE_TABLE_STRING: *((char **) table[i].valuePtr) = &p[1]; break; } } } *p = '='; argPos++; argCount--; } return FALSE; } /* *----------------------------------------------------------------------------- * * FileLockMemberValues -- * * Returns the values associated with lock directory file. * * Results: * 0 Valid lock file; values have been returned * > 0 Lock file problem (errno); values have not been returned * * Side effects: * The lock file may be deleted if it is invalid * *----------------------------------------------------------------------------- */ #define FL_MAX_ARGS 16 int FileLockMemberValues(const char *lockDir, // IN: const char *fileName, // IN: char *buffer, // OUT: size_t requiredSize, // IN: LockValues *memberValues) // OUT: { size_t len; int access; char *path; FileData fileData; FileIOResult result; FileIODescriptor desc; char *argv[FL_MAX_ARGS]; int err = 0; uint32 argc = 0; char *saveptr = NULL; ParseTable table[] = { { PARSE_TABLE_STRING, "lc", (void *) &memberValues->locationChecksum } }; ASSERT(lockDir != NULL); ASSERT(fileName != NULL); path = Unicode_Join(lockDir, DIRSEPS, fileName, NULL); FileIO_Invalidate(&desc); access = FILEIO_OPEN_ACCESS_READ; #if defined(_WIN32) access |= FILEIO_OPEN_SHARE_DELETE; #endif result = FileIOCreateRetry(&desc, path, access, FILEIO_OPEN, 0444, FILE_MAX_WAIT_TIME_MS); if (!FileIO_IsSuccess(result)) { err = FileMapErrorToErrno(__FUNCTION__, Err_Errno()); /* * A member file may "disappear" if is deleted (unlinked on POSIXen) * due to an unlock immediately after a directory scan but before the * scan is processed. Since this is a "normal" thing, ENOENT will be * suppressed. */ if (err != ENOENT) { Warning(LGPFX" %s open failure on '%s': %s\n", __FUNCTION__, path, Err_Errno2String(err)); } goto bail; } /* Attempt to obtain the lock file attributes now that it is opened */ err = FileAttributesRobust(path, &fileData); if (err != 0) { /* * A member file may "disappear" if is deleted (unlinked on POSIXen) * due to an unlock immediately after a directory scan but before the * scan is processed. Since this is a "normal" thing, ENOENT will be * suppressed. */ if (err != ENOENT) { Warning(LGPFX" %s file size failure on '%s': %s\n", __FUNCTION__, path, Err_Errno2String(err)); } FileIO_Close(&desc); goto bail; } /* Complain if the lock file is not the proper size */ if (fileData.fileSize != requiredSize) { Warning(LGPFX" %s file '%s': size %"FMT64"u, required size %"FMTSZ"d\n", __FUNCTION__, path, fileData.fileSize, requiredSize); FileIO_Close(&desc); goto corrupt; } /* Attempt to read the lock file data and validate how much was read. */ result = FileIO_Read(&desc, buffer, requiredSize, &len); FileIO_Close(&desc); if (!FileIO_IsSuccess(result)) { err = FileMapErrorToErrno(__FUNCTION__, Err_Errno()); Warning(LGPFX" %s read failure on '%s': %s\n", __FUNCTION__, path, Err_Errno2String(err)); goto bail; } if (len != requiredSize) { Warning(LGPFX" %s read length issue on '%s': %"FMTSZ"d and %"FMTSZ"d\n", __FUNCTION__, path, len, requiredSize); err = EIO; goto bail; } fixedUp: /* Extract and validate the lock file data. */ for (argc = 0; argc < FL_MAX_ARGS; argc++) { argv[argc] = strtok_r((argc == 0) ? buffer : NULL, " ", &saveptr); if (argv[argc] == NULL) { break; } } /* * Lock file arguments are space separated. There is a minimum of 5 * arguments - machineID, executionID, Lamport number, lock type * and process creation time. The maximum number of arguments is * FL_MAX_ARGS. * * Additional arguments, if present, form a property list - one or more * "name=value" pairs. * * Here is picture of valid forms: * * 0 1 2 3 4 5 6 Comment *------------------------- * A B C D E No property list * A B C D E x One property * A B C D E x y Two properties */ memberValues->locationChecksum = NULL; if ((argc < 5) || ((argc == FL_MAX_ARGS) && (strtok_r(NULL, " ", &saveptr) != NULL))) { goto corrupt; } if ((argc > 5) && FileLockParseArgs(argv, argc - 5, table, ARRAYSIZE(table))) { goto corrupt; } /* * Check for an old style lock file; if found, upgrade it (internally). * * The new style lock always has an executionID that is minimally * processID-processCreationTime (the '-' is the critical difference). */ if ((strchr(argv[1], '-') == NULL) && (strchr(argv[1], '(') == NULL) && (strchr(argv[1], ')') == NULL) && (argc == 6) && !FileLockParseArgs(argv, argc - 5, table, ARRAYSIZE(table))) { char *newBuffer; newBuffer = Str_SafeAsprintf(NULL, "%s %s-%s %s %s %s %s", argv[0], argv[1], argv[4], argv[2], argv[3], argv[4], argv[5]); Str_Strcpy(buffer, newBuffer, requiredSize); Posix_Free(newBuffer); goto fixedUp; } if (sscanf(argv[2], "%u", &memberValues->lamportNumber) != 1) { goto corrupt; } if ((strcmp(argv[3], LOCK_SHARED) != 0) && (strcmp(argv[3], LOCK_EXCLUSIVE) != 0)) { goto corrupt; } memberValues->machineID = argv[0]; memberValues->executionID = argv[1]; memberValues->lockType = argv[3]; memberValues->memberName = Unicode_Duplicate(fileName); Posix_Free(path); return 0; corrupt: Warning(LGPFX" %s removing problematic lock file '%s'\n", __FUNCTION__, path); if (argc) { uint32 i; Log(LGPFX" %s '%s' contents are:\n", __FUNCTION__, fileName); for (i = 0; i < argc; i++) { Log(LGPFX" %s %s argv[%u]: '%s'\n", __FUNCTION__, fileName, i, argv[i]); } } /* Remove the lock file and behave like it has disappeared */ err = FileDeletionRobust(path, FALSE); if (err == 0) { err = ENOENT; } bail: Posix_Free(path); return err; } /* *----------------------------------------------------------------------------- * * FileLockValidName -- * * Validate the format of the file name. * * Results: * TRUE Yes * FALSE No * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool FileLockValidName(const char *fileName) // IN: { uint32 i; ASSERT(fileName != NULL); /* The fileName must start with the ASCII character, 'M', 'D' or 'E' */ if (Unicode_FindSubstrInRange("MDE", 0, -1, fileName, 0, 1) == UNICODE_INDEX_NOT_FOUND) { return FALSE; } /* The fileName must contain 5 ASCII digits after the initial character */ for (i = 0; i < 5; i++) { if (Unicode_FindSubstrInRange("0123456789", 0, -1, fileName, i + 1, 1) == UNICODE_INDEX_NOT_FOUND) { return FALSE; } } /* The fileName must terminate with the appropriate suffix string */ return Unicode_EndsWith(fileName, FILELOCK_SUFFIX); } /* *----------------------------------------------------------------------------- * * FileLockActivateList * * Insure a lock list entry exists for the lock directory. * * Results: * 0 success * > 0 error (errno) * * Side effects: * None. * *----------------------------------------------------------------------------- */ static int FileLockActivateList(const char *dirName, // IN: LockValues *myValues) // IN: { ActiveLock *ptr; ASSERT(dirName != NULL); ASSERT(*dirName == 'D'); /* Search the list for a matching entry */ for (ptr = myValues->lockList; ptr != NULL; ptr = ptr->next) { if (Unicode_Compare(ptr->dirName, dirName) == 0) { break; } } /* No entry? Attempt to add one. */ if (ptr == NULL) { ptr = Util_SafeMalloc(sizeof *ptr); ptr->next = myValues->lockList; myValues->lockList = ptr; ptr->age = 0; ptr->dirName = Unicode_Duplicate(dirName); } /* Mark the entry (exists) */ ptr->marked = TRUE; return 0; } /* *----------------------------------------------------------------------------- * * FileLockLocationChecksum -- * * Compute the location checksum of the argument path. * * Results: * The location checksum as dynamically allocated string. * * Side effects: * None * *----------------------------------------------------------------------------- */ static char * FileLockLocationChecksum(const char *path) // IN: { int c; uint32 hash = 5381; #if defined(_WIN32) char *p; char *value = Unicode_Duplicate(path); /* Don't get fooled by mixed case; "normalize" */ Str_ToLower(value); p = value; #else char *p = (char *) path; #endif /* DBJ2 hash... good enough? */ while ((c = *p++)) { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } #if defined(_WIN32) Posix_Free(value); #endif return Str_SafeAsprintf(NULL, "%u", hash); } /* *----------------------------------------------------------------------------- * * FileLockScanDirectory -- * * Call the specified function for each member file found in the * specified directory. * * Results: * 0 success * > 0 failure * * Side effects: * Anything that this not a valid locking file is deleted. * *----------------------------------------------------------------------------- */ static int FileLockScanDirectory(const char *lockDir, // IN: int (*func)( // IN: const char *lockDir, const char *fileName, LockValues *memberValues, LockValues *myValues ), LockValues *myValues, // IN: Bool cleanUp) // IN: { uint32 i; int err; int numEntries; char **fileList = NULL; char *myExecutionID = NULL; char *locationChecksum = NULL; ASSERT(lockDir != NULL); numEntries = FileListDirectoryRobust(lockDir, &fileList); if (numEntries == -1) { Log(LGPFX" %s: Could not read the directory '%s': %d\n", __FUNCTION__, lockDir, Err_Errno()); return EDOM; // out of my domain } /* Pass 1: Validate entries and handle any 'D' entries */ for (i = 0, err = 0; i < numEntries; i++) { /* Remove any non-locking files */ if (!FileLockValidName(fileList[i])) { Log(LGPFX" %s discarding %s from %s'; invalid file name.\n", __FUNCTION__, fileList[i], lockDir); err = FileLockRemoveLockingFile(lockDir, fileList[i]); if (err != 0) { goto bail; } Posix_Free(fileList[i]); fileList[i] = NULL; continue; } /* * Any lockers appear to be entering? * * This should be rather rare. If a locker dies while entering * this will cleaned-up. */ if (*fileList[i] == 'D') { if (cleanUp) { err = FileLockActivateList(fileList[i], myValues); if (err != 0) { goto bail; } } Posix_Free(fileList[i]); fileList[i] = NULL; } } if (myValues->lockList != NULL) { goto bail; } myExecutionID = FileLockGetExecutionID(); locationChecksum = FileLockLocationChecksum(lockDir); /* Pass 2: Handle the 'M' entries */ for (i = 0, err = 0; i < numEntries; i++) { LockValues *ptr; Bool myLockFile; LockValues memberValues; char buffer[FILELOCK_DATA_SIZE]; if ((fileList[i] == NULL) || (*fileList[i] == 'E')) { continue; } myLockFile = (Unicode_Compare(fileList[i], myValues->memberName) == 0) ? TRUE : FALSE; if (myLockFile) { /* It's me! No need to read or validate anything. */ ptr = myValues; } else { /* It's not me! Attempt to extract the member values. */ err = FileLockMemberValues(lockDir, fileList[i], buffer, FILELOCK_DATA_SIZE, &memberValues); if (err != 0) { if (err == ENOENT) { err = 0; /* Not there anymore; locker unlocked or timed out */ continue; } break; } /* Remove any stale locking files */ if (FileLockMachineIDMatch(myValues->machineID, memberValues.machineID)) { char *dispose = NULL; if (FileLockValidExecutionID(memberValues.executionID)) { /* If it's mine it better still be where I put it! */ if ((strcmp(myExecutionID, memberValues.executionID) == 0) && ((memberValues.locationChecksum != NULL) && (strcmp(memberValues.locationChecksum, locationChecksum) != 0))) { dispose = Unicode_Duplicate("lock file has been moved."); } } else { dispose = Str_SafeAsprintf(NULL, "invalid executionID %s.", memberValues.executionID); } if (dispose) { Log(LGPFX" %s discarding %s from %s': %s\n", __FUNCTION__, fileList[i], lockDir, dispose); Posix_Free(dispose); Posix_Free(memberValues.memberName); err = FileLockRemoveLockingFile(lockDir, fileList[i]); if (err != 0) { break; } continue; } } ptr = &memberValues; } /* Locking file looks good; see what happens */ err = (*func)(lockDir, fileList[i], ptr, myValues); if (ptr == &memberValues) { Posix_Free(memberValues.memberName); } if (err != 0) { break; } } bail: Util_FreeStringList(fileList, numEntries); Posix_Free(locationChecksum); Posix_Free(myExecutionID); return err; } /* *----------------------------------------------------------------------------- * * FileLockScanner -- * * Call the specified function for each member file found in the * specified directory. If a rescan is necessary check the list * of outstanding locks and handle removing stale locks. * * Results: * 0 success * > 0 failure * * Side effects: * None * *----------------------------------------------------------------------------- */ static int FileLockScanner(const char *lockDir, // IN: int (*func)( // IN: const char *lockDir, const char *fileName, LockValues *memberValues, LockValues *myValues ), LockValues *myValues, // IN: Bool cleanUp) // IN: { int err; ActiveLock *ptr; ASSERT(lockDir != NULL); myValues->lockList = NULL; while (TRUE) { ActiveLock *prev; err = FileLockScanDirectory(lockDir, func, myValues, cleanUp); if ((err > 0) || ((err == 0) && (myValues->lockList == NULL))) { break; } prev = NULL; ptr = myValues->lockList; /* * Some 'D' entries have persisted. Age them and remove those that * have not progressed. Remove those that have disappeared. */ while (ptr != NULL) { Bool remove; if (ptr->marked) { if (ptr->age > FILELOCK_PROGRESS_DEARTH) { char *temp; char *path; UnicodeIndex index; ASSERT(*ptr->dirName == 'D'); Log(LGPFX" %s discarding %s data from '%s'.\n", __FUNCTION__, ptr->dirName, lockDir); path = Unicode_Join(lockDir, DIRSEPS, ptr->dirName, NULL); index = Unicode_FindLast(path, "D"); ASSERT(index != UNICODE_INDEX_NOT_FOUND); temp = Unicode_Replace(path, index, 1, "M"); FileDeletionRobust(temp, FALSE); Posix_Free(temp); temp = Unicode_Replace(path, index, 1, "E"); FileDeletionRobust(temp, FALSE); Posix_Free(temp); FileRemoveDirectoryRobust(path); Posix_Free(path); remove = TRUE; } else { ptr->marked = FALSE; ptr->age += FILELOCK_PROGRESS_SAMPLE; remove = FALSE; } } else { remove = TRUE; } if (remove) { if (prev == NULL) { myValues->lockList = ptr->next; } else { prev->next = ptr->next; } } prev = ptr; ptr = ptr->next; } FileSleeper(FILELOCK_PROGRESS_SAMPLE, FILELOCK_PROGRESS_SAMPLE); // relax } /* Clean up anything still on the list; they are no longer important */ while (myValues->lockList != NULL) { ptr = myValues->lockList; myValues->lockList = ptr->next; Posix_Free(ptr->dirName); Posix_Free(ptr); } return err; } /* *----------------------------------------------------------------------------- * * FileUnlockIntrinsic -- * * Release a lock on a file. * * Results: * 0 unlocked * > 0 errno * * Side effects: * None. * *----------------------------------------------------------------------------- */ int FileUnlockIntrinsic(FileLockToken *tokenPtr) // IN: { int err = 0; ASSERT(tokenPtr && (tokenPtr->signature == FILELOCK_TOKEN_SIGNATURE)); LOG(1, ("Requesting unlock on %s\n", tokenPtr->pathName)); if (tokenPtr->portable) { /* * If the lockFilePath (a pointer) is the fixed-address token representing * an implicit read lock, there is no lock file and the token can simply * be discarded. */ if (tokenPtr->u.portable.lockFilePath != &implicitReadToken) { char *lockDir; /* The lock directory path */ lockDir = Unicode_Append(tokenPtr->pathName, FILELOCK_SUFFIX); /* * TODO: under vmx86_debug validate the contents of the lock file as * matching the machineID and executionID. */ err = FileDeletionRobust(tokenPtr->u.portable.lockFilePath, FALSE); FileRemoveDirectoryRobust(lockDir); // just in case we can clean up if (err && vmx86_debug) { Log(LGPFX" %s failed for '%s': %s\n", __FUNCTION__, tokenPtr->u.portable.lockFilePath, Err_Errno2String(err)); } Posix_Free(lockDir); Posix_Free(tokenPtr->u.portable.lockFilePath); } tokenPtr->u.portable.lockFilePath = NULL; // Just in case... } else { ASSERT(FileIO_IsValid(&tokenPtr->u.mandatory.lockFd)); if (!FileIO_IsSuccess(FileIO_CloseAndUnlink(&tokenPtr->u.mandatory.lockFd))) { /* * Should succeed, but there is an unavoidable race: * close() must precede unlink(), but another thread could touch * the file between close() and unlink(). We only worry about other * FileLock-like manipulations; the advisory lock file should not * experience any name collisions. Treat races as success. * Specific errors: * EBUSY: other locked file * ENOENT: other locked + unlocked (w/ implicit unlink) file */ if (Err_Errno() == EBUSY || Err_Errno() == ENOENT) { LOG(0, ("Tolerating %s on unlink of advisory lock at %s\n", Err_Errno() == EBUSY ? "EBUSY" : "ENOENT", tokenPtr->pathName)); } else { err = Err_Errno(); if (vmx86_debug) { Log(LGPFX" %s failed for advisory lock '%s': %s\n", __FUNCTION__, tokenPtr->pathName, Err_Errno2String(err)); } } } } Posix_Free(tokenPtr->pathName); tokenPtr->signature = 0; // Just in case... tokenPtr->pathName = NULL; // Just in case... Posix_Free(tokenPtr); return err; } /* *----------------------------------------------------------------------------- * * FileLockWaitForPossession -- * * Wait until the caller has a higher priority towards taking * possession of a lock than the specified file. * * Results: * 0 success * > 0 error (errno) * * Side effects: * None. * *----------------------------------------------------------------------------- */ static int FileLockWaitForPossession(const char *lockDir, // IN: const char *fileName, // IN: LockValues *memberValues, // IN: LockValues *myValues) // IN: { int err = 0; ASSERT(lockDir != NULL); ASSERT(fileName != NULL); /* "Win" or wait? */ if (((memberValues->lamportNumber < myValues->lamportNumber) || ((memberValues->lamportNumber == myValues->lamportNumber) && (Unicode_Compare(memberValues->memberName, myValues->memberName) < 0))) && ((strcmp(memberValues->lockType, LOCK_EXCLUSIVE) == 0) || (strcmp(myValues->lockType, LOCK_EXCLUSIVE) == 0))) { char *path; Bool thisMachine; thisMachine = FileLockMachineIDMatch(myValues->machineID, memberValues->machineID); path = Unicode_Join(lockDir, DIRSEPS, fileName, NULL); while ((err = FileLockSleeper(myValues)) == 0) { /* still there? */ err = FileAttributesRobust(path, NULL); if (err != 0) { if (err == ENOENT) { /* Not there anymore; locker unlocked or timed out */ err = 0; } break; } /* still valid? */ if (thisMachine && !FileLockValidExecutionID(memberValues->executionID)) { /* Invalid Execution ID; remove the member file */ Warning(LGPFX" %s discarding file '%s'; invalid executionID.\n", __FUNCTION__, path); err = FileLockRemoveLockingFile(lockDir, fileName); break; } } /* * Log the disposition of each timeout for all non "try lock" locking * attempts. This can assist in debugging locking problems. */ if ((myValues->maxWaitTimeMsec != FILELOCK_TRYLOCK_WAIT) && (err == EAGAIN)) { if (thisMachine) { Log(LGPFX" %s timeout on '%s' due to a local process '%s'\n", __FUNCTION__, path, memberValues->executionID); } else { Log(LGPFX" %s timeout on '%s' due to another machine '%s'\n", __FUNCTION__, path, memberValues->machineID); } } Posix_Free(path); } return err; } /* *----------------------------------------------------------------------------- * * FileLockNumberScan -- * * Determine the maxmimum number value within the current locking set. * * Results: * 0 success * > 0 failure (errno) * * Side effects: * None. * *----------------------------------------------------------------------------- */ static int FileLockNumberScan(const char *lockDir, // IN: const char *fileName, // IN: LockValues *memberValues, // IN: LockValues *myValues) // IN/OUT: { ASSERT(lockDir != NULL); ASSERT(fileName != NULL); if (memberValues->lamportNumber > myValues->lamportNumber) { myValues->lamportNumber = memberValues->lamportNumber; } return 0; } /* *----------------------------------------------------------------------------- * * FileLockMakeDirectory -- * * Create a directory. * * Results: * 0 success * > 0 failure (errno) * * Side Effects: * File system may be modified. * *----------------------------------------------------------------------------- */ static int FileLockMakeDirectory(const char *pathName) // IN: { int err; #if !defined(_WIN32) mode_t save; save = umask(0); #endif ASSERT(pathName != NULL); err = FileCreateDirectoryRobust(pathName, 0777); #if !defined(_WIN32) umask(save); #endif return err; } /* *----------------------------------------------------------------------------- * * FileLockCreateEntryDirectory -- * * Create an entry directory in the specified locking directory. * * Due to FileLock_Unlock() attempting to remove the locking * directory on an unlock operation (to "clean up" and remove the * locking directory when it is no longer needed), this routine * must carefully handle a number of race conditions to insure the * the locking directory exists and the entry directory is created * within. * * Results: * 0 success * > 0 failure (errno) * * Side Effects: * On success returns the number identifying the entry directory and * the entry directory path name. * *----------------------------------------------------------------------------- */ static int FileLockCreateEntryDirectory(const char *lockDir, // IN: char **entryDirectory, // OUT: char **entryFilePath, // OUT: char **memberFilePath, // OUT: char **memberName) // OUT: { int err = 0; uint32 randomNumber = 0; ASSERT(lockDir != NULL); *entryDirectory = NULL; *entryFilePath = NULL; *memberFilePath = NULL; *memberName = NULL; /* Fun at the races */ while (TRUE) { char *temp; FileData fileData; err = FileAttributesRobust(lockDir, &fileData); if (err == 0) { /* The name exists. Deal with it... */ if (fileData.fileType == FILE_TYPE_REGULAR) { /* * It's a file. Assume this is an (active?) old style lock and * err on the safe side - don't remove it (and automatically * upgrade to a new style lock). */ Log(LGPFX" %s: '%s' exists; an old style lock file?\n", __FUNCTION__, lockDir); err = EBUSY; break; } if (fileData.fileType != FILE_TYPE_DIRECTORY) { /* Not a directory; attempt to remove the debris */ if (FileDeletionRobust(lockDir, FALSE) != 0) { Warning(LGPFX" %s: '%s' exists and is not a directory.\n", __FUNCTION__, lockDir); err = ENOTDIR; break; } continue; } } else { if (err == ENOENT) { /* Not there anymore; locker unlocked or timed out */ err = FileLockMakeDirectory(lockDir); if ((err != 0) && (err != EEXIST)) { Warning(LGPFX" %s creation failure on '%s': %s\n", __FUNCTION__, lockDir, Err_Errno2String(err)); break; } } else { Warning(LGPFX" %s stat failure on '%s': %s\n", __FUNCTION__, lockDir, Err_Errno2String(err)); break; } } /* There is a small chance of collision/failure; grab stings now */ randomNumber = (FileSimpleRandom() >> 8) & 0xFFFF; *memberName = Unicode_Format("M%05u%s", randomNumber, FILELOCK_SUFFIX); temp = Unicode_Format("D%05u%s", randomNumber, FILELOCK_SUFFIX); *entryDirectory = Unicode_Join(lockDir, DIRSEPS, temp, NULL); Posix_Free(temp); temp = Unicode_Format("E%05u%s", randomNumber, FILELOCK_SUFFIX); *entryFilePath = Unicode_Join(lockDir, DIRSEPS, temp, NULL); Posix_Free(temp); *memberFilePath = Unicode_Join(lockDir, DIRSEPS, *memberName, NULL); err = FileLockMakeDirectory(*entryDirectory); if (err == 0) { /* * The entry directory was safely created. See if a member file * is in use (the entry directory is removed once the member file * is created). If a member file is in use, choose another number, * otherwise the use of the this number is OK. * * Err on the side of caution... don't want to trash perfectly * good member files. */ err = FileAttributesRobust(*memberFilePath, NULL); if (err != 0) { if (err == ENOENT) { err = 0; break; } if (vmx86_debug) { Log(LGPFX" %s stat failure on '%s': %s\n", __FUNCTION__, *memberFilePath, Err_Errno2String(err)); } } FileRemoveDirectoryRobust(*entryDirectory); } else { if ((err != EEXIST) && // Another process/thread created it... (err != ENOENT)) { // lockDir is gone... Warning(LGPFX" %s creation failure on '%s': %s\n", __FUNCTION__, *entryDirectory, Err_Errno2String(err)); break; } } Posix_Free(*entryDirectory); Posix_Free(*entryFilePath); Posix_Free(*memberFilePath); Posix_Free(*memberName); *entryDirectory = NULL; *entryFilePath = NULL; *memberFilePath = NULL; *memberName = NULL; } if (err != 0) { Posix_Free(*entryDirectory); Posix_Free(*entryFilePath); Posix_Free(*memberFilePath); Posix_Free(*memberName); *entryDirectory = NULL; *entryFilePath = NULL; *memberFilePath = NULL; *memberName = NULL; } return err; } /* *----------------------------------------------------------------------------- * * FileLockCreateMemberFile -- * * Create the member file. * * Results: * 0 success * > 0 failure (errno) * * Side Effects: * None * *----------------------------------------------------------------------------- */ static int FileLockCreateMemberFile(FileIODescriptor *desc, // IN: const LockValues *myValues, // IN: const char *entryFilePath, // IN: const char *memberFilePath) // IN: { int cnt; int pid; size_t len; FileIOResult result; uint64 processCreationTime; int err = 0; char buffer[FILELOCK_DATA_SIZE] = { 0 }; ASSERT(entryFilePath != NULL); ASSERT(memberFilePath != NULL); /* * Populate the buffer with appropriate data * * Lock file arguments are space separated. There is a minimum of 5 * arguments - machineID, executionID, Lamport number, lock type * and process creation time. The maximum number of arguments is * FL_MAX_ARGS. * * Additional arguments, if present, form a property list - one or more * "name=value" pairs. * * Yes, the process creation time is redundently encoded. This is necessary * to maintain backwards compatibility. Should an older code pick up a * newer lock file and there is lock contention, the older code will log * the name of the process causing the contention - it's also encoded * into the executionID. */ cnt = sscanf(myValues->executionID, "%d-%"FMT64"u", &pid, &processCreationTime); ASSERT(cnt == 2); // ensure new format executionID Str_Sprintf(buffer, sizeof buffer, "%s %s %u %s %"FMT64"u lc=%s", myValues->machineID, myValues->executionID, myValues->lamportNumber, myValues->lockType, processCreationTime, myValues->locationChecksum); /* Attempt to write the data */ result = FileIO_Write(desc, buffer, sizeof buffer, &len); if (!FileIO_IsSuccess(result)) { err = FileMapErrorToErrno(__FUNCTION__, Err_Errno()); Warning(LGPFX" %s write of '%s' failed: %s\n", __FUNCTION__, entryFilePath, Err_Errno2String(err)); FileIO_Close(desc); return err; } if (!FileIO_IsSuccess(FileIO_Close(desc))) { err = FileMapErrorToErrno(__FUNCTION__, Err_Errno()); Warning(LGPFX" %s close of '%s' failed: %s\n", __FUNCTION__, entryFilePath, Err_Errno2String(err)); return err; } if (len != sizeof buffer) { Warning(LGPFX" %s write length issue on '%s': %"FMTSZ"d and %"FMTSZ"d\n", __FUNCTION__, entryFilePath, len, sizeof buffer); return EIO; } err = File_Rename(entryFilePath, memberFilePath); if (err != 0) { Warning(LGPFX" %s FileRename of '%s' to '%s' failed: %s\n", __FUNCTION__, entryFilePath, memberFilePath, Err_Errno2String(err)); if (vmx86_debug) { Log(LGPFX" %s FileLockFileType() of '%s': %s\n", __FUNCTION__, entryFilePath, Err_Errno2String(FileAttributesRobust(entryFilePath, NULL))); Log(LGPFX" %s FileLockFileType() of '%s': %s\n", __FUNCTION__, memberFilePath, Err_Errno2String(FileAttributesRobust(memberFilePath, NULL))); } return err; } return 0; } /* *----------------------------------------------------------------------------- * * FileLockIntrinsicMandatory -- * * Obtain a lock on a file; shared or exclusive access. * * This implementation uses the FILEIO_OPEN_LOCK_MANDATORY flag, * which requires kernel support for mandatory locking. Such locks * are automatically broken if the host holding the lock fails. * * maxWaitTimeMsec specifies the maximum amount of time, in * milliseconds, to wait for the lock before returning the "not * acquired" status. A value of FILELOCK_TRYLOCK_WAIT is the * equivalent of a "try lock" - the lock will be acquired only if * there is no contention. A value of FILELOCK_INFINITE_WAIT * specifies "waiting forever" to acquire the lock. * * Results: * NULL Lock not acquired. Check err. * err 0 Lock Timed Out * err > 0 errno * !NULL Lock Acquired. This is the "lockToken" for an unlock. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static FileLockToken * FileLockIntrinsicMandatory(const char *pathName, // IN: const char *lockFile, // IN: LockValues *myValues, // IN/OUT: int *err) // OUT: { int access; int errnum; FileIOResult result; FileLockToken *tokenPtr = Util_SafeMalloc(sizeof *tokenPtr); tokenPtr->signature = FILELOCK_TOKEN_SIGNATURE; tokenPtr->portable = FALSE; tokenPtr->pathName = Unicode_Duplicate(pathName); FileIO_Invalidate(&tokenPtr->u.mandatory.lockFd); access = myValues->exclusivity ? FILEIO_OPEN_ACCESS_WRITE : FILEIO_OPEN_ACCESS_READ; access |= FILEIO_OPEN_EXCLUSIVE_LOCK; do { result = FileIOCreateRetry(&tokenPtr->u.mandatory.lockFd, lockFile, access, FILEIO_OPEN_CREATE, 0600, 0); errnum = Err_Errno(); if (result != FILEIO_LOCK_FAILED) { break; } } while (FileLockSleeper(myValues) == 0); if (FileIO_IsSuccess(result)) { ASSERT(FileIO_IsValid(&tokenPtr->u.mandatory.lockFd)); *err = 0; return tokenPtr; } else { if (result == FILEIO_LOCK_FAILED) { *err = 0; } else { *err = FileMapErrorToErrno(__FUNCTION__, errnum); } Posix_Free(tokenPtr->pathName); ASSERT(!FileIO_IsValid(&tokenPtr->u.mandatory.lockFd)); Posix_Free(tokenPtr); return NULL; } } /* *----------------------------------------------------------------------------- * * FileLockIntrinsicPortable -- * * Obtain a lock on a file; shared or exclusive access. * * This implementation uses a HIGHLY portable directory-namespace + * Lamport bakery scheme that works on all filesystems that provide * atomicity of the directory namespace (That is, all known filesystems). * The various files involved are hidden within a "pathName.lck/" * subdirectory. * * The lock can be broken by removing the subdirectory. The lock * is self-cleaning on the same host (e.g. will detect a dead process * and will break the lock), but NOT self-cleaning across hosts. The * lock does not require any sort of time-based leases or heartbeats. * * Results: * NULL Lock not acquired. Check err. * err 0 Lock Timed Out * err > 0 errno * !NULL Lock Acquired. This is the "lockToken" for an unlock. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static FileLockToken * FileLockIntrinsicPortable(const char *pathName, // IN: const char *lockDir, // IN: LockValues *myValues, // IN/OUT: int *err) // OUT: { int access; FileIOResult result; FileIODescriptor desc; FileLockToken *tokenPtr; char *entryFilePath = NULL; char *memberFilePath = NULL; char *entryDirectory = NULL; ASSERT(pathName != NULL); ASSERT(err != NULL); /* * Attempt to create the locking and entry directories; obtain the * entry and member path names. */ *err = FileLockCreateEntryDirectory(lockDir, &entryDirectory, &entryFilePath, &memberFilePath, &myValues->memberName); switch (*err) { case 0: break; case EROFS: /* FALL THROUGH */ case EACCES: if (!myValues->exclusivity) { /* * Lock is for read/shared access however the lock directory could * not be created. Grant an implicit read lock whenever possible. * The address of a private variable will be used for the lock token. */ Warning(LGPFX" %s implicit %s lock succeeded on '%s'.\n", __FUNCTION__, LOCK_SHARED, pathName); *err = 0; memberFilePath = &implicitReadToken; } /* FALL THROUGH */ default: goto bail; } ASSERT(Unicode_LengthInCodeUnits(memberFilePath) - Unicode_LengthInCodeUnits(pathName) <= FILELOCK_OVERHEAD); /* Attempt to create the entry file */ access = FILEIO_OPEN_ACCESS_WRITE; #if defined(_WIN32) access |= FILEIO_OPEN_SHARE_DELETE; #else access |= FILEIO_OPEN_ACCESS_NOFOLLOW; #endif FileIO_Invalidate(&desc); result = FileIOCreateRetry(&desc, entryFilePath, access, FILEIO_OPEN_CREATE_SAFE, 0644, FILE_MAX_WAIT_TIME_MS); if (!FileIO_IsSuccess(result)) { *err = FileMapErrorToErrno(__FUNCTION__, Err_Errno()); /* clean up */ FileRemoveDirectoryRobust(entryDirectory); FileRemoveDirectoryRobust(lockDir); goto bail; } /* what is max(Number[1]... Number[all lockers])? */ *err = FileLockScanner(lockDir, FileLockNumberScan, myValues, FALSE); if (*err != 0) { /* clean up */ FileIO_Close(&desc); FileDeletionRobust(entryFilePath, FALSE); FileRemoveDirectoryRobust(entryDirectory); FileRemoveDirectoryRobust(lockDir); goto bail; } /* Number[i] = 1 + max([Number[1]... Number[all lockers]) */ myValues->lamportNumber++; /* Attempt to create the member file */ *err = FileLockCreateMemberFile(&desc, myValues, entryFilePath, memberFilePath); /* Remove entry directory; it has done its job */ FileRemoveDirectoryRobust(entryDirectory); if (*err != 0) { /* clean up */ FileDeletionRobust(entryFilePath, FALSE); FileDeletionRobust(memberFilePath, FALSE); FileRemoveDirectoryRobust(lockDir); goto bail; } /* Attempt to acquire the lock */ *err = FileLockScanner(lockDir, FileLockWaitForPossession, myValues, TRUE); switch (*err) { case 0: break; case EAGAIN: /* clean up */ FileDeletionRobust(memberFilePath, FALSE); FileRemoveDirectoryRobust(lockDir); /* FALL THROUGH */ default: break; } bail: Posix_Free(entryDirectory); Posix_Free(entryFilePath); if (*err == 0) { tokenPtr = Util_SafeMalloc(sizeof *tokenPtr); tokenPtr->signature = FILELOCK_TOKEN_SIGNATURE; tokenPtr->portable = TRUE; tokenPtr->pathName = Unicode_Duplicate(pathName); tokenPtr->u.portable.lockFilePath = memberFilePath; } else { Posix_Free(memberFilePath); tokenPtr = NULL; if (*err == EAGAIN) { *err = 0; // lock not acquired } } return tokenPtr; } /* *----------------------------------------------------------------------------- * * FileLockIntrinsic -- * * Obtain a lock on a file; shared or exclusive access. * * All FileLock_-based locks are advisory locks (i.e. the * lock is maintained separately from the file so only FileLock_ * callers experience locking). Advisory locks have an inherent problem * that they are difficult to break in the event one of the cooperating * entities fails, particularly across distributed filesystems. * * This wrapper function will adaptively switch between a scheme * implemented via mandatory locks and a more portable scheme depending * on host OS support. * * maxWaitTimeMsec specifies the maximum amount of time, in * milliseconds, to wait for the lock before returning the "not * acquired" status. A value of FILELOCK_TRYLOCK_WAIT is the * equivalent of a "try lock" - the lock will be acquired only if * there is no contention. A value of FILELOCK_INFINITE_WAIT * specifies "waiting forever" to acquire the lock. * * Results: * NULL Lock not acquired. Check err. * err 0 Lock Timed Out * err > 0 errno * !NULL Lock Acquired. This is the "lockToken" for an unlock. * * Side effects: * None. * *----------------------------------------------------------------------------- */ FileLockToken * FileLockIntrinsic(const char *pathName, // IN: Bool exclusivity, // IN: uint32 maxWaitTimeMsec, // IN: int *err) // OUT: { char *lockBase; LockValues myValues = { 0 }; FileLockToken *tokenPtr; /* Construct the locking directory path */ lockBase = Unicode_Append(pathName, FILELOCK_SUFFIX); myValues.lockType = exclusivity ? LOCK_EXCLUSIVE : LOCK_SHARED; myValues.exclusivity = exclusivity; myValues.startTimeMsec = Hostinfo_SystemTimerMS(); myValues.maxWaitTimeMsec = maxWaitTimeMsec; if (File_SupportsMandatoryLock(pathName)) { LOG(1, ("Requesting %s lock on %s (mandatory, %u).\n", myValues.lockType, pathName, myValues.maxWaitTimeMsec)); tokenPtr = FileLockIntrinsicMandatory(pathName, lockBase, &myValues, err); } else { myValues.machineID = (char *) FileLockGetMachineID(); // don't free this! myValues.executionID = FileLockGetExecutionID(); // free this! myValues.lamportNumber = 0; myValues.locationChecksum = FileLockLocationChecksum(lockBase); // free this! myValues.memberName = NULL; LOG(1, ("Requesting %s lock on %s (%s, %s, %u).\n", myValues.lockType, pathName, myValues.machineID, myValues.executionID, myValues.maxWaitTimeMsec)); tokenPtr = FileLockIntrinsicPortable(pathName, lockBase, &myValues, err); Posix_Free(myValues.memberName); Posix_Free(myValues.locationChecksum); Posix_Free(myValues.executionID); } Posix_Free(lockBase); return tokenPtr; } /* *----------------------------------------------------------------------------- * * FileLockIsLockedMandatory -- * * Is a file currently locked (at the time of the call)? * * The only way to check for a mandatory lock is to try opening * the file (and quickly closing it again). If the lock is held, * attempting to open the file will return FILEIO_LOCK_FAILED. * * Results: * TRUE YES * FALSE NO; if err is not NULL may check *err for an error * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool FileLockIsLockedMandatory(const char *lockFile, // IN: int *err) // OUT/OPT: { int access; FileIOResult result; FileIODescriptor desc; FileIO_Invalidate(&desc); /* * Check for lock by actually locking file, and dropping * lock quickly if open was successful. */ access = FILEIO_OPEN_ACCESS_READ | FILEIO_OPEN_ACCESS_WRITE | FILEIO_OPEN_EXCLUSIVE_LOCK; result = FileIOCreateRetry(&desc, lockFile, access, FILEIO_OPEN, 0644, 0); if (FileIO_IsSuccess(result)) { Bool ret; ret = !FileIO_IsSuccess(FileIO_Close(&desc)); ASSERT(!ret); return FALSE; } else if (result == FILEIO_LOCK_FAILED) { return TRUE; // locked } else if (result == FILEIO_FILE_NOT_FOUND) { return FALSE; // no lock file means unlocked } else { if (err != NULL) { *err = FileMapErrorToErrno(__FUNCTION__, Err_Errno()); } return FALSE; } } /* *----------------------------------------------------------------------------- * * FileLockIsLockedPortable -- * * Is a file currently locked (at the time of the call)? * * The "portable" lock is held if the lock directory exists and * there are any "M" entries (representing held locks). * * FileLocks implemented via mandatory locking are reported * as held locks (errno == ENOTDIR). * * Results: * TRUE YES * FALSE NO; if err is not NULL may check *err for an error * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool FileLockIsLockedPortable(const char *lockDir, // IN: int *err) // OUT/OPT: { uint32 i; int numEntries; Bool isLocked = FALSE; char **fileList = NULL; numEntries = FileListDirectoryRobust(lockDir, &fileList); if (numEntries == -1) { /* * If the lock directory doesn't exist, we should not count this * as an error. This is expected if the file isn't locked. */ if (err != NULL) { *err = (errno == ENOENT) ? 0 : errno; } return FALSE; } for (i = 0; i < numEntries; i++) { if (*fileList[i] == 'M') { isLocked = TRUE; break; } } Util_FreeStringList(fileList, numEntries); return isLocked; } /* *----------------------------------------------------------------------------- * * FileLockIsLocked -- * * Is a file currently locked (at the time of the call)? * * Results: * TRUE YES * FALSE NO; if err is not NULL may check *err for an error * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool FileLockIsLocked(const char *pathName, // IN: int *err) // OUT/OPT: { Bool isLocked; char *lockBase; ASSERT(pathName != NULL); lockBase = Unicode_Append(pathName, FILELOCK_SUFFIX); if (File_SupportsMandatoryLock(pathName)) { isLocked = FileLockIsLockedMandatory(lockBase, err); } else { isLocked = FileLockIsLockedPortable(lockBase, err); } Posix_Free(lockBase); return isLocked; } /* *---------------------------------------------------------------------- * * FileLock_TokenPathName -- * * Return the path name associated with a lock (token). The path name * is returned as a dynamically allocated string the caller is * responsible for. * * Results: * As above * * Side effects: * None. * *---------------------------------------------------------------------- */ char * FileLock_TokenPathName(const FileLockToken *lockToken) // IN: { ASSERT(lockToken && (lockToken->signature == FILELOCK_TOKEN_SIGNATURE)); return Unicode_Duplicate(lockToken->pathName); } open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/filePosix.c000066400000000000000000002445231321503522500241030ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * filePosix.c -- * * Interface to Posix-specific file functions. */ #include /* Needed before sys/vfs.h with glibc 2.0 --hpreg */ #if defined(__FreeBSD__) # include # include #else # if !defined(__APPLE__) # include # endif # include # include /* Needed before sys/mnttab.h in Solaris */ # if defined(sun) # include # elif __APPLE__ # include # else # include # endif #include #endif #include #include #include #include #include #include #include #if defined(__linux__) # include #endif #include "vmware.h" #include "posix.h" #include "file.h" #include "fileInt.h" #include "msg.h" #include "util.h" #include "str.h" #include "util.h" #include "timeutil.h" #include "dynbuf.h" #include "localconfig.h" #include "hostType.h" #include "vmfs.h" #include "hashTable.h" #ifdef VMX86_SERVER #include "fs_public.h" #endif #define LOGLEVEL_MODULE main #include "loglevel_user.h" #include "unicodeOperations.h" #if !defined(__FreeBSD__) && !defined(sun) #if !defined(__APPLE__) static char *FilePosixLookupMountPoint(char const *canPath, Bool *bind); #endif static char *FilePosixNearestExistingAncestor(char const *path); #if defined(VMX86_SERVER) #define VMFS3CONST 256 #include "hostType.h" /* Needed for VMFS implementation of File_GetFreeSpace() */ # include # endif #endif #if defined(VMX86_SERVER) #include "fs_user.h" #endif struct WalkDirContextImpl { int cnt; int iter; char **files; }; /* A string for NFS on ESX file system type */ #define FS_NFS_PREFIX_LEN 3 #define FS_NFS_ON_ESX "NFS" /* A string for VMFS on ESX file system type */ #define FS_VMFS_ON_ESX "VMFS" #define FS_VSAN_URI_PREFIX "vsan:" #if defined __ANDROID__ /* * Android doesn't support setmntent(), endmntent() or MOUNTED. */ #define NO_SETMNTENT #define NO_ENDMNTENT #endif /* Long path chunk growth size */ #define FILE_PATH_GROW_SIZE 1024 /* *----------------------------------------------------------------------------- * * FileRemoveDirectory -- * * Delete a directory. * * Results: * 0 success * > 0 failure (errno) * * Side effects: * May change the host file system. * *----------------------------------------------------------------------------- */ int FileRemoveDirectory(const char *pathName) // IN: { return (Posix_Rmdir(pathName) == -1) ? errno : 0; } /* *----------------------------------------------------------------------------- * * File_Rename -- * * Rename a file. * * Results: * 0 success * > 0 failure (errno) * * Side effects: * May change the host file system. * *----------------------------------------------------------------------------- */ int File_Rename(const char *oldName, // IN: const char *newName) // IN: { return (Posix_Rename(oldName, newName) == -1) ? errno : 0; } int File_RenameRetry(const char *oldFile, // IN: const char *newFile, // IN: uint32 maxWaitTimeMsec) // IN: Unused. { return File_Rename(oldFile, newFile); } /* *---------------------------------------------------------------------- * * FileDeletion -- * Delete the specified file. A NULL pathName will result in an error * and errno will be set to EFAULT. * * Results: * 0 success * > 0 failure (errno) * * Side effects: * May change the host file system. errno may be set. * *---------------------------------------------------------------------- */ int FileDeletion(const char *pathName, // IN: const Bool handleLink) // IN: { int err; if (pathName == NULL) { errno = EFAULT; return errno; } if (handleLink) { char *linkPath = Posix_ReadLink(pathName); if (linkPath == NULL) { /* If there is no link involved, continue */ err = errno; if (err != EINVAL) { goto bail; } } else { err = (Posix_Unlink(linkPath) == -1) ? errno : 0; Posix_Free(linkPath); /* Ignore a file that has already disappeared */ if (err != ENOENT) { goto bail; } } } err = (Posix_Unlink(pathName) == -1) ? errno : 0; bail: return err; } /* *----------------------------------------------------------------------------- * * File_UnlinkDelayed -- * * Same as File_Unlink for POSIX systems since we can unlink anytime. * * Results: * Return 0 if the unlink is successful. Otherwise, returns -1. * * Side effects: * None. * *----------------------------------------------------------------------------- */ int File_UnlinkDelayed(const char *pathName) // IN: { return (FileDeletion(pathName, TRUE) == 0) ? 0 : -1; } /* *----------------------------------------------------------------------------- * * FileAttributes -- * * Return the attributes of a file. Time units are in OS native time. * * Results: * 0 success * > 0 failure (errno) * * Side effects: * None * *----------------------------------------------------------------------------- */ int FileAttributes(const char *pathName, // IN: FileData *fileData) // OUT: { int err; struct stat statbuf; if (Posix_Stat(pathName, &statbuf) == -1) { err = errno; } else { if (fileData != NULL) { fileData->fileCreationTime = statbuf.st_ctime; fileData->fileModificationTime = statbuf.st_mtime; fileData->fileAccessTime = statbuf.st_atime; fileData->fileSize = statbuf.st_size; switch (statbuf.st_mode & S_IFMT) { case S_IFREG: fileData->fileType = FILE_TYPE_REGULAR; break; case S_IFDIR: fileData->fileType = FILE_TYPE_DIRECTORY; break; case S_IFBLK: fileData->fileType = FILE_TYPE_BLOCKDEVICE; break; case S_IFCHR: fileData->fileType = FILE_TYPE_CHARDEVICE; break; case S_IFLNK: fileData->fileType = FILE_TYPE_SYMLINK; break; default: fileData->fileType = FILE_TYPE_UNCERTAIN; break; } fileData->fileMode = statbuf.st_mode; fileData->fileOwner = statbuf.st_uid; fileData->fileGroup = statbuf.st_gid; } err = 0; } return err; } /* *---------------------------------------------------------------------- * * File_IsRemote -- * * Determine whether a file is on a remote filesystem. * * On ESX all files are treated as local files, as all * callers of this function wants to do is to post message * that performance will be degraded on remote filesystems. * On ESX (a) performance should be acceptable with remote * files, and (b) even if it is not, we should not ask users * whether they are aware that it is poor. ESX has * performance monitoring which can notify user if something * is wrong. * * On hosted platform we report remote files as faithfully * as we can because having mainmem file on NFS is known * to badly affect VM consistency when NFS filesystem gets * reconnected. Due to that we are conservative, and report * filesystem as remote if there was some problem with * determining file remoteness. * * Results: * The answer. * * Side effects: * None * *---------------------------------------------------------------------- */ #if !defined(__FreeBSD__) && !defined(sun) Bool File_IsRemote(const char *pathName) // IN: Path name { if (HostType_OSIsVMK()) { /* * All files and file systems are treated as "directly attached" * on ESX. See bug 158284. */ return FALSE; } else { struct statfs sfbuf; if (Posix_Statfs(pathName, &sfbuf) == -1) { Log(LGPFX" %s: statfs(%s) failed: %s\n", __func__, pathName, Err_Errno2String(errno)); return TRUE; } #if defined(__APPLE__) return sfbuf.f_flags & MNT_LOCAL ? FALSE : TRUE; #else if (NFS_SUPER_MAGIC == sfbuf.f_type) { return TRUE; } if (SMB_SUPER_MAGIC == sfbuf.f_type) { return TRUE; } if (CIFS_SUPER_MAGIC == sfbuf.f_type) { return TRUE; } return FALSE; #endif } } #endif /* !FreeBSD && !sun */ /* *---------------------------------------------------------------------- * * File_IsSymLink -- * * Check if the specified file is a symbolic link or not * * Results: * Bool - TRUE -> is a symlink, FALSE -> not a symlink or error * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_IsSymLink(const char *pathName) // IN: { struct stat statbuf; return (Posix_Lstat(pathName, &statbuf) == 0) && S_ISLNK(statbuf.st_mode); } /* *---------------------------------------------------------------------- * * File_Cwd -- * * Find the current directory on drive DRIVE. DRIVE is either NULL * (current drive) or a string starting with [A-Za-z]. * * Results: * NULL if error. * * Side effects: * The result is allocated * *---------------------------------------------------------------------- */ char * File_Cwd(const char *drive) // IN: { size_t size; char *buffer; char *path; if ((drive != NULL) && !Unicode_IsEmpty(drive)) { Warning(LGPFX" %s: Drive letter %s on Linux?\n", __FUNCTION__, drive); } size = FILE_PATH_GROW_SIZE; buffer = Util_SafeMalloc(size); while (TRUE) { if (getcwd(buffer, size) != NULL) { break; } Posix_Free(buffer); buffer = NULL; if (errno != ERANGE) { break; } size += FILE_PATH_GROW_SIZE; buffer = Util_SafeMalloc(size); } if (buffer == NULL) { Msg_Append(MSGID(filePosix.getcwd) "Unable to retrieve the current working directory: %s. " "Check if the directory has been deleted or unmounted.\n", Msg_ErrString()); Warning(LGPFX" %s: getcwd() failed: %s\n", __FUNCTION__, Msg_ErrString()); return NULL; } path = Unicode_Alloc(buffer, STRING_ENCODING_DEFAULT); Posix_Free(buffer); return path; } /* *---------------------------------------------------------------------- * * File_StripFwdSlashes -- * * Returns a new string with the extraneous forward slashes ("/") removed. * * Results: * As documented. * * Side effects: * None * *---------------------------------------------------------------------- */ char * File_StripFwdSlashes(const char *pathName) // IN: { char *ptr; char *path; char *cptr; char *prev; char *result; ASSERT(pathName != NULL); path = Unicode_GetAllocBytes(pathName, STRING_ENCODING_UTF8); ASSERT(path != NULL); ptr = path; cptr = path; prev = NULL; /* * Copy over if not DIRSEPC. If yes, copy over only if previous * character was not DIRSEPC. */ while (*ptr != '\0') { if (*ptr == DIRSEPC) { if (prev != ptr - 1) { *cptr++ = *ptr; } prev = ptr; } else { *cptr++ = *ptr; } ptr++; } *cptr = '\0'; result = Unicode_AllocWithUTF8(path); Posix_Free(path); return result; } /* *---------------------------------------------------------------------- * * File_FullPath -- * * This routine computes the canonical path from a supplied path. * The supplied path could be an absolute path name or a relative * one, with our without symlinks and /./ /../ separators. A * canonical representation of a path is defined as an absolute * path without symlinks and /./ /../ separators. The canonical * path of "." is the current working directory, ".." is parent * directory and so on. If the path is NULL or "", this routine * returns the current working directory. * There are mainly two use cases for this function. To find the * canonical path of a file or directory that exists, or when we * are about to create a child in an existing parent directory. * For other uses cases, this routine is not guaranteed to return * a canonical path. * * Results: * NULL if error (reported to the user) * * Side effects: * The result is allocated * *---------------------------------------------------------------------- */ char * File_FullPath(const char *pathName) // IN: { char *cwd; char *ret; if ((pathName != NULL) && File_IsFullPath(pathName)) { cwd = NULL; } else { cwd = File_Cwd(NULL); if (cwd == NULL) { return NULL; } } if ((pathName == NULL) || Unicode_IsEmpty(pathName)) { ret = Unicode_Duplicate(cwd); } else { char *path; if (File_IsFullPath(pathName)) { path = Unicode_Duplicate(pathName); } else { path = Unicode_Join(cwd, DIRSEPS, pathName, NULL); } ret = Posix_RealPath(path); if (ret == NULL) { char *dir; char *file; char *realDir; File_GetPathName(path, &dir, &file); realDir = Posix_RealPath(dir); if (realDir == NULL) { realDir = File_StripFwdSlashes(dir); } ret = Unicode_Join(realDir, DIRSEPS, file, NULL); Posix_Free(dir); Posix_Free(file); Posix_Free(realDir); } Posix_Free(path); } Posix_Free(cwd); return ret; } /* *---------------------------------------------------------------------- * * File_IsFullPath -- * * Is this a full path? * * Results: * TRUE if full path. * * Side effects: * None. * *---------------------------------------------------------------------- */ Bool File_IsFullPath(const char *pathName) // IN: { /* start with a slash? */ return pathName != NULL && pathName[0] == DIRSEPC; } /* *---------------------------------------------------------------------- * * File_GetTimes -- * * Get the date and time that a file was created, last accessed, * last modified and last attribute changed. * * Results: * TRUE if succeed or FALSE if error. * * Side effects: * If a particular time is not available, -1 will be returned for * that time. * *---------------------------------------------------------------------- */ Bool File_GetTimes(const char *pathName, // IN: VmTimeType *createTime, // OUT: Windows NT time format VmTimeType *accessTime, // OUT: Windows NT time format VmTimeType *writeTime, // OUT: Windows NT time format VmTimeType *attrChangeTime) // OUT: Windows NT time format { struct stat statBuf; ASSERT(createTime && accessTime && writeTime && attrChangeTime); *createTime = -1; *accessTime = -1; *writeTime = -1; *attrChangeTime = -1; if (Posix_Lstat(pathName, &statBuf) == -1) { Log(LGPFX" %s: error stating file \"%s\": %s\n", __FUNCTION__, pathName, Err_Errno2String(errno)); return FALSE; } /* * XXX We should probably use the MIN of all Unix times for the creation * time, so that at least times are never inconsistent in the * cross-platform format. Maybe atime is always that MIN. We should * check and change the code if it is not. * * XXX atime is almost always MAX. */ #if defined(__FreeBSD__) /* * FreeBSD: All supported versions have timestamps with nanosecond * resolution. FreeBSD 5+ has also file creation time. */ # if defined(__FreeBSD_version) && __FreeBSD_version >= 500043 *createTime = TimeUtil_UnixTimeToNtTime(statBuf.st_birthtimespec); # endif *accessTime = TimeUtil_UnixTimeToNtTime(statBuf.st_atimespec); *writeTime = TimeUtil_UnixTimeToNtTime(statBuf.st_mtimespec); *attrChangeTime = TimeUtil_UnixTimeToNtTime(statBuf.st_ctimespec); #elif defined(__linux__) /* * Linux: Glibc 2.3+ has st_Xtim. Glibc 2.1/2.2 has st_Xtime/__unusedX on * same place (see below). We do not support Glibc 2.0 or older. */ # if (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 3) && !defined(__UCLIBC__) { /* * stat structure is same between glibc 2.3 and older glibcs, just * these __unused fields are always zero. If we'll use __unused* * instead of zeroes, we get automatically nanosecond timestamps * when running on host which provides them. */ struct timespec timeBuf; timeBuf.tv_sec = statBuf.st_atime; timeBuf.tv_nsec = statBuf.__unused1; *accessTime = TimeUtil_UnixTimeToNtTime(timeBuf); timeBuf.tv_sec = statBuf.st_mtime; timeBuf.tv_nsec = statBuf.__unused2; *writeTime = TimeUtil_UnixTimeToNtTime(timeBuf); timeBuf.tv_sec = statBuf.st_ctime; timeBuf.tv_nsec = statBuf.__unused3; *attrChangeTime = TimeUtil_UnixTimeToNtTime(timeBuf); } # elif defined(__ANDROID__) { struct timespec timeBuf; timeBuf.tv_sec = statBuf.st_atime; timeBuf.tv_nsec = statBuf.st_atime_nsec; *accessTime = TimeUtil_UnixTimeToNtTime(timeBuf); timeBuf.tv_sec = statBuf.st_mtime; timeBuf.tv_nsec = statBuf.st_mtime_nsec; *writeTime = TimeUtil_UnixTimeToNtTime(timeBuf); timeBuf.tv_sec = statBuf.st_ctime; timeBuf.tv_nsec = statBuf.st_ctime_nsec; *attrChangeTime = TimeUtil_UnixTimeToNtTime(timeBuf); } # else *accessTime = TimeUtil_UnixTimeToNtTime(statBuf.st_atim); *writeTime = TimeUtil_UnixTimeToNtTime(statBuf.st_mtim); *attrChangeTime = TimeUtil_UnixTimeToNtTime(statBuf.st_ctim); # endif #elif defined(__APPLE__) /* Mac: No file create timestamp. */ *accessTime = TimeUtil_UnixTimeToNtTime(statBuf.st_atimespec); *writeTime = TimeUtil_UnixTimeToNtTime(statBuf.st_mtimespec); *attrChangeTime = TimeUtil_UnixTimeToNtTime(statBuf.st_ctimespec); #else { /* Solaris: No nanosecond timestamps, no file create timestamp. */ struct timespec timeBuf; timeBuf.tv_nsec = 0; timeBuf.tv_sec = statBuf.st_atime; *accessTime = TimeUtil_UnixTimeToNtTime(timeBuf); timeBuf.tv_sec = statBuf.st_mtime; *writeTime = TimeUtil_UnixTimeToNtTime(timeBuf); timeBuf.tv_sec = statBuf.st_ctime; *attrChangeTime = TimeUtil_UnixTimeToNtTime(timeBuf); } #endif return TRUE; } /* *---------------------------------------------------------------------- * * File_SetTimes -- * * Set the date and time that a file was created, last accessed, or * last modified. * * Results: * TRUE if succeed or FALSE if error. * * Side effects: * If fileName is a symlink, target's timestamps will be updated. * Symlink itself's timestamps will not be changed. * *---------------------------------------------------------------------- */ Bool File_SetTimes(const char *pathName, // IN: VmTimeType createTime, // IN: ignored VmTimeType accessTime, // IN: Windows NT time format VmTimeType writeTime, // IN: Windows NT time format VmTimeType attrChangeTime) // IN: ignored { struct timeval times[2]; struct timeval *aTime, *wTime; struct stat statBuf; char *path; int err; if (pathName == NULL) { return FALSE; } path = Unicode_GetAllocBytes(pathName, STRING_ENCODING_DEFAULT); if (path == NULL) { Log(LGPFX" %s: failed to convert \"%s\" to current encoding\n", __FUNCTION__, pathName); return FALSE; } err = (lstat(path, &statBuf) == -1) ? errno : 0; if (err != 0) { Log(LGPFX" %s: error stating file \"%s\": %s\n", __FUNCTION__, pathName, Err_Errno2String(err)); Posix_Free(path); return FALSE; } aTime = ×[0]; wTime = ×[1]; /* * Preserve old times if new time <= 0. * XXX Need a better implementation to preserve tv_usec. */ aTime->tv_sec = statBuf.st_atime; aTime->tv_usec = 0; wTime->tv_sec = statBuf.st_mtime; wTime->tv_usec = 0; if (accessTime > 0) { struct timespec ts; TimeUtil_NtTimeToUnixTime(&ts, accessTime); aTime->tv_sec = ts.tv_sec; aTime->tv_usec = ts.tv_nsec / 1000; } if (writeTime > 0) { struct timespec ts; TimeUtil_NtTimeToUnixTime(&ts, writeTime); wTime->tv_sec = ts.tv_sec; wTime->tv_usec = ts.tv_nsec / 1000; } err = (utimes(path, times) == -1) ? errno : 0; Posix_Free(path); if (err != 0) { Log(LGPFX" %s: utimes error on file \"%s\": %s\n", __FUNCTION__, pathName, Err_Errno2String(err)); return FALSE; } return TRUE; } /* *---------------------------------------------------------------------- * * File_SetFilePermissions -- * * Set file permissions. * * Results: * TRUE if succeed or FALSE if error. * * Side effects: * None. * *---------------------------------------------------------------------- */ Bool File_SetFilePermissions(const char *pathName, // IN: int perms) // IN: permissions { ASSERT(pathName != NULL); if (Posix_Chmod(pathName, perms) == -1) { /* The error is not critical, just log it. */ Log(LGPFX" %s: failed to change permissions on file \"%s\": %s\n", __FUNCTION__, pathName, Err_Errno2String(errno)); return FALSE; } return TRUE; } #if !defined(__FreeBSD__) && !defined(sun) /* *----------------------------------------------------------------------------- * * FilePosixGetParent -- * * The input buffer is a canonical path name. Change it in place to the * canonical path name of its parent directory. * * Although this code is quite simple, we encapsulate it in a function * because it is easy to get it wrong. * * Results: * TRUE The input buffer was (and remains) the root directory. * FALSE The input buffer was not the root directory and was changed in * place to its parent directory. * * Example: "/foo/bar" -> "/foo" FALSE * "/foo" -> "/" FALSE * "/" -> "/" TRUE * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool FilePosixGetParent(char **canPath) // IN/OUT: Canonical file path { char *pathName; char *baseName; ASSERT(canPath != NULL); ASSERT(File_IsFullPath(*canPath)); if (Unicode_Compare(*canPath, DIRSEPS) == 0) { return TRUE; } File_GetPathName(*canPath, &pathName, &baseName); Posix_Free(*canPath); if (Unicode_IsEmpty(pathName)) { /* empty string which denotes "/" */ Posix_Free(pathName); *canPath = Unicode_Duplicate("/"); } else { if (Unicode_IsEmpty(baseName)) { // Directory File_GetPathName(pathName, canPath, NULL); Posix_Free(pathName); } else { // File *canPath = pathName; } } Posix_Free(baseName); return FALSE; } /* *----------------------------------------------------------------------------- * * File_GetParent -- * * The input buffer is a canonical path name. Change it in place to the * canonical path name of its parent directory. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool File_GetParent(char **canPath) // IN/OUT: Canonical file path { return FilePosixGetParent(canPath); } /* *---------------------------------------------------------------------- * * FileGetStats -- * * Calls statfs on a full path (eg. something returned from File_FullPath). * If doNotAscend is FALSE, climb up the directory chain and call statfs * on each level until it succeeds. * * Results: * TRUE statfs succeeded * FALSE unable to statfs anything along the path * * Side effects: * None * *---------------------------------------------------------------------- */ static Bool FileGetStats(const char *pathName, // IN: Bool doNotAscend, // IN: struct statfs *pstatfsbuf) // OUT: { Bool retval = TRUE; char *dupPath = NULL; while (Posix_Statfs(dupPath ? dupPath : pathName, pstatfsbuf) == -1) { if (errno != ENOENT || doNotAscend) { retval = FALSE; break; } if (dupPath == NULL) { /* Dup fullPath, so as not to modify input parameters */ dupPath = Unicode_Duplicate(pathName); } FilePosixGetParent(&dupPath); } Posix_Free(dupPath); return retval; } /* *---------------------------------------------------------------------- * * File_GetFreeSpace -- * * Return the free space (in bytes) available to the user on a disk where * a file is or would be. If doNotAscend is FALSE, the helper function * ascends the directory chain on system call errors in order to obtain * the file system information. * * Results: * -1 if error (reported to the user) * * Side effects: * None * *---------------------------------------------------------------------- */ uint64 File_GetFreeSpace(const char *pathName, // IN: File name Bool doNotAscend) // IN: Do not ascend dir chain { uint64 ret; char *fullPath; struct statfs statfsbuf; fullPath = File_FullPath(pathName); if (fullPath == NULL) { return -1; } if (FileGetStats(fullPath, doNotAscend, &statfsbuf)) { ret = (uint64) statfsbuf.f_bavail * statfsbuf.f_bsize; } else { Warning("%s: Couldn't statfs %s\n", __func__, fullPath); ret = -1; } Posix_Free(fullPath); return ret; } #if defined(VMX86_SERVER) /* *---------------------------------------------------------------------- * * File_GetVMFSAttributes -- * * Acquire the attributes for a given file or directory on a VMFS volume. * * Results: * Integer return value and populated FS_PartitionListResult * * Side effects: * Will fail if file is not on VMFS or not enough memory for partition * query results * *---------------------------------------------------------------------- */ int File_GetVMFSAttributes(const char *pathName, // IN: File/dir to test FS_PartitionListResult **fsAttrs) // IN/OUT: VMFS Info { int fd; int ret; char *fullPath; char *directory = NULL; fullPath = File_FullPath(pathName); if (fullPath == NULL) { ret = -1; goto bail; } if (File_IsDirectory(fullPath)) { directory = Unicode_Duplicate(fullPath); } else { File_SplitName(fullPath, NULL, &directory, NULL); } if (!HostType_OSIsVMK()) { Log(LGPFX" %s: File %s not on VMFS volume\n", __func__, pathName); ret = -1; goto bail; } *fsAttrs = Util_SafeMalloc(FS_PARTITION_ARR_SIZE(FS_PLIST_DEF_MAX_PARTITIONS)); memset(*fsAttrs, 0, FS_PARTITION_ARR_SIZE(FS_PLIST_DEF_MAX_PARTITIONS)); (*fsAttrs)->ioctlAttr.maxPartitions = FS_PLIST_DEF_MAX_PARTITIONS; (*fsAttrs)->ioctlAttr.getAttrSpec = FS_ATTR_SPEC_BASIC; fd = Posix_Open(directory, O_RDONLY, 0); if (fd == -1) { Log(LGPFX" %s: could not open %s: %s\n", __func__, pathName, Err_Errno2String(errno)); ret = -1; Posix_Free(*fsAttrs); *fsAttrs = NULL; goto bail; } ret = ioctl(fd, IOCTLCMD_VMFS_FS_GET_ATTR, (char *) *fsAttrs); if (ret == -1) { Log(LGPFX" %s: Could not get volume attributes (ret = %d): %s\n", __func__, ret, Err_Errno2String(errno)); Posix_Free(*fsAttrs); *fsAttrs = NULL; } close(fd); bail: Posix_Free(fullPath); Posix_Free(directory); return ret; } /* *---------------------------------------------------------------------- * * File_GetVMFSFSType -- * * Get the filesystem type number of the file system on which the * given file/directory resides. * * Caller can specify either a pathname or an already opened fd of * the file/dir whose filesystem he wants to determine. * 'fd' takes precedence over 'pathName' so 'pathName' is used only * if 'fd' is -1. * * Results: * On success : return value 0 and file type number in 'fsTypeNum'. * On failure : return value -1 (errno will be set appropriately). * * Side effects: * On failure errno will be set. * *---------------------------------------------------------------------- */ int File_GetVMFSFSType(const char *pathName, // IN: File name to test int fd, // IN: fd of an already opened file uint16 *fsTypeNum) // OUT: Filesystem type number { int ret, savedErrno; Bool fdArg = (fd >= 0); /* fd or pathname ? */ if (!fsTypeNum || (!fdArg && !pathName)) { savedErrno = EINVAL; goto exit; } if (!fdArg) { fd = Posix_Open(pathName, O_RDONLY, 0); if (fd < 0) { savedErrno = errno; Log(LGPFX" %s : Could not open %s : %s\n", __func__, pathName, Err_Errno2String(savedErrno)); goto exit; } } ret = ioctl(fd, IOCTLCMD_VMFS_GET_FSTYPE, fsTypeNum); /* * Save errno to avoid close() affecting it. */ savedErrno = errno; if (!fdArg) { close(fd); } if (ret == -1) { Log(LGPFX" %s : Could not get filesystem type for %s (fd %d) : %s\n", __func__, (!fdArg ? pathName : "__na__"), fd, Err_Errno2String(savedErrno)); goto exit; } return 0; exit: errno = savedErrno; ASSERT(errno != 0); return -1; } /* *---------------------------------------------------------------------- * * File_GetVMFSVersion -- * * Get the version number of the VMFS file system on which the * given file resides. * * Results: * Integer return value and version number. * * Side effects: * Will fail if file is not on VMFS or not enough memory for partition * query results. * *---------------------------------------------------------------------- */ int File_GetVMFSVersion(const char *pathName, // IN: File name to test uint32 *versionNum) // OUT: Version number { int ret = -1; FS_PartitionListResult *fsAttrs = NULL; if (versionNum == NULL) { errno = EINVAL; goto exit; } ret = File_GetVMFSAttributes(pathName, &fsAttrs); if (ret < 0) { Log(LGPFX" %s: File_GetVMFSAttributes failed\n", __func__); } else { *versionNum = fsAttrs->versionNumber; } if (fsAttrs) { Posix_Free(fsAttrs); } exit: return ret; } /* *---------------------------------------------------------------------- * * File_GetVMFSBlockSize -- * * Acquire the blocksize for a given file on a VMFS file system. * * Results: * Integer return value and block size * * Side effects: * Will fail if file is not on VMFS or not enough memory for partition * query results * *---------------------------------------------------------------------- */ int File_GetVMFSBlockSize(const char *pathName, // IN: File name to test uint32 *blockSize) // IN/OUT: VMFS block size { int ret = -1; FS_PartitionListResult *fsAttrs = NULL; if (blockSize == NULL) { errno = EINVAL; goto exit; } ret = File_GetVMFSAttributes(pathName, &fsAttrs); if (ret < 0) { Log(LGPFX" %s: File_GetVMFSAttributes failed\n", __func__); } else { *blockSize = fsAttrs->fileBlockSize; } if (fsAttrs) { Posix_Free(fsAttrs); } exit: return ret; } /* *---------------------------------------------------------------------- * * File_GetVMFSMountInfo -- * * Acquire the FS mount point info such as fsType, major version, * local mount point (/vmfs/volumes/xyz), and for NFS, * remote IP and remote mount point for a given file. * * Results: * Integer return value and allocated data * * Side effects: * Only implemented on ESX. Will fail on other platforms. * remoteIP and remoteMountPoint are only populated for files on NFS. * *---------------------------------------------------------------------- */ int File_GetVMFSMountInfo(const char *pathName, // IN: char **fsType, // OUT: uint32 *version, // OUT: char **remoteIP, // OUT: char **remoteMountPoint, // OUT: char **localMountPoint) // OUT: { int ret; FS_PartitionListResult *fsAttrs = NULL; *localMountPoint = File_GetUniqueFileSystemID(pathName); if (*localMountPoint == NULL) { return -1; } /* Get file IP and mount point */ ret = File_GetVMFSAttributes(pathName, &fsAttrs); if (ret >= 0 && fsAttrs) { *version = fsAttrs->versionNumber; *fsType = Util_SafeStrdup(fsAttrs->fsType); /* * We only compare the first 3 characters 'NFS'xx. * This will cover both NFSv3 and NFSv4.1. */ if (strncmp(fsAttrs->fsType, FS_NFS_ON_ESX, FS_NFS_PREFIX_LEN) == 0) { char *sep = strchr(fsAttrs->logicalDevice, ' '); if (sep) { *sep++ = 0; *remoteIP = Util_SafeStrdup(fsAttrs->logicalDevice); *remoteMountPoint = Util_SafeStrdup(sep); } else { *remoteIP = NULL; *remoteMountPoint = NULL; } } else { *remoteIP = NULL; *remoteMountPoint = NULL; } Posix_Free(fsAttrs); } return ret; } #endif /* *---------------------------------------------------------------------- * * FileIsVMFS -- * * Is the given file on a filesystem that supports vmfs-specific * features like zeroed-thick and multiwriter files? * * Results: * TRUE if we're on VMFS. * * Side effects: * None * *---------------------------------------------------------------------- */ static Bool FileIsVMFS(const char *pathName) // IN: { Bool result = FALSE; #if defined(VMX86_SERVER) /* Right now only VMFS supports zeroedThick and multiWriter. */ FS_PartitionListResult *fsAttrs = NULL; if (File_GetVMFSAttributes(pathName, &fsAttrs) >= 0) { /* We want to match anything that starts with VMFS */ result = strncmp(fsAttrs->fsType, FS_VMFS_ON_ESX, strlen(FS_VMFS_ON_ESX)) == 0; } else { Log(LGPFX" %s: File_GetVMFSAttributes failed\n", __func__); } if (fsAttrs) { Posix_Free(fsAttrs); } #endif return result; } /* *---------------------------------------------------------------------- * * File_SupportsZeroedThick -- * * Check if the given file is on an FS supports creation of * the zeroed-thick files. * Currently only VMFS on ESX does support zeroed-thick files, but * this may change in the future. * * Results: * TRUE if FS supports creation of the zeroed-thick files. * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_SupportsZeroedThick(const char *pathName) // IN: { return FileIsVMFS(pathName); } /* *---------------------------------------------------------------------- * * File_SupportsMultiWriter -- * * Check if the given file is on an FS supports opening files * in multi-writer mode. * Currently only VMFS on ESX supports multi-writer mode, but * this may change in the future. * * Results: * TRUE if FS supports opening files in multi-writer mode. * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_SupportsMultiWriter(const char *pathName) // IN: { return FileIsVMFS(pathName); } /* *---------------------------------------------------------------------- * * File_SupportsOptimisticLock -- * * Return TRUE if the given file is on an FS that supports the * FILEIO_OPEN_OPTIMISTIC_LOCK flag (only VMFS). * * Results: * See above. * * Side effects: * None. * *---------------------------------------------------------------------- */ Bool File_SupportsOptimisticLock(const char *pathName) // IN: { #ifdef VMX86_SERVER uint16 fsTypeNum; char *dir; char *tempPath = NULL; const char *fullPath; int res; /* * File_GetVMFSFSType works much faster on directories, so get the * directory. */ if (File_IsFullPath(pathName)) { fullPath = pathName; } else { tempPath = File_FullPath(pathName); fullPath = tempPath; } File_GetPathName(fullPath, &dir, NULL); res = File_GetVMFSFSType(dir, -1, &fsTypeNum); Posix_Free(tempPath); Posix_Free(dir); return (res == 0) ? IS_VMFS_FSTYPENUM(fsTypeNum) : FALSE; #else return FALSE; #endif } /* *---------------------------------------------------------------------- * * File_GetCapacity -- * * Return the total capacity (in bytes) available to the user on a disk * where a file is or would be * * Results: * -1 if error (reported to the user) * * Side effects: * None * *---------------------------------------------------------------------- */ uint64 File_GetCapacity(const char *pathName) // IN: Path name { uint64 ret; char *fullPath; struct statfs statfsbuf; fullPath = File_FullPath(pathName); if (fullPath == NULL) { return -1; } if (FileGetStats(fullPath, FALSE, &statfsbuf)) { ret = (uint64) statfsbuf.f_blocks * statfsbuf.f_bsize; } else { Warning(LGPFX" %s: Couldn't statfs\n", __func__); ret = -1; } Posix_Free(fullPath); return ret; } /* *----------------------------------------------------------------------------- * * File_GetUniqueFileSystemID -- * * Returns a string which uniquely identifies the underlying filesystem * for a given path. * * 'path' can be relative (including empty) or absolute, and any number * of non-existing components at the end of 'path' are simply ignored. * * XXX: On POSIX systems, we choose the underlying device's name as the * unique ID. I make no claim that this is 100% unique so if you * need this functionality to be 100% perfect, I suggest you think * about it more deeply than I did. -meccleston * * Results: * On success: Allocated and NUL-terminated filesystem ID. * On failure: NULL. * * Side effects: * None * *----------------------------------------------------------------------------- */ char * File_GetUniqueFileSystemID(char const *path) // IN: File path { #ifdef VMX86_SERVER char vmfsVolumeName[FILE_MAXPATH]; char *existPath; char *canPath; existPath = FilePosixNearestExistingAncestor(path); canPath = Posix_RealPath(existPath); /* * Returns "/vmfs/devices" for DEVFS. Since /vmfs/devices is symbol linker, * We don't use realpath here. */ if (strncmp(existPath, DEVFS_MOUNT_POINT, strlen(DEVFS_MOUNT_POINT)) == 0) { char devfsName[FILE_MAXPATH]; if (sscanf(existPath, DEVFS_MOUNT_PATH "%[^/]%*s", devfsName) == 1) { Posix_Free(existPath); Posix_Free(canPath); return Str_SafeAsprintf(NULL, "%s/%s", DEVFS_MOUNT_POINT, devfsName); } } Posix_Free(existPath); if (canPath == NULL) { return NULL; } /* * VCFS doesn't have real mount points, so the mount point lookup below * returns "/vmfs", instead of the VCFS mount point. * * See bug 61646 for why we care. */ if (strncmp(canPath, VCFS_MOUNT_POINT, strlen(VCFS_MOUNT_POINT)) != 0 || sscanf(canPath, VCFS_MOUNT_PATH "%[^/]%*s", vmfsVolumeName) != 1) { Posix_Free(canPath); goto exit; } /* * If the path points to a file or directory that is on a vsan datastore, * we have to determine which namespace object is involved. */ if (strncmp(vmfsVolumeName, FS_VSAN_URI_PREFIX, strlen(FS_VSAN_URI_PREFIX)) == 0) { FS_PartitionListResult *fsAttrs = NULL; int res; res = File_GetVMFSAttributes(canPath, &fsAttrs); if (res >= 0 && fsAttrs != NULL && strncmp(fsAttrs->fsType, FS_VMFS_ON_ESX, strlen(FS_VMFS_ON_ESX)) == 0) { char *unique; unique = Str_SafeAsprintf(NULL, "%s/%s/%s", VCFS_MOUNT_POINT, vmfsVolumeName, fsAttrs->name); Posix_Free(fsAttrs); Posix_Free(canPath); return unique; } Posix_Free(fsAttrs); } Posix_Free(canPath); return Str_SafeAsprintf(NULL, "%s/%s", VCFS_MOUNT_POINT, vmfsVolumeName); exit: #endif return FilePosixGetBlockDevice(path); } #if !defined(__APPLE__) /* *----------------------------------------------------------------------------- * * FilePosixLookupMountPoint -- * * Looks up passed in canonical file path in list of mount points. * If there is a match, it returns the underlying device name of the * mount point along with a flag indicating whether the mount point is * mounted with the "--[r]bind" option. * * Results: * On success: The allocated, NUL-terminated mounted "device". * On failure: NULL. * * Side effects: * None * *----------------------------------------------------------------------------- */ static char * FilePosixLookupMountPoint(char const *canPath, // IN: Canonical file path Bool *bind) // OUT: Mounted with --[r]bind? { #if defined NO_SETMNTENT || defined NO_ENDMNTENT NOT_IMPLEMENTED(); errno = ENOSYS; return NULL; #else FILE *f; struct mntent mnt; char *buf; size_t size; size_t used; char *ret = NULL; ASSERT(canPath != NULL); ASSERT(bind != NULL); size = 4 * FILE_MAXPATH; // Should suffice for most locales retry: f = setmntent(MOUNTED, "r"); if (f == NULL) { return NULL; } buf = Util_SafeMalloc(size); while (Posix_Getmntent_r(f, &mnt, buf, size) != NULL) { /* * Our Posix_Getmntent_r graciously sets errno when the buffer * is too small, but on UTF-8 based platforms Posix_Getmntent_r * is #defined to the system's getmntent_r, which can simply * truncate the strings with no other indication. See how much * space it used and increase the buffer size if needed. Note * that if some of the strings are empty, they may share a * common nul in the buffer, and the resulting size calculation * will be a little over-zealous. */ used = 0; if (mnt.mnt_fsname) { used += strlen(mnt.mnt_fsname) + 1; } if (mnt.mnt_dir) { used += strlen(mnt.mnt_dir) + 1; } if (mnt.mnt_type) { used += strlen(mnt.mnt_type) + 1; } if (mnt.mnt_opts) { used += strlen(mnt.mnt_opts) + 1; } if (used >= size || !mnt.mnt_fsname || !mnt.mnt_dir || !mnt.mnt_type || !mnt.mnt_opts) { size += 4 * FILE_MAXPATH; ASSERT(size <= 32 * FILE_MAXPATH); Posix_Free(buf); endmntent(f); goto retry; } /* * NB: A call to realpath is not needed as getmntent() already * returns it in canonical form. Additionally, it is bad * to call realpath() as often a mount point is down, and * realpath calls stat which can block trying to stat * a filesystem that the caller of the function is not at * all expecting. */ if (strcmp(mnt.mnt_dir, canPath) == 0) { /* * The --bind and --rbind options behave differently. See * FilePosixGetBlockDevice() for details. * * Sadly (I blame a bug in 'mount'), there is no way to tell them * apart in /etc/mtab: the option recorded there is, in both cases, * always "bind". */ *bind = strstr(mnt.mnt_opts, "bind") != NULL; ret = Util_SafeStrdup(mnt.mnt_fsname); break; } } // 'canPath' is not a mount point. endmntent(f); Posix_Free(buf); return ret; #endif } #endif /* *----------------------------------------------------------------------------- * * FilePosixGetBlockDevice -- * * Retrieve the block device that backs file path 'path'. * * 'path' can be relative (including empty) or absolute, and any number of * non-existing components at the end of 'path' are simply ignored. * * Results: * On success: The allocated, NUL-terminated block device absolute path. * On failure: NULL. * * Side effects: * None * *----------------------------------------------------------------------------- */ char * FilePosixGetBlockDevice(char const *path) // IN: File path { char *existPath; Bool failed; #if defined(__APPLE__) struct statfs buf; #else char canPath[FILE_MAXPATH]; char canPath2[FILE_MAXPATH]; unsigned int retries = 0; char *realPath; #endif existPath = FilePosixNearestExistingAncestor(path); #if defined(__APPLE__) failed = statfs(existPath, &buf) == -1; Posix_Free(existPath); if (failed) { return NULL; } return Util_SafeStrdup(buf.f_mntfromname); #else realPath = Posix_RealPath(existPath); Posix_Free(existPath); if (realPath == NULL) { return NULL; } Str_Strcpy(canPath, realPath, sizeof canPath); Posix_Free(realPath); retry: Str_Strcpy(canPath2, canPath, sizeof canPath2); /* Find the nearest ancestor of 'canPath' that is a mount point. */ for (;;) { char *x; Bool bind = FALSE; char *ptr; ptr = FilePosixLookupMountPoint(canPath, &bind); if (ptr) { if (bind) { /* * 'canPath' is a mount point mounted with --[r]bind. This is the * mount equivalent of a hard link. Follow the rabbit... * * --bind and --rbind behave differently. Consider this mount * table: * * /dev/sda1 / ext3 * exit14:/vol/vol0/home /exit14/home nfs * / /bind (mounted with --bind) * / /rbind (mounted with --rbind) * * then what we _should_ return for these paths is: * * /bind/exit14/home -> /dev/sda1 * /rbind/exit14/home -> exit14:/vol/vol0/home * * XXX but currently because we cannot easily tell the difference, * we always assume --rbind and we return: * * /bind/exit14/home -> exit14:/vol/vol0/home * /rbind/exit14/home -> exit14:/vol/vol0/home */ Bool rbind = TRUE; if (rbind) { /* * Compute 'canPath = ptr + (canPath2 - canPath)' using and * preserving the structural properties of all canonical * paths involved in the expression. */ size_t canPathLen = strlen(canPath); char const *diff = canPath2 + (canPathLen > 1 ? canPathLen : 0); if (*diff != '\0') { Str_Sprintf(canPath, sizeof canPath, "%s%s", strlen(ptr) > 1 ? ptr : "", diff); } else { Str_Strcpy(canPath, ptr, sizeof canPath); } } else { Str_Strcpy(canPath, ptr, sizeof canPath); } Posix_Free(ptr); /* * There could be a series of these chained together. It is * possible for the mounts to get into a loop, so limit the total * number of retries to something reasonable like 10. */ retries++; if (retries > 10) { Warning(LGPFX" %s: The --[r]bind mount count exceeds %u. Giving " "up.\n", __func__, 10); return NULL; } goto retry; } return ptr; } /* XXX temporary work-around until this function is Unicoded. */ x = Util_SafeStrdup(canPath); failed = FilePosixGetParent(&x); Str_Strcpy(canPath, x, sizeof canPath); Posix_Free(x); /* * Prevent an infinite loop in case FilePosixLookupMountPoint() even * fails on "/". */ if (failed) { return NULL; } } #endif } /* *----------------------------------------------------------------------------- * * FilePosixNearestExistingAncestor -- * * Find the nearest existing ancestor of 'path'. * * 'path' can be relative (including empty) or absolute, and 'path' can * have any number of non-existing components at its end. * * Results: * The allocated, NUL-terminated, non-empty path of the * nearest existing ancestor. * * Side effects: * None * *----------------------------------------------------------------------------- */ static char * FilePosixNearestExistingAncestor(char const *path) // IN: File path { size_t resultSize; char *result; struct stat statbuf; resultSize = MAX(strlen(path), 1) + 1; result = Util_SafeMalloc(resultSize); Str_Strcpy(result, path, resultSize); for (;;) { char *ptr; if (*result == '\0') { Str_Strcpy(result, *path == DIRSEPC ? "/" : ".", resultSize); break; } if (Posix_Stat(result, &statbuf) == 0) { break; } ptr = strrchr(result, DIRSEPC); if (ptr == NULL) { ptr = result; } *ptr = '\0'; } return result; } #endif /* !FreeBSD && !sun */ /* *---------------------------------------------------------------------------- * * File_IsSameFile -- * * Determine whether both paths point to the same file. * * Caveats - While local files are matched based on inode and device * ID, some older versions of NFS return buggy device IDs, so the * determination cannot be done with 100% confidence across NFS. * Paths that traverse NFS mounts are matched based on device, inode * and all of the fields of the stat structure except for times. * This introduces a race condition in that if the target files are not * locked, they can change out from underneath this function yielding * false negative results. Cloned files sytems mounted across an old * version of NFS may yield a false positive. * * Results: * TRUE if both paths point to the same file, FALSE otherwise. * * Side effects: * Changes errno, maybe. * *---------------------------------------------------------------------------- */ Bool File_IsSameFile(const char *path1, // IN: const char *path2) // IN: { struct stat st1; struct stat st2; #if !defined(sun) // Solaris does not have statfs struct statfs stfs1; struct statfs stfs2; #endif ASSERT(path1 != NULL); ASSERT(path2 != NULL); /* * First take care of the easy checks. If the paths are identical, or if * the inode numbers or resident devices don't match, we're done. */ if (Unicode_Compare(path1, path2) == 0) { return TRUE; } if (Posix_Stat(path1, &st1) == -1) { return FALSE; } if (Posix_Stat(path2, &st2) == -1) { return FALSE; } if (st1.st_ino != st2.st_ino) { return FALSE; } if (st1.st_dev != st2.st_dev) { return FALSE; } if (HostType_OSIsVMK()) { /* * On ESX, post change 1074635 the st_dev field of the stat structure * is valid and differentiates between resident devices or NFS file * systems - no need to use statfs to obtain file system information. */ return TRUE; } #if !defined(sun) // Solaris does not have statfs if (Posix_Statfs(path1, &stfs1) != 0) { return FALSE; } if (Posix_Statfs(path2, &stfs2) != 0) { return FALSE; } #if defined(__APPLE__) || defined(__FreeBSD__) if ((stfs1.f_flags & MNT_LOCAL) && (stfs2.f_flags & MNT_LOCAL)) { return TRUE; } #else if ((stfs1.f_type != NFS_SUPER_MAGIC) && (stfs2.f_type != NFS_SUPER_MAGIC)) { return TRUE; } #endif #endif /* * At least one of the paths traverses NFS and some older NFS * implementations can set st_dev incorrectly. Do some extra checks of the * stat structure to increase our confidence. Since the st_ino numbers had * to match to get this far, the overwhelming odds are the two files are * the same. * * If another process was actively writing or otherwise modifying the file * while we stat'd it, then the following test could fail and we could * return a false negative. On the other hand, if NFS lies about st_dev * and the paths point to a cloned file system, then the we will return a * false positive. */ if ((st1.st_mode == st2.st_mode) && (st1.st_nlink == st2.st_nlink) && (st1.st_uid == st2.st_uid) && (st1.st_gid == st2.st_gid) && (st1.st_rdev == st2.st_rdev) && (st1.st_size == st2.st_size) && (st1.st_blksize == st2.st_blksize) && (st1.st_blocks == st2.st_blocks)) { return TRUE; } return FALSE; } /* *----------------------------------------------------------------------------- * * File_Replace -- * * Replace old file (destination) with new file (source), and attempt to * reproduce file permissions. A NULL value for either the oldName or * newName will result in failure and errno will be set to EFAULT. * * Results: * TRUE on success. * * Side effects: * errno may be set. * *----------------------------------------------------------------------------- */ Bool File_Replace(const char *oldName, // IN: old file const char *newName) // IN: new file { int status = 0; Bool result = FALSE; char *newPath = NULL; char *oldPath = NULL; struct stat st; if (newName == NULL) { status = EFAULT; goto bail; } else if ((newPath = Unicode_GetAllocBytes(newName, STRING_ENCODING_DEFAULT)) == NULL) { status = UNICODE_CONVERSION_ERRNO; Msg_Append(MSGID(filePosix.replaceConversionFailed) "Failed to convert file path \"%s\" to current encoding\n", newName); goto bail; } if (oldName == NULL) { status = EFAULT; goto bail; } else if ((oldPath = Unicode_GetAllocBytes(oldName, STRING_ENCODING_DEFAULT)) == NULL) { status = UNICODE_CONVERSION_ERRNO; Msg_Append(MSGID(filePosix.replaceConversionFailed) "Failed to convert file path \"%s\" to current encoding\n", oldName); goto bail; } if ((stat(oldPath, &st) == 0) && (chmod(newPath, st.st_mode) == -1)) { status = errno; Msg_Append(MSGID(filePosix.replaceChmodFailed) "Failed to duplicate file permissions from " "\"%s\" to \"%s\": %s\n", oldName, newName, Msg_ErrString()); goto bail; } if (rename(newPath, oldPath) < 0) { status = errno; Msg_Append(MSGID(filePosix.replaceRenameFailed) "Failed to rename \"%s\" to \"%s\": %s\n", newName, oldName, Msg_ErrString()); goto bail; } result = TRUE; bail: Posix_Free(newPath); Posix_Free(oldPath); errno = status; return result; } /* *---------------------------------------------------------------------- * * FilePosixGetMaxOrSupportsFileSize -- * * Given a file descriptor to a file on a volume, either find out the * max file size for the volume on which the file is located or check * if the volume supports the given file size. * If getMaxFileSize is set then find out the max file size and store it * in *maxFileSize on success, otherwise figure out if *fileSize is * supported. * * Results: * If getMaxFileSize was set: * TRUE with max file size stored in *fileSize. * Otherwise: * TRUE fileSize is supported. * FALSE fileSize not supported or could not figure out the answer. * * Side effects: * None. * *---------------------------------------------------------------------- */ static Bool FilePosixGetMaxOrSupportsFileSize(FileIODescriptor *fd, // IN: uint64 *fileSize, // IN/OUT: Bool getMaxFileSize) // IN: { uint64 value = 0; uint64 mask; ASSERT(fd != NULL); ASSERT(fileSize != NULL); if (!getMaxFileSize) { return FileIO_SupportsFileSize(fd, *fileSize); } /* * Try to do a binary search and figure out the max supported file size. */ for (mask = (1ULL << 62); mask != 0; mask >>= 1) { if (FileIO_SupportsFileSize(fd, value | mask)) { value |= mask; } } *fileSize = value; return TRUE; } /* *---------------------------------------------------------------------- * * FilePosixCreateTestGetMaxOrSupportsFileSize -- * * Given a path to a dir on a volume, either find out the max file size * for the volume on which the dir is located or check if the volume * supports the given file size. * If getMaxFileSize is set then find out the max file size and store it * in *maxFileSize on success, otherwise figure out if *fileSize is * supported. * * Results: * If getMaxFileSize was set: * TRUE if figured out the max file size. * FALSE failed to figure out the max file size. * Otherwise: * TRUE fileSize is supported. * FALSE fileSize not supported or could not figure out the answer. * * Side effects: * None. * *---------------------------------------------------------------------- */ static Bool FilePosixCreateTestGetMaxOrSupportsFileSize(const char *dirName, // IN: test dir uint64 *fileSize, // IN/OUT: Bool getMaxFileSize) // IN: { Bool retVal; int posixFD; char *temp; char *path; FileIODescriptor fd; ASSERT(fileSize != NULL); temp = Unicode_Append(dirName, "/.vmBigFileTest"); posixFD = File_MakeSafeTemp(temp, &path); Posix_Free(temp); if (posixFD == -1) { Log(LGPFX" %s: Failed to create temporary file in dir: %s\n", __func__, dirName); return FALSE; } fd = FileIO_CreateFDPosix(posixFD, O_RDWR); retVal = FilePosixGetMaxOrSupportsFileSize(&fd, fileSize, getMaxFileSize); /* Eventually perform destructive tests here... */ FileIO_Close(&fd); File_Unlink(path); Posix_Free(path); return retVal; } #ifdef VMX86_SERVER /* *---------------------------------------------------------------------- * * FileVMKGetMaxFileSize -- * * Given a path to a file on a volume, find out the max file size for * the volume on which the file is located. * Max file size gets stored in *maxFileSize on success. * * Results: * TRUE if figured out the max file size. * FALSE failed to figure out the max file size. * * Side effects: * None * *---------------------------------------------------------------------- */ static Bool FileVMKGetMaxFileSize(const char *pathName, // IN: uint64 *maxFileSize) // OUT: { int fd; Bool retval = TRUE; char *fullPath; char *dirPath = NULL; ASSERT(maxFileSize != NULL); fullPath = File_FullPath(pathName); if (fullPath == NULL) { Log(LGPFX" %s: Failed to get the full path for %s\n", __func__, pathName); retval = FALSE; goto bail; } if (File_IsDirectory(fullPath)) { dirPath = Unicode_Duplicate(fullPath); } else { dirPath = NULL; File_SplitName(fullPath, NULL, &dirPath, NULL); } /* * We always try to open the dir in order to avoid any contention on VMDK * descriptor file with those threads which already have descriptor file * opened for writing. */ fd = Posix_Open(dirPath, O_RDONLY, 0); if (fd == -1) { Log(LGPFX" %s: could not open %s: %s\n", __func__, dirPath, Err_Errno2String(errno)); retval = FALSE; goto bail; } if (ioctl(fd, IOCTLCMD_VMFS_GET_MAX_FILE_SIZE, maxFileSize) == -1) { Log(LGPFX" %s: Could not get max file size for path: %s, error: %s\n", __func__, pathName, Err_Errno2String(errno)); retval = FALSE; } close(fd); bail: Posix_Free(fullPath); Posix_Free(dirPath); return retval; } #endif /* *---------------------------------------------------------------------- * * FileVMKGetMaxOrSupportsFileSize -- * * Given a path to a file on a volume, either find out the max file size * for the volume on which the file is located or check if the volume * supports the given file size. * If getMaxFileSize is set then find out the max file size and store it * in *maxFileSize on success, otherwise figure out if *fileSize is * supported. * * Results: * If getMaxFileSize was set: * TRUE if figured out the max file size. * FALSE failed to figure out the max file size. * Otherwise: * TRUE fileSize is supported. * FALSE fileSize not supported or could not figure out the answer. * * Side effects: * None * *---------------------------------------------------------------------- */ static Bool FileVMKGetMaxOrSupportsFileSize(const char *pathName, // IN: uint64 *fileSize, // IN/OUT: Bool getMaxFileSize) // IN: { #if defined(VMX86_SERVER) FS_PartitionListResult *fsAttrs = NULL; uint64 maxFileSize; /* * Let's first try IOCTL to figure out max file size. */ if (FileVMKGetMaxFileSize(pathName, &maxFileSize)) { if (getMaxFileSize) { *fileSize = maxFileSize; return TRUE; } return (*fileSize <= maxFileSize); } /* * Try the old way if IOCTL failed. */ LOG(0, (LGPFX" %s: Failed to figure out max file size via " "IOCTLCMD_VMFS_GET_MAX_FILE_SIZE. Falling back to old method.\n", __func__)); maxFileSize = -1; if (File_GetVMFSAttributes(pathName, &fsAttrs) < 0) { Log(LGPFX" %s: File_GetVMFSAttributes Failed\n", __func__); return FALSE; } if (strcmp(fsAttrs->fsType, FS_VMFS_ON_ESX) == 0) { if (fsAttrs->versionNumber == 3) { maxFileSize = (VMFS3CONST * (uint64) fsAttrs->fileBlockSize * 1024); } else if (fsAttrs->versionNumber >= 5) { /* Get ready for 64 TB on VMFS5 and perform sanity check on version */ maxFileSize = (uint64) 0x400000000000ULL; } else { Log(LGPFX" %s: Unsupported filesystem version, %u\n", __func__, fsAttrs->versionNumber); Posix_Free(fsAttrs); return FALSE; } Posix_Free(fsAttrs); if (maxFileSize == -1) { Log(LGPFX" %s: Failed to figure out the max file size for %s\n", __func__, pathName); return FALSE; } if (getMaxFileSize) { *fileSize = maxFileSize; return TRUE; } else { return *fileSize <= maxFileSize; } } else { char *fullPath; char *parentPath; Bool supported; Log(LGPFX" %s: Trying create file and seek approach.\n", __func__); fullPath = File_FullPath(pathName); if (fullPath == NULL) { Log(LGPFX" %s: Error acquiring full path\n", __func__); Posix_Free(fsAttrs); return FALSE; } File_GetPathName(fullPath, &parentPath, NULL); supported = FilePosixCreateTestGetMaxOrSupportsFileSize(parentPath, fileSize, getMaxFileSize); Posix_Free(fsAttrs); Posix_Free(fullPath); Posix_Free(parentPath); return supported; } #endif Log(LGPFX" %s: did not execute properly\n", __func__); return FALSE; /* happy compiler */ } /* *---------------------------------------------------------------------- * * FileGetMaxOrSupportsFileSize -- * * Given a path to a file on a volume, either find out the max file size * for the volume on which the file is located or check if the volume * supports the given file size. * If getMaxFileSize is set then find out the max file size and store it * in *maxFileSize on success, otherwise figure out if *fileSize is * supported. * * Results: * If getMaxFileSize was set: * TRUE if figured out the max file size. * FALSE failed to figure out the max file size. * Otherwise: * TRUE fileSize is supported. * FALSE fileSize not supported or could not figure out the answer. * * Side effects: * None * *---------------------------------------------------------------------- */ Bool FileGetMaxOrSupportsFileSize(const char *pathName, // IN: uint64 *fileSize, // IN/OUT: Bool getMaxFileSize) // IN: { char *fullPath; char *folderPath; Bool retval = FALSE; ASSERT(pathName != NULL); ASSERT(fileSize != NULL); /* * We acquire the full path name for testing in * FilePosixCreateTestGetMaxOrSupportsFileSize(). This is also done in the * event that a user tries to create a virtual disk in the directory that * they want a vmdk created in (setting filePath only to the disk name, * not the entire path.). */ fullPath = File_FullPath(pathName); if (fullPath == NULL) { Log(LGPFX" %s: Error acquiring full path for path: %s.\n", __func__, pathName); goto out; } if (HostType_OSIsVMK()) { retval = FileVMKGetMaxOrSupportsFileSize(fullPath, fileSize, getMaxFileSize); goto out; } if (File_IsFile(fullPath)) { FileIOResult res; FileIODescriptor fd; FileIO_Invalidate(&fd); res = FileIO_Open(&fd, fullPath, FILEIO_OPEN_ACCESS_READ, FILEIO_OPEN); if (FileIO_IsSuccess(res)) { retval = FilePosixGetMaxOrSupportsFileSize(&fd, fileSize, getMaxFileSize); FileIO_Close(&fd); goto out; } } /* * On unknown filesystems create a temporary file in the argument file's * parent directory and use it as a test. */ if (File_IsDirectory(pathName)) { folderPath = Unicode_Duplicate(fullPath); } else { folderPath = NULL; File_SplitName(fullPath, NULL, &folderPath, NULL); } retval = FilePosixCreateTestGetMaxOrSupportsFileSize(folderPath, fileSize, getMaxFileSize); Posix_Free(folderPath); out: Posix_Free(fullPath); return retval; } /* *---------------------------------------------------------------------- * * File_GetMaxFileSize -- * * Given a path to a file on a volume, return the max file size for that * volume. The max file size is stored on *maxFileSize on success. * The function caps the max file size to be MAX_SUPPORTED_FILE_SIZE on * any type of FS. * * Results: * TRUE on success. * FALSE failed to figure out max file size due to some reasons. * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_GetMaxFileSize(const char *pathName, // IN: uint64 *maxFileSize) // OUT: { Bool result; if (maxFileSize == NULL) { Log(LGPFX" %s: maxFileSize passed as NULL.\n", __func__); return FALSE; } result = FileGetMaxOrSupportsFileSize(pathName, maxFileSize, TRUE); if (result) { /* * Cap the max supported file size at MAX_SUPPORTED_FILE_SIZE. */ if (*maxFileSize > MAX_SUPPORTED_FILE_SIZE) { *maxFileSize = MAX_SUPPORTED_FILE_SIZE; } } return result; } /* *---------------------------------------------------------------------- * * File_SupportsFileSize -- * * Check if the given file is on an FS that supports such file size. * The function caps the max supported file size to be * MAX_SUPPORTED_FILE_SIZE on any type of FS. * * Results: * TRUE if FS supports such file size. * FALSE otherwise (file size not supported, invalid path, read-only, ...) * * Side effects: * None * *---------------------------------------------------------------------- */ Bool File_SupportsFileSize(const char *pathName, // IN: uint64 fileSize) // IN: { /* * All supported filesystems can hold at least 2GB-1 bytes files. */ if (fileSize <= 0x7FFFFFFF) { return TRUE; } /* * Cap the max supported file size at MAX_SUPPORTED_FILE_SIZE. */ if (fileSize > MAX_SUPPORTED_FILE_SIZE) { return FALSE; } return FileGetMaxOrSupportsFileSize(pathName, &fileSize, FALSE); } /* *----------------------------------------------------------------------------- * * FileCreateDirectory -- * * Create a directory. The umask is honored. * * Results: * 0 success * > 0 failure (errno) * * Side effects: * May change the host file system. * *----------------------------------------------------------------------------- */ int FileCreateDirectory(const char *pathName, // IN: int mask) // IN: { int err; if (pathName == NULL) { err = errno = EFAULT; } else { err = (Posix_Mkdir(pathName, mask) == -1) ? errno : 0; } return err; } /* *---------------------------------------------------------------------- * * File_ListDirectory -- * * Gets the list of files (and directories) in a directory. * * Results: * Returns the number of files returned or -1 on failure. * * Side effects: * If ids is provided and the function succeeds, memory is * allocated for both the unicode strings and the array itself * and must be freed. (See Util_FreeStringList.) * The memory allocated for the array may be larger than necessary. * The caller may trim it with realloc() if it cares. * * A file name that cannot be represented in the default encoding * will appear as a string of three UTF8 substitution characters. * *---------------------------------------------------------------------- */ static int FileKeyDispose(const char *key, // IN: void *value, // IN: void *clientData) // IN: { Posix_Free((void *) key); return 0; } static int FileUnique(const char *key, // IN: void *value, // IN: void *clientData) // IN/OUT: a DynBuf { DynBuf *b = clientData; DynBuf_Append(b, &key, sizeof key); return 0; } int File_ListDirectory(const char *pathName, // IN: char ***ids) // OUT: relative paths { int err; DIR *dir; int count; HashTable *hash; ASSERT(pathName != NULL); dir = Posix_OpenDir(pathName); if (dir == NULL) { // errno is preserved return -1; } hash = HashTable_Alloc(256, HASH_STRING_KEY, NULL); count = 0; while (TRUE) { struct dirent *entry; errno = 0; entry = readdir(dir); if (entry == NULL) { err = errno; break; } /* Strip out undesirable paths. No one ever cares about these. */ if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0)) { continue; } /* Don't create the file list if we aren't providing it to the caller. */ if (ids) { char *id; if (Unicode_IsBufferValid(entry->d_name, -1, STRING_ENCODING_DEFAULT)) { id = Unicode_Alloc(entry->d_name, STRING_ENCODING_DEFAULT); } else { id = Unicode_EscapeBuffer(entry->d_name, -1, STRING_ENCODING_DEFAULT); Warning("%s: file '%s' in directory '%s' cannot be converted to " "UTF8\n", __FUNCTION__, pathName, id); Posix_Free(id); id = Unicode_Duplicate(UNICODE_SUBSTITUTION_CHAR UNICODE_SUBSTITUTION_CHAR UNICODE_SUBSTITUTION_CHAR); } /* * It is possible for a directory operation to change the contents * of a directory while this routine is running. If the OS decides * to physically rearrange the contents of the directory it is * possible for readdir to report a file more than once. Only add * a file to the return data if it is unique within the return * data. */ if (HashTable_Insert(hash, id, NULL)) { count++; } else { Posix_Free(id); } } else { count++; } } closedir(dir); if (ids) { ASSERT(count == HashTable_GetNumElements(hash)); if (err == 0) { DynBuf b; DynBuf_Init(&b); HashTable_ForEach(hash, FileUnique, &b); *ids = DynBuf_Detach(&b); DynBuf_Destroy(&b); } else { HashTable_ForEach(hash, FileKeyDispose, NULL); } } HashTable_Free(hash); return (errno = err) == 0 ? count : -1; } /* *----------------------------------------------------------------------------- * * File_WalkDirectoryEnd -- * * End the directory traversal. * * Results: * None * * Side effects: * The context is now invalid. * *----------------------------------------------------------------------------- */ void File_WalkDirectoryEnd(WalkDirContext context) // IN: { if (context != NULL) { if (context->cnt > 0) { Util_FreeStringList(context->files, context->cnt); } Posix_Free(context); } } /* *----------------------------------------------------------------------------- * * File_WalkDirectoryStart -- * * Start a directory tree walk at 'parentPath'. * * To read each entry, repeatedly pass the returned context to * File_WalkDirectoryNext() until that function returns FALSE. * * We assume no thread will change the working directory between the calls * to File_WalkDirectoryStart and File_WalkDirectoryEnd. * * Results: * A context used in subsequent calls to File_WalkDirectoryNext() or NULL * if an error is encountered. * * Side effects: * None * *----------------------------------------------------------------------------- */ WalkDirContext File_WalkDirectoryStart(const char *parentPath) // IN: { WalkDirContextImpl *context = malloc(sizeof *context); if (context != NULL) { context->files = NULL; context->iter = 0; context->cnt = File_ListDirectory(parentPath, &context->files); if (context->cnt == -1) { File_WalkDirectoryEnd(context); context = NULL; } } return context; } /* *----------------------------------------------------------------------------- * * File_WalkDirectoryNext -- * * Get the next entry in a directory traversal started with * File_WalkDirectoryStart. * * Results: * TRUE iff the traversal hasn't completed. * * If TRUE, *path holds an allocated string of a directory entry that the * caller must free (see free). * * If FALSE, errno is 0 iff the walk completed sucessfully. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool File_WalkDirectoryNext(WalkDirContext context, // IN: char **path) // OUT: { ASSERT(context); ASSERT(path != NULL); errno = 0; // Any errors showed up at "start time". if (context->iter < context->cnt) { *path = Util_SafeStrdup(context->files[context->iter++]); return TRUE; } return FALSE; } /* *---------------------------------------------------------------------- * * FileIsGroupsMember -- * * Determine if a gid is in the gid list of the current process * * Results: * FALSE if error (reported to the user) * * Side effects: * None * *---------------------------------------------------------------------- */ static Bool FileIsGroupsMember(gid_t gid) // IN: { int nr_members; gid_t *members; int res; int ret; members = NULL; nr_members = 0; for (;;) { gid_t *new; res = getgroups(nr_members, members); if (res == -1) { Warning(LGPFX" %s: Couldn't getgroups\n", __FUNCTION__); ret = FALSE; goto end; } if (res == nr_members) { break; } /* Was bug 17760 --hpreg */ new = realloc(members, res * sizeof *members); if (new == NULL) { Warning(LGPFX" %s: Couldn't realloc\n", __FUNCTION__); ret = FALSE; goto end; } members = new; nr_members = res; } for (res = 0; res < nr_members; res++) { if (members[res] == gid) { ret = TRUE; goto end; } } ret = FALSE; end: Posix_Free(members); return ret; } /* *---------------------------------------------------------------------- * * FileIsWritableDir -- * * Determine in a non-intrusive way if the user can create a file in a * directory * * Results: * FALSE if error (reported to the user) * * Side effects: * None * * Bug: * It would be cleaner to use the POSIX access(2), which deals well * with read-only filesystems. Unfortunately, access(2) doesn't deal with * the effective [u|g]ids. * *---------------------------------------------------------------------- */ Bool FileIsWritableDir(const char *dirName) // IN: { int err; uid_t euid; FileData fileData; err = FileAttributes(dirName, &fileData); if ((err != 0) || (fileData.fileType != FILE_TYPE_DIRECTORY)) { return FALSE; } euid = geteuid(); if (euid == 0) { /* Root can read or write any file. Well... This is not completely true because of read-only filesystems and NFS root squashing... What a nightmare --hpreg */ return TRUE; } if (fileData.fileOwner == euid) { fileData.fileMode >>= 6; } else if (FileIsGroupsMember(fileData.fileGroup)) { fileData.fileMode >>= 3; } /* Check for Read and Execute permissions */ return (fileData.fileMode & 3) == 3; } /* *---------------------------------------------------------------------- * * File_MakeCfgFileExecutable -- * * Make a .vmx file executable. This is sometimes necessary * to enable MKS access to the VM. * * Owner always gets rwx. Group/other get x where r is set. * * Results: * FALSE if error * * Side effects: * errno is set on error * *---------------------------------------------------------------------- */ Bool File_MakeCfgFileExecutable(const char *pathName) // IN: { struct stat s; if (Posix_Stat(pathName, &s) == 0) { mode_t newMode = s.st_mode; newMode |= S_IRUSR | S_IWUSR | S_IXUSR; ASSERT_ON_COMPILE(S_IRGRP >> 2 == S_IXGRP && S_IROTH >> 2 == S_IXOTH); newMode |= ((newMode & (S_IRGRP | S_IROTH)) >> 2); return newMode == s.st_mode || Posix_Chmod(pathName, newMode); } return FALSE; } /* *---------------------------------------------------------------------------- * * File_GetSizeAlternate -- * * An alternate way to determine the filesize. Useful for finding * problems with files on remote fileservers, such as described in bug * 19036. However, in Linux we do not have an alternate way, yet, to * determine the problem, so we call back into the regular getSize * function. * * Results: * Size of file or -1. * * Side effects: * None * *---------------------------------------------------------------------------- */ int64 File_GetSizeAlternate(const char *pathName) // IN: { return File_GetSize(pathName); } /* *---------------------------------------------------------------------------- * * File_IsCharDevice -- * * This function checks whether the given file is a char device * and return TRUE in such case. This is often useful on Windows * where files like COM?, LPT? must be differentiated from "normal" * disk files. * * Results: * TRUE is a character device * FALSE is not a character device or error * * Side effects: * None * *---------------------------------------------------------------------------- */ Bool File_IsCharDevice(const char *pathName) // IN: { FileData fileData; return (FileAttributes(pathName, &fileData) == 0) && (fileData.fileType == FILE_TYPE_CHARDEVICE); } /* *---------------------------------------------------------------------------- * * File_GetMountPath -- * * This function translates the path for a symlink to the physical path. * If checkEntirePath is TRUE, this function will try to translate * every parent directory to physical path. * Caller must free the returned buffer if valid path is returned. * * Results: * return valid physical path if successfully. * return NULL if error. * * Side effects: * The result is allocated. * *---------------------------------------------------------------------------- */ char * File_GetMountPath(const char *pathName, // IN: Bool checkEntirePath) // IN: { char *mountPath; if (pathName == NULL) { return NULL; } if (checkEntirePath) { return Posix_RealPath(pathName); } mountPath = Posix_ReadLink(pathName); if (mountPath != NULL) { return mountPath; } if (!Posix_Access(pathName, F_OK)) { return Util_SafeStrdup(pathName); } return NULL; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/fileStandAlone.c000066400000000000000000000462761321503522500250360ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * fileStandAlone.c -- * * This file contains lib/file routines which are unentangled - they do * not depend on other libraries besides lib/misc and its dependencies. */ #if defined(_WIN32) #include #endif #include #include #include #include #include "safetime.h" #if !defined(_WIN32) #include #endif #include #include #include #include "vmware.h" #include "util.h" #include "str.h" #include "strutil.h" #include "posix.h" #include "file.h" #include "unicodeOperations.h" /* *---------------------------------------------------------------------- * * File_GetModTime -- * * Get the last modification time of a file and return it. The time * unit is seconds since the POSIX/UNIX/Linux epoch. * * Results: * Last modification time of file or -1 if error. * * Side effects: * None. * *---------------------------------------------------------------------- */ int64 File_GetModTime(const char *pathName) // IN: { int64 theTime; struct stat statbuf; if (Posix_Stat(pathName, &statbuf) == 0) { theTime = statbuf.st_mtime; } else { theTime = -1; } return theTime; } #if defined(_WIN32) /* *--------------------------------------------------------------------------- * * FileFindFirstDirsep -- * * Return a pointer to the first directory separator. * * Results: * NULL No directory separator found * !NULL Pointer to the last directory separator * * Side effects: * None * *--------------------------------------------------------------------------- */ static char * FileFindFirstDirsep(const char *pathName) // IN: { char *p; ASSERT(pathName != NULL); p = (char *) pathName; while (*p != '\0') { if (File_IsDirsep(*p)) { return p; } p++; } return NULL; } #endif /* *--------------------------------------------------------------------------- * * FileFindLastDirsep -- * * Return a pointer to the last directory separator. * * Results: * NULL No directory separator found * !NULL Pointer to the last directory separator * * Side effects: * None * *--------------------------------------------------------------------------- */ static char * FileFindLastDirsep(const char *pathName, // IN: size_t len) // IN: { char *p; ASSERT(pathName != NULL); p = (char *) pathName + len; while (p-- != pathName) { if (File_IsDirsep(*p)) { return p; } } return NULL; } /* *---------------------------------------------------------------------- * * File_SplitName -- * * Split a file name into three components: VOLUME, DIRECTORY, * BASE. The return values must be freed. * * VOLUME is empty for an empty string or a UNIX-style path, the * drive letter and colon for a Win32 drive-letter path, or the * construction "\\server\share" for a Win32 UNC path. * * BASE is the longest string at the end that begins after the * volume string and after the last directory separator. * * DIRECTORY is everything in-between VOLUME and BASE. * * The concatenation of VOLUME, DIRECTORY, and BASE produces the * original string, so any of those strings may be empty. * * A NULL pointer may be passed for one or more OUT parameters, in * which case that parameter is not returned. * * Able to handle both UNC and drive-letter paths on Windows. * * Results: * As described. * * Side effects: * None. * *---------------------------------------------------------------------- */ void File_SplitName(const char *pathName, // IN: char **volume, // OUT/OPT: char **directory, // OUT/OPT: char **base) // OUT/OPT: { char *vol; char *dir; char *bas; char *baseBegin; char *volEnd; int volLen, dirLen; int len = strlen(pathName); ASSERT(pathName != NULL); /* * Get volume. */ volEnd = (char *) pathName; #ifdef WIN32 if ((len > 2) && (!Str_Strncmp("\\\\", pathName, 2) || !Str_Strncmp("//", pathName, 2))) { /* UNC path */ volEnd = FileFindFirstDirsep(volEnd + 2); if (volEnd != NULL) { volEnd = FileFindFirstDirsep(volEnd + 1); if (volEnd == NULL) { /* We have \\foo\bar, which is legal */ volEnd = (char *) pathName + len; } } else { /* We have \\foo, which is just bogus */ volEnd = (char *) pathName; } } else if ((len >= 2) && (pathName[1] == ':')) { // drive-letter path volEnd = (char *) pathName + 2; } #endif /* WIN32 */ volLen = volEnd - pathName; vol = Util_SafeMalloc(volLen + 1); memcpy(vol, pathName, volLen); vol[volLen] = '\0'; /* * Get base. */ baseBegin = FileFindLastDirsep(pathName, len); baseBegin = (baseBegin == NULL) ? (char *) pathName : baseBegin + 1; if (baseBegin < volEnd) { baseBegin = (char *) pathName + len; } bas = Util_SafeStrdup(baseBegin); /* * Get dir. */ dirLen = baseBegin - volEnd; dir = Util_SafeMalloc(dirLen + 1); memcpy(dir, volEnd, dirLen); dir[dirLen] = '\0'; /* * Return what needs to be returned. */ if (volume == NULL) { free(vol); } else { *volume = vol; } if (directory == NULL) { free(dir); } else { *directory = dir; } if (base == NULL) { free(bas); } else { *base = bas; } } /* *--------------------------------------------------------------------------- * * File_PathJoin -- * * Join the dirName and baseName together to create a (full) path. * * This code concatenates two strings together and omits a redundant * directory separator between the two. * * On Windows, the 'baseName' argument may not be a fully qualified path. * That is, it may not be an absolute path containing a drive letter nor * may it be a UNC path. * * Examples: * File_PathJoin("", "b") -> "/b" * File_PathJoin("/", "b") -> "/b" * File_PathJoin("a", "b") -> "a/b" * File_PathJoin("a/", "b") -> "a/b" * File_PathJoin("a/////", "b") -> "a/b" * File_PathJoin("a", "") -> "a/" * File_PathJoin("a", "/") -> "a/" * File_PathJoin("a", "/b") -> "a/b" * File_PathJoin("a", "/////b") -> "a/b" (only posix) * File_PathJoin("a/", "/b") -> "a/b" * File_PathJoin("a/////", "/////b") -> "a/b" (only posix) * * Results: * The constructed path which must be freed by the caller. * * Side effects: * None * *--------------------------------------------------------------------------- */ char * File_PathJoin(const char *dirName, // IN: const char *baseName) // IN: See above. { char *result; char *newDir = NULL; ASSERT(dirName); ASSERT(baseName); /* * Remove ALL directory separators from baseName begin. */ #if defined(_WIN32) { const char *oldBaseName = baseName; /* * Reject drive letters in baseName. */ ASSERT(Unicode_LengthInCodePoints(baseName) < 2 || Unicode_FindSubstrInRange(baseName, 1, 1, ":", 0, 1) == UNICODE_INDEX_NOT_FOUND); while (*baseName == '/' || *baseName == '\\') { baseName++; } /* * Reject UNC paths for baseName. */ ASSERT(baseName - oldBaseName < 2); } #else while (*baseName == '/') { baseName++; } #endif /* * Remove ALL directory separators from dirName end. */ newDir = File_StripSlashes(dirName); result = Unicode_Join(newDir, DIRSEPS, baseName, NULL); Posix_Free(newDir); return result; } /* *--------------------------------------------------------------------------- * * File_GetPathName -- * * Behaves like File_SplitName by splitting the fullpath into * pathname & filename components. * * The trailing directory separator [\|/] is stripped off the * pathname component. This in turn means that on Linux the root * directory will be returned as the empty string "". On Windows * it will be returned as X: where X is the drive letter. It is * important that callers of this functions are aware that the "" * on Linux means root "/". * * A NULL pointer may be passed for one or more OUT parameters, * in which case that parameter is not returned. * * Results: * As described. * * Side effects: * The return values must be freed. * *--------------------------------------------------------------------------- */ void File_GetPathName(const char *fullPath, // IN: char **pathName, // OUT/OPT: char **baseName) // OUT/OPT: { char *p; char *pName; char *bName; ASSERT(fullPath); p = FileFindLastDirsep(fullPath, strlen(fullPath)); if (p == NULL) { pName = Util_SafeStrdup(""); bName = Util_SafeStrdup(fullPath); } else { bName = Util_SafeStrdup(&fullPath[p - fullPath + 1]); pName = Util_SafeStrdup(fullPath); pName[p - fullPath] = '\0'; p = &pName[p - fullPath]; while (p-- != pName) { if (File_IsDirsep(*p)) { *p = '\0'; } else { break; } } } if (pathName == NULL) { free(pName); } else { *pathName = pName; } if (baseName == NULL) { free(bName); } else { *baseName = bName; } } /* *---------------------------------------------------------------------- * * File_StripSlashes -- * * Strip trailing slashes from the end of a path. * * Results: * The stripped filename. * * Side effects: * None. * *---------------------------------------------------------------------- */ char * File_StripSlashes(const char *path) // IN: { char *result; char *volume; char *dir; char *base; /* * SplitName handles all drive letter/UNC/whatever cases, all we * have to do is make sure the dir part is stripped of slashes if * there isn't a base part. */ File_SplitName(path, &volume, &dir, &base); if (!Unicode_IsEmpty(dir) && Unicode_IsEmpty(base)) { char *dir2 = Unicode_GetAllocBytes(dir, STRING_ENCODING_UTF8); size_t i = strlen(dir2); /* * Don't strip first slash on Windows, since we want at least * one slash to trail a drive letter/colon or UNC specifier. */ #if defined(_WIN32) while ((i > 1) && File_IsDirsep(dir2[i - 1])) { #else while ((i > 0) && File_IsDirsep(dir2[i - 1])) { #endif i--; } Posix_Free(dir); dir = Unicode_AllocWithLength(dir2, i, STRING_ENCODING_UTF8); Posix_Free(dir2); } result = Unicode_Join(volume, dir, base, NULL); Posix_Free(volume); Posix_Free(dir); Posix_Free(base); return result; } /* *----------------------------------------------------------------------------- * * File_MapPathPrefix -- * * Given a path and a newPrefix -> oldPrefix mapping, transform * oldPath according to the mapping. * * Results: * The new path, or NULL if there is no mapping. * * Side effects: * The returned string is allocated, free it. * *----------------------------------------------------------------------------- */ char * File_MapPathPrefix(const char *oldPath, // IN: const char **oldPrefixes, // IN: const char **newPrefixes, // IN: size_t numPrefixes) // IN: { int i; size_t oldPathLen = strlen(oldPath); for (i = 0; i < numPrefixes; i++) { char *newPath; char *oldPrefix; char *newPrefix; size_t oldPrefixLen; oldPrefix = File_StripSlashes(oldPrefixes[i]); newPrefix = File_StripSlashes(newPrefixes[i]); oldPrefixLen = strlen(oldPrefix); /* * If the prefix matches on a DIRSEPS boundary, or the prefix is the * whole string, replace it. * * If we don't insist on matching a whole directory name, we could * mess things of if one directory is a substring of another. * * Perform a case-insensitive compare on Windows. (There are * case-insensitive filesystems on MacOS also, but the problem * is more acute with Windows because of frequent drive-letter * case mismatches. So in lieu of actually asking the * filesystem, let's just go with a simple ifdef for now.) */ if ((oldPathLen >= oldPrefixLen) && #ifdef _WIN32 (Str_Strncasecmp(oldPath, oldPrefix, oldPrefixLen) == 0) && #else (Str_Strncmp(oldPath, oldPrefix, oldPrefixLen) == 0) && #endif (strchr(VALID_DIRSEPS, oldPath[oldPrefixLen]) || (oldPath[oldPrefixLen] == '\0'))) { size_t newPrefixLen = strlen(newPrefix); size_t newPathLen = (oldPathLen - oldPrefixLen) + newPrefixLen; ASSERT(newPathLen > 0); ASSERT(oldPathLen >= oldPrefixLen); newPath = Util_SafeMalloc((newPathLen + 1) * sizeof(char)); memcpy(newPath, newPrefix, newPrefixLen); memcpy(newPath + newPrefixLen, oldPath + oldPrefixLen, oldPathLen - oldPrefixLen + 1); /* * It should only match once. Weird self-referencing mappings * aren't allowed. */ Posix_Free(oldPrefix); Posix_Free(newPrefix); return newPath; } Posix_Free(oldPrefix); Posix_Free(newPrefix); } return NULL; } /* *----------------------------------------------------------------------------- * * File_PrependToPath -- * * This function checks if the elem is already present in the * searchPath, if it is then it is moved forward in the search path. * Otherwise it is prepended to the searchPath. * * Results: * Return file search path with elem in front. * * Side effects: * Caller must free returned string. * *----------------------------------------------------------------------------- */ char * File_PrependToPath(const char *searchPath, // IN: const char *elem) // IN: { const char sep = FILE_SEARCHPATHTOKEN[0]; char *newPath; char *path; size_t n; ASSERT(searchPath); ASSERT(elem); newPath = Str_SafeAsprintf(NULL, "%s%s%s", elem, FILE_SEARCHPATHTOKEN, searchPath); n = strlen(elem); path = newPath + n + 1; for (;;) { char *next = Str_Strchr(path, sep); size_t len = next ? next - path : strlen(path); if ((len == n) && (Str_Strncmp(path, elem, len) == 0)) { if (next) { memmove(path, next + 1, strlen(next + 1) + 1); } else { *--path = '\0'; } break; } if (!next) { break; } path = next + 1; } return newPath; } /* *----------------------------------------------------------------------------- * * File_ReplaceExtension -- * * Replaces the extension in input with newExtension. * * If the old extension exists in the list of extensions specified in ..., * truncate it before appending the new extension. * * If the extension is not found in the list, the newExtension is * just appended. * * If there isn't a list of extensions specified (numExtensions == 0), * truncate the old extension unconditionally. * * NB: newExtension and the extension list must have .'s. * * Results: * The name with newExtension added to it. The caller is responsible to * free it when they are done with it. * * Side effects: * None. * *----------------------------------------------------------------------------- */ char * File_ReplaceExtension(const char *pathName, // IN: const char *newExtension, // IN: uint32 numExtensions, // IN: ...) // IN: { char *p; char *place; char *result; size_t newExtLen; size_t resultLen; size_t pathNameLen; ASSERT(pathName); ASSERT(newExtension); ASSERT(*newExtension == '.'); pathNameLen = strlen(pathName); newExtLen = strlen(newExtension); resultLen = pathNameLen + newExtLen + 1; result = Util_SafeMalloc(resultLen); memcpy(result, pathName, pathNameLen + 1); p = FileFindLastDirsep(result, pathNameLen); if (p == NULL) { p = strrchr(result, '.'); } else { p = strrchr(p, '.'); } if (p == NULL) { /* No extension... just append */ place = &result[pathNameLen]; // The NUL } else if (numExtensions == 0) { /* Always truncate the old extension if extension list is empty. */ place = p; // The '.' } else { uint32 i; va_list arguments; /* * Only truncate the old extension if it exists in the valid * extensions list. */ place = &result[pathNameLen]; // The NUL va_start(arguments, numExtensions); for (i = 0; i < numExtensions ; i++) { const char *oldExtension = va_arg(arguments, const char *); ASSERT(*oldExtension == '.'); if (strcmp(p, oldExtension) == 0) { place = p; // The '.' break; } } va_end(arguments); } /* Add the new extension - in the appropriate place - to pathName */ memcpy(place, newExtension, newExtLen + 1); return result; } /* *----------------------------------------------------------------------------- * * File_RemoveExtension -- * * Return a copy of the given path name with the extension * removed. We ASSERT that the given path does have an extension. * * Results: * A newly allocated buffer with the modified string. The caller * is responsible to free it when they are done with it. * * Side effects: * None. * *----------------------------------------------------------------------------- */ char * File_RemoveExtension(const char *pathName) // IN: { char *p; char *result; ASSERT(pathName != NULL); result = Util_SafeStrdup(pathName); p = FileFindLastDirsep(result, strlen(pathName)); if (p == NULL) { p = strrchr(result, '.'); } else { p = strrchr(p, '.'); } ASSERT(p != NULL); if (p != NULL) { *p = '\0'; } return result; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/fileTemp.c000066400000000000000000000247661321503522500237130ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2011-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #if defined(_WIN32) #include #endif #include #include #include #include #include #include #include #include #include "vmware.h" #include "log.h" #include "file.h" #include "fileInt.h" #include "util.h" #include "unicodeOperations.h" #include "posix.h" #if !defined(O_BINARY) #define O_BINARY 0 #endif /* *---------------------------------------------------------------------- * * FileTempNum -- * * Compute a number to be used as an attachment to a base name. * In order to avoid race conditions, files and directories are * kept separate via enforced odd (file) and even (directory) * numberings. * * Regardless of the input value of *var, the output value will * be even or odd as determined by createTempFile. * * Results: * An odd number if createTempFile is TRUE. * An even number if createTempFile is FALSE. * * Side effects: * None * *---------------------------------------------------------------------- */ static void FileTempNum(Bool createTempFile, // IN: uint32 *var) // IN/OUT: { ASSERT(var); *var += (FileSimpleRandom() >> 8) & 0xFF; *var = (*var & ~0x1) | (createTempFile ? 1 : 0); } /* *---------------------------------------------------------------------- * * File_MakeTempEx2 -- * * Create a temporary file or a directory. * If a temporary file is created successfully, then return an open file * descriptor to that file. * * 'dir' specifies the directory in which to create the file. It * must not end in a slash. * * 'createTempFile', if TRUE, then a temporary file will be created. If * FALSE, then a temporary directory will be created. * * 'createNameFunc' specifies the user-specified callback function that * will be called to construct the fileName. 'createNameFuncData' will be * passed everytime 'createNameFunc' is called. 'createNameFunc' * should return the proper fileName. * * Check the documentation for File_MakeTempHelperFunc. * * Results: * if a temporary file is created, then Open file descriptor or -1; * if a temporary directory is created, then 0 or -1; * If successful then presult points to a dynamically allocated * string with the pathname of the temp file. * * Side effects: * Creates the requested object when successful. Errno is set on error * * Files and directories are effectively in separate name spaces; * the numerical value attached via createNameFunc is odd for files * and even for directories. * *---------------------------------------------------------------------- */ int File_MakeTempEx2(const char *dir, // IN: Bool createTempFile, // IN: File_MakeTempCreateNameFunc *createNameFunc, // IN: void *createNameFuncData, // IN: char **presult) // OUT: { uint32 i; int fd = -1; uint32 var = 0; char *path = NULL; if ((dir == NULL) || (createNameFunc == NULL)) { errno = EFAULT; return -1; } ASSERT(presult); *presult = NULL; for (i = 0; i < (MAX_INT32 / 2); i++) { char *fileName; /* construct suffixed pathname to use */ Posix_Free(path); path = NULL; /* * Files and directories are kept separate (odd and even respectfully). * This way the available exclusion mechanisms work properly - O_EXCL * on files, mkdir on directories - and races are avoided. * * Not attempting an open on a directory is a good thing... */ FileTempNum(createTempFile, &var); fileName = (*createNameFunc)(var, createNameFuncData); ASSERT(fileName); /* construct base full pathname to use */ path = Unicode_Join(dir, DIRSEPS, fileName, NULL); Posix_Free(fileName); if (createTempFile) { fd = Posix_Open(path, O_CREAT | O_EXCL | O_BINARY | O_RDWR, 0600); } else { fd = Posix_Mkdir(path, 0700); } if (fd != -1) { *presult = path; path = NULL; break; } if (errno != EEXIST) { Log(LGPFX" Failed to create temporary %s \"%s\": %s.\n", createTempFile ? "file" : "directory", path, Err_Errno2String(errno)); goto exit; } } if (fd == -1) { Warning(LGPFX" Failed to create temporary %s \"%s\": " "The name space is full.\n", createTempFile ? "file" : "directory", path); errno = EAGAIN; } exit: Posix_Free(path); return fd; } /* *---------------------------------------------------------------------------- * * FileMakeTempExCreateNameFunc -- * * This is a helper function designed for File_MakeTempEx function. * Everytime this function is called, this creates a fileName with the * format and returns back to the caller. * * 'num' specifies the nth time this function is called. * * 'data' specifies the payload that is specified when File_MakeTempEx2() * function is called. This points to a UTF8 string. * * Results: * if successful, a dynamically allocated string with the basename of * the temp file. NULL otherwise. * * Side effects: * None * *---------------------------------------------------------------------------- */ static char * FileMakeTempExCreateNameFunc(uint32 num, // IN: void *data) // IN: { if (data == NULL) { return NULL; } return Unicode_Format("%s%u", (char *) data, num); } /* *---------------------------------------------------------------------- * * File_MakeTempEx -- * * Create a temporary file and, if successful, return an open file * descriptor to that file. * * 'dir' specifies the directory in which to create the file. It * must not end in a slash. * * 'fileName' specifies the base filename of the created file. * * Results: * Open file descriptor or -1; if successful then presult points * to a dynamically allocated string with the pathname of the temp * file. * * Side effects: * Creates a file if successful. Errno is set on error * *---------------------------------------------------------------------- */ int File_MakeTempEx(const char *dir, // IN: const char *fileName, // IN: char **presult) // OUT: { return File_MakeTempEx2(dir, TRUE, FileMakeTempExCreateNameFunc, (void *) fileName, presult); } /* *---------------------------------------------------------------------- * * File_MakeSafeTempDir -- * * Create a temporary directory in a safe area. * * Optional argument 'prefix' specifies the name prefix of the * created directory. When not provided a default will be provided. * * Results: * NULL Failure * !NULL Path name of created directory * * Side effects: * Creates a directory if successful. Errno is set on error * *---------------------------------------------------------------------- */ char * File_MakeSafeTempDir(const char *prefix) // IN: { char *result = NULL; char *dir = File_GetSafeTmpDir(TRUE); if (dir != NULL) { const char *effectivePrefix = (prefix == NULL) ? "safeDir" : prefix; File_MakeTempEx2(dir, FALSE, FileMakeTempExCreateNameFunc, (void *) effectivePrefix, &result); Posix_Free(dir); } return result; } /* *---------------------------------------------------------------------- * * File_MakeSafeTemp -- * * Exactly the same as File_MakeTempEx except uses a safe directory * as the default temporary directory. * * Results: * Open file descriptor or -1 * * Side effects: * Creates a file if successful. * *---------------------------------------------------------------------- */ int File_MakeSafeTemp(const char *tag, // IN (OPT): char **presult) // OUT: { int fd; char *dir = NULL; char *fileName = NULL; ASSERT(presult); *presult = NULL; if (tag && File_IsFullPath(tag)) { File_GetPathName(tag, &dir, &fileName); } else { dir = File_GetSafeTmpDir(TRUE); fileName = Unicode_Duplicate(tag ? tag : "vmware"); } fd = File_MakeTempEx(dir, fileName, presult); Posix_Free(dir); Posix_Free(fileName); return fd; } /* *----------------------------------------------------------------------------- * * File_DoesVolumeSupportAcls -- * * Determines if the volume that the pathname resides on supports * ACLs. * * Results: * TRUE it does * FALSE it doesn't * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool File_DoesVolumeSupportAcls(const char *path) // IN: { Bool succeeded = FALSE; #if defined(_WIN32) Bool res; char *vol; char *vol2; const utf16_t *vol2W; DWORD fsFlags; ASSERT(path); File_SplitName(path, &vol, NULL, NULL); vol2 = Unicode_Append(vol, DIRSEPS); vol2W = UNICODE_GET_UTF16(vol2); res = GetVolumeInformationW(vol2W, NULL, 0, NULL, NULL, &fsFlags, NULL, 0); UNICODE_RELEASE_UTF16(vol2W); if (res) { if ((fsFlags & FS_PERSISTENT_ACLS) == 0) { goto exit; } } else { Log(LGPFX" %s: GetVolumeInformation failed: %d\n", __FUNCTION__, GetLastError()); goto exit; } succeeded = TRUE; exit: Posix_Free(vol); Posix_Free(vol2); #endif return succeeded; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/file/fileTempPosix.c000066400000000000000000000337771321503522500247400ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if !defined(__FreeBSD__) && !defined(sun) # include #endif #include "vmware.h" #include "file.h" #include "fileInt.h" #include "util.h" #include "su.h" #include "vm_atomic.h" #include "str.h" #include "vm_product.h" #include "random.h" #include "userlock.h" #include "unicodeOperations.h" #include "err.h" #include "posix.h" #include "mutexRankLib.h" #include "hostType.h" #include "localconfig.h" #define LOGLEVEL_MODULE util #include "loglevel_user.h" /* *---------------------------------------------------------------------- * * FileTryDir -- * * Check to see if the given directory is actually a directory * and is writable by us. * * Results: * The expanded directory name on success, NULL on failure. * * Side effects: * The result is allocated. * *---------------------------------------------------------------------- */ static char * FileTryDir(const char *dirName) // IN: Is this a writable directory? { char *edirName; if (dirName != NULL) { edirName = Util_ExpandString(dirName); if ((edirName != NULL) && FileIsWritableDir(edirName)) { return edirName; } Posix_Free(edirName); } return NULL; } /* *---------------------------------------------------------------------- * * FileGetTmpDir -- * * Determine the best temporary directory. Unsafe since the * returned directory is generally going to be 0777, thus all sorts * of denial of service or symlink attacks are possible. * * Results: * NULL if error (reported to the user). * * Side effects: * The result is allocated. * *---------------------------------------------------------------------- */ static char * FileGetTmpDir(Bool useConf) // IN: Use the config file? { char *dirName; char *edirName; /* Make several attempts to find a good temporary directory candidate */ if (useConf) { dirName = (char *)LocalConfig_GetString(NULL, "tmpDirectory"); edirName = FileTryDir(dirName); Posix_Free(dirName); if (edirName != NULL) { return edirName; } } /* Posix_Getenv string must _not_ be freed */ edirName = FileTryDir(Posix_Getenv("TMPDIR")); if (edirName != NULL) { return edirName; } /* P_tmpdir is usually defined in */ edirName = FileTryDir(P_tmpdir); if (edirName != NULL) { return edirName; } edirName = FileTryDir("/tmp"); if (edirName != NULL) { return edirName; } edirName = FileTryDir("~"); if (edirName != NULL) { return edirName; } dirName = File_Cwd(NULL); if (dirName != NULL) { edirName = FileTryDir(dirName); Posix_Free(dirName); if (edirName != NULL) { return edirName; } } edirName = FileTryDir("/"); if (edirName != NULL) { return edirName; } Warning("%s: Couldn't get a temporary directory\n", __FUNCTION__); return NULL; } #undef HOSTINFO_TRYDIR #if !defined(__FreeBSD__) && !defined(sun) /* *----------------------------------------------------------------------------- * * FileGetUserName -- * * Retrieve the name associated with a user ID. Thread-safe * version. --hpreg * * Results: * The allocated name on success * NULL on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ static char * FileGetUserName(uid_t uid) // IN: { char *memPool; char *userName; struct passwd pw; struct passwd *pw_p; long memPoolSize; #if defined(__APPLE__) memPoolSize = _PASSWORD_LEN; #else memPoolSize = sysconf(_SC_GETPW_R_SIZE_MAX); if (memPoolSize <= 0) { Warning("%s: sysconf(_SC_GETPW_R_SIZE_MAX) failed.\n", __FUNCTION__); return NULL; } #endif memPool = malloc(memPoolSize); if (memPool == NULL) { Warning("%s: Not enough memory.\n", __FUNCTION__); return NULL; } if ((Posix_Getpwuid_r(uid, &pw, memPool, memPoolSize, &pw_p) != 0) || pw_p == NULL) { Posix_Free(memPool); Warning("%s: Unable to retrieve the username associated with " "user ID %u.\n", __FUNCTION__, uid); return NULL; } userName = strdup(pw_p->pw_name); Posix_Free(memPool); if (userName == NULL) { Warning("%s: Not enough memory.\n", __FUNCTION__); return NULL; } return userName; } /* *----------------------------------------------------------------------------- * * FileAcceptableSafeTmpDir -- * * Determines if the specified path is acceptable as the safe * temp directory. The directory must either be creatable * with the appropriate permissions and userId or it must * already exist with those settings. * * Results: * TRUE if path is acceptible, FALSE otherwise * * Side effects: * Directory may be created * *----------------------------------------------------------------------------- */ static Bool FileAcceptableSafeTmpDir(const char *dirname, // IN: int userId) // IN: { Bool result; static const mode_t mode = 0700; result = (Posix_Mkdir(dirname, mode) == 0); if (!result) { int error = errno; if (EEXIST == error) { struct stat st; /* * The name already exists. Check that it is what we want: a * directory owned by the current effective user with permissions * 'mode'. It is crucial to use lstat() instead of stat() here, * because we do not want the name to be a symlink (created by * another user) pointing to a directory owned by the current * effective user with permissions 'mode'. */ if (Posix_Lstat(dirname, &st) == 0) { /* * Our directory inherited S_ISGID if its parent had it. So it * is important to ignore that bit, and it is safe to do so * because that bit does not affect the owner's permissions. */ if (S_ISDIR(st.st_mode) && (st.st_uid == userId) && ((st.st_mode & 05777) == mode)) { result = TRUE; } } } } return result; } /* *----------------------------------------------------------------------------- * * FileFindExistingSafeTmpDir -- * * Searches the directory baseTmpDir to see if any subdirectories * are suitable to use as the safe temp directory. The safe temp * directory must have the correct permissions and userId. * * Results: * Path to discovered safe temp directory (must be freed). * NULL returned if no suitable directory is found. * * Side effects: * None * *----------------------------------------------------------------------------- */ static char * FileFindExistingSafeTmpDir(uid_t userId, // IN: const char *userName, // IN: const char *baseTmpDir) // IN: { int i; int numFiles; char *pattern; char *tmpDir = NULL; char **fileList = NULL; /* * We always use the pattern PRODUCT-USER-xxxx when creating * alternative safe temp directories, so check for ones with * those names and the appropriate permissions. */ pattern = Unicode_Format("%s-%s-", PRODUCT_GENERIC_NAME_LOWER, userName); if (pattern == NULL) { return NULL; } numFiles = File_ListDirectory(baseTmpDir, &fileList); if (numFiles == -1) { Posix_Free(pattern); return NULL; } for (i = 0; i < numFiles; i++) { if (Unicode_StartsWith(fileList[i], pattern)) { char *path = Unicode_Join(baseTmpDir, DIRSEPS, fileList[i], NULL); if (File_IsDirectory(path) && FileAcceptableSafeTmpDir(path, userId)) { tmpDir = path; break; } Posix_Free(path); } } Util_FreeStringList(fileList, numFiles); Posix_Free(pattern); return tmpDir; } /* *----------------------------------------------------------------------------- * * FileCreateSafeTmpDir -- * * Creates a new directory within baseTmpDir with the correct permissions * and userId to ensure it is safe from symlink attacks. * * Results: * Path to created safe temp directory (must be freed). * NULL returned if no suitable directory could be created. * * Side effects: * Directory may be created. * *----------------------------------------------------------------------------- */ static char * FileCreateSafeTmpDir(uid_t userId, // IN: const char *userName, // IN: const char *baseTmpDir) // IN: { static const int MAX_DIR_ITERS = 250; int curDirIter = 0; char *tmpDir = NULL; while (TRUE) { /* * We use a random number that makes it more likely that we will create * an unused name than if we had simply tried suffixes in numeric order. */ tmpDir = Str_Asprintf(NULL, "%s%s%s-%s-%u", baseTmpDir, DIRSEPS, PRODUCT_GENERIC_NAME_LOWER, userName, FileSimpleRandom()); if (tmpDir == NULL) { Warning("%s: Out of memory error.\n", __FUNCTION__); break; } if (FileAcceptableSafeTmpDir(tmpDir, userId)) { break; } if (++curDirIter > MAX_DIR_ITERS) { Warning("%s: Failed to create a safe temporary directory, path " "\"%s\". The maximum number of attempts was exceeded.\n", __FUNCTION__, tmpDir); Posix_Free(tmpDir); tmpDir = NULL; break; } Posix_Free(tmpDir); tmpDir = NULL; } return tmpDir; } #endif // __linux__ /* *----------------------------------------------------------------------------- * * File_GetSafeTmpDir -- * * Return a safe temporary directory (i.e. a temporary directory which * is not prone to symlink attacks, because it is only writable by the * current effective user). * * Guaranteed to return the same directory every time it is * called during the lifetime of the current process, for the * current effective user ID. (Barring the user manually deleting * or renaming the directory.) * * Results: * The allocated directory path on success. * NULL on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ char * File_GetSafeTmpDir(Bool useConf) // IN: { char *tmpDir; #if defined(__FreeBSD__) || defined(sun) tmpDir = FileGetTmpDir(useConf); #else static Atomic_Ptr lckStorage; static char *safeDir; char *baseTmpDir = NULL; char *userName = NULL; uid_t userId; MXUserExclLock *lck; userId = geteuid(); /* Get and take lock for our safe dir. */ lck = MXUser_CreateSingletonExclLock(&lckStorage, "getSafeTmpDirLock", RANK_getSafeTmpDirLock); MXUser_AcquireExclLock(lck); /* * Check if we've created a temporary dir already and if it is still usable. */ tmpDir = NULL; if (safeDir && FileAcceptableSafeTmpDir(safeDir, userId)) { tmpDir = Util_SafeStrdup(safeDir); goto exit; } /* We don't have a useable temporary dir, create one. */ baseTmpDir = FileGetTmpDir(useConf); if (baseTmpDir == NULL) { Warning("%s: FileGetTmpDir failed.\n", __FUNCTION__); goto exit; } userName = FileGetUserName(userId); if (userName == NULL) { Warning("%s: FileGetUserName failed, using numeric ID " "as username instead.\n", __FUNCTION__); /* Fallback on just using the userId as the username. */ userName = Str_Asprintf(NULL, "uid-%d", userId); if (userName == NULL) { Warning("%s: Str_Asprintf error.\n", __FUNCTION__); goto exit; } } tmpDir = Str_Asprintf(NULL, "%s%s%s-%s", baseTmpDir, DIRSEPS, PRODUCT_GENERIC_NAME_LOWER, userName); if (tmpDir == NULL) { Warning("%s: Out of memory error.\n", __FUNCTION__); goto exit; } if (!FileAcceptableSafeTmpDir(tmpDir, userId)) { /* * We didn't get our first choice for the safe temp directory. * Search through the unsafe tmp directory to see if there is * an acceptable one to use. */ Posix_Free(tmpDir); tmpDir = FileFindExistingSafeTmpDir(userId, userName, baseTmpDir); if (tmpDir == NULL) { /* * We didn't find any usable directories, so try to create one now. */ tmpDir = FileCreateSafeTmpDir(userId, userName, baseTmpDir); } } if (tmpDir != NULL) { /* * We have successfully created a temporary directory, remember it for * future calls. */ Posix_Free(safeDir); safeDir = Util_SafeStrdup(tmpDir); } exit: MXUser_ReleaseExclLock(lck); Posix_Free(baseTmpDir); Posix_Free(userName); #endif return tmpDir; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/foundryMsg/000077500000000000000000000000001321503522500232015ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/foundryMsg/Makefile.am000066400000000000000000000021311321503522500252320ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libFoundryMsg.la libFoundryMsg_la_SOURCES = libFoundryMsg_la_SOURCES += foundryMsg.c libFoundryMsg_la_SOURCES += foundryPropertyListCommon.c libFoundryMsg_la_SOURCES += vixTranslateErrOpenSource.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/foundryMsg/foundryMsg.c000066400000000000000000002341141321503522500255070ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * foundryMsg.c -- * * This is a library for formatting and parsing the messages sent * between a foundry client and the VMX. It is a stand-alone library * so it can be used by the VMX tree without also linking in the * entire foundry client-side library. */ #include "vmware.h" #include "util.h" #include "str.h" #include "base64.h" #include "vixOpenSource.h" #include "vixCommands.h" #include "unicodeBase.h" static char PlainToObfuscatedCharMap[256]; static char ObfuscatedToPlainCharMap[256]; /* * An entry in the command info table. There is one VixCommandInfo per op * code, and each entry contains a description of the op code plus security- * related metadata. */ typedef struct VixCommandInfo { int opCode; const char *commandName; VixCommandSecurityCategory category; Bool used; // Is there an opcode for this entry? } VixCommandInfo; #define VIX_DEFINE_COMMAND_INFO(x, category) { x, #x, category, TRUE } #define VIX_DEFINE_UNUSED_COMMAND { 0, NULL, VIX_COMMAND_CATEGORY_UNKNOWN, FALSE } /* * Contains the information for every VIX command op code. This table is * organized to allow for direct look up, so it must be complete. Any index * that does not correspond to a valid VIX op code must be marked with * VIX_DEFINE_UNUSED_COMMAND. * * When you add or remove a command to vixCommands.h, this table needs to * be updated as well. When adding a new command, you need to give it a * security category. There are descriptions of the categories in vixCommands.h * where they are defined, but in general, if the command affects the host or * a VM (but not the guest), then the command should be CATEGORY_PRIVILEGED. * If the command is a guest command (a command the runs inside the guest * OS) than it should be CATEGORY_ALWAYS_ALLOWED. Also, if a command is * required to establish a connection with the VMX, it needs to be * CATEGORY_ALWAYS_ALLOWED. */ static const VixCommandInfo vixCommandInfoTable[] = { VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_UNKNOWN, VIX_COMMAND_CATEGORY_UNKNOWN), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_VM_POWERON, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_VM_POWEROFF, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_VM_RESET, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_VM_SUSPEND, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_RUN_PROGRAM, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_KEYSTROKES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_READ_REGISTRY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_WRITE_REGISTRY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_COPY_FILE_FROM_GUEST_TO_HOST, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_COPY_FILE_FROM_HOST_TO_GUEST, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_SNAPSHOT, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_REMOVE_SNAPSHOT, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_REVERT_TO_SNAPSHOT, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_VM_CLONE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_GUEST_FILE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GUEST_FILE_EXISTS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_FIND_VM, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CALL_PROCEDURE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_REGISTRY_KEY_EXISTS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_WIN32_WINDOW_MESSAGE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CONSOLIDATE_SNAPSHOTS, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_INSTALL_TOOLS, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CANCEL_INSTALL_TOOLS, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_UPGRADE_VIRTUAL_HARDWARE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_RELOAD_VM, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_VM, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_WAIT_FOR_TOOLS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_RUNNING_VM_SNAPSHOT, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CONSOLIDATE_RUNNING_VM_SNAPSHOT, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_NUM_SHARED_FOLDERS, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_SHARED_FOLDER_STATE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_EDIT_SHARED_FOLDER_STATE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_REMOVE_SHARED_FOLDER, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_ADD_SHARED_FOLDER, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_RUN_SCRIPT_IN_GUEST, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_OPEN_VM, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, /* GET_HANDLE_STATE is needed for the initial handshake */ VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_HANDLE_STATE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_WORKING_COPY, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DISCARD_WORKING_COPY, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SAVE_WORKING_COPY, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CAPTURE_SCREEN, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_TOOLS_STATE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CHANGE_SCREEN_RESOLUTION, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DIRECTORY_EXISTS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_GUEST_REGISTRY_KEY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_GUEST_DIRECTORY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_GUEST_EMPTY_DIRECTORY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_TEMPORARY_FILE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_PROCESSES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_MOVE_GUEST_FILE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_DIRECTORY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CHECK_USER_ACCOUNT, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_DIRECTORY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_REGISTER_VM, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_UNREGISTER_VM, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, /* CREATE_SESSION_KEY is needed for the initial handshake */ VIX_DEFINE_COMMAND_INFO(VIX_CREATE_SESSION_KEY_COMMAND, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VMXI_HGFS_SEND_PACKET_COMMAND, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_KILL_PROCESS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LOGOUT_IN_GUEST, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_READ_VARIABLE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_WRITE_VARIABLE, VIX_COMMAND_CATEGORY_MIXED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CONNECT_DEVICE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_IS_DEVICE_CONNECTED, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_FILE_INFO, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SET_FILE_INFO, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_MOUSE_EVENTS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_OPEN_TEAM, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_ANSWER_MESSAGE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_ENABLE_SHARED_FOLDERS, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_MOUNT_HGFS_FOLDERS, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_HOT_EXTEND_DISK, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CONNECT_HOST, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_LINKED_CLONE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, /* * HOWTO: Adding a new Vix Command. Step 2b. * Take the command you added to vixCommands.h, and add it to this * table. The command needs to go in the index that matches the command * ID as specified in the enum in vixCommands.h. */ VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SAMPLE_COMMAND, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_GUEST_NETWORKING_CONFIG, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SET_GUEST_NETWORKING_CONFIG, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_VM_PAUSE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_VM_UNPAUSE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_PERFORMANCE_DATA, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_SNAPSHOT_SCREENSHOT, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_WAIT_FOR_USER_ACTION_IN_GUEST, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CHANGE_VIRTUAL_HARDWARE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_HOT_PLUG_CPU, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_HOT_PLUG_MEMORY, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_HOT_ADD_DEVICE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_HOT_REMOVE_DEVICE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, /* GET_VMX_DEVICE_STATE is needed for the initial handshake. */ VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GET_VMX_DEVICE_STATE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SET_SNAPSHOT_INFO, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SNAPSHOT_SET_MRU, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LOGOUT_HOST, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_HOT_PLUG_BEGIN_BATCH, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_HOT_PLUG_COMMIT_BATCH, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_TRANSFER_CONNECTION, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_TRANSFER_REQUEST, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_TRANSFER_FINAL_DATA, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_UNUSED_COMMAND, VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_FILESYSTEMS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CHANGE_DISPLAY_TOPOLOGY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SUSPEND_AND_RESUME, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_REMOVE_BULK_SNAPSHOT, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_COPY_FILE_FROM_READER_TO_GUEST, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_GENERATE_NONCE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CHANGE_DISPLAY_TOPOLOGY_MODES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_QUERY_CHILDREN, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_FILES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_DIRECTORY_EX, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_MOVE_GUEST_FILE_EX, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_MOVE_GUEST_DIRECTORY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_TEMPORARY_FILE_EX, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_TEMPORARY_DIRECTORY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SET_GUEST_FILE_ATTRIBUTES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_COPY_FILE_FROM_GUEST_TO_READER, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_START_PROGRAM, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_PROCESSES_EX, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_READ_ENV_VARIABLES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_INITIATE_FILE_TRANSFER_FROM_GUEST, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_INITIATE_FILE_TRANSFER_TO_GUEST, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_ACQUIRE_CREDENTIALS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_RELEASE_CREDENTIALS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_VALIDATE_CREDENTIALS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_TERMINATE_PROCESS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_GUEST_FILE_EX, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_GUEST_DIRECTORY_EX, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_HOT_CHANGE_MONITOR_TYPE, VIX_COMMAND_CATEGORY_PRIVILEGED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_ADD_AUTH_ALIAS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_REMOVE_AUTH_ALIAS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_AUTH_PROVIDER_ALIASES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_AUTH_MAPPED_ALIASES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_CREATE_REGISTRY_KEY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_REGISTRY_KEYS, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_REGISTRY_KEY, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_SET_REGISTRY_VALUE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_LIST_REGISTRY_VALUES, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_DELETE_REGISTRY_VALUE, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), VIX_DEFINE_COMMAND_INFO(VIX_COMMAND_REMOVE_AUTH_ALIAS_BY_CERT, VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED), }; static const VixCommandInfo *VixGetCommandInfoForOpCode(int opCode); static void VixMsgInitializeObfuscationMapping(void); static VixError VixMsgEncodeBuffer(const uint8 *buffer, size_t bufferLength, Bool includeEncodingId, char **result); static VixError VixMsgDecodeBuffer(const char *str, Bool nullTerminateResult, char **result, size_t *bufferLength); static VixError VMAutomationMsgParserInit(const char *caller, unsigned int line, VMAutomationMsgParser *state, const VixMsgHeader *msg, size_t headerLength, size_t fixedLength, size_t miscDataLength, const char *packetType); /* *---------------------------------------------------------------------------- * * VixMsg_AllocResponseMsg -- * * Allocate and initialize a response message. * * Results: * The message, with the headers properly initialized. * * Side effects: * None. * *---------------------------------------------------------------------------- */ VixCommandResponseHeader * VixMsg_AllocResponseMsg(const VixCommandRequestHeader *requestHeader, // IN VixError error, // IN uint32 additionalError, // IN size_t responseBodyLength, // IN const void *responseBody, // IN size_t *responseMsgLength) // OUT { char *responseBuffer = NULL; VixCommandResponseHeader *responseHeader; size_t totalMessageSize; ASSERT((NULL != responseBody) || (0 == responseBodyLength)); /* * We don't have scatter/gather, so copy everything into one buffer. */ totalMessageSize = sizeof(VixCommandResponseHeader) + responseBodyLength; if (totalMessageSize > VIX_COMMAND_MAX_SIZE) { /* * We don't want to allocate any responses larger than * VIX_COMMAND_MAX_SIZE, since the VMX will ignore them. * If we hit this ASSERT, we will need to either revise this * value, or start packetizing certain commands. */ ASSERT(0); return NULL; } responseBuffer = Util_SafeMalloc(totalMessageSize); responseHeader = (VixCommandResponseHeader *) responseBuffer; VixMsg_InitResponseMsg(responseHeader, requestHeader, error, additionalError, totalMessageSize); if ((responseBodyLength > 0) && (responseBody)) { memcpy(responseBuffer + sizeof(VixCommandResponseHeader), responseBody, responseBodyLength); } if (NULL != responseMsgLength) { *responseMsgLength = totalMessageSize; } return responseHeader; } // VixMsg_AllocResponseMsg /* *---------------------------------------------------------------------------- * * VixMsg_InitResponseMsg -- * * Initialize a response message. * * Results: * The message, with the headers properly initialized. * * Side effects: * None. * *---------------------------------------------------------------------------- */ void VixMsg_InitResponseMsg(VixCommandResponseHeader *responseHeader, // IN const VixCommandRequestHeader *requestHeader, // IN VixError error, // IN uint32 additionalError, // IN size_t totalMessageSize) // IN { size_t responseBodyLength; ASSERT(NULL != responseHeader); ASSERT(totalMessageSize >= sizeof(VixCommandResponseHeader)); responseBodyLength = totalMessageSize - sizeof(VixCommandResponseHeader); /* * Fill in the response header. */ responseHeader->commonHeader.magic = VIX_COMMAND_MAGIC_WORD; responseHeader->commonHeader.messageVersion = VIX_COMMAND_MESSAGE_VERSION; responseHeader->commonHeader.totalMessageLength = totalMessageSize; responseHeader->commonHeader.headerLength = sizeof(VixCommandResponseHeader); responseHeader->commonHeader.bodyLength = responseBodyLength; responseHeader->commonHeader.credentialLength = 0; responseHeader->commonHeader.commonFlags = 0; if (NULL != requestHeader) { responseHeader->requestCookie = requestHeader->cookie; } else { responseHeader->requestCookie = 0; } responseHeader->responseFlags = 0; responseHeader->duration = 0xFFFFFFFF; responseHeader->error = error; responseHeader->additionalError = additionalError; responseHeader->errorDataLength = 0; } // VixMsg_InitResponseMsg /* *----------------------------------------------------------------------------- * * VixMsg_AllocRequestMsg -- * * Allocate and initialize a request message. * * Results: * The message, with the headers properly initialized. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixCommandRequestHeader * VixMsg_AllocRequestMsg(size_t msgHeaderAndBodyLength, // IN int opCode, // IN uint64 cookie, // IN int credentialType, // IN const char *credential) // IN { size_t totalMessageSize; VixCommandRequestHeader *commandRequest = NULL; size_t providedCredentialLength = 0; size_t totalCredentialLength = 0; char *destPtr; if ((VIX_USER_CREDENTIAL_NAME_PASSWORD == credentialType) || (VIX_USER_CREDENTIAL_HOST_CONFIG_SECRET == credentialType) || (VIX_USER_CREDENTIAL_HOST_CONFIG_HASHED_SECRET == credentialType) || (VIX_USER_CREDENTIAL_TICKETED_SESSION == credentialType) || (VIX_USER_CREDENTIAL_SSPI == credentialType) || (VIX_USER_CREDENTIAL_SAML_BEARER_TOKEN == credentialType)) { /* * All of these are optional. */ if (NULL != credential) { providedCredentialLength = strlen(credential); totalCredentialLength += providedCredentialLength; } /* * Add 1 to each string to include '\0' for the end of the string. */ totalCredentialLength += 1; } else { totalCredentialLength = 0; } totalMessageSize = msgHeaderAndBodyLength + totalCredentialLength; if (totalMessageSize > VIX_COMMAND_MAX_REQUEST_SIZE) { /* * We don't want to allocate any requests larger than * VIX_COMMAND_MAX_REQUEST_SIZE, since the VMX will ignore them. * If we hit this ASSERT, we will need to either revise this * value, or start packetizing certain commands. */ ASSERT(0); return NULL; } commandRequest = (VixCommandRequestHeader *) Util_SafeCalloc(1, totalMessageSize); commandRequest->commonHeader.magic = VIX_COMMAND_MAGIC_WORD; commandRequest->commonHeader.messageVersion = VIX_COMMAND_MESSAGE_VERSION; commandRequest->commonHeader.totalMessageLength = msgHeaderAndBodyLength + totalCredentialLength; commandRequest->commonHeader.headerLength = sizeof(VixCommandRequestHeader); commandRequest->commonHeader.bodyLength = msgHeaderAndBodyLength - sizeof(VixCommandRequestHeader); commandRequest->commonHeader.credentialLength = totalCredentialLength; commandRequest->commonHeader.commonFlags = VIX_COMMAND_REQUEST; commandRequest->opCode = opCode; commandRequest->cookie = cookie; commandRequest->timeOut = 0xFFFFFFFF; commandRequest->requestFlags = 0; commandRequest->userCredentialType = credentialType; if ((VIX_USER_CREDENTIAL_NAME_PASSWORD == credentialType) || (VIX_USER_CREDENTIAL_HOST_CONFIG_SECRET == credentialType) || (VIX_USER_CREDENTIAL_HOST_CONFIG_HASHED_SECRET == credentialType) || (VIX_USER_CREDENTIAL_TICKETED_SESSION == credentialType) || (VIX_USER_CREDENTIAL_SSPI == credentialType) || (VIX_USER_CREDENTIAL_SAML_BEARER_TOKEN == credentialType)) { destPtr = (char *) commandRequest; destPtr += commandRequest->commonHeader.headerLength; destPtr += commandRequest->commonHeader.bodyLength; if (NULL != credential) { Str_Strcpy(destPtr, credential, providedCredentialLength + 1); destPtr += providedCredentialLength; } *(destPtr++) = 0; } return commandRequest; } // VixMsg_AllocRequestMsg /* *----------------------------------------------------------------------------- * * VixMsg_ValidateMessage -- * * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_ValidateMessage(const void *vMsg, // IN size_t msgLength) // IN { const VixMsgHeader *message; if ((NULL == vMsg) || (msgLength < sizeof *message)) { return VIX_E_INVALID_MESSAGE_HEADER; } /* * Sanity check the header. * Some basic rules: All the length values in the VixMsgHeader * struct are uint32. The headerLength must be large enough to * accomodate the base header: VixMsgHeader. The bodyLength and * the credentialLength can be 0. * * We cannot compare message->totalMessageLength and msgLength. * When we first read just the header, message->totalMessageLength * is > msgLength. When we have read the whole message, then * message->totalMessageLength <= msgLength. So, it depends on * when we call this function. Instead, we just make sure the message * is internally consistent, and then rely on the higher level code to * decide how much to read and when it has read the whole message. */ message = vMsg; if ((VIX_COMMAND_MAGIC_WORD != message->magic) || (message->headerLength < sizeof(VixMsgHeader)) || (message->totalMessageLength < ((uint64)message->headerLength + message->bodyLength + message->credentialLength)) || (message->totalMessageLength > VIX_COMMAND_MAX_SIZE) || (VIX_COMMAND_MESSAGE_VERSION != message->messageVersion)) { return VIX_E_INVALID_MESSAGE_HEADER; } return VIX_OK; } // VixMsg_ValidateMessage /* *----------------------------------------------------------------------------- * * VixMsg_ValidateRequestMsg -- * * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_ValidateRequestMsg(const void *vMsg, // IN size_t msgLength) // IN { VixError err; const VixCommandRequestHeader *message; err = VixMsg_ValidateMessage(vMsg, msgLength); if (VIX_OK != err) { return(err); } /* * Sanity check the parts of the header that are specific to requests. */ message = vMsg; if (message->commonHeader.headerLength < sizeof(VixCommandRequestHeader)) { return VIX_E_INVALID_MESSAGE_HEADER; } if (message->commonHeader.totalMessageLength > VIX_COMMAND_MAX_REQUEST_SIZE) { return VIX_E_INVALID_MESSAGE_HEADER; } if (!(VIX_COMMAND_REQUEST & message->commonHeader.commonFlags)) { return VIX_E_INVALID_MESSAGE_HEADER; } if ((VIX_REQUESTMSG_INCLUDES_AUTH_DATA_V1 & message->requestFlags) && (message->commonHeader.totalMessageLength < (uint64)message->commonHeader.headerLength + message->commonHeader.bodyLength + message->commonHeader.credentialLength + sizeof (VixMsgAuthDataV1))) { return VIX_E_INVALID_MESSAGE_HEADER; } return VIX_OK; } // VixMsg_ValidateRequestMsg /* *----------------------------------------------------------------------------- * * VixMsg_ValidateResponseMsg -- * * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_ValidateResponseMsg(const void *vMsg, // IN size_t msgLength) // IN { VixError err; const VixCommandResponseHeader *message; if ((NULL == vMsg) || (msgLength < sizeof *message)) { return VIX_E_INVALID_MESSAGE_HEADER; } err = VixMsg_ValidateMessage(vMsg, msgLength); if (VIX_OK != err) { return(err); } /* * Sanity check the parts of the header that are specific to responses. */ message = vMsg; if (message->commonHeader.headerLength < sizeof(VixCommandResponseHeader)) { return VIX_E_INVALID_MESSAGE_HEADER; } if (VIX_COMMAND_REQUEST & message->commonHeader.commonFlags) { return VIX_E_INVALID_MESSAGE_HEADER; } return VIX_OK; } // VixMsg_ValidateResponseMsg /* *----------------------------------------------------------------------------- * * VixMsg_ParseWriteVariableRequest -- * * Extract the value's name and the value itself from the request * message, while validating message. * * The strings returned from this function just point to memory in * the message itself, so they must not be free()'d. * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_ParseWriteVariableRequest(VixMsgWriteVariableRequest *msg, // IN char **valueName, // OUT char **value) // OUT { VixError err; char *valueNameLocal = NULL; char *valueLocal = NULL; uint64 headerAndBodyLength; if ((NULL == msg) || (NULL == valueName) || (NULL == value)) { ASSERT(0); err = VIX_E_FAIL; goto abort; } *valueName = NULL; *value = NULL; /* * In most cases we will have already called VixMsg_ValidateResponseMsg() * on this request before, but call it here so that this function will * always be sufficient to validate the request. */ err = VixMsg_ValidateRequestMsg(msg, msg->header.commonHeader.totalMessageLength); if (VIX_OK != err) { goto abort; } if (msg->header.commonHeader.totalMessageLength < sizeof *msg) { err = VIX_E_INVALID_MESSAGE_BODY; goto abort; } headerAndBodyLength = (uint64) msg->header.commonHeader.headerLength + msg->header.commonHeader.bodyLength; if (headerAndBodyLength < ((uint64) sizeof *msg + msg->nameLength + 1 + msg->valueLength + 1)) { err = VIX_E_INVALID_MESSAGE_BODY; goto abort; } valueNameLocal = ((char *) msg) + sizeof(*msg); if ('\0' != valueNameLocal[msg->nameLength]) { err = VIX_E_INVALID_MESSAGE_BODY; goto abort; } valueLocal = valueNameLocal + msg->nameLength + 1; if ('\0' != valueLocal[msg->valueLength]) { err = VIX_E_INVALID_MESSAGE_BODY; goto abort; } *valueName = valueNameLocal; *value = valueLocal; err = VIX_OK; abort: return err; } // VixMsg_ParseWriteVariableRequest /* *----------------------------------------------------------------------------- * * VixMsgInitializeObfuscationMapping -- * * * Results: * None * * Side effects: * None. * *----------------------------------------------------------------------------- */ void VixMsgInitializeObfuscationMapping(void) { size_t charIndex; static Bool initializedTable = FALSE; if (initializedTable) { return; } for (charIndex = 0; charIndex < sizeof(PlainToObfuscatedCharMap); charIndex++) { PlainToObfuscatedCharMap[charIndex] = 0; ObfuscatedToPlainCharMap[charIndex] = 0; } PlainToObfuscatedCharMap['\\'] = '1'; PlainToObfuscatedCharMap['\''] = '2'; PlainToObfuscatedCharMap['\"'] = '3'; PlainToObfuscatedCharMap[' '] = '4'; PlainToObfuscatedCharMap['\r'] = '5'; PlainToObfuscatedCharMap['\n'] = '6'; PlainToObfuscatedCharMap['\t'] = '7'; ObfuscatedToPlainCharMap['1'] = '\\'; ObfuscatedToPlainCharMap['2'] = '\''; ObfuscatedToPlainCharMap['3'] = '\"'; ObfuscatedToPlainCharMap['4'] = ' '; ObfuscatedToPlainCharMap['5'] = '\r'; ObfuscatedToPlainCharMap['6'] = '\n'; ObfuscatedToPlainCharMap['7'] = '\t'; initializedTable = TRUE; } // VixMsgInitializeObfuscationMapping /* *----------------------------------------------------------------------------- * * VixMsg_ObfuscateNamePassword -- * * This is NOT ENCRYPTION. * * This function does 2 things: * * It removes spaces, quotes and other characters that may make * parsing params in a string difficult. The name and password is * passed from the VMX to the tools through the backdoor as a * string containing quoted parameters. * * * It means that somebody doing a trivial string search on * host memory won't see a name/password. * * This is used ONLY between the VMX and guest through the backdoor. * This is NOT secure. * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_ObfuscateNamePassword(const char *userName, // IN const char *password, // IN char **result) // OUT { VixError err = VIX_OK; char *packedBuffer = NULL; char *resultString = NULL; char *destPtr; size_t packedBufferLength = 0; size_t nameLength = 0; size_t passwordLength = 0; if (NULL != userName) { nameLength = strlen(userName); } if (NULL != password) { passwordLength = strlen(password); } /* * Leave space for null terminating characters. */ packedBufferLength = nameLength + 1 + passwordLength + 1; packedBuffer = VixMsg_MallocClientData(packedBufferLength); if (packedBuffer == NULL) { err = VIX_E_OUT_OF_MEMORY; goto abort; } destPtr = packedBuffer; if (NULL != userName) { Str_Strcpy(destPtr, userName, nameLength + 1); destPtr += nameLength; } *(destPtr++) = 0; if (NULL != password) { Str_Strcpy(destPtr, password, passwordLength + 1); destPtr += passwordLength; } *(destPtr++) = 0; err = VixMsgEncodeBuffer(packedBuffer, packedBufferLength, FALSE, &resultString); if (err != VIX_OK) { goto abort; } abort: Util_ZeroFree(packedBuffer, packedBufferLength); if (err == VIX_OK) { *result = resultString; } return err; } // VixMsg_ObfuscateNamePassword /* *----------------------------------------------------------------------------- * * VixMsg_DeObfuscateNamePassword -- * * This reverses VixMsg_ObfuscateNamePassword. * See the notes for that procedure. * * Results: * VixError. VIX_OK if successful. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_DeObfuscateNamePassword(const char *packagedName, // IN char **userNameResult, // OUT char **passwordResult) // OUT { VixError err; char *packedString = NULL; char *srcPtr; size_t packedStringLength; char *userName = NULL; char *passwd = NULL; err = VixMsgDecodeBuffer(packagedName, FALSE, &packedString, &packedStringLength); if (err != VIX_OK) { goto abort; } srcPtr = packedString; if (NULL != userNameResult) { Bool allocateFailed; userName = VixMsg_StrdupClientData(srcPtr, &allocateFailed); if (allocateFailed) { err = VIX_E_OUT_OF_MEMORY; goto abort; } } srcPtr = srcPtr + strlen(srcPtr); srcPtr++; if (NULL != passwordResult) { Bool allocateFailed; passwd = VixMsg_StrdupClientData(srcPtr, &allocateFailed); if (allocateFailed) { err = VIX_E_OUT_OF_MEMORY; goto abort; } } *userNameResult = userName; userName = NULL; *passwordResult = passwd; passwd = NULL; abort: Util_ZeroFree(packedString, packedStringLength); Util_ZeroFreeString(userName); Util_ZeroFreeString(passwd); return err; } // VixMsg_DeObfuscateNamePassword /* *----------------------------------------------------------------------------- * * VixMsg_EncodeString -- * * This makes a string safe to pass over a backdoor Tclo command as a * string. It base64 encodes a string, which removes quote, space, * backslash, and other characters. This will also allow us to pass * UTF-8 strings. * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_EncodeString(const char *str, // IN char **result) // OUT { if (NULL == str) { str = ""; } return VixMsgEncodeBuffer(str, strlen(str), TRUE, result); } // VixMsg_EncodeString /* *----------------------------------------------------------------------------- * * VixMsgEncodeBuffer -- * * This makes a string safe to pass over a backdoor Tclo command as a * string. It base64 encodes a string, which removes quote, space, * backslash, and other characters. This will also allow us to pass * UTF-8 strings. * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsgEncodeBuffer(const uint8 *buffer, // IN size_t bufferLength, // IN Bool includeEncodingId, // IN: Add 'a' (ASCII) at start of output char ** result) // OUT { VixError err = VIX_OK; char *base64String = NULL; char *resultString = NULL; size_t resultBufferLength = 0; char *srcPtr; char *endSrcPtr; char *destPtr; size_t base64Length; base64Length = Base64_EncodedLength((uint8 const *) buffer, bufferLength); base64String = VixMsg_MallocClientData(base64Length); if (base64String == NULL) { err = VIX_E_OUT_OF_MEMORY; goto abort; } if (!(Base64_Encode((uint8 const *) buffer, bufferLength, base64String, base64Length, &base64Length))) { err = VIX_E_FAIL; goto abort; } VixMsgInitializeObfuscationMapping(); /* * Expand it to make space for escaping some characters. */ resultBufferLength = base64Length * 2; if (includeEncodingId) { resultBufferLength++; } resultString = VixMsg_MallocClientData(resultBufferLength + 1); if (resultString == NULL) { err = VIX_E_OUT_OF_MEMORY; goto abort; } destPtr = resultString; srcPtr = base64String; endSrcPtr = base64String + base64Length; if (includeEncodingId) { /* * Start with the character-set type. * 'a' means ASCII. */ *(destPtr++) = 'a'; } /* * Now, escape problematic characters. */ while (srcPtr < endSrcPtr) { if (PlainToObfuscatedCharMap[(unsigned int) (*srcPtr)]) { *(destPtr++) = '\\'; *(destPtr++) = PlainToObfuscatedCharMap[(unsigned int) (*srcPtr)]; } else { *(destPtr++) = *srcPtr; } srcPtr++; } VERIFY((destPtr - resultString) <= resultBufferLength); *destPtr = 0; abort: free(base64String); if (err == VIX_OK) { *result = resultString; } return err; } // VixMsgEncodeBuffer /* *----------------------------------------------------------------------------- * * VixMsg_DecodeString -- * * This reverses VixMsg_EncodeString. * See the notes for that procedure. * * Results: * VixError. VIX_OK if successful. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_DecodeString(const char *str, // IN char **result) // OUT { /* * Check the character set. * 'a' means ASCII. */ if ((NULL == str) || ('a' != *str)) { *result = NULL; return VIX_E_INVALID_ARG; } return VixMsgDecodeBuffer(str + 1, TRUE, result, NULL); } // VixMsg_DecodeString /* *----------------------------------------------------------------------------- * * VixMsgDecodeBuffer -- * * This reverses VixMsgEncodeBuffer. * See the notes for that procedure. * * Results: * VixError. VIX_OK if successful. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsgDecodeBuffer(const char *str, // IN Bool nullTerminateResult, // OUT char **result, // OUT size_t *bufferLength) // OUT: Optional { VixError err = VIX_OK; char *base64String = NULL; char *resultStr = NULL; char *srcPtr; char *destPtr; size_t resultStrAllocatedLength; size_t resultStrLogicalLength; Bool allocateFailed; if (NULL != bufferLength) { *bufferLength = 0; } /* * Remove escaped special characters. * Do this in a private copy because we will change the string in place. */ VixMsgInitializeObfuscationMapping(); base64String = VixMsg_StrdupClientData(str, &allocateFailed); if (allocateFailed) { err = VIX_E_OUT_OF_MEMORY; goto abort; } destPtr = base64String; srcPtr = base64String; while (*srcPtr) { if ('\\' == *srcPtr) { srcPtr++; /* * There should never be a null byte as part of an escape character or * an escape character than translates into a null byte. */ if ((0 == *srcPtr) || (0 == ObfuscatedToPlainCharMap[(unsigned int) (*srcPtr)])) { goto abort; } *(destPtr++) = ObfuscatedToPlainCharMap[(unsigned int) (*srcPtr)]; } else { *(destPtr++) = *srcPtr; } srcPtr++; } *destPtr = 0; /* * Add 1 to the Base64_DecodedLength(), since we base64 encoded the string * without the NUL terminator and need to add one. */ resultStrAllocatedLength = Base64_DecodedLength(base64String, destPtr - base64String); if (nullTerminateResult) { resultStrAllocatedLength += 1; } resultStr = Util_SafeMalloc(resultStrAllocatedLength); if (!Base64_Decode(base64String, resultStr, resultStrAllocatedLength, &resultStrLogicalLength) || (resultStrLogicalLength > resultStrAllocatedLength)) { free(resultStr); resultStr = NULL; goto abort; } if (nullTerminateResult) { VERIFY(resultStrLogicalLength < resultStrAllocatedLength); resultStr[resultStrLogicalLength] = 0; } if (NULL != bufferLength) { *bufferLength = resultStrLogicalLength; } abort: free(base64String); if (err == VIX_OK) { *result = resultStr; } return err; } // VixMsgDecodeBuffer /* *----------------------------------------------------------------------------- * * VixAsyncOp_ValidateCommandInfoTable -- * * Checks that the command info table is generally well-formed. * Makes sure that the table is big enough to contain all the * command op codes and that they are present in the right order. * * Results: * Bool * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool VixMsg_ValidateCommandInfoTable(void) { int i; /* * Check at compile time that there is as many entries in the * command info table as there are commands. We need the +1 since * VIX_COMMAND_UNKNOWN is in the table and its opcode is -1. * * If this has failed for you, you've probably added a new command to VIX * without adding it to the command info table above. */ ASSERT_ON_COMPILE(ARRAYSIZE(vixCommandInfoTable) == (VIX_COMMAND_LAST_NORMAL_COMMAND + 1)); /* * Iterated over all the elements in the command info table to make * sure that op code matches the index (they are shifted by one because * of VIX_COMMAND_UNKNOWN) and that every used entry has a non-NULL name. */ for (i = 0; i < ARRAYSIZE(vixCommandInfoTable); i++) { if (vixCommandInfoTable[i].used && ((vixCommandInfoTable[i].opCode != (i - 1)) || (NULL == vixCommandInfoTable[i].commandName))) { Warning("%s: Mismatch or NULL in command with op code %d at " "index %d.\n", __FUNCTION__, vixCommandInfoTable[i].opCode, i); return FALSE; } } return TRUE; } // VixMsg_ValidateCommandInfoTable /* *----------------------------------------------------------------------------- * * VixAsyncOp_GetDebugStrForOpCode -- * * Get a human readable string representing the given op code, or * "Unrecognized op" if the op code is invalid. * * Results: * const char * * * Side effects: * None * *----------------------------------------------------------------------------- */ const char * VixAsyncOp_GetDebugStrForOpCode(int opCode) // IN { const char *opName = "Unrecognized op"; const VixCommandInfo *commandInfo; commandInfo = VixGetCommandInfoForOpCode(opCode); if (NULL != commandInfo) { opName = commandInfo->commandName; ASSERT(NULL != opName); } return opName; } // VixAsyncOp_GetDebugStrForOpCode /* *----------------------------------------------------------------------------- * * VixMsg_GetCommandSecurityCategory -- * * Get the security category asociated with the given op code. * * Results: * VixCommandSecurityCategory: the security category for the op code, * or VIX_COMMAND_CATEGORY_UNKNOWN is the op code is invalid. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixCommandSecurityCategory VixMsg_GetCommandSecurityCategory(int opCode) // IN { VixCommandSecurityCategory category = VIX_COMMAND_CATEGORY_UNKNOWN; const VixCommandInfo *commandInfo; commandInfo = VixGetCommandInfoForOpCode(opCode); if (NULL != commandInfo) { category = commandInfo->category; } return category; } // VixMsg_GetCommandSecurityCategory /* *----------------------------------------------------------------------------- * * VixGetCommandInfoForOpCode -- * * Looks up the information for an opcode from the global op code table. * * Results: * A const pointer to the command info struct for the opCode, or NULL * if the op code is invalid. * * Side effects: * None * *----------------------------------------------------------------------------- */ static const VixCommandInfo * VixGetCommandInfoForOpCode(int opCode) // IN { const VixCommandInfo *commandInfo = NULL; if ((opCode >= VIX_COMMAND_UNKNOWN) && (opCode < VIX_COMMAND_LAST_NORMAL_COMMAND)) { /* Add 1 to the op code, since VIX_COMMAND_UNKNOWN is -1 */ if (vixCommandInfoTable[opCode + 1].used) { commandInfo = &vixCommandInfoTable[opCode + 1]; } } return commandInfo; } // VixGetCommandInfoForOpCode /* *----------------------------------------------------------------------------- * * VixMsg_AllocGenericRequestMsg -- * * Allocate and initialize a generic request message. * * Assumes the caller holds the lock to 'propertyList'. * * Results: * Returns VixError. * Upon retrun, *request will contain either the message with the * headers properly initialized or NULL. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_AllocGenericRequestMsg(int opCode, // IN uint64 cookie, // IN int credentialType, // IN const char *userNamePassword, // IN int options, // IN VixPropertyListImpl *propertyList, // IN VixCommandGenericRequest **request) // OUT { VixError err; VixCommandGenericRequest *requestLocal = NULL; size_t msgHeaderAndBodyLength; char *serializedBufferBody = NULL; size_t serializedBufferLength = 0; if (NULL == request) { ASSERT(0); err = VIX_E_FAIL; goto abort; } *request = NULL; if (NULL != propertyList) { err = VixPropertyList_Serialize(propertyList, FALSE, &serializedBufferLength, &serializedBufferBody); if (VIX_OK != err) { goto abort; } } msgHeaderAndBodyLength = sizeof(*requestLocal) + serializedBufferLength; requestLocal = (VixCommandGenericRequest *) VixMsg_AllocRequestMsg(msgHeaderAndBodyLength, opCode, cookie, credentialType, userNamePassword); if (NULL == requestLocal) { err = VIX_E_FAIL; goto abort; } requestLocal->options = options; requestLocal->propertyListSize = serializedBufferLength; if (NULL != serializedBufferBody) { char *dst = (char *)request + sizeof(*request); memcpy(dst, serializedBufferBody, serializedBufferLength); } *request = requestLocal; err = VIX_OK; abort: free(serializedBufferBody); return err; } // VixMsg_AllocGenericRequestMsg /* *----------------------------------------------------------------------------- * * VixMsg_ParseGenericRequestMsg -- * * Extract the options and property list from the request * message, while validating message. * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixMsg_ParseGenericRequestMsg(const VixCommandGenericRequest *request, // IN int *options, // OUT VixPropertyListImpl *propertyList) // OUT { VixError err; uint64 headerAndBodyLength; if ((NULL == request) || (NULL == options) || (NULL == propertyList)) { ASSERT(0); err = VIX_E_FAIL; goto abort; } *options = 0; VixPropertyList_Initialize(propertyList); /* * In most cases we will have already called VixMsg_ValidateResponseMsg() * on this request before, but call it here so that this function will * always be sufficient to validate the request. */ err = VixMsg_ValidateRequestMsg(request, request->header.commonHeader.totalMessageLength); if (VIX_OK != err) { goto abort; } if (request->header.commonHeader.totalMessageLength < sizeof *request) { err = VIX_E_INVALID_MESSAGE_BODY; goto abort; } headerAndBodyLength = (uint64) request->header.commonHeader.headerLength + request->header.commonHeader.bodyLength; if (headerAndBodyLength < ((uint64) sizeof *request + request->propertyListSize)) { err = VIX_E_INVALID_MESSAGE_BODY; goto abort; } if (request->propertyListSize > 0) { const char *serializedBuffer = (const char *) request + sizeof(*request); err = VixPropertyList_Deserialize(propertyList, serializedBuffer, request->propertyListSize, VIX_PROPERTY_LIST_BAD_ENCODING_ERROR); if (VIX_OK != err) { goto abort; } } *options = request->options; err = VIX_OK; abort: return err; } // VixMsg_ParseGenericRequestMsg /* *----------------------------------------------------------------------------- * * VixMsg_ParseSimpleResponseWithString -- * * Takes a response packet that consists of a VixCommandResponseHeader * followed by a string containing the response data, validates * the packet, and then passes out a pointer to that string. * * Results: * VixError * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixMsg_ParseSimpleResponseWithString(const VixCommandResponseHeader *response, // IN const char **result) // OUT { VixError err; VMAutomationMsgParser parser; err = VMAutomationMsgParserInitResponse(&parser, response, sizeof *response); if (VIX_OK != err) { goto abort; } err = VMAutomationMsgParserGetOptionalString(&parser, response->commonHeader.bodyLength, result); abort: return err; } /* *----------------------------------------------------------------------------- * * VixMsg_MallocClientData -- * * Allocates the memory needed to copy from a client-provided buffer. * * Results: * Pointer to allocated memory * * Side effects: * None. * *----------------------------------------------------------------------------- */ void * VixMsg_MallocClientData(size_t size) // IN { return malloc(size); } // VixMsg_MallocClientData /* *----------------------------------------------------------------------------- * * VixMsg_ReallocClientData -- * * Reallocates the memory needed to copy from a client-provided buffer. * * Results: * Pointer to allocated memory * * Side effects: * Frees memory pointed to by ptr. * *----------------------------------------------------------------------------- */ void * VixMsg_ReallocClientData(void *ptr, // IN size_t size) // IN { return realloc(ptr, size); } // VixMsg_ReallocClientData /* *----------------------------------------------------------------------------- * * VixMsg_StrdupClientData -- * * Allocates memory and copies client-provided string. * * Results: * Pointer to allocated string * * Side effects: * None. * *----------------------------------------------------------------------------- */ char * VixMsg_StrdupClientData(const char *s, // IN Bool *allocateFailed) // OUT { char* newString = NULL; ASSERT(allocateFailed); if (NULL == allocateFailed) { goto abort; } *allocateFailed = FALSE; if (NULL != s) { #if defined(_WIN32) newString = _strdup(s); #else newString = strdup(s); #endif if (NULL == newString) { *allocateFailed = TRUE; } } abort: return newString; } // VixMsg_StrdupClientData /* *----------------------------------------------------------------------------- * * __VMAutomationValidateString -- * * Verifies that string at specified address is NUL terminated within * specified number of bytes, and is valid UTF-8. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static VixError __VMAutomationValidateString(const char *caller, // IN unsigned int line, // IN const char *buffer, // IN size_t available) // IN { size_t stringLength; /* * NUL terminated string needs at least one byte - NUL one. */ if (available < 1) { Log("%s(%u): Message body too short to contain string.\n", caller, line); return VIX_E_INVALID_MESSAGE_BODY; } /* * Reject message if there is no NUL before request end. There must * be one... */ stringLength = Str_Strlen(buffer, available); if (stringLength >= available) { Log("%s(%u): Variable string is not NUL terminated " "before message end.\n", caller, line); return VIX_E_INVALID_MESSAGE_BODY; } /* * If string is shorter than expected, complain. Maybe it is too strict, * but clients seems to not send malformed messages, so keep doing this. */ if (stringLength + 1 != available) { Log("%s(%u): Retrieved fixed string \"%s\" with " "trailing garbage.\n", caller, line, buffer); return VIX_E_INVALID_MESSAGE_BODY; } /* * If string is not UTF-8, reject it. We do not want to pass non-UTF-8 * strings through vmx bowels - they could hit some ASSERT somewhere... */ if (!Unicode_IsBufferValid(buffer, stringLength, STRING_ENCODING_UTF8)) { Log("%s(%u): Variable string is not an UTF8 string.\n", caller, line); return VIX_E_INVALID_UTF8_STRING; } return VIX_OK; } /* *----------------------------------------------------------------------------- * * __VMAutomationValidateStringInBuffer -- * * Verifies that string at specified address is NUL terminated within * specified number of bytes, and is valid UTF-8. * String does not have to occupy the entire buffer. * * Results: * VixError. VIX_OK on success. * Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static VixError __VMAutomationValidateStringInBuffer(const char *caller, // IN unsigned int line, // IN const char *buffer, // IN size_t available, // IN size_t *strLen) // IN { size_t stringLength; /* * NUL terminated string needs at least one byte - NUL one. */ if (available < 1) { Log("%s(%u): Message body too short to contain string.\n", caller, line); return VIX_E_INVALID_MESSAGE_BODY; } /* * Reject message if there is no NUL before request end. There must * be one... */ stringLength = Str_Strlen(buffer, available); *strLen = stringLength; if (stringLength >= available) { Log("%s(%u): Variable string is not NUL terminated " "before message end.\n", caller, line); return VIX_E_INVALID_MESSAGE_BODY; } /* * If string is not UTF-8, reject it. We do not want to pass non-UTF-8 * strings through vmx bowels - they could hit some ASSERT somewhere... */ if (!Unicode_IsBufferValid(buffer, stringLength, STRING_ENCODING_UTF8)) { Log("%s(%u): Variable string is not an UTF8 string.\n", caller, line); return VIX_E_INVALID_UTF8_STRING; } return VIX_OK; } /* *----------------------------------------------------------------------------- * * __VMAutomationMsgParserInitRequest -- * VMAutomationMsgParserInitRequest -- * * Initializes request parser, and performs basic message validation * not performed elsewhere. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError __VMAutomationMsgParserInitRequest(const char *caller, // IN unsigned int line, // IN VMAutomationMsgParser *state, // OUT (opt) const VixCommandRequestHeader *msg, // IN size_t fixedLength) // IN { size_t miscDataLength = 0; /* * If the VM is encrypted, there is additional data factored into * the total message size that needs to be accounted for. */ if (VIX_REQUESTMSG_INCLUDES_AUTH_DATA_V1 & msg->requestFlags) { miscDataLength = sizeof(VixMsgAuthDataV1); } else { miscDataLength = 0; } return VMAutomationMsgParserInit(caller, line, state, &msg->commonHeader, sizeof *msg, fixedLength, miscDataLength, "request"); } /* *----------------------------------------------------------------------------- * * __VMAutomationMsgParserInitResponse -- * VMAutomationMsgParserInitResponse -- * * Initializes response parser, and performs basic message validation * not performed elsewhere. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError __VMAutomationMsgParserInitResponse(const char *caller, // IN unsigned int line, // IN VMAutomationMsgParser *state, // OUT (opt) const VixCommandResponseHeader *msg, // IN size_t fixedLength) // IN { return VMAutomationMsgParserInit(caller, line, state, &msg->commonHeader, sizeof *msg, fixedLength, 0, "response"); } /* *----------------------------------------------------------------------------- * * VMAutomationMsgParserInit -- * * Initializes message parser, and performs basic message validation * not performed elsewhere. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None * *----------------------------------------------------------------------------- */ static VixError VMAutomationMsgParserInit(const char *caller, // IN unsigned int line, // IN VMAutomationMsgParser *state, // OUT (opt) const VixMsgHeader *msg, // IN size_t headerLength, // IN size_t fixedLength, // IN size_t miscDataLength, // IN const char *packetType) // IN { uint32 headerAndBodyLength; // use int64 to prevent overflow int64 computedTotalLength = (int64)msg->headerLength + (int64)msg->bodyLength + (int64)msg->credentialLength + (int64)miscDataLength; int64 extBodySize = (int64)msg->headerLength + (int64)msg->bodyLength - (int64)fixedLength; if (computedTotalLength != (int64)msg->totalMessageLength) { Log("%s:%d, header information mismatch.\n", __FILE__, __LINE__); return VIX_E_INVALID_MESSAGE_HEADER; } if (extBodySize < 0) { Log("%s:%d, %s too short.\n", __FILE__, __LINE__, packetType); return VIX_E_INVALID_MESSAGE_HEADER; } /* * Protocol allows for headerLength expansion, but predefined structures * do not anticipate that even a bit. So give up if header length is * incompatible with our structures. */ if (msg->headerLength != headerLength) { Log("%s(%u): %s header length %u is not supported " "(%"FMTSZ"u is required).\n", caller, line, packetType, msg->headerLength, headerLength); return VIX_E_INVALID_MESSAGE_HEADER; } /* * Message looks reasonable. Skip over fixed part. */ headerAndBodyLength = msg->headerLength + msg->bodyLength; if (state) { state->currentPtr = (const char *)msg + fixedLength; state->endPtr = (const char *)msg + headerAndBodyLength; } return VIX_OK; } /* *----------------------------------------------------------------------------- * * VMAutomation_VerifyRequestLength -- * * Ensures that request contains at least fixedLength bytes in * header and body. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VMAutomation_VerifyRequestLength(const VixCommandRequestHeader *request, // IN size_t fixedLength) // IN { return VMAutomationMsgParserInitRequest(NULL, request, fixedLength); } /* *----------------------------------------------------------------------------- * * VMAutomationMsgParserGetRemainingData -- * * Fetches all data remaining in the request. * * Results: * Pointer to the data. * * Side effects: * None. * *----------------------------------------------------------------------------- */ const void * VMAutomationMsgParserGetRemainingData(VMAutomationMsgParser *state, // IN/OUT size_t *length) // OUT { const void *data; *length = state->endPtr - state->currentPtr; data = state->currentPtr; state->currentPtr = state->endPtr; return data; } /* *----------------------------------------------------------------------------- * * VMAutomationMsgParserGetData -- * __VMAutomationMsgParserGetData -- * * Fetches specified number of bytes. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError __VMAutomationMsgParserGetData(const char *caller, // IN unsigned int line, // IN VMAutomationMsgParser *state, // IN/OUT size_t length, // IN const char **result) // OUT (opt) { size_t available; available = state->endPtr - state->currentPtr; /* If message is too short, return an error. */ if (available < length) { Log("%s(%u): Message has only %"FMTSZ"u bytes available when " "looking for %"FMTSZ"u bytes od data.\n", caller, line, available, length); return VIX_E_INVALID_MESSAGE_BODY; } if (result) { *result = state->currentPtr; } state->currentPtr += length; return VIX_OK; } /* *----------------------------------------------------------------------------- * * VMAutomationMsgParserGetOptionalString -- * __VMAutomationMsgParserGetOptionalString -- * * Fetches string of specified length from the request. Length includes * terminating NUL byte, which must be present. Length of zero results * in NULL being returned. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError __VMAutomationMsgParserGetOptionalString(const char *caller, // IN unsigned int line, // IN VMAutomationMsgParser *state, // IN/OUT size_t length, // IN const char **result) // OUT { if (length) { VixError err; const char *string; err = __VMAutomationMsgParserGetData(caller, line, state, length, &string); if (VIX_OK != err) { return err; } err = __VMAutomationValidateString(caller, line, string, length); if (VIX_OK != err) { return err; } *result = string; } else { *result = NULL; } return VIX_OK; } /* *----------------------------------------------------------------------------- * * VMAutomationMsgParserGetOptionalStrings -- * __VMAutomationMsgParserGetOptionalStrings -- * * Fetches an array of strings from the request. Length includes the * terminating NUL byte of each string. * * Results: * VixError. VIX_OK on success. * Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError __VMAutomationMsgParserGetOptionalStrings(const char *caller, // IN unsigned int line, // IN VMAutomationMsgParser *state, // IN/OUT uint32 count, // IN size_t length, // IN const char **result) // OUT { VixError err = VIX_OK; const char *buffer; const char *theResult; int i; size_t strLen; if (0 == count) { *result = NULL; goto abort; } err = __VMAutomationMsgParserGetData(caller, line, state, length, &buffer); if (VIX_OK != err) { return err; } theResult = buffer; for (i = 0; i < count; ++i) { err = __VMAutomationValidateStringInBuffer(caller, line, buffer, length, &strLen); if (VIX_OK != err) { return err; } ASSERT(strLen < length); buffer += (strLen + 1); length -= (strLen + 1); } /* * If string is shorter than expected, complain. Maybe it is too strict, * but clients seems to not send malformed messages, so keep doing this. */ if (length != 0) { Log("%s(%u): Retrieved an array of string with trailing garbage.\n", caller, line); return VIX_E_INVALID_MESSAGE_BODY; } *result = theResult; abort: return err; } /* *----------------------------------------------------------------------------- * * VMAutomationMsgParserGetString -- * __VMAutomationMsgParserGetString -- * * Fetches string of specified length from the request. Length of * string is specified in number of usable characters: function consumes * length + 1 bytes from request, and first length bytes must be non-NUL, * while length+1st byte must be NUL. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError __VMAutomationMsgParserGetString(const char *caller, // IN unsigned int line, // IN VMAutomationMsgParser *state, // IN/OUT size_t length, // IN const char **result) // OUT { VixError err; const char *string; length++; if (!length) { Log("%s(%u): String is too long.\n", caller, line); return VIX_E_INVALID_ARG; } err = __VMAutomationMsgParserGetData(caller, line, state, length, &string); if (VIX_OK != err) { return err; } err = __VMAutomationValidateString(caller, line, string, length); if (VIX_OK != err) { return err; } *result = string; return VIX_OK; } /* *----------------------------------------------------------------------------- * * VMAutomationMsgParserGetPropertyList -- * __VMAutomationMsgParserGetPropertyList -- * * Fetches specified number of bytes. * * Results: * VixError. VIX_OK on success. Some other VIX_* code if message is malformed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError __VMAutomationMsgParserGetPropertyList(const char *caller, // IN unsigned int line, // IN VMAutomationMsgParser *state, // IN/OUT size_t length, // IN VixPropertyListImpl *propList) // IN/OUT { VixError err; err = VIX_OK; if (length) { const char *data; err = __VMAutomationMsgParserGetData(caller, line, state, length, &data); if (VIX_OK == err) { err = VixPropertyList_Deserialize(propList, data, length, VIX_PROPERTY_LIST_BAD_ENCODING_ERROR); } } return err; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/foundryMsg/foundryPropertyListCommon.c000066400000000000000000001536101321503522500306130ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * foundryPropertyListCommon.c -- * * Some utility functions for manipulating property lists. Property * lists are now used in both the client and the VMX. The VMX uses them * as part of the socket protocol with the client. As a result, these * functions have been factored out into the stand-alone message library * so it can be used by the VMX tree without also linking in the * entire foundry client-side library. */ #include "vmware.h" #include "util.h" #include "str.h" #include "unicode.h" #include "vixCommands.h" #include "vixOpenSource.h" /* * The length of the 'size' field is 4 bytes -- avoid the confusion * of size_t on 32 vs 64 bit platforms. */ #define PROPERTY_LENGTH_SIZE 4 /* * Lets not trust sizeof() */ #define PROPERTY_SIZE_INT32 4 #define PROPERTY_SIZE_INT64 8 #define PROPERTY_SIZE_BOOL 1 // The size may be different on different machines. // To be safe, we always use 8 bytes. #define PROPERTY_SIZE_POINTER 8 static VixError VixPropertyListDeserializeImpl(VixPropertyListImpl *propList, const char *buffer, size_t bufferSize, Bool clobber, VixPropertyListBadEncodingAction action); /* *----------------------------------------------------------------------------- * * VixPropertyList_Initialize -- * * Initialize a list to be empty. This is an internal function * that is used both when we allocate a property list that wil be passed * to the client as a handle, and when we allocate an internal property * list that was not allocated as a handle. * * Results: * None. * * Side effects: * *----------------------------------------------------------------------------- */ void VixPropertyList_Initialize(VixPropertyListImpl *propList) // IN { ASSERT(propList); propList->properties = NULL; } // VixPropertyList_Initialize /* *----------------------------------------------------------------------------- * * VixPropertyList_RemoveAllWithoutHandles -- * * Delete all properties in a list. This is an internal procedure * that takes a VixPropertyListImpl as a parameter. * * Results: * None * * Side effects: * The property list is empty. * *----------------------------------------------------------------------------- */ void VixPropertyList_RemoveAllWithoutHandles(VixPropertyListImpl *propList) // IN { VixPropertyValue *property; if (NULL == propList) { return; } while (NULL != propList->properties) { property = propList->properties; propList->properties = property->next; if (VIX_PROPERTYTYPE_STRING == property->type) { if (property->isSensitive) { Util_ZeroString(property->value.strValue); } free(property->value.strValue); } else if (VIX_PROPERTYTYPE_BLOB == property->type) { if (property->isSensitive) { Util_Zero(property->value.blobValue.blobContents, property->value.blobValue.blobSize); } free(property->value.blobValue.blobContents); } free(property); } } // VixPropertyList_RemoveAllWithoutHandles /* *----------------------------------------------------------------------------- * * VixPropertyList_MarkAllSensitive -- * * Mark all properties in a list sensitive. * * Results: * As above * * Side effects: * None * *----------------------------------------------------------------------------- */ void VixPropertyList_MarkAllSensitive(VixPropertyListImpl *propList) // IN/OUT: { if (NULL != propList) { VixPropertyValue *property = propList->properties; while (NULL != property) { property->isSensitive = TRUE; property = property->next; } } } // VixPropertyList_MarkAllSensitive /* *----------------------------------------------------------------------------- * * VixPropertyList_Serialize -- * * Serialize a property list to a buffer. The buffer is allocated by * this routine to be of the required size and should be freed by caller. * * This function should be modified to deal with the case of * properties of type VIX_PROPERTYTYPE_HANDLE. * * * Results: * VixError. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixPropertyList_Serialize(VixPropertyListImpl *propList, // IN: Bool dirtyOnly, // IN: size_t *resultSize, // OUT: char **resultBuffer) // OUT: { VixError err = VIX_OK; VixPropertyValue *property = NULL; char *serializeBuffer = NULL; int valueLength; size_t headerSize; size_t propertyIDSize; size_t propertyTypeSize; size_t propertyValueLengthSize; size_t bufferSize = 0; size_t pos = 0; ASSERT_ON_COMPILE(PROPERTY_LENGTH_SIZE == sizeof valueLength); if ((NULL == propList) || (NULL == resultSize) || (NULL == resultBuffer)) { err = VIX_E_INVALID_ARG; goto abort; } propertyIDSize = sizeof(property->propertyID); propertyTypeSize = sizeof(property->type); propertyValueLengthSize = PROPERTY_LENGTH_SIZE; headerSize = propertyIDSize + propertyTypeSize + propertyValueLengthSize; /* * Walk the property list to determine size of the needed buffer */ property = propList->properties; while (NULL != property) { /* * If only the dirty properties need to be serialized * then skip the unchanged ones. */ if (dirtyOnly && (!property->isDirty)) { property = property->next; continue; } bufferSize += headerSize; switch (property->type) { //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_INTEGER: bufferSize += PROPERTY_SIZE_INT32; break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_STRING: if (property->value.strValue) { valueLength = strlen(property->value.strValue) + 1; /* * The deserialization code rejects all non-UTF-8 strings. * There should not be any non-UTF-8 strings passing * through our code since we should have either converted * non-UTF-8 strings from system APIs to UTF-8, or validated * that any client-provided strings were UTF-8. But this * if we've missed something, this should hopefully catch the * offending code close to the act. */ if (!Unicode_IsBufferValid(property->value.strValue, valueLength, STRING_ENCODING_UTF8)) { Log("%s: attempted to send a non-UTF-8 string for " "property %d.\n", __FUNCTION__, property->propertyID); ASSERT(0); err = VIX_E_INVALID_UTF8_STRING; } bufferSize += valueLength; } else { err = VIX_E_INVALID_ARG; goto abort; } break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_BOOL: bufferSize += PROPERTY_SIZE_BOOL; break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_INT64: bufferSize += PROPERTY_SIZE_INT64; break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_BLOB: bufferSize += property->value.blobValue.blobSize; break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_POINTER: /* * We should not serialize any pointer. * Catch such programming errors. */ err = VIX_E_INVALID_ARG; Log("%s:%d, pointer properties cannot be serialized.\n", __FUNCTION__, __LINE__); goto abort; //////////////////////////////////////////////////////// default: err = VIX_E_UNRECOGNIZED_PROPERTY; goto abort; } property = property->next; } *resultBuffer = (char*) VixMsg_MallocClientData(bufferSize); if (NULL == *resultBuffer) { err = VIX_E_OUT_OF_MEMORY; goto abort; } serializeBuffer = *resultBuffer; pos = 0; property = propList->properties; /* * Write out the properties to the buffer in the following format: * PropertyID | PropertyType | DataLength | Data */ while (NULL != property) { /* * If only the dirty properties need to be serialized * then skip the unchanged ones. */ if (dirtyOnly && (!property->isDirty)) { property = property->next; continue; } memcpy(&(serializeBuffer[pos]), &(property->propertyID), propertyIDSize); pos += propertyIDSize; memcpy(&(serializeBuffer[pos]), &(property->type), propertyTypeSize); pos += propertyTypeSize; switch (property->type) { //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_INTEGER: valueLength = PROPERTY_SIZE_INT32; memcpy(&(serializeBuffer[pos]), &valueLength, propertyValueLengthSize); pos += propertyValueLengthSize; memcpy(&(serializeBuffer[pos]), &(property->value.intValue), valueLength); break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_STRING: valueLength = (int) strlen(property->value.strValue) + 1; memcpy(&(serializeBuffer[pos]), &valueLength, propertyValueLengthSize); pos += propertyValueLengthSize; Str_Strcpy(&(serializeBuffer[pos]), property->value.strValue, valueLength); break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_BOOL: valueLength = PROPERTY_SIZE_BOOL; memcpy(&(serializeBuffer[pos]), &valueLength, propertyValueLengthSize); pos += propertyValueLengthSize; memcpy(&(serializeBuffer[pos]), &(property->value.boolValue), valueLength); break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_INT64: valueLength = PROPERTY_SIZE_INT64; memcpy(&(serializeBuffer[pos]), &valueLength, propertyValueLengthSize); pos += propertyValueLengthSize; memcpy(&(serializeBuffer[pos]), &(property->value.int64Value), valueLength); break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_BLOB: if (property->value.blobValue.blobContents) { valueLength = property->value.blobValue.blobSize; memcpy(&(serializeBuffer[pos]), &valueLength, propertyValueLengthSize); pos += propertyValueLengthSize; memcpy(&(serializeBuffer[pos]), property->value.blobValue.blobContents, valueLength); } else { err = VIX_E_INVALID_ARG; goto abort; } break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_POINTER: NOT_IMPLEMENTED(); //////////////////////////////////////////////////////// default: err = VIX_E_UNRECOGNIZED_PROPERTY; goto abort; } pos += valueLength; property = property->next; } ASSERT(pos == bufferSize); *resultSize = bufferSize; abort: if (VIX_OK != err) { free(serializeBuffer); if (NULL != resultBuffer) { *resultBuffer = NULL; } if (NULL != resultSize) { *resultSize = 0; } } return err; } // FoundryPropertList_Serialize /* *----------------------------------------------------------------------------- * * VixPropertyList_Deserialize -- * * Deserialize a property list from a buffer. Repeated properties * are clobbered. * * Results: * VixError. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixPropertyList_Deserialize(VixPropertyListImpl *propList, // IN const char *buffer, // IN size_t bufferSize, // IN VixPropertyListBadEncodingAction action) // IN { return VixPropertyListDeserializeImpl(propList, buffer, bufferSize, TRUE, // clobber action); } // VixPropertyList_Deserialize /* *----------------------------------------------------------------------------- * * VixPropertyList_DeserializeNoClobber -- * * Deserialize a property list from a buffer. Repeated properties * are preserved. * * Results: * VixError. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixPropertyList_DeserializeNoClobber(VixPropertyListImpl *propList, // IN const char *buffer, // IN size_t bufferSize, // IN VixPropertyListBadEncodingAction action) // IN { return VixPropertyListDeserializeImpl(propList, buffer, bufferSize, FALSE, // clobber action); } // VixPropertyList_DeserializeNoClobber /* *----------------------------------------------------------------------------- * * VixPropertyListDeserializeImpl -- * * Deserialize a property list from a buffer. * * This function should be modified to deal with the case of * properties of type VIX_PROPERTYTYPE_HANDLE. * * Results: * VixError. * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError VixPropertyListDeserializeImpl(VixPropertyListImpl *propList, // IN const char *buffer, // IN size_t bufferSize, // IN Bool clobber, // IN VixPropertyListBadEncodingAction action) // IN { VixError err = VIX_OK; VixPropertyValue *property = NULL; size_t pos = 0; char *strPtr; int *intPtr; Bool *boolPtr; int64 *int64Ptr; unsigned char* blobPtr; int *propertyIDPtr; int *lengthPtr; size_t propertyIDSize; size_t propertyTypeSize; size_t propertyValueLengthSize; size_t headerSize; VixPropertyType *propertyTypePtr; Bool allocateFailed; Bool needToEscape; if ((NULL == propList) || (NULL == buffer)) { err = VIX_E_INVALID_ARG; goto abort; } propertyIDSize = sizeof(*propertyIDPtr); propertyTypeSize = sizeof(*propertyTypePtr); propertyValueLengthSize = PROPERTY_LENGTH_SIZE; headerSize = propertyIDSize + propertyTypeSize + propertyValueLengthSize; /* * Read properties from the buffer and add them to the property list. */ while ((pos+headerSize) < bufferSize) { propertyIDPtr = (int*) &(buffer[pos]); pos += propertyIDSize; propertyTypePtr = (VixPropertyType*) &(buffer[pos]); pos += propertyTypeSize; lengthPtr = (int*) &(buffer[pos]); pos += propertyValueLengthSize; /* * Do not allow lengths of 0 or fewer bytes. Those do not make sense, * unless you can pass a NULL blob, which Serialize() does not allow. * Also, make sure the value is contained within the bounds of the buffer. */ if ((*lengthPtr < 1) || ((*lengthPtr + pos) > bufferSize)) { err = VIX_E_INVALID_SERIALIZED_DATA; goto abort; } /* * Create the property if missing */ if (clobber) { err = VixPropertyList_FindProperty(propList, *propertyIDPtr, *propertyTypePtr, 0, // index TRUE, //createIfMissing &property); } else { err = VixPropertyListAppendProperty(propList, *propertyIDPtr, *propertyTypePtr, &property); } if (VIX_OK != err) { goto abort; } /* * Initialize the property to the received value */ switch (*propertyTypePtr) { //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_INTEGER: if (PROPERTY_SIZE_INT32 != *lengthPtr) { err = VIX_E_INVALID_SERIALIZED_DATA; goto abort; } intPtr = (int*) &(buffer[pos]); property->value.intValue = *intPtr; break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_STRING: strPtr = (char*) &(buffer[pos]); /* * The length that Serialize() generates includes the terminating * NUL character. */ if (strPtr[*lengthPtr - 1] != '\0') { err = VIX_E_INVALID_SERIALIZED_DATA; goto abort; } needToEscape = FALSE; /* * Make sure the string is valid UTF-8 before copying it. We * expect all strings stored in the process to be UTF-8. */ if (!Unicode_IsBufferValid(strPtr, *lengthPtr, STRING_ENCODING_UTF8)) { Log("%s: non-UTF-8 string received for property %d.\n", __FUNCTION__, *propertyIDPtr); switch (action) { case VIX_PROPERTY_LIST_BAD_ENCODING_ERROR: err = VIX_E_INVALID_UTF8_STRING; goto abort; case VIX_PROPERTY_LIST_BAD_ENCODING_ESCAPE: needToEscape = TRUE; } } free(property->value.strValue); if (needToEscape) { property->value.strValue = Unicode_EscapeBuffer(strPtr, *lengthPtr, STRING_ENCODING_UTF8); if (NULL == property->value.strValue) { err = VIX_E_OUT_OF_MEMORY; goto abort; } } else { property->value.strValue = VixMsg_StrdupClientData(strPtr, &allocateFailed); if (allocateFailed) { err = VIX_E_OUT_OF_MEMORY; goto abort; } } break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_BOOL: if (PROPERTY_SIZE_BOOL != *lengthPtr) { err = VIX_E_INVALID_SERIALIZED_DATA; goto abort; } boolPtr = (Bool*) &(buffer[pos]); property->value.boolValue = *boolPtr; break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_INT64: if (PROPERTY_SIZE_INT64 != *lengthPtr) { err = VIX_E_INVALID_SERIALIZED_DATA; goto abort; } int64Ptr = (int64*) &(buffer[pos]); property->value.int64Value = *int64Ptr; break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_BLOB: blobPtr = (unsigned char*) &(buffer[pos]); property->value.blobValue.blobSize = *lengthPtr; /* * Use regular malloc() when allocating amounts specified by another * process. Admittedly we've already bounds checked it, but this is * pretty easy to handle. */ free(property->value.blobValue.blobContents); property->value.blobValue.blobContents = VixMsg_MallocClientData(*lengthPtr); if (NULL == property->value.blobValue.blobContents) { err = VIX_E_OUT_OF_MEMORY; goto abort; } memcpy(property->value.blobValue.blobContents, blobPtr, *lengthPtr); break; //////////////////////////////////////////////////////// case VIX_PROPERTYTYPE_POINTER: /* * Deserialize an pointer property should not be allowed. * An evil peer could send us such data. */ err = VIX_E_INVALID_SERIALIZED_DATA; Log("%s:%d, pointer properties cannot be serialized.\n", __FUNCTION__, __LINE__); goto abort; //////////////////////////////////////////////////////// default: err = VIX_E_UNRECOGNIZED_PROPERTY; goto abort; } pos += *lengthPtr; } abort: if ((VIX_OK != err) && (NULL != propList)) { VixPropertyList_RemoveAllWithoutHandles(propList); } return err; } // VixPropertyList_Deserialize /* *----------------------------------------------------------------------------- * * VixPropertyList_FindProperty -- * * This is an internal routine that finds a property in the list. * * If the property is found, then this also checks that the property * has an expected type; if the types mismatch thenit returns an error. * * It optionally creates a property if it is missing. * * Results: * VixError * * Side effects: * *----------------------------------------------------------------------------- */ VixError VixPropertyList_FindProperty(VixPropertyListImpl *propList, // IN int propertyID, // IN VixPropertyType type, // IN int index, // IN Bool createIfMissing, // IN VixPropertyValue **resultEntry) // OUT { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == resultEntry) { err = VIX_E_INVALID_ARG; goto abort; } *resultEntry = NULL; property = propList->properties; while (NULL != property) { if (propertyID == property->propertyID) { if (index > 0) { index--; } else { if ((VIX_PROPERTYTYPE_ANY != type) && (type != property->type)) { err = VIX_E_TYPE_MISMATCH; } *resultEntry = property; goto abort; } } // (propertyID == property->propertyID) property = property->next; } // while (NULL != property) /* * If we get to here, then the property doesn't exist. * Either create it or return an error. */ if (!createIfMissing) { err = VIX_E_UNRECOGNIZED_PROPERTY; goto abort; } err = VixPropertyListAppendProperty(propList, propertyID, type, resultEntry); abort: return err; } /* *----------------------------------------------------------------------------- * * VixPropertyListAppendProperty -- * * This is an internal routine that creates a property for the * append routines. * * Results: * VixError * * Side effects: * *----------------------------------------------------------------------------- */ VixError VixPropertyListAppendProperty(VixPropertyListImpl *propList, // IN int propertyID, // IN VixPropertyType type, // IN VixPropertyValue **resultEntry) // OUT { VixError err = VIX_OK; VixPropertyValue *lastProperty; VixPropertyValue *property = NULL; if (NULL == resultEntry) { err = VIX_E_INVALID_ARG; goto abort; } *resultEntry = NULL; property = (VixPropertyValue *) Util_SafeCalloc(1, sizeof(VixPropertyValue)); property->type = type; property->propertyID = propertyID; property->isDirty = TRUE; property->isSensitive = FALSE; /* * We only have to initialize the values that we release, so * we don't try to release an invalid reference. */ if (VIX_PROPERTYTYPE_STRING == property->type) { property->value.strValue = NULL; } else if (VIX_PROPERTYTYPE_BLOB == property->type) { property->value.blobValue.blobContents = NULL; } else if (VIX_PROPERTYTYPE_HANDLE == property->type) { property->value.handleValue = VIX_INVALID_HANDLE; } /* * Put the new property on the end of the list. Some property lists, * like a list of VMs or snapshots, assume the order is meaningful and * so it should be preserved. */ lastProperty = propList->properties; while ((NULL != lastProperty) && (NULL != lastProperty->next)) { lastProperty = lastProperty->next; } if (NULL == lastProperty) { propList->properties = property; } else { lastProperty->next = property; } property->next = NULL; *resultEntry = property; abort: return err; } // VixPropertyListAppendProperty /* *----------------------------------------------------------------------------- * * VixPropertyList_GetString -- * * Return a copy of a string property value. The value is identified * by the integer property ID. * * This fails if the value is not present, or if it is a different * type, or if the caller did not pass a valid out parameter to * receive the value. * * Results: * VixError. VIX_OK if the property was found. * VIX_E_UNRECOGNIZED_PROPERTY if the property was not found. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_GetString(VixPropertyListImpl *propList, // IN int propertyID, // IN int index, // IN char **resultValue) // OUT { VixError err = VIX_OK; VixPropertyValue *property = NULL; if ((NULL == propList) || (NULL == resultValue)) { err = VIX_E_INVALID_ARG; goto abort; } *resultValue = NULL; err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_STRING, index, FALSE, &property); if (VIX_OK != err) { goto abort; } if (NULL != property->value.strValue) { *resultValue = Util_SafeStrdup(property->value.strValue); } abort: return err; } // VixPropertyList_GetString /* *----------------------------------------------------------------------------- * * VixPropertyListSetStringImpl -- * * Saves a copy of a string property value. Sets sensitivity. * * Results: * As above * * Side effects: * None * *----------------------------------------------------------------------------- */ static void VixPropertyListSetStringImpl(VixPropertyValue *property, // IN: const char *value, // IN: Bool isSensitive) // IN: { if (NULL != property->value.strValue) { if (property->isSensitive) { Util_ZeroString(property->value.strValue); } free(property->value.strValue); property->value.strValue = NULL; } if (NULL != value) { property->value.strValue = Util_SafeStrdup(value); } property->isDirty = TRUE; property->isSensitive = isSensitive; } // VixPropertyListSetStringImpl /* *----------------------------------------------------------------------------- * * VixPropertyList_SetString -- * * Saves a copy of a string property value. The value is identified * by the integer property ID. * * Value names are unique within a single property list. * If a previous value with the same propertyID value already * existed in this property list, then it is replaced with the new * value. Otherwise, a new value is added. * * This fails if the value is present but has a different type. * * Results: * VixError * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_SetString(VixPropertyListImpl *propList, // IN: int propertyID, // IN: const char *value) // IN: { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == propList) { err = VIX_E_INVALID_ARG; goto abort; } /* * Find or create an entry for this property. */ err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_STRING, 0, TRUE, &property); if (VIX_OK == err) { VixPropertyListSetStringImpl(property, value, property->isSensitive); } abort: return err; } // VixPropertyList_SetString /* *----------------------------------------------------------------------------- * * VixPropertyList_SetStringSensitive -- * * Saves a copy of a string property value. The value is identified * by the integer property ID. Mark sensitive. * * Value names are unique within a single property list. * If a previous value with the same propertyID value already * existed in this property list, then it is replaced with the new * value. Otherwise, a new value is added. * * This fails if the value is present but has a different type. * * Results: * VixError * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_SetStringSensitive(VixPropertyListImpl *propList, // IN: int propertyID, // IN: const char *value) // IN: { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == propList) { err = VIX_E_INVALID_ARG; goto abort; } /* * Find or create an entry for this property. */ err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_STRING, 0, TRUE, &property); if (VIX_OK == err) { VixPropertyListSetStringImpl(property, value, TRUE); } abort: return err; } // VixPropertyList_SetString /* *----------------------------------------------------------------------------- * * VixPropertyList_GetInteger -- * * Return a copy of a integer property value. The value is identified * by the integer property ID. * * This fails if the value is not present, or if it is a different * type, or if the caller did not pass a valid out parameter to * receive the value. * * Results: * VixError. VIX_OK if the property was found. * VIX_E_UNRECOGNIZED_PROPERTY if the property was not found. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_GetInteger(VixPropertyListImpl *propList, // IN int propertyID, // IN int index, // IN int *resultValue) // OUT { VixError err = VIX_OK; VixPropertyValue *property = NULL; if ((NULL == resultValue) || (NULL == propList)) { err = VIX_E_INVALID_ARG; goto abort; } err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_INTEGER, index, FALSE, &property); if (VIX_OK != err) { goto abort; } *resultValue = property->value.intValue; abort: return err; } // VixPropertyList_GetInteger /* *----------------------------------------------------------------------------- * * VixPropertyList_SetInteger -- * * Saves a copy of a integer property value. The value is identified * by the integer property ID. * * Value names are unique within a single property list. * If a previous value with the same propertyID value already * existed in this property list, then it is replaced with the new * value. Otherwise, a new value is added. * * This fails if the value is present but has a different type. * * Results: * VixError. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_SetInteger(VixPropertyListImpl *propList, // IN int propertyID, // IN int value) // IN { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == propList) { err = VIX_E_INVALID_ARG; goto abort; } /* * Find or create an entry for this property. */ err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_INTEGER, 0, TRUE, &property); if (VIX_OK != err) { goto abort; } property->value.intValue = value; property->isDirty = TRUE; abort: return err; } // VixPropertyList_SetInteger /* *----------------------------------------------------------------------------- * * VixPropertyList_GetBool -- * * Return a copy of a boolean property value. The value is identified * by the integer property ID. * * This fails if the value is not present, or if it is a different * type, or if the caller did not pass a valid out parameter to * receive the value. * * Results: * VixError. VIX_OK if the property was found. * VIX_E_UNRECOGNIZED_PROPERTY if the property was not found. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_GetBool(VixPropertyListImpl *propList, // IN int propertyID, // IN int index, // IN Bool *resultValue) // OUT { VixError err = VIX_OK; VixPropertyValue *property = NULL; if ((NULL == resultValue) || (NULL == propList)) { err = VIX_E_INVALID_ARG; goto abort; } err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_BOOL, index, FALSE, &property); if (VIX_OK != err) { goto abort; } if (NULL == property) { goto abort; } *resultValue = property->value.boolValue; abort: return err; } // VixPropertyList_GetBool /* *----------------------------------------------------------------------------- * * VixPropertyList_SetBool -- * * Saves a copy of a Bool property value. The value is identified * by the integer property ID. * * Value names are unique within a single property list. * If a previous value with the same propertyID value already * existed in this property list, then it is replaced with the new * value. Otherwise, a new value is added. * * This fails if the value is present but has a different type. * * Results: * VixError. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_SetBool(VixPropertyListImpl *propList, // IN int propertyID, // IN Bool value) // IN { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == propList) { err = VIX_E_INVALID_ARG; goto abort; } /* * Find or create an entry for this property. */ err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_BOOL, 0, TRUE, &property); if (VIX_OK != err) { goto abort; } property->value.boolValue = value; property->isDirty = TRUE; abort: return err; } /* *----------------------------------------------------------------------------- * * VixPropertyList_GetInt64 -- * * Return a copy of a Int64 property value. The value is identified * by the integer property ID. * * This fails if the value is not present, or if it is a different * type, or if the caller did not pass a valid out parameter to * receive the value. * * Results: * VixError. VIX_OK if the property was found. * VIX_E_UNRECOGNIZED_PROPERTY if the property was not found. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_GetInt64(VixPropertyListImpl *propList, // IN int propertyID, // IN int index, // IN int64 *resultValue) // OUT { VixError err = VIX_OK; VixPropertyValue *property = NULL; if ((NULL == resultValue) || (NULL == propList)) { err = VIX_E_INVALID_ARG; goto abort; } err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_INT64, index, FALSE, &property); if (VIX_OK != err) { goto abort; } *resultValue = property->value.int64Value; abort: return err; } // VixPropertyList_GetInt64 /* *----------------------------------------------------------------------------- * * VixPropertyList_SetInt64 -- * * Saves a copy of a int64 property value. The value is identified * by the integer property ID. * * Value names are unique within a single property list. * If a previous value with the same propertyID value already * existed in this property list, then it is replaced with the new * value. Otherwise, a new value is added. * * This fails if the value is present but has a different type. * * Results: * VixError. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_SetInt64(VixPropertyListImpl *propList, // IN int propertyID, // IN int64 value) // IN { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == propList) { err = VIX_E_INVALID_ARG; goto abort; } /* * Find or create an entry for this property. */ err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_INT64, 0, TRUE, &property); if (VIX_OK != err) { goto abort; } property->value.int64Value = value; property->isDirty = TRUE; abort: return err; } // VixPropertyList_SetInt64 /* *----------------------------------------------------------------------------- * * VixPropertyList_GetBlob -- * * Return a copy of a Blob property value. The value is identified * by the integer property ID. * * This fails if the value is not present, or if it is a different * type, or if the caller did not pass a valid out parameter to * receive the value. * * Results: * VixError. VIX_OK if the property was found. * VIX_E_UNRECOGNIZED_PROPERTY if the property was not found. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_GetBlob(VixPropertyListImpl *propList, // IN int propertyID, // IN int index, // IN int *resultSize, // OUT unsigned char **resultValue) // OUT { VixError err = VIX_OK; VixPropertyValue *property = NULL; if ((NULL == propList) || (NULL == resultSize) || (NULL == resultValue)) { err = VIX_E_INVALID_ARG; goto abort; } *resultSize = 0; *resultValue = NULL; err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_BLOB, index, FALSE, &property); if (VIX_OK != err) { goto abort; } if ((property->value.blobValue.blobSize > 0) && (NULL != property->value.blobValue.blobContents)) { *resultSize = property->value.blobValue.blobSize; *resultValue = Util_SafeMalloc(property->value.blobValue.blobSize); memcpy(*resultValue, property->value.blobValue.blobContents, property->value.blobValue.blobSize); } abort: return err; } // VixPropertyList_GetBlob /* *----------------------------------------------------------------------------- * * VixPropertyListSetBlobImpl -- * * Saves a copy of a blob property value. Set sensitivity. * * Results: * As above. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void VixPropertyListSetBlobImpl(VixPropertyValue *property, // IN: int blobSize, // IN: const unsigned char *value, // IN: Bool isSensitive) // IN: { if (NULL != property->value.blobValue.blobContents) { if (property->isSensitive) { Util_Zero(property->value.blobValue.blobContents, property->value.blobValue.blobSize); } free(property->value.blobValue.blobContents); property->value.blobValue.blobContents = NULL; } property->value.blobValue.blobSize = blobSize; if ((NULL != value) && (blobSize > 0)) { property->value.blobValue.blobContents = Util_SafeMalloc(blobSize); memcpy(property->value.blobValue.blobContents, value, blobSize); } property->isDirty = TRUE; property->isSensitive = isSensitive; } // VixPropertyListSetBlobImpl /* *----------------------------------------------------------------------------- * * VixPropertyList_SetBlob -- * * Saves a copy of a blob property value. The value is identified * by the integer property ID. * * Value names are unique within a single property list. * If a previous value with the same propertyID value already * existed in this property list, then it is replaced with the new * value. Otherwise, a new value is added. * * This fails if the value is present but has a different type. * * Results: * VixError. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_SetBlob(VixPropertyListImpl *propList, // IN: int propertyID, // IN: int blobSize, // IN: const unsigned char *value) // IN: { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == propList) { err = VIX_E_INVALID_ARG; goto abort; } /* * Find or create an entry for this property. */ err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_BLOB, 0, TRUE, &property); if (VIX_OK == err) { VixPropertyListSetBlobImpl(property, blobSize, value, property->isSensitive); } abort: return err; } // VixPropertyList_SetBlob /* *----------------------------------------------------------------------------- * * VixPropertyList_SetBlobSensitive -- * * Saves a copy of a blob property value. The value is identified * by the integer property ID. Set sentivity. * * Value names are unique within a single property list. * If a previous value with the same propertyID value already * existed in this property list, then it is replaced with the new * value. Otherwise, a new value is added. * * This fails if the value is present but has a different type. * * Results: * VixError. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_SetBlobSensitive(VixPropertyListImpl *propList, // IN: int propertyID, // IN: int blobSize, // IN: const unsigned char *value) // IN: { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == propList) { err = VIX_E_INVALID_ARG; goto abort; } /* * Find or create an entry for this property. */ err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_BLOB, 0, TRUE, &property); if (VIX_OK == err) { VixPropertyListSetBlobImpl(property, blobSize, value, TRUE); } abort: return err; } // VixPropertyList_SetBlob /* *----------------------------------------------------------------------------- * * VixPropertyList_GetPtr -- * * Return a copy of a void* property value. The value is identified * by the integer property ID. * * This is a SHALLOW copy. It only copies the pointer, not what the * pointer references. * * This fails if the value is not present, or if it is a different * type, or if the caller did not pass a valid out parameter to * receive the value. * * Results: * VixError. VIX_OK if the property was found. * VIX_E_UNRECOGNIZED_PROPERTY if the property was not found. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_GetPtr(VixPropertyListImpl *propList, // IN int propertyID, // IN int index, // IN void **resultValue) // OUT { VixError err = VIX_OK; VixPropertyValue *property = NULL; if ((NULL == resultValue) || (NULL == propList)) { err = VIX_E_INVALID_ARG; goto abort; } err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_POINTER, index, FALSE, &property); if (VIX_OK != err) { goto abort; } *resultValue = property->value.ptrValue; abort: return err; } // VixPropertyList_GetPtr /* *----------------------------------------------------------------------------- * * VixPropertyList_SetPtr -- * * Saves a copy of a ptr property value. The value is identified * by the integer property ID. * * This is a SHALLOW copy. It only copies the pointer, not what the * pointer references. * * Value names are unique within a single property list. * If a previous value with the same propertyID value already * existed in this property list, then it is replaced with the new * value. Otherwise, a new value is added. * * This fails if the value is present but has a different type. * * Results: * VixError. * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError VixPropertyList_SetPtr(VixPropertyListImpl *propList, // IN int propertyID, // IN void *value) // IN { VixError err = VIX_OK; VixPropertyValue *property = NULL; if (NULL == propList) { err = VIX_E_INVALID_ARG; goto abort; } /* * Find or create an entry for this property. */ err = VixPropertyList_FindProperty(propList, propertyID, VIX_PROPERTYTYPE_POINTER, 0, TRUE, &property); if (VIX_OK != err) { goto abort; } property->value.ptrValue = value; property->isDirty = TRUE; abort: return err; } // VixPropertyList_SetPtr /* *----------------------------------------------------------------------------- * * VixPropertyList_PropertyExists -- * * * Results: * Bool * * Side effects: * *----------------------------------------------------------------------------- */ Bool VixPropertyList_PropertyExists(VixPropertyListImpl *propList, // IN int propertyID, // IN VixPropertyType type) // IN { VixError err = VIX_OK; VixPropertyValue *property = NULL; Bool foundIt = FALSE; err = VixPropertyList_FindProperty(propList, propertyID, type, 0, // index FALSE, // createIfMissing &property); if ((VIX_OK == err) && (NULL != property)) { foundIt = TRUE; } return foundIt; } // VixPropertyList_PropertyExists /* *----------------------------------------------------------------------------- * * VixPropertyList_NumItems -- * * Returns a count of the properties in the list. * * Results: * int - Number of properties in property list. * * Side effects: * None. * *----------------------------------------------------------------------------- */ int VixPropertyList_NumItems(VixPropertyListImpl *propList) // IN { VixPropertyValue *prop; int count = 0; if (propList == NULL) { return 0; } for (prop = propList->properties; prop != NULL; prop = prop->next) { ++count; } return count; } // VixPropertyList_NumItems /* *----------------------------------------------------------------------------- * * VixPropertyList_Empty -- * * Returns whether the property list has no properties. * * Results: * Bool - True iff property list has no properties. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool VixPropertyList_Empty(VixPropertyListImpl *propList) // IN { return (propList == NULL || propList->properties == NULL); } // VixPropertyList_Empty open-vm-tools-stable-10.2.0/open-vm-tools/lib/foundryMsg/vixTranslateErrOpenSource.c000066400000000000000000000237361321503522500305200ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * vixTranslateErrorOpenSource.c -- * * Routines which translate between various other error code systems * into foundry errors. * * This is the minimal functions needed to build the tools for open source. * Most of the error translation functions are in foundryTranslateError.c, * which is NOT being released as open source. We do not want to include * any unnecessary error functions, since those use lots of different * error code definitions, and that would drag in a lot of headers from * bora/lib/public. */ #include "vmware.h" #include "vixOpenSource.h" #include #include #ifdef _WIN32 #include "windowsu.h" #endif /* *----------------------------------------------------------------------------- * * Vix_TranslateGuestRegistryError -- * * Translate a guest windows registry error to a Foundry error. * * Results: * VixError * * Side effects: * None. * *----------------------------------------------------------------------------- */ VixError Vix_TranslateGuestRegistryError(int systemError) // IN { VixError err = VIX_E_FAIL; #ifdef _WIN32 char *msg; switch (systemError) { case ERROR_INVALID_PARAMETER: case ERROR_FILE_NOT_FOUND: err = VIX_E_REG_KEY_INVALID; break; case ERROR_ACCESS_DENIED: err = VIX_E_GUEST_USER_PERMISSIONS; break; case ERROR_CHILD_MUST_BE_VOLATILE: err = VIX_E_REG_KEY_PARENT_VOLATILE; break; default: return Vix_TranslateSystemError(systemError); } msg = Win32U_FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, systemError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), NULL); Log("Foundry operation failed with guest windows registry error: %s (%d), translated to %"FMT64"d\n", msg, systemError, err); free(msg); #endif return err; } // Vix_TranslateGuestRegistryError /* *----------------------------------------------------------------------------- * * Vix_TranslateSystemError -- * * Translate a System error to a Foundry error. * * Results: * VixError * * Side effects: * *----------------------------------------------------------------------------- */ VixError Vix_TranslateSystemError(int systemError) // IN { VixError err = VIX_E_FAIL; #ifdef _WIN32 char *msg; switch (systemError) { case ERROR_ACCESS_DENIED: err = VIX_E_FILE_ACCESS_ERROR; break; case ERROR_INVALID_NAME: err = VIX_E_FILE_NAME_INVALID; break; case ERROR_FILENAME_EXCED_RANGE: err = VIX_E_FILE_NAME_TOO_LONG; break; case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_BAD_PATHNAME: case ERROR_DIRECTORY: case ERROR_BUFFER_OVERFLOW: err = VIX_E_FILE_NOT_FOUND; break; case ERROR_DIR_NOT_EMPTY: err = VIX_E_DIRECTORY_NOT_EMPTY; break; case ERROR_TOO_MANY_OPEN_FILES: case ERROR_NO_MORE_FILES: case ERROR_WRITE_PROTECT: case ERROR_WRITE_FAULT: case ERROR_READ_FAULT: case ERROR_SHARING_VIOLATION: case ERROR_SEEK: case ERROR_CANNOT_MAKE: Log("%s: system error = %d\n", __FUNCTION__, systemError); err = VIX_E_FILE_ERROR; break; case ERROR_HANDLE_DISK_FULL: case ERROR_DISK_FULL: err = VIX_E_DISK_FULL; break; case ERROR_FILE_EXISTS: case ERROR_ALREADY_EXISTS: err = VIX_E_FILE_ALREADY_EXISTS; break; case ERROR_BUSY: case ERROR_PATH_BUSY: err = VIX_E_OBJECT_IS_BUSY; break; case ERROR_INVALID_PARAMETER: err = VIX_E_INVALID_ARG; break; case ERROR_NOT_SUPPORTED: err = VIX_E_NOT_SUPPORTED; break; case ERROR_NO_DATA: case ERROR_INVALID_DATA: err = VIX_E_NOT_FOUND; break; case ERROR_NOT_ENOUGH_MEMORY: err = VIX_E_OUT_OF_MEMORY; break; default: err = VIX_E_FAIL; } msg = Win32U_FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, systemError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), NULL); Log("Foundry operation failed with system error: %s (%d), translated to %"FMT64"d\n", msg, systemError, err); free(msg); #else // linux, other *nix err = Vix_TranslateErrno(systemError); #endif return err; } // Vix_TranslateSystemError /* *----------------------------------------------------------------------------- * * Vix_TranslateCOMError -- * * Translate a COM (Windows) error to a Foundry error. * * Results: * VixError. * * Side effects: * None. * *----------------------------------------------------------------------------- */ #ifdef _WIN32 VixError Vix_TranslateCOMError(HRESULT hrError) // IN { VixError err = VIX_E_FAIL; switch (hrError) { case E_ACCESSDENIED: err = VIX_E_FILE_ACCESS_ERROR; break; case STG_E_PATHNOTFOUND: case STG_E_FILENOTFOUND: err = VIX_E_FILE_NOT_FOUND; break; case STG_E_MEDIUMFULL: err = VIX_E_DISK_FULL; break; case STG_E_FILEALREADYEXISTS: err = VIX_E_FILE_ALREADY_EXISTS; break; case E_INVALIDARG: case E_POINTER: err = VIX_E_INVALID_ARG; break; case E_NOTIMPL: case E_NOINTERFACE: err = VIX_E_NOT_SUPPORTED; break; case E_OUTOFMEMORY: err = VIX_E_OUT_OF_MEMORY; break; case E_FAIL: default: err = VIX_E_FAIL; } return err; } // Vix_TranslateCOMError #endif /* *----------------------------------------------------------------------------- * * Vix_TranslateCryptoError -- * * Translate a Crypto error to a Foundry error. * * Results: * VixError * * Side effects: * *----------------------------------------------------------------------------- */ VixError Vix_TranslateCryptoError(CryptoError cryptoError) // IN { if (CRYPTO_ERROR_SUCCESS == cryptoError) { return VIX_OK; } else if (CRYPTO_ERROR_OPERATION_FAILED == cryptoError) { return VIX_E_GUEST_USER_PERMISSIONS; } else if (CRYPTO_ERROR_UNKNOWN_ALGORITHM == cryptoError) { return VIX_E_CRYPTO_UNKNOWN_ALGORITHM; } else if (CRYPTO_ERROR_BAD_BUFFER_SIZE == cryptoError) { return VIX_E_CRYPTO_BAD_BUFFER_SIZE; } else if (CRYPTO_ERROR_INVALID_OPERATION == cryptoError) { return VIX_E_CRYPTO_INVALID_OPERATION; } else if (CRYPTO_ERROR_NOMEM == cryptoError) { return VIX_E_OUT_OF_MEMORY; } else if (CRYPTO_ERROR_NEED_PASSWORD == cryptoError) { return VIX_E_CRYPTO_NEED_PASSWORD; } else if (CRYPTO_ERROR_BAD_PASSWORD == cryptoError) { return VIX_E_CRYPTO_BAD_PASSWORD; } else if (CRYPTO_ERROR_IO_ERROR == cryptoError) { Log("%s: crypto error = %d\n", __FUNCTION__, (int)cryptoError); return VIX_E_FILE_ERROR; } else if (CRYPTO_ERROR_UNKNOWN_ERROR == cryptoError) { return VIX_E_FAIL; } else if (CRYPTO_ERROR_NAME_NOT_FOUND == cryptoError) { return VIX_E_CRYPTO_NOT_IN_DICTIONARY; } else if (CRYPTO_ERROR_NO_CRYPTO == cryptoError) { return VIX_E_CRYPTO_NO_CRYPTO; } return VIX_E_FAIL; } /* *----------------------------------------------------------------------------- * * Vix_TranslateErrno -- * * Translate a Posix errno to a Foundry error. * * Results: * VixError * * Side effects: * None * *----------------------------------------------------------------------------- */ VixError Vix_TranslateErrno(int systemError) // IN { VixError err = VIX_E_FAIL; /* * Be careful while adding new error code translations. This function is * complied for both Windows and POSIX guests. Few errors i.e. ETIMEDOUT, * ENOBUFS are defined only for POSIX guests. When a new error code * translation is added, make sure you build a sandbox job and it is * successful. */ switch (systemError) { case EPERM: case EACCES: err = VIX_E_FILE_ACCESS_ERROR; break; case EAGAIN: case EBUSY: err = VIX_E_OBJECT_IS_BUSY; break; case EEXIST: err = VIX_E_FILE_ALREADY_EXISTS; break; case EFBIG: err = VIX_E_FILE_TOO_BIG; break; case ENOTEMPTY: err = VIX_E_DIRECTORY_NOT_EMPTY; break; case ENOTDIR: err = VIX_E_NOT_A_DIRECTORY; break; #ifndef _WIN32 case ETIMEDOUT: case ENOBUFS: #endif case EIO: case EMFILE: case ENFILE: case EMLINK: case EROFS: Log("%s: errno = %d\n", __FUNCTION__, systemError); err = VIX_E_FILE_ERROR; break; case ENODEV: case ENOENT: err = VIX_E_FILE_NOT_FOUND; break; case ENOSPC: err = VIX_E_DISK_FULL; break; case EISDIR: err = VIX_E_NOT_A_FILE; break; case ESRCH: err = VIX_E_NO_SUCH_PROCESS; break; case ENAMETOOLONG: err = VIX_E_FILE_NAME_TOO_LONG; break; #ifndef _WIN32 case EMSGSIZE: #endif case EINVAL: err = VIX_E_INVALID_ARG; break; #ifndef _WIN32 case ELOOP: #endif case ENOMEM: err = VIX_E_OUT_OF_MEMORY; break; default: err = VIX_E_FAIL; } Log("Foundry operation failed with system error: %s (%d), translated to %"FMT64"d\n", strerror(systemError), systemError, err); return err; } // Vix_TranslateErrno open-vm-tools-stable-10.2.0/open-vm-tools/lib/glibUtils/000077500000000000000000000000001321503522500230025ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/glibUtils/Makefile.am000066400000000000000000000021751321503522500250430ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2011-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libGlibUtils.la libGlibUtils_la_CPPFLAGS = libGlibUtils_la_CPPFLAGS += @GLIB2_CPPFLAGS@ libGlibUtils_la_SOURCES = libGlibUtils_la_SOURCES += fileLogger.c libGlibUtils_la_SOURCES += stdLogger.c libGlibUtils_la_SOURCES += sysLogger.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/glibUtils/fileLogger.c000066400000000000000000000311361321503522500252310ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /** * @file fileLogger.c * * Logger that uses file streams and provides optional log rotation. */ #include "glibUtils.h" #include #include #include #if defined(G_PLATFORM_WIN32) # include # include #else # include # include #endif typedef struct FileLogger { GlibLogger handler; GIOChannel *file; gchar *path; gint logSize; guint64 maxSize; guint maxFiles; gboolean append; gboolean error; GStaticMutex lock; } FileLogger; #if !defined(_WIN32) /* ******************************************************************************* * FileLoggerIsValid -- */ /** * * Checks that the file descriptor backing this logger is still valid. * * This is a racy workaround for an issue with glib code; or, rather, two * issues. The first issue is that we can't intercept G_LOG_FLAG_RECURSION, * and glib just aborts when that happens (see gnome bug 618956). The second * is that if a GIOChannel channel write fails, that calls * g_io_channel_error_from_errno, which helpfully logs stuff, causing recursion. * Don't get me started on why that's, well, at least questionable. * * This is racy because between the check and the actual GIOChannel operation, * the state of the FD may have changed. In reality, since the bug this is * fixing happens in very special situations where code outside this file is * doing weird things like closing random fds, it should be OK. * * We may still get other write errors from the GIOChannel than EBADF, but * those would be harder to work around. Hopefully this handles the most usual * cases. * * See bug 783999 for some details about what triggers the bug. * * @param[in] logger The logger instance. * * @return TRUE if the I/O channel is still valid. * ******************************************************************************* */ static gboolean FileLoggerIsValid(FileLogger *logger) { if (logger->file != NULL) { int fd = g_io_channel_unix_get_fd(logger->file); return fcntl(fd, F_GETFD) >= 0; } return FALSE; } #else #define FileLoggerIsValid(logger) TRUE #endif /* * This function is a temporary workaround for a broken glib version * 2.42.2 that is missing g_get_user_name_utf8 export. After glib * is fixed this needs to be removed and call to GlibGetUserName * replaced by g_get_user_name. See bug 1434059 for details. */ const char* GlibGetUserName() { #if !defined(_WIN32) return g_get_user_name(); #else wchar_t buffer[256] = { 0 }; DWORD len = ARRAYSIZE(buffer); static char* user_name_utf8 = NULL; if (!user_name_utf8) { if (GetUserNameW(buffer, &len)) { user_name_utf8 = g_utf16_to_utf8(buffer, -1, NULL, NULL, NULL); } } return user_name_utf8; #endif } /* ******************************************************************************* * FileLoggerGetPath -- */ /** * * Parses the given template file name and expands embedded variables, and * places the log index information at the right position. * * The following variables are expanded: * * - ${USER}: user's login name. * - ${PID}: current process's pid. * - ${IDX}: index of the log file (for rotation). * * @param[in] data Log handler data. * @param[in] index Index of the log file. * * @return The expanded log file path. * ****************************************************************************** */ static gchar * FileLoggerGetPath(FileLogger *data, gint index) { gboolean hasIndex = FALSE; gchar indexStr[11]; gchar *logpath; gchar *vars[] = { "${USER}", NULL, "${PID}", NULL, "${IDX}", indexStr, }; gchar *tmp; size_t i; logpath = g_strdup(data->path); vars[1] = (char *) GlibGetUserName(); vars[3] = g_strdup_printf("%u", (unsigned int) getpid()); g_snprintf(indexStr, sizeof indexStr, "%d", index); for (i = 0; i < G_N_ELEMENTS(vars); i += 2) { char *last = logpath; char *start; while ((start = strstr(last, vars[i])) != NULL) { gchar *tmp; char *end = start + strlen(vars[i]); size_t offset = (start - last) + strlen(vars[i+1]); *start = '\0'; tmp = g_strdup_printf("%s%s%s", logpath, vars[i+1], end); g_free(logpath); logpath = tmp; last = logpath + offset; /* XXX: ugly, but well... */ if (i == 4) { hasIndex = TRUE; } } } g_free(vars[3]); /* * Always make sure we add the index if it's not 0, since that's used for * backing up old log files. */ if (index != 0 && !hasIndex) { char *sep = strrchr(logpath, '.'); char *pathsep = strrchr(logpath, '/'); if (pathsep == NULL) { pathsep = strrchr(logpath, '\\'); } if (sep != NULL && sep > pathsep) { *sep = '\0'; sep++; tmp = g_strdup_printf("%s.%d.%s", logpath, index, sep); } else { tmp = g_strdup_printf("%s.%d", logpath, index); } g_free(logpath); logpath = tmp; } return logpath; } /* ******************************************************************************* * FileLoggerOpen -- */ /** * * Opens a log file for writing, backing up the existing log file if one is * present. Only one old log file is preserved. * * @note Make sure this function is called with the write lock held. * * @param[in] data Log handler data. * * @return Log file pointer (NULL on error). * ******************************************************************************* */ static GIOChannel * FileLoggerOpen(FileLogger *data) { GIOChannel *logfile = NULL; gchar *path; g_return_val_if_fail(data != NULL, NULL); path = FileLoggerGetPath(data, 0); if (g_file_test(path, G_FILE_TEST_EXISTS)) { /* GStatBuf was added in 2.26. */ #if GLIB_CHECK_VERSION(2, 26, 0) GStatBuf fstats; #else struct stat fstats; #endif if (g_stat(path, &fstats) > -1) { data->logSize = (gint) fstats.st_size; } if (!data->append || data->logSize >= data->maxSize) { /* * Find the last log file and iterate back, changing the indices as we go, * so that the oldest log file has the highest index (the new log file * will always be index "0"). When not rotating, "maxFiles" is 1, so we * always keep one backup. */ gchar *log; guint id; GPtrArray *logfiles = g_ptr_array_new(); /* * Find the id of the last log file. The pointer array will hold * the names of all existing log files + the name of the last log * file, which may or may not exist. */ for (id = 0; id < data->maxFiles; id++) { log = FileLoggerGetPath(data, id); g_ptr_array_add(logfiles, log); if (!g_file_test(log, G_FILE_TEST_IS_REGULAR)) { break; } } /* Rename the existing log files, increasing their index by 1. */ for (id = logfiles->len - 1; id > 0; id--) { gchar *dest = g_ptr_array_index(logfiles, id); gchar *src = g_ptr_array_index(logfiles, id - 1); if (!g_file_test(dest, G_FILE_TEST_IS_DIR) && (!g_file_test(dest, G_FILE_TEST_EXISTS) || g_unlink(dest) == 0)) { g_rename(src, dest); } else { g_unlink(src); } } /* Cleanup. */ for (id = 0; id < logfiles->len; id++) { g_free(g_ptr_array_index(logfiles, id)); } g_ptr_array_free(logfiles, TRUE); data->logSize = 0; data->append = FALSE; } } logfile = g_io_channel_new_file(path, data->append ? "a" : "w", NULL); g_free(path); if (logfile != NULL) { g_io_channel_set_encoding(logfile, NULL, NULL); } return logfile; } /* ******************************************************************************* * FileLoggerLog -- */ /** * * Logs a message to the configured destination file. Also opens the file for * writing if it hasn't been done yet. * * @param[in] domain Log domain. * @param[in] level Log level. * @param[in] message Message to log. * @param[in] data File logger. * ******************************************************************************* */ static void FileLoggerLog(const gchar *domain, GLogLevelFlags level, const gchar *message, gpointer data) { FileLogger *logger = data; gsize written; g_static_mutex_lock(&logger->lock); if (logger->error) { goto exit; } if (logger->file == NULL) { if (logger->file == NULL) { logger->file = FileLoggerOpen(data); } if (logger->file == NULL) { logger->error = TRUE; goto exit; } } if (!FileLoggerIsValid(logger)) { logger->error = TRUE; goto exit; } /* Write the log file and do log rotation accounting. */ if (g_io_channel_write_chars(logger->file, message, -1, &written, NULL) == G_IO_STATUS_NORMAL) { if (logger->maxSize > 0) { logger->logSize += (gint) written; if (logger->logSize >= logger->maxSize) { g_io_channel_unref(logger->file); logger->append = FALSE; logger->file = FileLoggerOpen(logger); } else { g_io_channel_flush(logger->file, NULL); } } else { g_io_channel_flush(logger->file, NULL); } } exit: g_static_mutex_unlock(&logger->lock); } /* ****************************************************************************** * FileLoggerDestroy -- */ /** * * Cleans up the internal state of a file logger. * * @param[in] _data File logger data. * ****************************************************************************** */ static void FileLoggerDestroy(gpointer data) { FileLogger *logger = data; if (logger->file != NULL) { g_io_channel_unref(logger->file); } g_static_mutex_free(&logger->lock); g_free(logger->path); g_free(logger); } /* ******************************************************************************* * GlibUtils_CreateFileLogger -- */ /** * * @brief Creates a new file logger based on the given configuration. * * @param[in] path Path to log file. * @param[in] append Whether to append to existing log file. * @param[in] maxSize Maximum log file size (in MB, 0 = no limit). * @param[in] maxFiles Maximum number of old files to be kept. * * @return A new logger, or NULL on error. * ******************************************************************************* */ GlibLogger * GlibUtils_CreateFileLogger(const char *path, gboolean append, guint maxSize, guint maxFiles) { FileLogger *data = NULL; g_return_val_if_fail(path != NULL, NULL); data = g_new0(FileLogger, 1); data->handler.addsTimestamp = FALSE; data->handler.shared = FALSE; data->handler.logfn = FileLoggerLog; data->handler.dtor = FileLoggerDestroy; data->path = g_filename_from_utf8(path, -1, NULL, NULL, NULL); if (data->path == NULL) { g_free(data); return NULL; } data->append = append; data->maxSize = maxSize * 1024 * 1024; data->maxFiles = maxFiles + 1; /* To account for the active log file. */ g_static_mutex_init(&data->lock); return &data->handler; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/glibUtils/stdLogger.c000066400000000000000000000150431321503522500251030ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /** * @file stdLogger.c * * A very simplified version of a file logger that uses the standard output * streams (stdout / stderr). */ #include "glibUtils.h" #include #if defined(_WIN32) static GStaticMutex gConsoleLock = G_STATIC_MUTEX_INIT; static gint gRefCount = 0; #endif typedef struct StdLogger { GlibLogger handler; #if defined(_WIN32) gboolean attached; #endif } StdLogger; /* ******************************************************************************* * StdLoggerLog -- */ /** * * Logs a message to stdout or stderr depending on its severity. * * @param[in] domain Unused. * @param[in] level Log level. * @param[in] message Message to log. * @param[in] data Logger data. * ******************************************************************************* */ static void StdLoggerLog(const gchar *domain, GLogLevelFlags level, const gchar *message, gpointer data) { gchar *local; FILE *dest = (level < G_LOG_LEVEL_MESSAGE) ? stderr : stdout; #if defined(_WIN32) StdLogger *sdata = data; if (!sdata->attached) { g_static_mutex_lock(&gConsoleLock); if (gRefCount != 0 || GlibUtils_AttachConsole()) { gRefCount++; sdata->attached = TRUE; } g_static_mutex_unlock(&gConsoleLock); } if (!sdata->attached) { return; } #endif local = g_locale_from_utf8(message, -1, NULL, NULL, NULL); if (local != NULL) { fputs(local, dest); g_free(local); } else { fputs(message, dest); } } /* ******************************************************************************* * StdLoggerDestroy -- */ /** * * Cleans up the internal state of the logger. * * @param[in] data Logger data. * ******************************************************************************* */ static void StdLoggerDestroy(gpointer data) { #if defined(_WIN32) StdLogger *sdata = data; g_static_mutex_lock(&gConsoleLock); if (sdata->attached && --gRefCount == 0) { FreeConsole(); } g_static_mutex_unlock(&gConsoleLock); #endif g_free(data); } #if defined(_WIN32) /* ******************************************************************************* * GlibUtilsIsRedirected -- */ /** * * Checks whether given standard device (standard input, standard output, * or standard error) has been redirected to an on-disk file/pipe. * Win32-only. * * @param[in] nStdHandle The standard device number. * * @return TRUE if device redirected to a file/pipe. * ******************************************************************************* */ static gboolean GlibUtilsIsRedirected(DWORD nStdHandle) { HANDLE handle = GetStdHandle(nStdHandle); DWORD type = handle ? GetFileType(handle) : FILE_TYPE_UNKNOWN; return type == FILE_TYPE_DISK || type == FILE_TYPE_PIPE; } /* ******************************************************************************* * GlibUtils_AttachConsole -- */ /** * * Attaches a console to the current process. If the parent process already has * a console open, reuse it. Otherwise, create a new console for the current * process. Win32-only. * * It's safe to call this function multiple times (it won't do anything if * the process already has a console). * * @note Attaching to the parent process's console is only available on XP and * later. * * @return Whether the process is attached to a console. * ******************************************************************************* */ gboolean GlibUtils_AttachConsole(void) { typedef BOOL (WINAPI *AttachConsoleFn)(DWORD); gboolean ret = TRUE; AttachConsoleFn _AttachConsole; BOOL reopenStdout; BOOL reopenStderr; if (GetConsoleWindow() != NULL) { goto exit; } reopenStdout = !GlibUtilsIsRedirected(STD_OUTPUT_HANDLE); reopenStderr = !GlibUtilsIsRedirected(STD_ERROR_HANDLE); if (!reopenStdout && !reopenStderr) { goto exit; } _AttachConsole = (AttachConsoleFn) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "AttachConsole"); if ((_AttachConsole != NULL && _AttachConsole(ATTACH_PARENT_PROCESS)) || AllocConsole()) { FILE *fptr; if (reopenStdout) { fptr = _wfreopen(L"CONOUT$", L"a", stdout); if (fptr == NULL) { g_warning("_wfreopen failed for stdout/CONOUT$: %d (%s)", errno, strerror(errno)); ret = FALSE; } } if (reopenStderr) { fptr = _wfreopen(L"CONOUT$", L"a", stderr); if (fptr == NULL) { g_warning("_wfreopen failed for stderr/CONOUT$: %d (%s)", errno, strerror(errno)); ret = FALSE; } else { setvbuf(fptr, NULL, _IONBF, 0); } } } else { ret = FALSE; } exit: if (!ret) { g_warning("Console redirection unavailable."); } return ret; } #endif /* ******************************************************************************* * GlibUtils_CreateStdLogger -- */ /** * * @brief Configures a new std logger. * * @return A new logger instance. * ******************************************************************************* */ GlibLogger * GlibUtils_CreateStdLogger(void) { StdLogger *data = g_new0(StdLogger, 1); data->handler.logfn = StdLoggerLog; data->handler.addsTimestamp = FALSE; data->handler.shared = FALSE; data->handler.dtor = StdLoggerDestroy; return &data->handler; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/glibUtils/sysLogger.c000066400000000000000000000137331321503522500251330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /** * @file sysLogger.c * * Logger that writes to syslog(3). Since there's only one "syslog connection" * for the whole application, this code does reference counting to allow * different domains to be configured with a "syslog" handler, and still be * able to call closelog(3) when appropriate. */ #include "glibUtils.h" #include #include #include typedef struct SysLogger { GlibLogger handler; gchar *domain; gint refcount; } SysLogger; static SysLogger *gSysLogger; static GStaticMutex gSysLoggerLock = G_STATIC_MUTEX_INIT; /* ******************************************************************************* * SysLoggerLog -- */ /** * * @brief Sends the given log message to syslog. * * @param[in] domain Unused. * @param[in] level Log level. * @param[in] message Message to log. * @param[in] data Unused. * ****************************************************************************** */ static void SysLoggerLog(const gchar *domain, GLogLevelFlags level, const gchar *message, gpointer data) { gchar *local; int priority; /* glib and syslog disagree about critical / error. */ if (level & G_LOG_LEVEL_ERROR) { priority = LOG_CRIT; } else if (level & G_LOG_LEVEL_CRITICAL) { priority = LOG_ERR; } else if (level & G_LOG_LEVEL_WARNING) { priority = LOG_WARNING; } else if (level & G_LOG_LEVEL_MESSAGE) { priority = LOG_NOTICE; } else if (level & G_LOG_LEVEL_INFO) { priority = LOG_INFO; } else { priority = LOG_DEBUG; } local = g_locale_from_utf8(message, -1, NULL, NULL, NULL); if (local != NULL) { syslog(priority, "%s", local); g_free(local); } else { syslog(priority, "%s", message); } } /* ******************************************************************************* * SysLoggerUnref -- */ /** * * @brief Decreases the ref count and closes syslog if it reaches 0. * * @param[in] data Unused. * ******************************************************************************* */ static void SysLoggerUnref(gpointer data) { g_return_if_fail(data == gSysLogger); g_return_if_fail(gSysLogger->refcount > 0); g_static_mutex_lock(&gSysLoggerLock); gSysLogger->refcount -= 1; if (gSysLogger->refcount == 0) { closelog(); g_free(gSysLogger->domain); g_free(gSysLogger); gSysLogger = NULL; } g_static_mutex_unlock(&gSysLoggerLock); } /* ******************************************************************************* * GlibUtils_CreateSysLogger -- */ /** * * @brief Initializes syslog if it hasn't been done yet. * * Since syslog is shared, it's not recommended to change the default domain * during the lifetime of the application, since that may not reflect on the * syslogs (and, when it does, it might be confusing). * * @param[in] domain Application name, used as the syslog identity. * @param[in] facility Facility to use. One of: "daemon", "local[0-7]", "user" (default). * * @return Syslog logger data. * ******************************************************************************* */ GlibLogger * GlibUtils_CreateSysLogger(const char *domain, const char *facility) { g_static_mutex_lock(&gSysLoggerLock); if (gSysLogger == NULL) { int facid = LOG_USER; if (facility != NULL) { int idx; if (strcmp(facility, "daemon") == 0) { facid = LOG_DAEMON; } else if (sscanf(facility, "local%d", &idx) == 1) { switch (idx) { case 0: facid = LOG_LOCAL0; break; case 1: facid = LOG_LOCAL1; break; case 2: facid = LOG_LOCAL2; break; case 3: facid = LOG_LOCAL3; break; case 4: facid = LOG_LOCAL4; break; case 5: facid = LOG_LOCAL5; break; case 6: facid = LOG_LOCAL6; break; case 7: facid = LOG_LOCAL7; break; default: g_message("Invalid local facility for %s: %s\n", domain, facility); break; } } else if (strcmp(facility, "user") != 0) { g_message("Invalid syslog facility for %s: %s\n", domain, facility); } } gSysLogger = g_new0(SysLogger, 1); gSysLogger->handler.addsTimestamp = TRUE; gSysLogger->handler.shared = FALSE; gSysLogger->handler.logfn = SysLoggerLog; gSysLogger->handler.dtor = SysLoggerUnref; gSysLogger->domain = g_strdup(domain); gSysLogger->refcount = 1; openlog(gSysLogger->domain, LOG_CONS | LOG_PID, facid); } else { gSysLogger->refcount += 1; } g_static_mutex_unlock(&gSysLoggerLock); return &gSysLogger->handler; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/guestApp/000077500000000000000000000000001321503522500226345ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/guestApp/Makefile.am000066400000000000000000000017431321503522500246750ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libGuestApp.la libGuestApp_la_SOURCES = libGuestApp_la_SOURCES += guestApp.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/guestApp/guestApp.c000066400000000000000000000502301321503522500245700ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * guestApp.c -- * * Utility functions common to all guest applications */ #include #include #include #include "vmware.h" #include "vm_version.h" #include "vm_tools_version.h" #include "guestApp.h" #include "backdoor.h" #include "backdoor_def.h" #include "conf.h" #include "rpcout.h" #include "debug.h" #include "strutil.h" #include "str.h" #include "msg.h" #include "file.h" #include "posix.h" #include "vmware/guestrpc/tclodefs.h" #ifdef _MSC_VER #include #include #include "productState.h" #include "winregistry.h" #include "windowsUtil.h" #endif /* * For Netware/Linux/BSD/Solaris, the install path * is the hardcoded value below. For Windows, it is * determined dynamically in GuestApp_GetInstallPath(), * so the empty string here is just for completeness. */ #if defined _WIN32 # define GUESTAPP_TOOLS_INSTALL_PATH "" #elif defined __APPLE__ # define GUESTAPP_TOOLS_INSTALL_PATH "/Library/Application Support/VMware Tools" #else # define GUESTAPP_TOOLS_INSTALL_PATH "/etc/vmware-tools" #endif #if defined _WIN32 static char *GuestAppGetOrCreateConfPath(void); static DWORD GuestAppCreateConfPathSecInfo(PSECURITY_ATTRIBUTES *confPathSecAttrs, PACL *confPathAcl); static VOID GuestAppDestroyConfPathSecInfo(PSECURITY_ATTRIBUTES confPathSecAttrs, PACL confPathAcl); static DWORD GuestAppCreateConfPathSD(PSECURITY_DESCRIPTOR *confPathSD, PACL *confPathAcl); static VOID GuestAppDestroyConfPathSD(PSECURITY_DESCRIPTOR confPathSd, PACL confPathAcl); static DWORD GuestAppCreateConfPathAcl(PACL *newAcl); static VOID GuestAppDestroyConfPathAcl(PACL confPathAcl); #endif /* *----------------------------------------------------------------------------- * * GuestApp_GetDefaultScript -- * * Returns the default power script for the given configuration option. * * Results: * Script name on success, NULL of the option is not recognized. * * Side effects: * None. * *----------------------------------------------------------------------------- */ const char * GuestApp_GetDefaultScript(const char *confName) // IN { const char *value = NULL; if (strcmp(confName, CONFNAME_SUSPENDSCRIPT) == 0) { value = CONFVAL_SUSPENDSCRIPT_DEFAULT; } else if (strcmp(confName, CONFNAME_RESUMESCRIPT) == 0) { value = CONFVAL_RESUMESCRIPT_DEFAULT; } else if (strcmp(confName, CONFNAME_POWEROFFSCRIPT) == 0) { value = CONFVAL_POWEROFFSCRIPT_DEFAULT; } else if (strcmp(confName, CONFNAME_POWERONSCRIPT) == 0) { value = CONFVAL_POWERONSCRIPT_DEFAULT; } return value; } #if defined _WIN32 /* *------------------------------------------------------------------------------ * * GuestApp_GetInstallPathW -- * * Returns the tools installation path as a UTF-16 encoded string, or NULL on * error. The caller must deallocate the returned string using free. * * Results: * See above. * * Side effects: * None. *------------------------------------------------------------------------------ */ LPWSTR GuestApp_GetInstallPathW(void) { static LPCWSTR TOOLS_KEY_NAME = L"Software\\VMware, Inc.\\VMware Tools"; static LPCWSTR INSTALLPATH_VALUE_NAME = L"InstallPath"; HKEY key = NULL; LONG rc = ERROR_SUCCESS; DWORD cbData = 0; DWORD temp = 0; PWCHAR data = NULL; rc = RegOpenKeyExW(HKEY_LOCAL_MACHINE, TOOLS_KEY_NAME, 0, KEY_READ, &key); if (ERROR_SUCCESS != rc) { Debug("%s: Couldn't open key \"%S\".\n", __FUNCTION__, TOOLS_KEY_NAME); Debug("%s: RegOpenKeyExW error 0x%x.\n", __FUNCTION__, GetLastError()); goto exit; } rc = RegQueryValueExW(key, INSTALLPATH_VALUE_NAME, 0, NULL, NULL, &cbData); if (ERROR_SUCCESS != rc) { Debug("%s: Couldn't get length of value \"%S\".\n", __FUNCTION__, INSTALLPATH_VALUE_NAME); Debug("%s: RegQueryValueExW error 0x%x.\n", __FUNCTION__, GetLastError()); goto exit; } /* * The data in the registry may not be null terminated. So allocate enough * space for one extra WCHAR and use that space to write our own NULL. */ data = (LPWSTR) malloc(cbData + sizeof(WCHAR)); if (NULL == data) { Debug("%s: Couldn't allocate %d bytes.\n", __FUNCTION__, cbData); goto exit; } temp = cbData; rc = RegQueryValueExW(key, INSTALLPATH_VALUE_NAME, 0, NULL, (LPBYTE) data, &temp); if (ERROR_SUCCESS != rc) { Debug("%s: Couldn't get data for value \"%S\".\n", __FUNCTION__, INSTALLPATH_VALUE_NAME); Debug("%s: RegQueryValueExW error 0x%x.\n", __FUNCTION__, GetLastError()); goto exit; } data[cbData / sizeof(WCHAR)] = L'\0'; exit: if (NULL != key) { RegCloseKey(key); } return data; } #endif /* *---------------------------------------------------------------------- * * GuestApp_GetInstallPath -- * * Get the tools installation path. The caller is responsible for * freeing the memory allocated for the path. * * Results: * The path in UTF-8 if successful. * NULL otherwise. * * Side effects: * Allocates memory. * *---------------------------------------------------------------------- */ char * GuestApp_GetInstallPath(void) { char *pathUtf8 = NULL; #if defined _WIN32 size_t pathLen = 0; if (WinReg_GetSZ(HKEY_LOCAL_MACHINE, CONF_VMWARE_TOOLS_REGKEY, "InstallPath", &pathUtf8) != ERROR_SUCCESS) { Warning("%s: Unable to retrieve install path: %s\n", __FUNCTION__, Msg_ErrString()); return NULL; } /* Strip off the trailing backslash, if present */ pathLen = strlen(pathUtf8); if (pathLen > 0) { if (pathUtf8[pathLen - 1] == '\\') { pathUtf8[pathLen - 1] = '\0'; } } #else pathUtf8 = Str_Asprintf(NULL, "%s", GUESTAPP_TOOLS_INSTALL_PATH); #endif return pathUtf8; } /* *---------------------------------------------------------------------- * * GuestApp_GetConfPath -- * * Get the path to the Tools configuration file. * * The return conf path is a dynamically allocated UTF-8 encoded * string that should be freed by the caller. * * However, the function will also return NULL if we fail to create * a "VMware/VMware Tools" directory. This can occur if we're not running * as Administrator, which VMwareUser doesn't. But I believe that * VMwareService will always come up before VMwareUser, so by the time * a non-root user process calls this function, the directory exists. * * Results: * The path in UTF-8, or NULL on failure. * * Side effects: * Allocates memory. * *---------------------------------------------------------------------- */ char * GuestApp_GetConfPath(void) { static char *confPath = NULL; if (confPath == NULL) { #if defined _WIN32 confPath = GuestAppGetOrCreateConfPath(); #else /* Just call into GuestApp_GetInstallPath. */ confPath = GuestApp_GetInstallPath(); #endif } /* * Return a copy of the cached confPath. */ return confPath ? Util_SafeStrdup(confPath) : NULL; } #if defined _WIN32 /* *---------------------------------------------------------------------- * * GuestAppGetOrCreateConfPath -- * * Get the path to the Tools configuration file. * * The return conf path is a dynamically allocated UTF-8 encoded * string that should be freed by the caller. * The directory will be created if it doesn't exist. * * However, the function will also return NULL if we fail to create * a "VMware/VMware Tools" directory. This can occur if we're not running * as Administrator, which VMwareUser doesn't. But I believe that * VMwareService will always come up before VMwareUser, so by the time * a non-root user process calls this function, the directory exists. * * Results: * The path in UTF-8, or NULL on failure. * * Side effects: * Allocates memory and creates the directory if it does not exist. * *---------------------------------------------------------------------- */ static char * GuestAppGetOrCreateConfPath(void) { PSECURITY_ATTRIBUTES confPathSecAttrs = NULL; PACL confPathAcl = NULL; char *path; char *tmp; DWORD status = ERROR_SUCCESS; path = W32Util_GetVmwareCommonAppDataFilePath(NULL); if (path == NULL) { goto exit; } tmp = Str_SafeAsprintf(NULL, "%s%c%s", path, DIRSEPC, ProductState_GetName()); free(path); path = tmp; if (File_Exists(path)) { goto exit; } status = GuestAppCreateConfPathSecInfo(&confPathSecAttrs, &confPathAcl); if (ERROR_SUCCESS != status) { Warning("%s: Error: Get security info failed %u\n", __FUNCTION__, status); goto exit; } if (!CreateDirectoryA(path, confPathSecAttrs)) { status = GetLastError(); if (ERROR_ALREADY_EXISTS == status) { Debug("%s: Error: CreateDirectory path exists %u\n", __FUNCTION__, status); status = ERROR_SUCCESS; } else { Warning("%s: Error: CreateDirectory failed %u\n", __FUNCTION__, status); goto exit; } } exit: GuestAppDestroyConfPathSecInfo(confPathSecAttrs, confPathAcl); if (ERROR_SUCCESS != status) { free(path); path = NULL; } return path; } /* *----------------------------------------------------------------------------- * * GuestAppCreateConfPathSecInfo -- * * Creates the user access security attributes. * * Results: * ERROR_SUCCESS on success or appropriate failure code. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ static DWORD GuestAppCreateConfPathSecInfo(PSECURITY_ATTRIBUTES *confPathSecAttrs, // OUT: security attrs PACL *confPathAcl) // OUT: acl { PSECURITY_ATTRIBUTES newSA = NULL; PSECURITY_DESCRIPTOR newSD = NULL; PACL newAcl = NULL; DWORD status = ERROR_SUCCESS; Debug("%s: entered\n", __FUNCTION__); ASSERT(NULL != confPathSecAttrs); ASSERT(NULL != confPathAcl); /* Initialize a security descriptor. */ newSA = malloc(sizeof *newSA); if (NULL == newSA) { status = ERROR_NOT_ENOUGH_MEMORY; Warning("%s: Error: malloc failed %u\n", __FUNCTION__, status); goto exit; } memset(newSA, 0, sizeof *newSA); status = GuestAppCreateConfPathSD(&newSD, &newAcl); if (ERROR_SUCCESS != status) { Warning("%s: Error: SD creation failed %u\n", __FUNCTION__, status); goto exit; } newSA->nLength = sizeof *newSA; newSA->bInheritHandle = FALSE; newSA->lpSecurityDescriptor = newSD; exit: if (ERROR_SUCCESS != status) { GuestAppDestroyConfPathSecInfo(newSA, newAcl); newSA = NULL; newAcl = NULL; } *confPathSecAttrs = newSA; *confPathAcl = newAcl; return status; } /* *----------------------------------------------------------------------------- * * GuestAppDestroyConfPathSecInfo -- * * Destroys the security attributes and ACL. * * Results: * None. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ static VOID GuestAppDestroyConfPathSecInfo(PSECURITY_ATTRIBUTES confPathSecAttrs, // IN/OUT: security attrs PACL confPathAcl) // IN/OUT: acl { if (NULL != confPathSecAttrs) { GuestAppDestroyConfPathSD(confPathSecAttrs->lpSecurityDescriptor, confPathAcl); free(confPathSecAttrs); } } /* *----------------------------------------------------------------------------- * * GuestAppCreateConfPathSD -- * * Creates a security descriptor for the configuration path. * * Results: * ERROR_SUCCESS on success or appropriate failure code. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ static DWORD GuestAppCreateConfPathSD(PSECURITY_DESCRIPTOR *confPathSD, // OUT: security PACL *confPathAcl) // OUT: acl { DWORD status = ERROR_SUCCESS; PACL newConfPathAcl = NULL; PSECURITY_DESCRIPTOR newConfPathSD = NULL; ASSERT(NULL != confPathSD); ASSERT(NULL != confPathAcl); status = GuestAppCreateConfPathAcl(&newConfPathAcl); if (ERROR_SUCCESS != status) { Warning("%s: Error: Get Acl failed %u\n", __FUNCTION__, status); goto exit; } /* Initialize a security descriptor. */ newConfPathSD = malloc(SECURITY_DESCRIPTOR_MIN_LENGTH); if (NULL == newConfPathSD) { status = ERROR_NOT_ENOUGH_MEMORY; Warning("%s: Error: malloc failed %u\n", __FUNCTION__, status); goto exit; } if (!InitializeSecurityDescriptor(newConfPathSD, SECURITY_DESCRIPTOR_REVISION)) { status = GetLastError(); Warning("%s: Error: InitializeSecurityDescriptor failed %u\n", __FUNCTION__, status); goto exit; } /* Add the ACL to the security descriptor. */ if (!SetSecurityDescriptorDacl(newConfPathSD, TRUE, newConfPathAcl, FALSE)) { status = GetLastError(); Warning("%s: Error: SetSecurityDescriptorDacl failed %u\n", __FUNCTION__, status); goto exit; } exit: if (ERROR_SUCCESS != status) { GuestAppDestroyConfPathSD(newConfPathSD, newConfPathAcl); newConfPathSD = NULL; newConfPathAcl = NULL; } *confPathSD = newConfPathSD; *confPathAcl = newConfPathAcl; return status; } /* *----------------------------------------------------------------------------- * * GuestAppDestroyConfPathSD -- * * Destroys the security descriptor and access control list. * * Results: * None. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ static VOID GuestAppDestroyConfPathSD(PSECURITY_DESCRIPTOR confPathSd, // IN/OUT: security PACL confPathAcl) // IN/OUT: acl { free(confPathSd); GuestAppDestroyConfPathAcl(confPathAcl); } /* *----------------------------------------------------------------------------- * * GuestAppCreateConfPathAcl -- * * Create a new user access ACL. * * Results: * ERROR_SUCCESS on success or appropriate failure code. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ static DWORD GuestAppCreateConfPathAcl(PACL *confPathAcl) // OUT: ACL { PACL newAcl = NULL; PSID systemSID = NULL; PSID adminsGrpSID = NULL; PSID everyoneSID = NULL; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; DWORD newAclSize; DWORD status = ERROR_SUCCESS; ASSERT(NULL != confPathAcl); /* Create a well-known SID for the Everyone group. */ if (!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyoneSID)) { status = GetLastError(); Warning("%s: Error: AllocateAndInitializeSid Error %u\n", __FUNCTION__, status); goto exit; } /* Create a well-known SID for the Administrators group. */ if (!AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &adminsGrpSID)) { status = GetLastError(); Warning("%s: Error: AllocateAndInitializeSid Error %u\n", __FUNCTION__, status); goto exit; } /* Create a well-known SID for the System user. */ if (!AllocateAndInitializeSid(&SIDAuthNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &systemSID)) { status = GetLastError(); Warning("%s: Error: AllocateAndInitializeSid Error %u\n", __FUNCTION__, status); goto exit; } /* * Get the size of the new ACL. See the following link for this calculation. * http://msdn.microsoft.com/en-us/library/windows/desktop/aa378853(v=vs.85).aspx? */ newAclSize = sizeof *newAcl; newAclSize += GetLengthSid(systemSID) + sizeof (ACCESS_ALLOWED_ACE) - sizeof (DWORD); newAclSize += GetLengthSid(adminsGrpSID) + sizeof (ACCESS_ALLOWED_ACE) - sizeof (DWORD); newAclSize += GetLengthSid(everyoneSID) + sizeof (ACCESS_ALLOWED_ACE) - sizeof (DWORD); /* Align newAclSize to a DWORD. */ newAclSize = (newAclSize + (sizeof (DWORD) - 1)) & 0xfffffffc; /* Allocate the new ACL. */ newAcl = malloc(newAclSize); if (NULL == newAcl) { status = ERROR_NOT_ENOUGH_MEMORY; Warning("%s: Error: malloc Acl failed %u\n", __FUNCTION__, status); goto exit; } /* Initialize the new DACL. */ if (!InitializeAcl(newAcl, newAclSize, ACL_REVISION)) { status = GetLastError(); Warning("%s: Error: Init Acl failed %u\n", __FUNCTION__, status); goto exit; } /* Add the ACE to the DACL for the sid. Note: no inheritence. */ if (!AddAccessAllowedAceEx(newAcl, ACL_REVISION, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, GENERIC_READ | GENERIC_EXECUTE, everyoneSID)) { status = GetLastError(); Warning("%s: Error: Add Everyone Ace to Acl failed %u\n", __FUNCTION__, status); goto exit; } /* Add the ACE to the ACL for the sid. Note: no inheritence. */ if (!AddAccessAllowedAceEx(newAcl, ACL_REVISION, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, GENERIC_ALL, adminsGrpSID)) { status = GetLastError(); Warning("%s: Error: Add admins Grp Ace to Acl failed %u\n", __FUNCTION__, status); goto exit; } /* Add the ACE to the ACL for the sid. Note: no inheritence. */ if (!AddAccessAllowedAceEx(newAcl, ACL_REVISION, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE, GENERIC_ALL, systemSID)) { status = GetLastError(); Warning("%s: Error: Add system Ace to Acl failed %u\n", __FUNCTION__, status); goto exit; } exit: /* Free the allocated SIDs. */ if (NULL != everyoneSID) { FreeSid(everyoneSID);; } if (NULL != adminsGrpSID) { FreeSid(adminsGrpSID); } if (NULL != systemSID) { FreeSid(systemSID); } if (ERROR_SUCCESS != status) { GuestAppDestroyConfPathAcl(newAcl); newAcl = NULL; } *confPathAcl = newAcl; return status; } /* *----------------------------------------------------------------------------- * * GuestAppDestroyConfPathAcl -- * * Destroys the ACL. * * Results: * None. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ static VOID GuestAppDestroyConfPathAcl(PACL confPathAcl) // IN/OUT: security { free(confPathAcl); } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/guestRpc/000077500000000000000000000000001321503522500226405ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/guestRpc/Makefile.am000066400000000000000000000032751321503522500247030ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2008-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libGuestRpc.la libGuestRpc_la_SOURCES = libGuestRpc_la_SOURCES += nicinfo_xdr.c # XXX: Autoreconf complains about this and recommends using AM_CFLAGS instead. # Problem is, $(CFLAGS) is appended to the compiler command line after AM_CFLAGS # and after libGuestRpc_la_CFLAGS, so "-Wall -Werror" will override this flag. CFLAGS += -Wno-unused CLEANFILES = CLEANFILES += nicinfo.h CLEANFILES += nicinfo_xdr.c EXTRA_DIST = EXTRA_DIST += nicinfo.x # Rules to invoke rpcgen. rpcgen will generate funny paths in the generated # files if not invoked in the same directory as the source file, so we need # to copy the sources to the build dir before compiling them. nicinfo.h: nicinfo.x @RPCGEN_WRAPPER@ lib/guestRpc/nicinfo.x $@ nicinfo_xdr.c: nicinfo.x nicinfo.h @RPCGEN_WRAPPER@ lib/guestRpc/nicinfo.x $@ open-vm-tools-stable-10.2.0/open-vm-tools/lib/guestRpc/nicinfo.x000066400000000000000000000171741321503522500244700ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * nicinfo.x -- * * Definition of the data structures used in the GuestRpc commands to * provide information about the guest NICs. */ /* * Enumerates the different versions of the messages. Starting at 2, since * version one is legacy code we can't change. */ enum NicInfoVersion { NIC_INFO_V1 = 1, /* XXX Not represented here. */ NIC_INFO_V2 = 2, NIC_INFO_V3 = 3 }; /* * These are arbitrary limits to avoid possible DoS attacks. * The IP limit is large enough to hold an IP address (either v4 or v6). */ const NICINFO_MAX_IP_LEN = 64; const NICINFO_MAX_IPS = 2048; const NICINFO_MAX_NICS = 16; /* MAC Addresses are "AA:BB:CC:DD:EE:FF" = 18 bytes. */ const NICINFO_MAC_LEN = 18; /* * Corresponds to public/guestInfo.h::GuestInfoIPAddressFamilyType. */ enum NicInfoAddrType { NICINFO_ADDR_IPV4 = 0, NICINFO_ADDR_IPV6 = 1 }; struct VmIpAddress { NicInfoAddrType addressFamily; Bool dhcpEnabled; char ipAddress[NICINFO_MAX_IP_LEN]; /* * For IPv4, may be either a hexadecimal mask ("0xffffff00") or CIDR-style * prefix length ("24"). For IPv6, will only be a prefix length. */ char subnetMask[NICINFO_MAX_IP_LEN]; }; struct GuestNic { char macAddress[NICINFO_MAC_LEN]; struct VmIpAddress ips; }; /* * This structure is not entirely necessary, but it makes the generated * code nicer to code to. */ struct GuestNicList { struct GuestNic nics; }; /* *----------------------------------------------------------------------------- * * NIC Info version 3. * * V3 adds routing, DNS, and WINS information to the NIC list. * *----------------------------------------------------------------------------- */ /* * IP v4 and v6 addressing. * * These types were redefined primarily to allow much more efficient wire * encoding. */ /* * See RFC 4001, InetAddress. */ const INET_ADDRESS_MAX_LEN = 255; typedef opaque InetAddress; /* * See RFC 4001, InetAddressType. */ enum InetAddressType { IAT_UNKNOWN = 0, IAT_IPV4 = 1, IAT_IPV6 = 2, IAT_IPV4Z = 3, IAT_IPV6Z = 4, IAT_DNS = 16 }; /* * See RFC 4001, InetAddressPrefixLength. */ typedef unsigned int InetAddressPrefixLength; /* * See RFC 4293, IpAddressOriginTC. */ enum IpAddressOrigin { IAO_OTHER = 1, IAO_MANUAL = 2, IAO_DHCP = 4, IAO_LINKLAYER = 5, IAO_RANDOM = 6 }; /* * See RFC 4293, IpAddressStatusTC. * * "The status of an address. Most of the states correspond to states * from the IPv6 Stateless Address Autoconfiguration protocol. * ... * "In the absence of other information, an IPv4 address is always * preferred(1)." */ enum IpAddressStatus { IAS_PREFERRED = 1, IAS_DEPRECATED = 2, IAS_INVALID = 3, IAS_INACCESSIBLE = 4, IAS_UNKNOWN = 5, IAS_TENTATIVE = 6, IAS_DUPLICATE = 7, IAS_OPTIMISTIC = 8 }; /* * Convenient type for lists of addresses. */ struct TypedIpAddress { InetAddressType ipAddressAddrType; InetAddress ipAddressAddr; }; /* * See RFC 4293, IpAddressEntry. * * "An address mapping for a particular interface." * * We deviate from the RFC in a few places: * - The prefix length is listed explicitly here rather than reference * a separate prefix table. * - Interface indices aren't included as this structure is dependent * upon/encapsulated by a GuestNicV3 structure. */ struct IpAddressEntry { TypedIpAddress ipAddressAddr; InetAddressPrefixLength ipAddressPrefixLength; IpAddressOrigin *ipAddressOrigin; IpAddressStatus *ipAddressStatus; }; /* * Runtime DNS resolver state. */ /* * Quoth RFC 2181 §11 (Name Syntax): * "The length of any one label is limited to between 1 and 63 octets. A * full domain name is limited to 255 octets (including the separators)." */ const DNSINFO_MAX_ADDRLEN = 255; typedef string DnsHostname; /* * Arbitrary limits. */ const DNSINFO_MAX_SUFFIXES = 10; const DNSINFO_MAX_SERVERS = 16; struct DnsConfigInfo { DnsHostname *hostName; DnsHostname *domainName; TypedIpAddress serverList; DnsHostname searchSuffixes; }; /* * Runtime WINS resolver state. Addresses are assumed to be IPv4 only. */ struct WinsConfigInfo { TypedIpAddress primary; TypedIpAddress secondary; }; /* * Runtime routing tables. */ /* * Arbitrary limit. */ const NICINFO_MAX_ROUTES = 100; /* * See RFC 4292 for details. */ enum InetCidrRouteType { ICRT_OTHER = 1, ICRT_REJECT = 2, ICRT_LOCAL = 3, ICRT_REMOTE = 4 }; struct InetCidrRouteEntry { TypedIpAddress inetCidrRouteDest; InetAddressPrefixLength inetCidrRoutePfxLen; /* * Next hop isn't mandatory. */ TypedIpAddress *inetCidrRouteNextHop; /* * inetCidrRouteProto is omitted as we're concerned only with static/ * netmgmt routes. */ /* This is an array index into GuestNicListV3::nics. */ uint32 inetCidrRouteIfIndex; /* XXX Do we really need this? */ InetCidrRouteType inetCidrRouteType; /* -1 == unused. */ uint32 inetCidrRouteMetric; }; /* * Fun with DHCP */ const DHCP_MAX_CONFIG_SIZE = 16384; struct DhcpConfigInfo { bool enabled; string dhcpSettings; }; /* * Top-level containers. */ /* * Describes a single NIC. */ struct GuestNicV3 { string macAddress; IpAddressEntry ips; DnsConfigInfo *dnsConfigInfo; WinsConfigInfo *winsConfigInfo; DhcpConfigInfo *dhcpConfigInfov4; DhcpConfigInfo *dhcpConfigInfov6; }; /* * Attempts to model general network state. */ struct NicInfoV3 { GuestNicV3 nics; InetCidrRouteEntry routes; DnsConfigInfo *dnsConfigInfo; WinsConfigInfo *winsConfigInfo; DhcpConfigInfo *dhcpConfigInfov4; DhcpConfigInfo *dhcpConfigInfov6; }; /* * This defines the protocol for a "nic info" message. The union allows * us to create new versions of the protocol later by creating new values * in the NicInfoVersion enumeration, without having to change much of * the code calling the (de)serialization functions. * * Since the union doesn't have a default case, de-serialization will fail * if an unknown version is provided on the wire. */ union GuestNicProto switch (NicInfoVersion ver) { case NIC_INFO_V2: struct GuestNicList *nicsV2; case NIC_INFO_V3: struct NicInfoV3 *nicInfoV3; }; open-vm-tools-stable-10.2.0/open-vm-tools/lib/hashMap/000077500000000000000000000000001321503522500224255ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/hashMap/Makefile.am000066400000000000000000000017351321503522500244670ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2013-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libHashMap.la libHashMap_la_SOURCES = libHashMap_la_SOURCES += hashMap.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/hashMap/hashMap.c000066400000000000000000000617131321503522500241620ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #include "vm_basic_types.h" #include "vm_assert.h" #include #include #include "hashMap.h" #include "clamped.h" #ifdef VMX86_SERVER #include "aioMgr.h" #include "iovector.h" #endif /* * hashMap.c -- * * This is a map data structure that can store a sparsely indexed data set. * It is not intended to be thread safe nor should it be used in a way that * this may cause problems. * * Entries are stored based on a simple hash of their key. Memory * allocations are kept to a minimum to ensure that this is appropriate for * use in a kernel mode driver. Linear probing is used to resolve hash * collisions. * * This implementation only supports static length keys. It might be * possible to store the keys outside the table and thus support keys of * variable length but this isn't currently planned. This would allow for * string keys for example. * * Callers should not store pointers to objects stored in the map as they may * become invalid as a result of a resize. If you need to share objects * stored as values in the map, then store pointers to the objects instead. * * All objects are copied into the map and must be freed as appropriate by * the caller. * * This particular HashMap has some important differences from the hash table * implementation in bora/lib/misc * - HashMap supports key removal * - HashMap only supports fixed size keys and values while hashTable * supports string and insensitive string keys and only supports pointer * data. This means its possible to store entire data structures in * HashMap. * - HashMap uses linear probing to resolve collisions while hashTable uses * chaining. HashMap will dynamically resize itself as necessary. * - Pointers to HashMap values will be invalidated if the internal structure * is resized. If this is a problem, you should store the pointer in the * HashMap rather than the object itself. * - HashMap will ensure that a maximum load factor is not exceeded. * * hashMap is now restrictd to userworld applications on ESX builds ONLY. * See PR 817760 which has an attached patchfile to remove this limitation * if in future that is felt to be desireable. */ #define HASHMAP_DEFAULT_ALPHA 2 struct HashMap { uint8 *entries; uint32 numEntries; uint32 count; uint32 alpha; size_t keySize; size_t dataSize; size_t entrySize; size_t keyOffset; size_t dataOffset; }; #ifdef VMX86_SERVER typedef #include "vmware_pack_begin.h" struct HashMapOnDisk { uint32 numEntries; uint32 count; uint32 alpha; uint64 keySize; uint64 dataSize; uint64 entrySize; uint64 keyOffset; uint64 dataOffset; } #include "vmware_pack_end.h" HashMapOnDisk; #endif typedef enum { HashMapState_EMPTY = 0, HashMapState_FILLED, HashMapState_DELETED, } HashMapEntryState; typedef struct { uint32 state; uint32 hash; } HashMapEntryHeader; #define NO_FREE_INDEX ((uint32) -1) static Bool InitMap(struct HashMap *map, uint32 numEntries, uint32 alpha, size_t keySize, size_t dataSize); static void CalculateEntrySize(struct HashMap *map); static void GetEntry(struct HashMap *map, uint32 index, HashMapEntryHeader **header, void **key, void **data); static uint32 ComputeHash(struct HashMap *map, const void *key); static Bool LookupKey(struct HashMap* map, const void *key, HashMapEntryHeader **header, void **data, uint32 *freeIndex); static Bool CompareKeys(struct HashMap *map, const void *key, const void *compare); static Bool NeedsResize(struct HashMap *map); static void Resize(struct HashMap *map); INLINE void EnsureSanity(HashMap *map); /* * ---------------------------------------------------------------------------- * * CheckSanity -- * * Same code as EnsureSanity except return Bool instead of ASSERTing * * Results: * TRUE is sane. * * Side Effects: * None. * * ---------------------------------------------------------------------------- */ #ifdef VMX86_DEBUG static INLINE Bool CheckSanity(HashMap *map) { uint32 i, cnt = 0; ASSERT(map); for (i = 0; i < map->numEntries; i++) { HashMapEntryHeader *header = NULL; void *key, *data; GetEntry(map, i, &header, &key, &data); ASSERT(header); ASSERT(header->state == HashMapState_FILLED || header->state == HashMapState_EMPTY || header->state == HashMapState_DELETED); if (header->state == HashMapState_FILLED) { cnt++; if (header->hash != ComputeHash(map, key)) { return FALSE; } } } if (cnt != map->count) { return FALSE; } if (!map->numEntries) { return FALSE; } return TRUE; } #endif /* * ---------------------------------------------------------------------------- * * HashMap_AllocMap -- * * Allocate a map and the space for the entries. * * Results: * Returns a pointer to a HashMap or NULL on failure. * * Side Effects: * Allocates memory. * * ---------------------------------------------------------------------------- */ struct HashMap* HashMap_AllocMap(uint32 numEntries, // IN size_t keySize, // IN size_t dataSize) // IN { return HashMap_AllocMapAlpha(numEntries, HASHMAP_DEFAULT_ALPHA, keySize, dataSize); } /* * ---------------------------------------------------------------------------- * * HashMap_AllocMapAlpha -- * * Allocate a map and the space for the entries. The value of alpha is * treated as a denominator for the maximum allowable load factor. I.e. an * alpha value of 2 would correspond to a maximum load factor of 0.5. The * map will be enlarged when elements are added in order to maintain this * load factor. * * Results: * Returns a pointer to a HashMap or NULL on failure. * * Side Effects: * Allocates memory. * * ---------------------------------------------------------------------------- */ struct HashMap* HashMap_AllocMapAlpha(uint32 numEntries, // IN uint32 alpha, // IN size_t keySize, // IN size_t dataSize) // IN { struct HashMap *map; map = calloc(1, sizeof *map); ASSERT(alpha); if (map) { if (!InitMap(map, numEntries, alpha, keySize, dataSize)) { HashMap_DestroyMap(map); return NULL; } } return map; } /* * ---------------------------------------------------------------------------- * * HashMap_DestroyMap -- * * Destroy a HashMap, clear out all the entries and free the memory. * * Results: * None. * * Side Effects: * Frees memory. * * ---------------------------------------------------------------------------- */ void HashMap_DestroyMap(struct HashMap *map) // IN { if (map) { free(map->entries); } free(map); } /* * ---------------------------------------------------------------------------- * * InitMap -- * * Initializes a map's internal structure. The value of alpha is treated * as a denominator for the maximum allowable load factor. I.e. an alpha * value of 2 would correspond to a maximum load factor of 0.5. The map * will be enlarged when elements are added in order to maintain this load * factor. * * Results: * Returns TRUE on success or FALSE if the memory allocation failed. * * Side Effects: * Allocates memory. * * ---------------------------------------------------------------------------- */ static Bool InitMap(struct HashMap *map, // IN uint32 numEntries, // IN uint32 alpha, // IN size_t keySize, // IN size_t dataSize) // IN { ASSERT(map); ASSERT(alpha); ASSERT(numEntries); /* * Ensure that the entries map is at least large enough to hold all of the * entries that were requested taking into account the alpha factor. */ numEntries *= alpha; map->numEntries = numEntries; map->alpha = alpha; map->keySize = keySize; map->dataSize = dataSize; CalculateEntrySize(map); map->entries = calloc(numEntries, map->entrySize); if (map->entries) { EnsureSanity(map); } return map->entries != NULL; } /* * ---------------------------------------------------------------------------- * * HashMap_Put -- * * Put the value at data against the key. This will replace any existing * data that is in the table without warning. * * Results: * TRUE if the put operation is successful * FALSE otherwise * * Side Effects: * The value in data is copied to the table and can be referenced in the * future by the value in key. * * ---------------------------------------------------------------------------- */ Bool HashMap_Put(struct HashMap *map, // IN const void *key, // IN const void *data) // IN { uint32 freeIndex; HashMapEntryHeader *header; void *tableData; if (!LookupKey(map, key, &header, &tableData, &freeIndex)) { uint32 hash = ComputeHash(map, key); void *tableKey; if (NeedsResize(map)) { Resize(map); if (LookupKey(map, key, &header, &tableData, &freeIndex)) { /* * Somehow our key appeared after resizing the table. */ ASSERT(FALSE); } if (freeIndex == NO_FREE_INDEX) { /* * The resize must have failed. */ return FALSE; } } map->count++; GetEntry(map, freeIndex, &header, &tableKey, &tableData); ASSERT(header); header->state = HashMapState_FILLED; header->hash = hash; memcpy(tableKey, key, map->keySize); } ASSERT(data || map->dataSize == 0); memcpy(tableData, data, map->dataSize); EnsureSanity(map); return TRUE; } /* * ---------------------------------------------------------------------------- * * HashMap_Get -- * * Get the value corresponding to the given key. * * Results: * Returns a pointer to the data that was previously stored by HashMap_Put or * NULL if the key wasn't found. * * Side Effects: * None. * * ---------------------------------------------------------------------------- */ void * HashMap_Get(struct HashMap *map, // IN const void *key) // IN { void *data; uint32 freeIndex; HashMapEntryHeader *header; if (LookupKey(map, key, &header, &data, &freeIndex)) { return data; } return NULL; } /* * ---------------------------------------------------------------------------- * * HashMap_Clear -- * * Remove all entries from the HashMap. * * Results: * None. * * Side Effects: * All entries in the map are removed. * * ---------------------------------------------------------------------------- */ void HashMap_Clear(struct HashMap *map) // IN { int i = 0; HashMapEntryHeader *header; void *key, *data; ASSERT(map); for (i = 0; i < map->numEntries; i++) { GetEntry(map, i, &header, &key, &data); ASSERT(header); header->state = HashMapState_EMPTY; } map->count = 0; EnsureSanity(map); } /* * ---------------------------------------------------------------------------- * * HashMap_Remove -- * * Remove an entry from the map. * * Results: * Returns TRUE if the entry was in the map, FALSE if the entry was not in * the map. * * Side Effects: * The entry is removed from the map. * * ---------------------------------------------------------------------------- */ Bool HashMap_Remove(struct HashMap *map, // IN const void *key) // IN { uint32 freeIndex; HashMapEntryHeader *header; void *tableData; if (!LookupKey(map, key, &header, &tableData, &freeIndex)) { return FALSE; } /* * XXX: This could be made slightly smarter. We could check the next entry * to see if it's EMPTY and then mark this one as empty as well. */ map->count--; header->state = HashMapState_DELETED; EnsureSanity(map); return TRUE; } /* * ---------------------------------------------------------------------------- * * HashMap_Count -- * * Returns the current count of entries in the map. * * Results: * The current count of entries in the map. * * Side Effects: * None. * * ---------------------------------------------------------------------------- */ uint32 HashMap_Count(struct HashMap *map) // IN { return map->count; } /* * ---------------------------------------------------------------------------- * * CalculateEntrySize -- * * Calculate the size of the entry and the offsets to the key and data. * * Results: * None. * * Side Effects: * The map structure is adjusted to contain the correct sizes. * * ---------------------------------------------------------------------------- */ void CalculateEntrySize(struct HashMap *map) // IN { size_t alignKeySize, alignDataSize; size_t alignKeyOffset, alignDataOffset; ASSERT(map); alignKeySize = ROUNDUP(map->keySize, 4); alignDataSize = ROUNDUP(map->dataSize, 4); alignKeyOffset = sizeof (HashMapEntryHeader); alignDataOffset = ROUNDUP(alignKeyOffset + alignKeySize, 4); map->entrySize = sizeof (HashMapEntryHeader) + alignKeySize + alignDataSize; map->keyOffset = alignKeyOffset; map->dataOffset = alignDataOffset; } /* * ---------------------------------------------------------------------------- * * LookupKey -- * * Use linear probing to find a free space in the table or the data that * we're interested in. * * Returns: * - TRUE if the key was found in the table, FALSE otherwise. * - Returns the entry header on header, data pointer on data and the first * non-filled index that was encountered on freeIndex * * Side Effects: * - Header and Data are changed. They should only be considered valid if * the key was found. * - FreeIndex will be updated to point to the first non-filled index. * * ---------------------------------------------------------------------------- */ Bool LookupKey(struct HashMap* map, // IN const void *key, // IN HashMapEntryHeader **header, // OUT void **data, // OUT uint32 *freeIndex) // OUT { uint32 hash = ComputeHash(map, key); uint32 index = hash % map->numEntries; uint32 probe = 0; Bool done = FALSE, found = FALSE; void *tableKey; ASSERT(map); ASSERT(key); ASSERT(data); ASSERT(freeIndex); *freeIndex = NO_FREE_INDEX; while (!done && probe < map->numEntries + 1) { uint32 currentIndex = (index + probe) % map->numEntries; GetEntry(map, currentIndex, header, &tableKey, data); ASSERT(header); switch ((*header)->state) { case HashMapState_EMPTY: done = TRUE; /* FALL THROUGH */ case HashMapState_DELETED: /* * We're not done if we've found a deleted space. This may just mean * that the entry was deleted but that the target entry may appear * later. */ if (*freeIndex == NO_FREE_INDEX) { *freeIndex = currentIndex; } break; case HashMapState_FILLED: if ((*header)->hash == hash) { found = CompareKeys(map, key, tableKey); if (found) { done = TRUE; } } break; default: NOT_REACHED(); } probe++; } ASSERT(found || *freeIndex != NO_FREE_INDEX || map->count == map->numEntries); return found; } /* * ---------------------------------------------------------------------------- * * GetEntry -- * * Get a specific entry from the entries list. This does not perform any * hash compare, it's a simple index based lookup. * * Results: * The header is stored in header, key in key and the data in data. These * are all direct pointers into the table. * * Side Effects: * The header, key and data pointers are modified. * * ---------------------------------------------------------------------------- */ void GetEntry(struct HashMap *map, // IN uint32 index, // IN HashMapEntryHeader **header, // OUT void **key, // OUT void **data) // OUT { uint8 *entry; ASSERT(map); ASSERT(header); ASSERT(key); ASSERT(data); ASSERT(index < map->numEntries); entry = ((uint8 *)map->entries) + (map->entrySize * index); ASSERT(entry); *header = (HashMapEntryHeader *) (entry); *key = (void*) (entry + map->keyOffset); *data = (void*) (entry + map->dataOffset); } /* * ---------------------------------------------------------------------------- * * ComputeHash -- * * Compute the hash of the given key. * * Results: * An opaque hash value based on the given key. Given the same key in the * same map, this function will always return the same value. * * Side Effects: * None. * * ---------------------------------------------------------------------------- */ uint32 ComputeHash(struct HashMap *map, // IN const void *key) // IN { /* * djb2, with n == 33. See http://www.cse.yorku.ca/~oz/hash.html. * * This hash function is largely borrowed from the emmet library in bora/lib * This hash table implementation does a hash compare before comparing the * keys so it's inappropriate for the hash function to take the modulo before * returning. */ uint32 h = 5381; const uint8 *keyByte; size_t i = 0; for (keyByte = key, i = 0; i < map->keySize; keyByte++, i++) { h *= 33; h += *keyByte; } return h; } /* * ---------------------------------------------------------------------------- * * CompareKeys -- * * Compare two keys to one another. * * Results: * Returns TRUE if the two keys are binary equal over the length specified * in the map. FALSE if the two keys are different. * * Side Effects: * None. * * ---------------------------------------------------------------------------- */ Bool CompareKeys(struct HashMap *map, // IN const void *key, // IN const void *compare) // IN { return memcmp(key, compare, map->keySize) == 0; } /* * ---------------------------------------------------------------------------- * * NeedsResize -- * * Determine if adding another element to the map will require that the map * be resized. This takes into account the maximum load factor that is * allowed for this map. * * Results: * Returns TRUE if the map should be resized. * * Side Effects: * None. * * ---------------------------------------------------------------------------- */ Bool NeedsResize(struct HashMap *map) { uint32 required; Clamped_UMul32(&required, map->count, map->alpha); return required >= map->numEntries; } /* * ---------------------------------------------------------------------------- * * Resize -- * * Doubles the size of the entries array until it is at least large enough * to ensure the maximum load factor is not exceeded. * * Results: * None. * * Side Effects: * The entries list is doubled in size and the entries are copied into the * appropriate location. Callers should not assume that the locations that * were valid before this was called are still valid as all entries may * appear at different locations after this function completes. * * ---------------------------------------------------------------------------- */ void Resize(struct HashMap *map) // IN { struct HashMap oldHashMap = *map; int i; if (map->numEntries == MAX_UINT32) { if (map->count < MAX_UINT32) { /* * We're already at the maximum size of the array and there's still * room for the new entry, don't bother resizing. */ return; } else { /* * This situation is fatal, though we're unlikely to ever hit this with * realistic usage. */ Panic("Ran out of room in the hashtable\n"); } } /* * We might, at some point, want to look at making this grow geometrically * until we hit some threshold and then grow arithmetically after that. To * keep it simple for now, however, we'll just grow geometrically all the * time. */ map->entries = calloc(oldHashMap.numEntries * 2, oldHashMap.entrySize); if (!map->entries) { map->entries = oldHashMap.entries; return; } do { if (!Clamped_UMul32(&map->numEntries, map->numEntries, 2)) { /* Prevent overflow and */ break; } } while (NeedsResize(map)); map->count = 0; for (i = 0; i < oldHashMap.numEntries; i++) { HashMapEntryHeader *oldHeader; HashMapEntryHeader *newHeader; void *oldKey; void *oldData; void *newKey; void *newData; uint32 freeIndex; GetEntry(&oldHashMap, i, &oldHeader, &oldKey, &oldData); switch (oldHeader->state) { case HashMapState_EMPTY: case HashMapState_DELETED: continue; case HashMapState_FILLED: if (!LookupKey(map, oldKey, &newHeader, &newData, &freeIndex)) { GetEntry(map, freeIndex, &newHeader, &newKey, &newData); newHeader->hash = oldHeader->hash; newHeader->state = HashMapState_FILLED; memcpy(newKey, oldKey, map->keySize); memcpy(newData, oldData, map->dataSize); map->count++; } else { /* * There is only one way that this could happen; the key is in the * old map twice. That's clearly an error. */ ASSERT(FALSE); continue; } } } ASSERT(oldHashMap.count == map->count); free(oldHashMap.entries); EnsureSanity(map); } /* * ---------------------------------------------------------------------------- * * HashMap_Iterate -- * * Iterate over the contents of the map, optionally clearing each entry as * it's passed. * * Results: * None. * * Side Effects: * itFn is called for each entry in the hashMap until. If clear is TRUE, * each entry will be removed from the map after it has been seen by the * iterator function. * * ---------------------------------------------------------------------------- */ void HashMap_Iterate(HashMap *map, // IN HashMapIteratorFn itFn, // IN Bool clear, // IN void *userData) // IN/OUT { int i = 0; HashMapEntryHeader *header; void *key, *data; ASSERT(map); ASSERT(itFn); for (i = 0; i < map->numEntries; i++) { GetEntry(map, i, &header, &key, &data); if (header->state == HashMapState_FILLED) { itFn(key, data, userData); if (clear) { map->count--; } } if (clear) { header->state = HashMapState_EMPTY; } } ASSERT(map->count == 0 || !clear); } /* * ---------------------------------------------------------------------------- * * EnsureSanity -- * * Ensure that the HashMap contents are still sane. That is, each entry has * a correctly computed hash, the count is correct and the header states are * valid for all entries. This should be called at the end of every * function which modifies the map. * * Results: * None. * * Side Effects: * Fails an assert if the contents are incorrect. * * ---------------------------------------------------------------------------- */ void EnsureSanity(HashMap *map) { ASSERT(CheckSanity(map) == TRUE); } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/000077500000000000000000000000001321503522500217735ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/Makefile.am000066400000000000000000000022511321503522500240270ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libHgfs.la libHgfs_la_SOURCES = libHgfs_la_SOURCES += cpName.c libHgfs_la_SOURCES += cpNameLite.c libHgfs_la_SOURCES += cpNameLinux.c libHgfs_la_SOURCES += cpNameUtil.c libHgfs_la_SOURCES += cpNameUtilLinux.c libHgfs_la_SOURCES += hgfsUtil.c libHgfs_la_SOURCES += hgfsEscape.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/cpName.c000066400000000000000000000325561321503522500233550ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpName.c -- * * Shared portions of cross-platform name conversion routines used * by hgfs. [bac] * */ #ifdef sun #include #endif #include "cpName.h" #include "cpNameInt.h" #include "vm_assert.h" #include "hgfsEscape.h" /* *---------------------------------------------------------------------- * * CPName_GetComponent -- * * Get the next component of the CP name. * * Returns the length of the component starting with the begin * pointer, and a pointer to the next component in the buffer, if * any. The "next" pointer is set to "end" if there is no next * component. * * Results: * length (not including NUL termination) >= 0 of next * component on success. * error < 0 on failure (invalid component). * * Side effects: * None * *---------------------------------------------------------------------- */ int CPName_GetComponent(char const *begin, // IN: Beginning of buffer char const *end, // IN: End of buffer char const **next) // OUT: Start of next component { char const *walk; char const *myNext; size_t len; ASSERT(begin); ASSERT(end); ASSERT(next); ASSERT(begin <= end); for (walk = begin; ; walk++) { if (walk == end) { /* End of buffer. No NUL was found */ myNext = end; break; } if (*walk == '\0') { /* Found a NUL */ if (walk == begin) { Log("%s: error: first char can't be NUL\n", __FUNCTION__); return -1; } myNext = walk + 1; /* Skip consecutive path delimiters. */ while ((*myNext == '\0') && (myNext != end)) { myNext++; } if (myNext == end) { /* Last character in the buffer is not allowed to be NUL */ Log("%s: error: last char can't be NUL\n", __FUNCTION__); return -1; } break; } } len = walk - begin; *next = myNext; return (int) len; } /* *---------------------------------------------------------------------- * * CPNameEscapeAndConvertFrom -- * * Converts a cross-platform name representation into a string for * use in the local filesystem. * Escapes illegal characters as a part of convertion. * This is a cross-platform implementation and takes the path separator * argument as an argument. The path separator is prepended before each * additional path component, so this function never adds a trailing path * separator. * * Results: * 0 on success. * error < 0 on failure (the converted string did not fit in * the buffer provided or the input was invalid). * * Side effects: * None * *---------------------------------------------------------------------- */ int CPNameEscapeAndConvertFrom(char const **bufIn, // IN/OUT: Input to convert size_t *inSize, // IN/OUT: Size of input size_t *outSize, // IN/OUT: Size of output buffer char **bufOut, // IN/OUT: Output buffer char pathSep) // IN: Path separator character { int result; int inputSize; inputSize = HgfsEscape_GetSize(*bufIn, *inSize); if (inputSize < 0) { result = -1; } else if (inputSize != 0) { char *savedBufOut = *bufOut; char const *savedOutConst = savedBufOut; size_t savedOutSize = *outSize; if (inputSize > *outSize) { Log("%s: error: not enough room for escaping\n", __FUNCTION__); return -1; } /* Leaving space for the leading path separator, thus output to savedBufOut + 1. */ *inSize = HgfsEscape_Do(*bufIn, *inSize, savedOutSize, savedBufOut + 1); result = CPNameConvertFrom(&savedOutConst, inSize, outSize, bufOut, pathSep); *bufIn += *inSize; *inSize = 0; } else { result = CPNameConvertFrom(bufIn, inSize, outSize, bufOut, pathSep); } return result; } /* *---------------------------------------------------------------------- * * CPNameConvertFrom -- * * Converts a cross-platform name representation into a string for * use in the local filesystem. This is a cross-platform * implementation and takes the path separator argument as an * argument. The path separator is prepended before each additional * path component, so this function never adds a trailing path * separator. * * Results: * 0 on success. * error < 0 on failure (the converted string did not fit in * the buffer provided or the input was invalid). * * Side effects: * None * *---------------------------------------------------------------------- */ int CPNameConvertFrom(char const **bufIn, // IN/OUT: Input to convert size_t *inSize, // IN/OUT: Size of input size_t *outSize, // IN/OUT: Size of output buffer char **bufOut, // IN/OUT: Output buffer char pathSep) // IN: Path separator character { char const *in; char const *inEnd; size_t myOutSize; char *out; Bool inPlaceConvertion = (*bufIn == *bufOut); ASSERT(bufIn); ASSERT(inSize); ASSERT(outSize); ASSERT(bufOut); in = *bufIn; if (inPlaceConvertion) { in++; // Skip place for the leading path separator. } inEnd = in + *inSize; myOutSize = *outSize; out = *bufOut; for (;;) { char const *next; int len; int newLen; len = CPName_GetComponent(in, inEnd, &next); if (len < 0) { Log("%s: error: get next component failed\n", __FUNCTION__); return len; } /* Bug 27926 - preventing escaping from shared folder. */ if ((len == 1 && *in == '.') || (len == 2 && in[0] == '.' && in[1] == '.')) { Log("%s: error: found dot/dotdot\n", __FUNCTION__); return -1; } if (len == 0) { /* No more component */ break; } newLen = ((int) myOutSize) - len - 1; if (newLen < 0) { Log("%s: error: not enough room\n", __FUNCTION__); return -1; } myOutSize = (size_t) newLen; *out++ = pathSep; if (!inPlaceConvertion) { memcpy(out, in, len); } out += len; in = next; } /* NUL terminate */ if (myOutSize < 1) { Log("%s: error: not enough room\n", __FUNCTION__); return -1; } *out = '\0'; /* Path name size should not require more than 4 bytes. */ ASSERT((in - *bufIn) <= 0xFFFFFFFF); /* Update pointers. */ *inSize -= (in - *bufIn); *outSize = myOutSize; *bufIn = in; *bufOut = out; return 0; } /* *---------------------------------------------------------------------------- * * CPName_Print -- * * Converts a CPName formatted string to a valid, NUL-terminated string by * replacing all embedded NUL characters with '|'. * * Results: * Pointer to a static buffer containing the converted string. * * Side effects: * None. * *---------------------------------------------------------------------------- */ char const * CPName_Print(char const *in, // IN: Name to print size_t size) // IN: Size of name { /* Static so it does not go on a kernel stack --hpreg */ static char out[128]; size_t i; ASSERT(in); ASSERT(sizeof out >= 4); if (size > sizeof out - 1) { size = sizeof out - 4; out[size] = '.'; out[size + 1] = '.'; out[size + 2] = '.'; out[size + 3] = '\0'; } else { out[size] = '\0'; } for (i = 0; i < size; i++) { out[i] = in[i] != '\0' ? in[i] : '|'; } return out; } /* *---------------------------------------------------------------------------- * * CPName_LinuxConvertTo -- * * Wrapper function that calls CPNameConvertTo() with the correct arguments * for Linux path conversions. * * Makes a cross-platform name representation from the Linux path input * string and writes it into the output buffer. * * Results: * On success, returns the number of bytes used in the cross-platform name, * NOT including the final terminating NUL character. On failure, returns * a negative error. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int CPName_LinuxConvertTo(char const *nameIn, // IN: Buf to convert size_t bufOutSize, // IN: Size of the output buffer char *bufOut) // OUT: Output buffer { return CPNameConvertTo(nameIn, bufOutSize, bufOut, '/'); } /* *---------------------------------------------------------------------------- * * CPName_WindowsConvertTo -- * * Wrapper function that calls CPNameConvertTo() with the correct arguments * for Windows path conversions. * * Makes a cross-platform name representation from the Linux path input * string and writes it into the output buffer. * * Results: * On success, returns the number of bytes used in the cross-platform name, * NOT including the final terminating NUL character. On failure, returns * a negative error. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int CPName_WindowsConvertTo(char const *nameIn, // IN: Buf to convert size_t bufOutSize, // IN: Size of the output buffer char *bufOut) // OUT: Output buffer { return CPNameConvertTo(nameIn, bufOutSize, bufOut, '\\'); } /* *---------------------------------------------------------------------- * * CPNameConvertTo -- * * Makes a cross-platform name representation from the input string * and writes it into the output buffer. * HGFS convention is to echange names between guest and host in uescaped form. * Both ends perform necessary name escaping according to its own rules * to avoid presenitng invalid file names to OS. Thus the name needs to be unescaped * as a part of conversion to host-independent format. * * Results: * On success, returns the number of bytes used in the * cross-platform name, NOT including the final terminating NUL * character. On failure, returns a negative error. * * Side effects: * None * *---------------------------------------------------------------------- */ int CPNameConvertTo(char const *nameIn, // IN: Buf to convert size_t bufOutSize, // IN: Size of the output buffer char *bufOut, // OUT: Output buffer char pathSep) // IN: path separator to use { char *origOut = bufOut; char const *endOut = bufOut + bufOutSize; size_t cpNameLength = 0; ASSERT(nameIn); ASSERT(bufOut); /* Skip any path separators at the beginning of the input string */ while (*nameIn == pathSep) { nameIn++; } /* * Copy the string to the output buf, converting all path separators into '\0'. * Collapse multiple consecutive path separators into a single one since * CPName_GetComponent can't handle consecutive path separators. */ while (*nameIn != '\0' && bufOut < endOut) { if (*nameIn == pathSep) { *bufOut = '\0'; do { nameIn++; } while (*nameIn == pathSep); } else { *bufOut = *nameIn; nameIn++; } bufOut++; } /* * NUL terminate. XXX This should go away. * * When we get rid of NUL termination here, this test should * also change to "if (*nameIn != '\0')". */ if (bufOut == endOut) { return -1; } *bufOut = '\0'; /* Path name size should not require more than 4 bytes. */ ASSERT((bufOut - origOut) <= 0xFFFFFFFF); /* If there were any trailing path separators, dont count them [krishnan] */ cpNameLength = bufOut - origOut; while ((cpNameLength >= 1) && (origOut[cpNameLength - 1] == 0)) { cpNameLength--; } cpNameLength = HgfsEscape_Undo(origOut, cpNameLength); /* Return number of bytes used */ return (int) cpNameLength; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/cpNameInt.h000066400000000000000000000052101321503522500240200ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpNameInt.h -- * * Cross-platform name format used by hgfs. * */ #ifndef __CP_NAME_INT_H__ #define __CP_NAME_INT_H__ #include "vm_basic_types.h" /* * Used by CPName_ConvertFrom */ int CPNameConvertFrom(char const **bufIn, // IN/OUT: Input to convert size_t *inSize, // IN/OUT: Size of input size_t *outSize, // IN/OUT: Size of output buffer char **bufOut, // IN/OUT: Output buffer char pathSep); // IN: Path separator character int CPNameEscapeAndConvertFrom(char const **bufIn, // IN/OUT: Input to convert size_t *inSize, // IN/OUT: Size of input size_t *outSize, // IN/OUT: Size of output buffer char **bufOut, // IN/OUT: Output buffer char pathSep); // IN: Path separator character /* * Common code for CPName_ConvertTo */ int CPNameConvertTo(char const *nameIn, // IN: Buf to convert size_t bufOutSize, // IN: Size of the output buffer char *bufOut, // OUT: Output buffer char pathSep); // IN: path separator to use #endif /* __CP_NAME_INT_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/cpNameLinux.c000066400000000000000000000127561321503522500243750ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpNameLinux.c -- * * Linux implementation of cross-platform name conversion * routines used by hgfs. [bac] * */ #if defined sun && !defined SOL9 #include #endif #include "cpName.h" #include "cpNameInt.h" #include "vm_assert.h" #include "hgfsEscape.h" /* *---------------------------------------------------------------------- * * CPName_ConvertFrom -- * * Converts a cross-platform name representation into a string for * use in the local filesystem. * * Results: * Length (not including NUL termination) >= 0 of resulting * string on success. * Negative error on failure (the converted string did not fit in * the buffer provided or the input was invalid). * * Side effects: * None * *---------------------------------------------------------------------- */ int CPName_ConvertFrom(char const **bufIn, // IN/OUT: Input to convert size_t *inSize, // IN/OUT: Size of input size_t *outSize, // IN/OUT: Size of output buffer char **bufOut) // IN/OUT: Output buffer { ASSERT(bufIn); ASSERT(inSize); ASSERT(outSize); ASSERT(bufOut); return CPNameEscapeAndConvertFrom(bufIn, inSize, outSize, bufOut, '/'); } /* *---------------------------------------------------------------------- * * CPName_ConvertFromRoot -- * * Append the appropriate prefix to the output buffer for accessing * the root of the local filesystem. CPName_ConvertFrom prepends * leading path separators before each path component, but only * when the next component has nonzero length, so we still need to * special case this for Linux. * * The pointers and sizes are updated appropriately. * * Results: * Status of name conversion * * Side effects: * None * *---------------------------------------------------------------------- */ HgfsNameStatus CPName_ConvertFromRoot(char const **bufIn, // IN/OUT: Input to convert size_t *inSize, // IN/OUT: Size of input size_t *outSize, // IN/OUT: Size of output buffer char **bufOut) // IN/OUT: Output buffer { char const *next; char *out; int len; ASSERT(bufIn); ASSERT(inSize); ASSERT(outSize); ASSERT(bufOut); out = *bufOut; /* * Get first component */ len = CPName_GetComponent(*bufIn, *bufIn + *inSize, &next); if (len < 0) { Log("%s: get first component failed\n", __FUNCTION__); return HGFS_NAME_STATUS_FAILURE; } /* Space for leading '/' plus NUL termination */ if (*outSize < len + 2) { return HGFS_NAME_STATUS_FAILURE; } /* Put a leading '/' in the output buffer either way */ *out++ = '/'; memcpy(out, *bufIn, len); out += len; /* NUL terminate */ *out = '\0'; *inSize -= next - *bufIn; *outSize -= out - *bufOut; *bufIn = next; *bufOut = out; return HGFS_NAME_STATUS_COMPLETE; } /* *---------------------------------------------------------------------------- * * CPName_ConvertTo -- * * Wrapper function that calls the Linux implementation of _ConvertTo(). * * Makes a cross-platform name representation from the Linux path input * string and writes it into the output buffer. * If the name being converter may be a result a of name escaping the * function performs unescaping. HGFS convention is to always exchange * unescaped names between guest and host and to perform necessary * name escaping on both ends. * * Results: * On success, returns the number of bytes used in the * cross-platform name, NOT including the final terminating NUL * character. On failure, returns a negative error. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int CPName_ConvertTo(char const *nameIn, // IN: Buf to convert size_t bufOutSize, // IN: Size of the output buffer char *bufOut) // OUT: Output buffer { int result; result = CPName_LinuxConvertTo(nameIn, bufOutSize, bufOut); return result; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/cpNameLite.c000066400000000000000000000062421321503522500241640ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpNameLite.c -- * * Shared portions of cross-platform name conversion routines used * by hgfs. Unlike the real CP name conversion routines, these ones * just convert path separators to nul characters and vice versa. * */ #include "cpNameLite.h" #include "vm_assert.h" /* *---------------------------------------------------------------------- * * CPNameLite_ConvertTo -- * * Makes a cross-platform lite name representation from the input * string. * * Results: * None * * Side effects: * None * *---------------------------------------------------------------------- */ void CPNameLite_ConvertTo(char *bufIn, // IN/OUT: Input to convert size_t inSize, // IN: Size of input buffer char pathSep) // IN: Path separator { size_t pos; ASSERT(bufIn); for (pos = 0; pos < inSize; pos++) { if (bufIn[pos] == pathSep) { bufIn[pos] = '\0'; } } } /* *---------------------------------------------------------------------- * * CPNameLite_ConvertFrom -- * * Converts a cross-platform lite name representation into a string for * use in the local filesystem. This is a cross-platform * implementation and takes the path separator as an * argument. * * Results: * None * * Side effects: * None * *---------------------------------------------------------------------- */ void CPNameLite_ConvertFrom(char *bufIn, // IN/OUT: Input to convert size_t inSize, // IN: Size of input buffer char pathSep) // IN: Path separator { size_t pos; ASSERT(bufIn); for (pos = 0; pos < inSize; pos++) { if (bufIn[pos] == '\0') { bufIn[pos] = pathSep; } } } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/cpNameUtil.c000066400000000000000000000255341321503522500242110ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpNameUtil.c * * Common implementations of CPName utility functions. */ /* Some of the headers below cannot be included in driver code */ #if !defined __KERNEL__ && !defined _KERNEL && !defined KERNEL #include "cpNameUtil.h" #include "hgfsServerPolicy.h" #include "hgfsVirtualDir.h" #include "util.h" #include "vm_assert.h" #include "str.h" #include "cpNameUtilInt.h" #define WIN_DIRSEPC '\\' #define WIN_DIRSEPS "\\" /* *---------------------------------------------------------------------------- * * CPNameUtil_Strrchr -- * * Performs strrchr(3) on a CPName path. * * Results: * Pointer to last occurrence of searchChar in cpNameIn if found, NULL if * not found. * * Side effects: * None. * *---------------------------------------------------------------------------- */ char * CPNameUtil_Strrchr(char const *cpNameIn, // IN: CPName path to search size_t cpNameInSize, // IN: Size of CPName path char searchChar) // IN: Character to search for { ssize_t index; ASSERT(cpNameIn); ASSERT(cpNameInSize > 0); for (index = cpNameInSize - 1; cpNameIn[index] != searchChar && index >= 0; index--); return (index < 0) ? NULL : (char *)(cpNameIn + index); } /* *---------------------------------------------------------------------------- * * CPNameUtil_LinuxConvertToRoot -- * * Performs CPName conversion and such that the result can be converted back * to an absolute path (in the "root" share) by a Linux hgfs server. * * Note that nameIn must contain an absolute path. * * Results: * Size of the output buffer on success, negative value on error * * Side effects: * None. * *---------------------------------------------------------------------------- */ int CPNameUtil_LinuxConvertToRoot(char const *nameIn, // IN: buf to convert size_t bufOutSize, // IN: size of the output buffer char *bufOut) // OUT: output buffer { const size_t shareNameSize = HGFS_STR_LEN(HGFS_SERVER_POLICY_ROOT_SHARE_NAME); int result; ASSERT(nameIn); ASSERT(bufOut); if (bufOutSize <= shareNameSize) { return -1; } /* Prepend the name of the "root" share directly in the output buffer */ memcpy(bufOut, HGFS_SERVER_POLICY_ROOT_SHARE_NAME, shareNameSize); bufOut[shareNameSize] = '\0'; result = CPName_LinuxConvertTo(nameIn, bufOutSize - shareNameSize - 1, bufOut + shareNameSize + 1); /* Return either the same error code or the correct size */ return (result < 0) ? result : (int)(result + shareNameSize + 1); } /* *---------------------------------------------------------------------------- * * CPNameUtil_WindowsConvertToRoot -- * * Performs CPName conversion and appends necessary strings ("root" and * "drive"|"unc") so that the result can be converted back to an absolute * path (in the "root" share) by a Windows hgfs server. * * Note that nameIn must contain an absolute path. * * Results: * Size of the output buffer on success, negative value on error * * Side effects: * None. * *---------------------------------------------------------------------------- */ int CPNameUtil_WindowsConvertToRoot(char const *nameIn, // IN: buf to convert size_t bufOutSize, // IN: size of the output buffer char *bufOut) // OUT: output buffer { const char partialName[] = HGFS_SERVER_POLICY_ROOT_SHARE_NAME; const size_t partialNameLen = HGFS_STR_LEN(HGFS_SERVER_POLICY_ROOT_SHARE_NAME); const char *partialNameSuffix = ""; size_t partialNameSuffixLen; char *fullName; size_t fullNameLen; size_t nameLen; int result; ASSERT(nameIn); ASSERT(bufOut); /* * Create the full name. Note that Str_Asprintf should not be * used here as it uses FormatMessages which interprets 'data', a UTF-8 * string, as a string in the current locale giving wrong results. */ /* * Is this file path a UNC path? */ if (nameIn[0] == WIN_DIRSEPC && nameIn[1] == WIN_DIRSEPC) { partialNameSuffix = WIN_DIRSEPS HGFS_UNC_DIR_NAME WIN_DIRSEPS; partialNameSuffixLen = HGFS_STR_LEN(WIN_DIRSEPS) + HGFS_STR_LEN(HGFS_UNC_DIR_NAME) + HGFS_STR_LEN(WIN_DIRSEPS); } else { partialNameSuffix = WIN_DIRSEPS HGFS_DRIVE_DIR_NAME WIN_DIRSEPS; partialNameSuffixLen = HGFS_STR_LEN(WIN_DIRSEPS) + HGFS_STR_LEN(HGFS_DRIVE_DIR_NAME) + HGFS_STR_LEN(WIN_DIRSEPS); } /* Skip any path separators at the beginning of the input string */ while (*nameIn == WIN_DIRSEPC) { nameIn++; } nameLen = strlen(nameIn); fullNameLen = partialNameLen + partialNameSuffixLen + nameLen; fullName = (char *)Util_SafeMalloc(fullNameLen + 1); memcpy(fullName, partialName, partialNameLen); memcpy(fullName + partialNameLen, partialNameSuffix, partialNameSuffixLen); if (nameIn[1] == ':') { /* * If the name is in format ":" strip out ':' from it * because the rest of the code assumes that driver letter in a * platform independent name is represented by a single character without colon. */ fullName[partialNameLen + partialNameSuffixLen] = nameIn[0]; memcpy(fullName + partialNameLen + partialNameSuffixLen + 1, nameIn + 2, nameLen - 2); fullNameLen--; } else { memcpy(fullName + partialNameLen + partialNameSuffixLen, nameIn, nameLen); } fullName[fullNameLen] = '\0'; /* CPName_ConvertTo strips out the ':' character */ result = CPName_WindowsConvertTo(fullName, bufOutSize, bufOut); free(fullName); return result; } /* *---------------------------------------------------------------------------- * * CPNameUtil_Utf8FormHostToUtf8FormC -- * * Convert CPname to form C (precomposed) which is used by the HGFS * protocol from host preferred format. On Mac hosts the current format * is unicode form D, so conversion is required, others the current * format is the same. * * Input/output name lengths include the nul-terminator so that the * conversion routine will include the final character when breaking * up the CPName into it's individual components. * * * Results: * TRUE if success result string is in form C format, FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool CPNameUtil_Utf8FormHostToUtf8FormC(const char *cpNameToConvert, // IN: size_t cpNameToConvertLen, // IN: includes nul char **cpUtf8FormCName, // OUT: size_t *cpUtf8FormCNameLen) // OUT: includes nul { return CPNameUtilConvertUtf8FormCAndD(cpNameToConvert, cpNameToConvertLen, TRUE, cpUtf8FormCName, cpUtf8FormCNameLen); } /* *---------------------------------------------------------------------------- * * CPNameUtil_Utf8FormCToUtf8FormHost -- * * Convert from CP unicode form C (decomposed) name used by the HGFS * protocol to the host preferred format. On Mac OS is unicode form D * (precomposed), everyone else this stays as form C (precomposed). * * Input/output name lengths include the nul-terminator so that the * conversion routine will include the final character when breaking * up the CPName into it's individual components. * * Results: * TRUE if success result string is in CP format, FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool CPNameUtil_Utf8FormCToUtf8FormHost(const char *cpUtf8FormCName, // IN: size_t cpUtf8FormCNameLen, // IN: includes nul char **cpConvertedName, // OUT: size_t *cpConvertedNameLen) // OUT: includes nul { return CPNameUtilConvertUtf8FormCAndD(cpUtf8FormCName, cpUtf8FormCNameLen, FALSE, cpConvertedName, cpConvertedNameLen); } /* *---------------------------------------------------------------------------- * * CPNameUitl_CharReplace -- * * A simple function to replace all oldChar's with newChar's in a binary * buffer. This is used for either replacing NULL with local DIRSPEC to * convert from relative cross-platform name to local relative name, or * replacing local DIRSEPC with NULL to convert from local relative name * to relative cross-platform file name * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ void CPNameUtil_CharReplace(char *buf, // IN/OUT size_t bufSize, // IN char oldChar, // IN char newChar) // IN { size_t i; ASSERT(buf); for (i = 0; i < bufSize; i++) { if (buf[i] == oldChar) { buf[i] = newChar; } } } #endif /* __KERNEL__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/cpNameUtilInt.h000066400000000000000000000037751321503522500246740ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpNameUtilInt.h -- * * Cross-platform name format used by hgfs. * */ #ifndef __CP_NAME_UTIL_INT_H__ #define __CP_NAME_UTIL_INT_H__ #include "vm_basic_types.h" /* * Used by CPNameUtil_Utf8FormHostToUtf8FormC and * CPNameUtil_Utf8FormCToUtf8FormHost. */ Bool CPNameUtilConvertUtf8FormCAndD(const char *cpNameToConvert, size_t cpNameToConvertLen, Bool convertToFormC, char **cpConvertedName, size_t *cpConvertedNameLen); #endif /* __CP_NAME_UTIL_INT_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/cpNameUtilLinux.c000066400000000000000000000140201321503522500252150ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpNameUtilLinux.c * * Linux implementation of CPName utility functions. These are not included * in the main CPName API since they may require other calls on the * resulting CPName to be from the same OS-type. */ /* Some of the headers in cpNameUtil.c cannot be included in driver code */ #if !defined __KERNEL__ && !defined _KERNEL && !defined KERNEL #include "cpNameUtil.h" #include "cpNameUtilInt.h" #if defined __APPLE__ #include "codeset.h" #endif /* defined __APPLE__ */ #include "util.h" /* *---------------------------------------------------------------------------- * * CPNameUtil_ConvertToRoot -- * * Pass through function that calls Linux version of _ConvertToRoot(). * * Performs CPName conversion and such that the result can be converted back * to an absolute path (in the "root" share) by a Linux hgfs server. * * Note that nameIn must contain an absolute path. * * Results: * Size of the output buffer on success, negative value on error. * * Side effects: * None. * *---------------------------------------------------------------------------- */ int CPNameUtil_ConvertToRoot(char const *nameIn, // IN: buf to convert size_t bufOutSize, // IN: size of the output buffer char *bufOut) // OUT: output buffer { return CPNameUtil_LinuxConvertToRoot(nameIn, bufOutSize, bufOut); } /* *---------------------------------------------------------------------------- * * CPNameUtilConvertUtf8FormCAndD -- * * Helper conversion routine to convert between a CP format name * in unicode form C (precomposed) format which is used by the HGFS * protocol requests and the unicode form D (decomposed) format, * which is used on Mac OS host (everyone else uses form C). * * Results: * TRUE if success result string is converted, FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool CPNameUtilConvertUtf8FormCAndD(const char *cpNameToConvert, // IN: size_t cpNameToConvertLen, // IN: includes nul Bool convertToFormC, // IN: char **cpConvertedName, // OUT: size_t *cpConvertedNameLen) // OUT: includes nul { Bool status = TRUE; #if defined __APPLE__ const char *begin; const char *end; const char *next; char *newData = NULL; char *convertedName = NULL; size_t convertedNameLen; uint32 newDataLen = 0; int len; ASSERT(cpNameToConvert); ASSERT(cpConvertedName); ASSERT(cpConvertedNameLen); /* * Get first component. We bypass the higher level CPName_GetComponent * function so we'll have more control over the illegal characters. */ begin = cpNameToConvert; end = cpNameToConvert + cpNameToConvertLen - 1; /* Get the length of this component, and a pointer to the next. */ while ((len = CPName_GetComponent(begin, end, &next)) != 0) { uint32 origNewDataLen = newDataLen; if (len < 0) { status = FALSE; goto exit; } if (convertToFormC) { status = CodeSet_Utf8FormDToUtf8FormC(begin, len, &convertedName, &convertedNameLen); } else { status = CodeSet_Utf8FormCToUtf8FormD(begin, len, &convertedName, &convertedNameLen); } if (!status) { goto exit; } /* * Append this component to our list: allocate one more for NUL. */ newDataLen += convertedNameLen + 1; newData = (char *)Util_SafeRealloc(newData, newDataLen); memcpy(newData + origNewDataLen, convertedName, convertedNameLen); newData[newDataLen - 1] = '\0'; free(convertedName); convertedName = NULL; begin = next; } *cpConvertedName = newData; /* Including nul terminator */ *cpConvertedNameLen = newDataLen; exit: if (!status) { if (newData != NULL) { free(newData); } } #else /* defined __APPLE__ */ /* No conversion required return a copy of what is received. */ *cpConvertedName = Util_SafeCalloc(1, cpNameToConvertLen); memcpy(*cpConvertedName, cpNameToConvert, cpNameToConvertLen); *cpConvertedNameLen = cpNameToConvertLen; #endif /* defined __APPLE__ */ return status; } #endif /* __KERNEL__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/hgfsEscape.c000066400000000000000000000765351321503522500242270ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsEscape.c -- * * Escape and unescape illegal filenames for different platforms. * */ #ifdef __KERNEL__ # include "driver-config.h" # include #elif defined __FreeBSD__ # if defined _KERNEL # include # define strchr(s,c) index(s,c) # else # include # endif # define memmove(s1,s2,n) bcopy(s2,s1,n) #elif defined __APPLE__ && defined KERNEL # include #elif !defined sun # include # include #else # include #endif #include "vmware.h" #include "hgfsEscape.h" #include "cpName.h" #ifdef _WIN32 #define UNREFERENCED_PARAMETER(P) (P) /* These characters are illegal in Windows file names. */ const char* HGFS_ILLEGAL_CHARS = "/\\*?:\"<>|"; const char* HGFS_SUBSTITUTE_CHARS = "!@#$^&(){}"; /* Last character of a file name in Windows can be neither dot nor space. */ const char* HGFS_ILLEGAL_LAST_CHARS = ". "; /* http://msdn.microsoft.com/en-us/library/aa365247.aspx */ char *HgfsReservedNames[] = {"CON", "PRN", "AUX", "NUL"}; char *HgfsReservedNamesWithNumber[] = {"COM", "LPT"}; #define HGFS_RESERVED_NAME_CHARS_LENGTH 3 #define HGFS_RESERVED_NAME_WITH_NUMBER_CHARS_LENGTH (HGFS_RESERVED_NAME_CHARS_LENGTH + 1) /* Check for special escaping cases - reserved names and illegal last characters. */ #define IS_SPECIAL_CASE_ESCAPE(b,o,l) HgfsIsSpecialCaseEscape(b,o,l) /* Process Windows reserved names. */ #define PROCESS_RESERVED_NAME(b,s,p,o,c) \ if (!HgfsProcessReservedName(b,s,p,o,c)) \ { \ return FALSE; \ } /* Process Windows reserved names. */ #define PROCESS_LAST_CHARACTER(b,s,p,c) \ if (!HgfsProcessLastCharacter(b,s,p,c)) \ { \ return FALSE; \ } #else // _WIN32 #define UNREFERENCED_PARAMETER(P) /* There is no special escape sequences on other than Windows platforms. */ #define IS_SPECIAL_CASE_ESCAPE(b,o,l) FALSE /* There is no reserved names on other then Windows platforms. */ #define PROCESS_RESERVED_NAME(b,s,p,o,c) /* There is no special processing for the last character on non-Windows platforms. */ #define PROCESS_LAST_CHARACTER(b,s,p,c) #if defined __APPLE__ /* These characters are illegal in MAC OS file names. */ const char* HGFS_ILLEGAL_CHARS = "/:"; const char* HGFS_SUBSTITUTE_CHARS = "!&"; #else // __APPLE__ /* These characters are illegal in Linux file names. */ const char* HGFS_ILLEGAL_CHARS = "/"; const char* HGFS_SUBSTITUTE_CHARS = "!"; #endif // __APPLE__ #endif // _WIN32 #define HGFS_ESCAPE_CHAR '%' #define HGFS_ESCAPE_SUBSTITUE_CHAR ']' typedef enum { HGFS_ESCAPE_ILLEGAL_CHARACTER, HGFS_ESCAPE_RESERVED_NAME, HGFS_ESCAPE_ILLEGAL_LAST_CHARACTER, HGFS_ESCAPE_ESCAPE_SEQUENCE, HGFS_ESCAPE_COMPLETE } HgfsEscapeReason; typedef Bool (*HgfsEnumCallback)(char const *bufIn, uint32 offset, HgfsEscapeReason reason, void* context); /* * The structure is used by HgfsAddEscapeCharacter to keep context information between * invocations * All offsets defined in this structure are in characters, not bytes */ typedef struct { uint32 processedOffset; // Offset of the first unprocessed input character uint32 outputBufferLength; // Number of characters in the output buffer uint32 outputOffset; // Number of characters that are already in the output char *outputBuffer; // Pointer to the output buffer } HgfsEscapeContext; static void HgfsEscapeUndoComponent(char *bufIn, uint32 *totalLength); static int HgfsEscapeGetComponentSize(char const *bufIn, uint32 sizeIn); static int HgfsEscapeDoComponent(char const *bufIn, uint32 sizeIn, uint32 sizeBufOut, char *bufOut); /* *----------------------------------------------------------------------------- * * HgfsAddEscapeCharacter -- * * Callback function that is called by HgfsEnumerate to insert an escape sequence * into the input name. * * Results: * TRUE if successful, FALSE if there is an error like the output buffer is * too small. * * Side effects: * Updates the output buffer pointer (stored in the context variable). * *----------------------------------------------------------------------------- */ static Bool HgfsAddEscapeCharacter(char const * bufIn, // IN: input name uint32 offset, // IN: offset that requires escaping HgfsEscapeReason reason, // IN: reason for esaping void *context) // IN/OUT: convertion context { HgfsEscapeContext *escapeContext = (HgfsEscapeContext *)context; uint32 charactersToCopy; uint32 outputSpace; char* illegal; Bool result = TRUE; ASSERT(offset >= escapeContext->processedOffset); // Scanning forward charactersToCopy = offset - escapeContext->processedOffset; if (escapeContext->outputOffset + charactersToCopy > escapeContext->outputBufferLength) { return FALSE; } memcpy(escapeContext->outputBuffer + escapeContext->outputOffset, bufIn + escapeContext->processedOffset, charactersToCopy * sizeof *bufIn); escapeContext->outputOffset += charactersToCopy; escapeContext->processedOffset += charactersToCopy; outputSpace = escapeContext->outputBufferLength - escapeContext->outputOffset; switch(reason) { case HGFS_ESCAPE_ILLEGAL_CHARACTER: if (outputSpace < 2) { return FALSE; } illegal = strchr(HGFS_ILLEGAL_CHARS, bufIn[escapeContext->processedOffset]); escapeContext->processedOffset++; // Skip illegal input character ASSERT(illegal != NULL); escapeContext->outputBuffer[escapeContext->outputOffset] = HGFS_SUBSTITUTE_CHARS[illegal - HGFS_ILLEGAL_CHARS]; escapeContext->outputOffset++; escapeContext->outputBuffer[escapeContext->outputOffset] = HGFS_ESCAPE_CHAR; escapeContext->outputOffset++; break; case HGFS_ESCAPE_RESERVED_NAME: if (outputSpace < 1) { return FALSE; } escapeContext->outputBuffer[escapeContext->outputOffset] = HGFS_ESCAPE_CHAR; escapeContext->outputOffset++; break; case HGFS_ESCAPE_ILLEGAL_LAST_CHARACTER: if (outputSpace < 1) { return FALSE; } escapeContext->outputBuffer[escapeContext->outputOffset] = HGFS_ESCAPE_CHAR; escapeContext->outputOffset++; break; case HGFS_ESCAPE_ESCAPE_SEQUENCE: if (outputSpace < 2) { return FALSE; } escapeContext->processedOffset++; // Skip input esape character escapeContext->outputBuffer[escapeContext->outputOffset] = HGFS_ESCAPE_SUBSTITUE_CHAR; escapeContext->outputOffset++; escapeContext->outputBuffer[escapeContext->outputOffset] = HGFS_ESCAPE_CHAR; escapeContext->outputOffset++; break; case HGFS_ESCAPE_COMPLETE: if (outputSpace < 1) { return FALSE; } escapeContext->outputBuffer[escapeContext->outputOffset] = '\0'; break; default: result = FALSE; ASSERT(FALSE); } return result; } /* *----------------------------------------------------------------------------- * * HgfsCountEscapeChars -- * * Callback function that is called by HgfsEnumerate to count additional characters * that need to be inserted in the input name. * * Results: * TRUE since it never fails. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsCountEscapeChars(char const *bufIn, // IN: input name uint32 offset, // IN: offset where escape is needed HgfsEscapeReason reason, // IN: reason for escaping void *context) // IN/OUT: context info { UNREFERENCED_PARAMETER(bufIn); UNREFERENCED_PARAMETER(offset); if (reason != HGFS_ESCAPE_COMPLETE) { uint32 *counter = (uint32*)context; (*counter)++; } return TRUE; } #ifdef _WIN32 /* *----------------------------------------------------------------------------- * * HgfsLetterToUpper -- * * Converts lowercase English letters to uppercase. * If the symbol is not a lowercase English letter returns the original character. * * Results: * Converted character. * * Side effects: * None * *----------------------------------------------------------------------------- */ static char HgfsLetterToUpper(char letter) { if (letter >= 'a' && letter <= 'z') { return letter - ('a' - 'A'); } return letter; } /* *----------------------------------------------------------------------------- * * HgfsIsEqualPrefix -- * * Verifies if the string prefix is equal to the given prefix. * It assumes that the prefix includes only uppercase English letters or numbers * and it does not have any international characters. * The string must be either NULL terminated or not shorter then the prefix. * * Results: * TRUE if the uppcased string starts with the given prefix. False otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsIsEqualPrefix(char const *prefix, // IN: prefix to check char const *string, // IN: input string uint32 prefixLength) // IN: length of the prefix in characters { int i; for (i = 0; i < prefixLength; i++) { ASSERT(prefix[i] > 0 && (prefix[i] < 'a' || prefix[i] > 'z' )); if (prefix[i] != HgfsLetterToUpper(string[i])) { return FALSE; } } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsIsReservedPrefix -- * * Verifies if the name's prefix is one of the reserved names. * * Results: * TRUE if the name's prefix is one of the reserved names. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsIsReservedPrefix(char const *bufIn) // IN: input name { uint32 i; for (i = 0; i < ARRAYSIZE(HgfsReservedNames); i++) { if (HgfsIsEqualPrefix(HgfsReservedNames[i], bufIn, HGFS_RESERVED_NAME_CHARS_LENGTH)) { return TRUE; } } return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsIsReservedPrefixWithNumber -- * * Verifies if the name's prefix is one of the reserved names with number: * COM1-9 or LPT1-9. * * Results: * TRUE if the name's prefix is one of the reserved names with number. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsIsReservedPrefixWithNumber(char const *bufIn) // IN: input name { uint32 i; for (i = 0; i < ARRAYSIZE(HgfsReservedNamesWithNumber); i++) { if (HgfsIsEqualPrefix(HgfsReservedNamesWithNumber[i], bufIn, HGFS_RESERVED_NAME_CHARS_LENGTH) && bufIn[HGFS_RESERVED_NAME_CHARS_LENGTH] >= '1' && bufIn[HGFS_RESERVED_NAME_CHARS_LENGTH] <= '9') { return TRUE; } } return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsIsSpecialCaseEscape -- * * Verifies if the escape character is a part of special case escape sequence * that exists only in Windows - escaped reserved name or escaped illegal last * character. * * Results: * TRUE if the name's prefix is one of the reserved names with number. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsIsSpecialCaseEscape(char const *bufIn, // IN: input name uint32 offset, // IN: offset of the escape character uint32 length) // IN: length of the name in characters { if (offset + 1 == length && strchr(HGFS_ILLEGAL_LAST_CHARS, bufIn[offset - 1]) != NULL) { return TRUE; } if (offset == HGFS_RESERVED_NAME_CHARS_LENGTH && (length == HGFS_RESERVED_NAME_CHARS_LENGTH + 1 || bufIn[offset+1] == '.')) { return HgfsIsReservedPrefix(bufIn); } if (offset == HGFS_RESERVED_NAME_WITH_NUMBER_CHARS_LENGTH && (length == HGFS_RESERVED_NAME_WITH_NUMBER_CHARS_LENGTH + 1 || bufIn[offset+1] == '.')) { return HgfsIsReservedPrefixWithNumber(bufIn); } return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsProcessReservedName -- * * Verifies if the name is one of reserved Windows file names. * If it is a reserved name invokes callback that performs required * processing. * * Results: * TRUE if no processing is required of if processing succeeded, * FALSE if processing failed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsProcessReservedName(char const *bufIn, // IN: Unescaped input buffer uint32 sizeIn, // IN: Length of the input HgfsEnumCallback processEscape, // IN: Callack that is invoked // if input is reserved name uint32 *offset, // OUT: New offset in the input void *context) // IN/OUT: Context for callback { /* Look reserved names: CON, PRN, AUX, NUL. */ if (sizeIn >= HGFS_RESERVED_NAME_CHARS_LENGTH && HgfsIsReservedPrefix(bufIn)) { if (HGFS_RESERVED_NAME_CHARS_LENGTH == sizeIn || bufIn[HGFS_RESERVED_NAME_CHARS_LENGTH] == '.') { if (!processEscape(bufIn, HGFS_RESERVED_NAME_CHARS_LENGTH, HGFS_ESCAPE_RESERVED_NAME, context)) { return FALSE; } *offset = HGFS_RESERVED_NAME_CHARS_LENGTH; } } /* Look reserved names with numbers: COM1-9 and LPT1-9. */ if (sizeIn >= HGFS_RESERVED_NAME_WITH_NUMBER_CHARS_LENGTH && HgfsIsReservedPrefixWithNumber(bufIn)) { if (HGFS_RESERVED_NAME_WITH_NUMBER_CHARS_LENGTH == sizeIn || bufIn[HGFS_RESERVED_NAME_WITH_NUMBER_CHARS_LENGTH] == '.') { if (!processEscape(bufIn, HGFS_RESERVED_NAME_WITH_NUMBER_CHARS_LENGTH, HGFS_ESCAPE_RESERVED_NAME, context)) { return FALSE; } *offset = HGFS_RESERVED_NAME_WITH_NUMBER_CHARS_LENGTH; } } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsProcessLastCharacter -- * * Verifies if the trailing character in the name is a valid last character. * In Windows it is illegal to have a file name that ends with dot ('.') or * space (' '). The only exception is "." and ".." directory names. * If the last character is invalid the function invokes a callback to process it. * * Results: * TRUE if no processing is required of if processing succeeded, * FALSE if processing failed. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsProcessLastCharacter(char const *bufIn, // IN: Unescaped input buffer uint32 sizeIn, // IN: Length of the input HgfsEnumCallback processEscape, // IN: Callack that is invoked // when escaping is needed void *context) // IN/OUT: Callback context { /* If the filename is '.' or '..' we shouldn't escape it. */ if ((sizeIn == 1 && bufIn[0] == '.') || (sizeIn == 2 && bufIn[0] == '.' && bufIn[1] == '.')) { return TRUE; } /* Invoke the callback if the last character is illegal. */ if (strchr(HGFS_ILLEGAL_LAST_CHARS, bufIn[sizeIn - 1]) != NULL) { if (!processEscape(bufIn, sizeIn, HGFS_ESCAPE_ILLEGAL_LAST_CHARACTER, context)) { return FALSE; } } return TRUE; } #endif // WIN32 /* *----------------------------------------------------------------------------- * * HgfsIsEscapeSequence -- * * Verifies if input buffer has an escape sequence at the position * defined by offset. * * Results: * TRUE if there is an escape sequence at the position defined by offset. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsIsEscapeSequence(char const *bufIn, // IN: input name uint32 offset, // IN: offset of the escape character uint32 length) // IN: length of the name in characters { if (bufIn[offset] == HGFS_ESCAPE_CHAR && offset > 0) { char *substitute; if (bufIn[offset - 1] == HGFS_ESCAPE_SUBSTITUE_CHAR && offset > 1) { /* * Possibly a valid sequence, check it must be preceded with a substitute * character or another escape-escape character. Otherwise, HGFS did * not generate this sequence and should leave it alone. */ if (bufIn[offset - 2] == HGFS_ESCAPE_SUBSTITUE_CHAR) { return TRUE; } substitute = strchr(HGFS_SUBSTITUTE_CHARS, bufIn[offset - 2]); if (substitute != NULL) { return TRUE; } } substitute = strchr(HGFS_SUBSTITUTE_CHARS, bufIn[offset - 1]); if (substitute != NULL) { return TRUE; } return IS_SPECIAL_CASE_ESCAPE(bufIn,offset,length); } return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsEscapeEnumerate -- * * The function scans the input buffer and calls processEscape callback for every * place in the input buffer which require escaping. * * Callback does the required processing. There are two different callbacks - * one counts extra symbols that are needed for escaping and another produces * escaped output name based on input name. * * 1. The first function calculates number of extra characters. It just increments * a counter which is passed to it in context variable every time it is called * for the reason different from "complete processing" assuming that * exactly one extra character is required to escape any invalid input. * * 2. The second function produces output name by copying everything from input * name into the output name up to the place which require escaping and * then inserts appropriate escape sequence into the output. It keeps track of its * progress and keeps pointer to the output buffer in the context variable. * HgfsEscapeEnumerate calls calback function one more time at the end of the * input buffer to let callback finish processing of the input (for example copy * the rest of the name after the last escape sequence from input buffer to * output buffer). * * Results: * TRUE if the input has been processed successfully by the callback, false otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsEscapeEnumerate(char const *bufIn, // IN: Buffer with unescaped input uint32 sizeIn, // IN: Number of input *characters* HgfsEnumCallback processEscape, // IN: Callack that is invoked every // time escaping is required void *context) // IN/OUT: Context for processEscape { /* First look for invalid characters in the input name. */ uint32 i, offset = 0; if (sizeIn == 0) { return TRUE; } ASSERT(processEscape); PROCESS_RESERVED_NAME(bufIn, sizeIn, processEscape, &offset, context); for (i = offset; i < sizeIn; i++) { if (strchr(HGFS_ILLEGAL_CHARS, bufIn[i]) != NULL) { if (!processEscape(bufIn, i, HGFS_ESCAPE_ILLEGAL_CHARACTER, context)) { return FALSE; } } else if (HgfsIsEscapeSequence(bufIn, i, sizeIn)) { if (!processEscape(bufIn, i, HGFS_ESCAPE_ESCAPE_SEQUENCE, context)) { return FALSE; } } } PROCESS_LAST_CHARACTER(bufIn, sizeIn, processEscape, context); if (!processEscape(bufIn, sizeIn, HGFS_ESCAPE_COMPLETE, context)) { return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsEscape_Do -- * * Escape any characters that are not legal in a windows filename. * Escape reserved file names that can't be used in Windows. * We also of course have to escape the escape character, which is "%", * when it is part of a character sequence that would require unescaping * * sizeBufOut must account for the NUL terminator. * * Results: * On success, the size (excluding the NUL terminator) of the * escaped, NUL terminated buffer. * On failure (bufOut not big enough to hold result), negative value. * * Side effects: * None * *----------------------------------------------------------------------------- */ int HgfsEscape_Do(char const *bufIn, // IN: Buffer with unescaped input uint32 sizeIn, // IN: Size of input buffer uint32 sizeBufOut, // IN: Size of output buffer char *bufOut) // OUT: Buffer for escaped output { const char *currentComponent = bufIn; uint32 sizeLeft = sizeBufOut; char *outPointer = bufOut; const char *end = bufIn + sizeIn; const char *next; ASSERT(sizeIn > 0); if (bufIn[sizeIn - 1] == '\0') { /* * In some cases a NUL terminated string is passed to HgfsEscape_Do * so it make sense to support such input even if CPName_GetComponent * does not. Detect this case and make the input compliant with * CPName_GetComponent by removing terminating NUL. */ end--; sizeIn--; } /* * Absolute symbolic link name starts with the '\0'. HgfsEscapeDo needs to work * with such names. Leading NULL symbols should be skipped here since * CPName_GetComponent does not support such names. */ while (*currentComponent == '\0' && currentComponent - bufIn < sizeIn) { currentComponent++; sizeLeft--; *outPointer++ = '\0'; } while (currentComponent - bufIn < sizeIn) { int escapedLength; int componentSize = CPName_GetComponent(currentComponent, end, &next); if (componentSize < 0) { return componentSize; } escapedLength = HgfsEscapeDoComponent(currentComponent, componentSize, sizeLeft, outPointer); if (escapedLength < 0) { return escapedLength; } currentComponent = next; sizeLeft -= escapedLength + 1; outPointer += escapedLength + 1; } return (int) (outPointer - bufOut) - 1; // Do not count the last NUL terminator } /* *----------------------------------------------------------------------------- * * HgfsEscape_GetSize -- * * Calculates required size in bytes for the buffer that is needed to hold escaped * cross platform path name. Returns 0 if no escaping is required. * * Results: * On success, the size (excluding the NUL terminator) of the * escaped, NUL terminated buffer. * Returns 0 if the name is a valid Windows file name. * Returns -1 if the name is not a valid file name. * * Side effects: * None * *----------------------------------------------------------------------------- */ int HgfsEscape_GetSize(char const *bufIn, // IN: Buffer with unescaped input uint32 sizeIn) // IN: Size of the input buffer { uint32 result = 0; const char *currentComponent = bufIn; const char *end = bufIn + sizeIn; const char *next; if (sizeIn == 0) { // No need to escape an empty name. return 0; } if (bufIn[sizeIn - 1] == '\0') { /* * In some cases, a NUL-terminated string is passed to HgfsEscape_GetSize, * so it makes sense to support such input even if CPName_GetComponent * does not. Detect this case and make the input compliant with * CPName_GetComponent by removing the terminating NUL. */ end--; sizeIn--; } /* Skip leading NULs to keep CPName_GetComponent happy. */ while (*currentComponent == '\0' && currentComponent - bufIn < sizeIn) { currentComponent++; } while (currentComponent - bufIn < sizeIn) { int componentSize = CPName_GetComponent(currentComponent, end, &next); if (componentSize < 0) { Log("%s: failed to calculate escaped name size - name is invalid\n", __FUNCTION__); return -1; } result += HgfsEscapeGetComponentSize(currentComponent, componentSize); currentComponent = next; } return (result == 0) ? 0 : result + sizeIn; } /* *----------------------------------------------------------------------------- * * HgfsEscape_Undo -- * * Unescape a buffer that was escaped using HgfsEscapeBuffer. * * The unescaping is done in place in the input buffer, and * can not fail. * * Results: * The size (excluding the NUL terminator) of the unescaped, NUL * terminated buffer. * * Side effects: * None * *----------------------------------------------------------------------------- */ uint32 HgfsEscape_Undo(char *bufIn, // IN: Characters to be unescaped uint32 sizeIn) // IN: Number of characters in bufIn { uint32 componentSize; uint32 unprocessedSize = sizeIn + 1; uint32 result = 0; char *currentComponent = bufIn; ASSERT(bufIn != NULL); while (currentComponent != NULL) { HgfsEscapeUndoComponent(currentComponent, &unprocessedSize); componentSize = strlen(currentComponent) + 1; // Unescaped size result += componentSize; if (unprocessedSize > 1) { currentComponent = currentComponent + componentSize; componentSize = strlen(currentComponent) + 1; // Size of the next component } else { currentComponent = NULL; } } return result - 1; } /* *----------------------------------------------------------------------------- * * HgfsEscapeUndoComponent -- * * Unescape a buffer that was escaped using HgfsEscapeBuffer. * * The unescaping is done in place in the input buffer, and * can not fail. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsEscapeUndoComponent(char *bufIn, // IN: Characters to be unescaped uint32 *unprocessedLength) // IN: Unprocessed characters // in the whole name { size_t offset; size_t sizeIn; char* curOutBuffer; char* escapePointer; ASSERT(bufIn != NULL); curOutBuffer = bufIn; sizeIn = strlen(curOutBuffer); escapePointer = strchr(curOutBuffer, HGFS_ESCAPE_CHAR); while (escapePointer != NULL) { offset = escapePointer - bufIn; if (HgfsIsEscapeSequence(bufIn, offset, sizeIn)) { char* substitute = strchr(HGFS_SUBSTITUTE_CHARS, bufIn[offset - 1]); if (substitute != NULL) { bufIn[offset - 1] = HGFS_ILLEGAL_CHARS[substitute - HGFS_SUBSTITUTE_CHARS]; } else if (bufIn[offset - 1] == HGFS_ESCAPE_SUBSTITUE_CHAR) { bufIn[offset - 1] = HGFS_ESCAPE_CHAR; } memmove(escapePointer, escapePointer + 1, (*unprocessedLength) - offset - 1); (*unprocessedLength)--; sizeIn--; if (sizeIn > 0) { escapePointer = strchr(escapePointer, HGFS_ESCAPE_CHAR); } else { escapePointer = NULL; } } else { escapePointer = strchr(escapePointer + 1, HGFS_ESCAPE_CHAR); } } ASSERT((*unprocessedLength) > sizeIn); (*unprocessedLength) -= sizeIn + 1; } /* *----------------------------------------------------------------------------- * * HgfsEscapeDoComponent -- * * Escape any characters that are not legal in a windows filename. * Escape reserved file names that can't be used in Windows. * We also of course have to escape the escape character, which is "%", * when it is part of a character sequence that would require unescaping * * sizeBufOut must account for the NUL terminator. * * Results: * On success, the size (excluding the NUL terminator) of the * escaped, NUL terminated buffer. * On failure (bufOut not big enough to hold result), negative value. * * Side effects: * None * *----------------------------------------------------------------------------- */ int HgfsEscapeDoComponent(char const *bufIn, // IN: Buffer with unescaped input uint32 sizeIn, // IN: Size of input buffer uint32 sizeBufOut, // IN: Size of output buffer char *bufOut) // OUT: Buffer for escaped output { HgfsEscapeContext conversionContext; conversionContext.processedOffset = 0; conversionContext.outputBufferLength = sizeBufOut / sizeof *bufOut; conversionContext.outputOffset = 0; conversionContext.outputBuffer = bufOut; if (!HgfsEscapeEnumerate(bufIn, sizeIn, HgfsAddEscapeCharacter, &conversionContext)) { return -1; } return conversionContext.outputOffset * sizeof *bufOut; } /* *----------------------------------------------------------------------------- * * HgfsEscapeGetComponentSize -- * * Calculates number of addtitional characters that are needed to escape * name for one NUL terminated component of the path. * * Results: * Number of additional escape characters needed to escape the name. * Returns 0 if no escaping is required. * * Side effects: * None * *----------------------------------------------------------------------------- */ int HgfsEscapeGetComponentSize(char const *bufIn, // IN: Buffer with unescaped input uint32 sizeIn) // IN: Size of the in input buffer { int result = 0; HgfsEscapeEnumerate(bufIn, sizeIn, HgfsCountEscapeChars, &result); return result; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfs/hgfsUtil.c000066400000000000000000000177471321503522500237440ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsUtil.c -- * * Utility routines used by both HGFS servers and clients, such as * conversion routines between Unix time and Windows NT time. * The former is in units of seconds since midnight 1/1/1970, while the * latter is in units of 100 nanoseconds since midnight 1/1/1601. */ /* * hgfsUtil.h must be included before vm_basic_asm.h, as hgfsUtil.h * includes kernel headers on Linux. That is, vmware.h must come after * hgfsUtil.h. */ #include "hgfsUtil.h" #include "vmware.h" #include "vm_basic_asm.h" #ifndef _WIN32 /* * NT time of the Unix epoch: * midnight January 1, 1970 UTC */ #define UNIX_EPOCH ((((uint64)369 * 365) + 89) * 24 * 3600 * 10000000) /* * NT time of the Unix 32 bit signed time_t wraparound: * 03:14:07 January 19, 2038 UTC */ #define UNIX_S32_MAX (UNIX_EPOCH + (uint64)0x80000000 * 10000000) /* *----------------------------------------------------------------------------- * * HgfsConvertToNtTime -- * * Convert from Unix time to Windows NT time. * * Results: * The time in Windows NT format. * * Side effects: * None * *----------------------------------------------------------------------------- */ uint64 HgfsConvertToNtTime(time_t unixTime, // IN: Time in Unix format (seconds) long nsec) // IN: nanoseconds { return (uint64)unixTime * 10000000 + nsec / 100 + UNIX_EPOCH; } /* *----------------------------------------------------------------------------- * * HgfsConvertFromNtTimeNsec -- * * Convert from Windows NT time to Unix time. If NT time is outside of * UNIX time range (1970-2038), returned time is nearest time valid in * UNIX. * * Results: * 0 on success * non-zero if NT time is outside of valid range for UNIX * * Side effects: * None * *----------------------------------------------------------------------------- */ int HgfsConvertFromNtTimeNsec(struct timespec *unixTime, // OUT: Time in UNIX format uint64 ntTime) // IN: Time in Windows NT format { #ifdef __i386__ uint32 sec; uint32 nsec; ASSERT(unixTime); /* We assume that time_t is 32bit */ ASSERT_ON_COMPILE(sizeof (unixTime->tv_sec) == 4); /* Cap NT time values that are outside of Unix time's range */ if (ntTime >= UNIX_S32_MAX) { unixTime->tv_sec = 0x7FFFFFFF; unixTime->tv_nsec = 0; return 1; } #else ASSERT(unixTime); #endif if (ntTime < UNIX_EPOCH) { unixTime->tv_sec = 0; unixTime->tv_nsec = 0; return -1; } #ifdef __i386__ Div643232(ntTime - UNIX_EPOCH, 10000000, &sec, &nsec); unixTime->tv_sec = sec; unixTime->tv_nsec = nsec * 100; #else unixTime->tv_sec = (ntTime - UNIX_EPOCH) / 10000000; unixTime->tv_nsec = ((ntTime - UNIX_EPOCH) % 10000000) * 100; #endif return 0; } /* *----------------------------------------------------------------------------- * * HgfsConvertFromNtTime -- * * Convert from Windows NT time to Unix time. * * Results: * 0 on success * nonzero if time is not representable on UNIX * * Side effects: * None * *----------------------------------------------------------------------------- */ int HgfsConvertFromNtTime(time_t *unixTime, // OUT: Time in UNIX format uint64 ntTime) // IN: Time in Windows NT format { struct timespec tm; int ret; ret = HgfsConvertFromNtTimeNsec(&tm, ntTime); *unixTime = tm.tv_sec; return ret; } #endif /* !def(_WIN32) */ #undef UNIX_EPOCH #undef UNIX_S32_MAX /* *----------------------------------------------------------------------------- * * HgfsConvertFromInternalStatus -- * * This function converts between a platform-specific status code and a * cross-platform status code to be sent down the wire. * * Results: * Converted status code. * * Side effects: * None. * *----------------------------------------------------------------------------- */ #ifdef _WIN32 HgfsStatus HgfsConvertFromInternalStatus(HgfsInternalStatus status) // IN { switch(status) { case ERROR_SUCCESS: return HGFS_STATUS_SUCCESS; case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: return HGFS_STATUS_NO_SUCH_FILE_OR_DIR; case ERROR_INVALID_HANDLE: return HGFS_STATUS_INVALID_HANDLE; case ERROR_ALREADY_EXISTS: case ERROR_FILE_EXISTS: return HGFS_STATUS_FILE_EXISTS; case ERROR_DIR_NOT_EMPTY: return HGFS_STATUS_DIR_NOT_EMPTY; case RPC_S_PROTOCOL_ERROR: return HGFS_STATUS_PROTOCOL_ERROR; case ERROR_ACCESS_DENIED: return HGFS_STATUS_ACCESS_DENIED; case ERROR_INVALID_NAME: return HGFS_STATUS_INVALID_NAME; case ERROR_SHARING_VIOLATION: return HGFS_STATUS_SHARING_VIOLATION; case ERROR_DISK_FULL: case ERROR_HANDLE_DISK_FULL: return HGFS_STATUS_NO_SPACE; case ERROR_NOT_SUPPORTED: return HGFS_STATUS_OPERATION_NOT_SUPPORTED; case ERROR_INVALID_PARAMETER: return HGFS_STATUS_INVALID_PARAMETER; case ERROR_NOT_SAME_DEVICE: return HGFS_STATUS_NOT_SAME_DEVICE; case ERROR_FILENAME_EXCED_RANGE: return HGFS_STATUS_NAME_TOO_LONG; case ERROR_CONNECTION_INVALID: // HGFS_ERROR_STALE_SESSION return HGFS_STATUS_STALE_SESSION; case ERROR_MAX_SESSIONS_REACHED: return HGFS_STATUS_TOO_MANY_SESSIONS; case ERROR_INTERNAL_ERROR: case HGFS_INTERNAL_STATUS_ERROR: default: return HGFS_STATUS_GENERIC_ERROR; } } #else /* Win32 */ HgfsStatus HgfsConvertFromInternalStatus(HgfsInternalStatus status) // IN { switch(status) { case 0: return HGFS_STATUS_SUCCESS; case ENOENT: return HGFS_STATUS_NO_SUCH_FILE_OR_DIR; case EBADF: return HGFS_STATUS_INVALID_HANDLE; case EPERM: return HGFS_STATUS_OPERATION_NOT_PERMITTED; case EISDIR: case EEXIST: return HGFS_STATUS_FILE_EXISTS; case ENOTDIR: return HGFS_STATUS_NOT_DIRECTORY; case ENOTEMPTY: return HGFS_STATUS_DIR_NOT_EMPTY; case EPROTO: return HGFS_STATUS_PROTOCOL_ERROR; case EACCES: return HGFS_STATUS_ACCESS_DENIED; case EINVAL: return HGFS_STATUS_INVALID_NAME; case ENOSPC: return HGFS_STATUS_NO_SPACE; case EOPNOTSUPP: return HGFS_STATUS_OPERATION_NOT_SUPPORTED; case ENAMETOOLONG: return HGFS_STATUS_NAME_TOO_LONG; case EPARAMETERNOTSUPPORTED: return HGFS_STATUS_INVALID_PARAMETER; case EXDEV: return HGFS_STATUS_NOT_SAME_DEVICE; case ENETRESET: // HGFS_ERROR_STALE_SESSION return HGFS_STATUS_STALE_SESSION; case ECONNREFUSED: return HGFS_STATUS_TOO_MANY_SESSIONS; case EINTERNAL: case HGFS_INTERNAL_STATUS_ERROR: default: return HGFS_STATUS_GENERIC_ERROR; } } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsBd/000077500000000000000000000000001321503522500222415ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsBd/Makefile.am000066400000000000000000000017311321503522500242770ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libHgfsBd.la libHgfsBd_la_SOURCES = libHgfsBd_la_SOURCES += hgfsBd.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsBd/hgfsBd.c000066400000000000000000000246011321503522500236050ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsBd.c -- * * Backdoor calls used by hgfs pserver. [bac] */ #if defined(__KERNEL__) || defined(_KERNEL) || defined(KERNEL) # include "kernelStubs.h" #else # include # include # include # include # include "str.h" // for Str_Strcpy # include "debug.h" #endif #include "vm_assert.h" #include "rpcout.h" #include "hgfs.h" // for common HGFS definitions #include "hgfsBd.h" /* *----------------------------------------------------------------------------- * * HgfsBdGetBufInt -- * * Allocates a buffer to send a hgfs request in. This can be either a * HGFS_PACKET_MAX or HGFS_LARGE_PACKET_MAX size buffer depending on the * external funciton called. * * Results: * Pointer to a buffer that has the correct backdoor command prefix for * sending hgfs requests over the backdoor. * NULL on failure (not enough memory). * * Side effects: * None. * *----------------------------------------------------------------------------- */ static char * HgfsBdGetBufInt(size_t bufSize) { /* * Allocate a buffer that is large enough for an HGFS packet and the * synchronous HGFS command, write the command, and return a pointer that * points into the buffer, after the command. */ size_t len = bufSize + HGFS_SYNC_REQREP_CLIENT_CMD_LEN; char *buf = (char*) calloc(sizeof(char), len); if (!buf) { Debug("HgfsBd_GetBuf: Failed to allocate a bd buffer\n"); return NULL; } Str_Strcpy(buf, HGFS_SYNC_REQREP_CLIENT_CMD, len); return buf + HGFS_SYNC_REQREP_CLIENT_CMD_LEN; } /* *----------------------------------------------------------------------------- * * HgfsBd_GetBuf -- * * Get a buffer of size HGFS_PACKET_MAX to send hgfs requests in. * * Results: * See HgfsBdGetBufInt. * * Side effects: * Allocates memory that must be freed with a call to HgfsBd_PutBuf. * *----------------------------------------------------------------------------- */ char * HgfsBd_GetBuf(void) { return HgfsBdGetBufInt(HGFS_PACKET_MAX); } /* *----------------------------------------------------------------------------- * * HgfsBd_GetLargeBuf -- * * Get a buffer of size HGFS_LARGE_PACKET_MAX to send hgfs requests in. * * Results: * See HgfsBdGetBufInt. * * Side effects: * Allocates memory that must be freed with a call to HgfsBd_PutBuf. * *----------------------------------------------------------------------------- */ char * HgfsBd_GetLargeBuf(void) { return HgfsBdGetBufInt(HGFS_LARGE_PACKET_MAX); } /* *----------------------------------------------------------------------------- * * HgfsBd_PutBuf -- * * Release a buffer obtained with HgfsBd_GetBuf. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsBd_PutBuf(char *buf) // IN { ASSERT(buf); free(buf - HGFS_SYNC_REQREP_CLIENT_CMD_LEN); } /* *----------------------------------------------------------------------------- * * HgfsBd_GetChannel -- * * Allocate a new RpcOut channel, and try to open the connection. * * Results: * Pointer to the allocated, opened channel on success. * NULL on failure (not enough memory, or failed to open the connection). * * Side effects: * None * *----------------------------------------------------------------------------- */ RpcOut * HgfsBd_GetChannel(void) { RpcOut *out = RpcOut_Construct(); Bool status; if (!out) { Debug("HgfsBd_GetChannel: Failed to allocate an RpcOut\n"); return NULL; } status = RpcOut_start(out); if (status == FALSE) { RpcOut_Destruct(out); return NULL; } return out; } /* *----------------------------------------------------------------------------- * * HgfsBd_CloseChannel -- * * Close the channel and free the RpcOut object. * * Results: * TRUE if closing the channel succeeded, FALSE if it failed. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsBd_CloseChannel(RpcOut *out) // IN: Channel to close and free { Bool success; ASSERT(out); success = RpcOut_stop(out); if (success == TRUE) { RpcOut_Destruct(out); } return success; } /* *----------------------------------------------------------------------------- * * HgfsBd_Dispatch -- * * Get a reply to an hgfs request. We call RpcOut_Sent, which * returns a buffer with the reply in it, and we pass this back to * the caller. * * Results: * On success, returns zero. On failure, returns a negative error. * * Side effects: * None * *----------------------------------------------------------------------------- */ int HgfsBd_Dispatch(RpcOut *out, // IN: Channel to send on char *packetIn, // IN: Buf containing request packet size_t *packetSize, // IN/OUT: Size of packet in/out char const **packetOut) // OUT: Buf containing reply packet { Bool success; Bool rpcStatus; char const *reply; size_t replyLen; char *bdPacket = packetIn - HGFS_SYNC_REQREP_CLIENT_CMD_LEN; ASSERT(out); ASSERT(packetIn); ASSERT(packetSize); ASSERT(packetOut); memcpy(bdPacket, HGFS_SYNC_REQREP_CLIENT_CMD, HGFS_SYNC_REQREP_CLIENT_CMD_LEN); success = RpcOut_send(out, bdPacket, *packetSize + HGFS_CLIENT_CMD_LEN, &rpcStatus, &reply, &replyLen); if (!success || !rpcStatus) { Debug("HgfsBd_Dispatch: RpcOut_send returned failure\n"); return -1; } ASSERT(replyLen <= HGFS_LARGE_PACKET_MAX); *packetOut = reply; *packetSize = replyLen; return 0; } /* *----------------------------------------------------------------------------- * * HgfsBd_Enabled -- * * Test to see if hgfs is enabled on the host. * * Results: * TRUE if hgfs is enabled. * FALSE if hgfs is disabled. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsBd_Enabled(RpcOut *out, // IN: RPCI Channel char *requestPacket) // IN: Buffer (obtained from HgfsBd_GetBuf) { char const *replyPacket; // Buffer returned by HgfsBd_Dispatch size_t replyLen; Bool success; Bool rpcStatus; /* * Send a bogus (empty) request to the VMX. If hgfs is disabled on * the host side then the request will fail (because the RPCI call * itself will fail). If hgfs is enabled, we will get a packet back * (it will be an error packet because our request was malformed, * but we just discard it anyway). */ success = RpcOut_send(out, requestPacket - HGFS_CLIENT_CMD_LEN, HGFS_CLIENT_CMD_LEN, &rpcStatus, &replyPacket, &replyLen); if (success && rpcStatus) { ASSERT(replyLen <= HGFS_LARGE_PACKET_MAX); } return success && rpcStatus; } /* *----------------------------------------------------------------------------- * * HgfsBd_OpenBackdoor -- * * Check if the HGFS channel is open, and, if not, open it. This is a * one-stop convenience wrapper around HgfsBd_Enabled, HgfsBd_GetBuf, and * HgfsBd_GetChannel. * * Results: * TRUE if the backdoor is now open, regardless of its previous state. * FALSE if the backdoor could not be opened. * * Side effects: * May open a channel to the host. * *----------------------------------------------------------------------------- */ Bool HgfsBd_OpenBackdoor(RpcOut **out) // IN/OUT: RPCI Channel { char *packetBuffer = NULL; Bool success = FALSE; ASSERT(out); /* Short-circuit: backdoor is already open. */ if (*out != NULL) { return TRUE; } /* Open the channel. */ *out = HgfsBd_GetChannel(); if (*out == NULL) { return FALSE; } /* Allocate a buffer for use in pinging the HGFS server. */ packetBuffer = HgfsBd_GetBuf(); if (packetBuffer == NULL) { goto out; } /* Ping the HGFS server. */ if (!HgfsBd_Enabled(*out, packetBuffer)) { goto out; } success = TRUE; out: if (packetBuffer != NULL) { HgfsBd_PutBuf(packetBuffer); } if (!success && *out != NULL) { HgfsBd_CloseChannel(*out); *out = NULL; } return success; } /* *----------------------------------------------------------------------------- * * HgfsBd_CloseBackdoor -- * * Closes the backdoor channel, if it's open. * * Results: * TRUE if the channel is now closed, regardless of its previous state. * FALSE if we could not close the channel. * * Side effects: * May close the channel to the host. * *----------------------------------------------------------------------------- */ Bool HgfsBd_CloseBackdoor(RpcOut **out) // IN/OUT: RPCI Channel { Bool success = TRUE; ASSERT(out); if (*out != NULL) { if (!HgfsBd_CloseChannel(*out)) { success = FALSE; } *out = NULL; } return success; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsHelper/000077500000000000000000000000001321503522500231335ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsHelper/Makefile.am000066400000000000000000000017571321503522500252010ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2009-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libHgfsHelper.la libHgfsHelper_la_SOURCES = libHgfsHelper_la_SOURCES += hgfsHelperPosix.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsHelper/hgfsHelperPosix.c000066400000000000000000000053571321503522500264230ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsHelperPosix.c -- * * Provides a posix helper library for guest applications to access * the HGFS file system. * */ #if !defined __linux__ && !defined __FreeBSD__ && !defined sun && !defined __APPLE__ # error This file should not be compiled #endif #include "vmware.h" #include "debug.h" #include "hgfsHelper.h" #if defined __linux__ #define HGFSHLPR_DEFAULT_MOUNT_PATH "/mnt/hgfs" #elif defined sun #define HGFSHLPR_DEFAULT_MOUNT_PATH "/hgfs" #elif defined __APPLE__ #define HGFSHLPR_DEFAULT_MOUNT_PATH "/Volumes/VMware Shared Folders" #endif /* *----------------------------------------------------------------------------- * * HgfsHlpr_QuerySharesDefaultRootPath -- * * Queries the driver for its share's root paths. * Currently only one is expected to be supported * and returned, although later versions may not. * E.g. "/mnt/hgfs" is the root path to * the HGFS shares. * * Results: * TRUE always. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsHlpr_QuerySharesDefaultRootPath(char **hgfsRootPath) { #if defined __FreeBSD__ return FALSE; #else ASSERT(hgfsRootPath != NULL); *hgfsRootPath = Unicode_AllocWithUTF8(HGFSHLPR_DEFAULT_MOUNT_PATH); Debug("%s: HGFS shares root path name \"%s\"\n", __FUNCTION__, *hgfsRootPath); return TRUE; #endif } /* *----------------------------------------------------------------------------- * * HgfsHlpr_FreeSharesRootPath -- * * Frees the share's root paths previously returned * to the caller from the HgfsHlpr_QuerySharesRootPath. * * Results: * None. * * Side Effects: * None. * *----------------------------------------------------------------------------- */ void HgfsHlpr_FreeSharesRootPath(char *hgfsRootPath) { free(hgfsRootPath); } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/000077500000000000000000000000001321503522500231625ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/Makefile.am000066400000000000000000000025341321503522500252220ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libHgfsServer.la libHgfsServer_la_SOURCES = libHgfsServer_la_SOURCES += hgfsServer.c libHgfsServer_la_SOURCES += hgfsServerLinux.c libHgfsServer_la_SOURCES += hgfsServerPacketUtil.c libHgfsServer_la_SOURCES += hgfsDirNotifyStub.c libHgfsServer_la_SOURCES += hgfsServerParameters.c libHgfsServer_la_SOURCES += hgfsServerOplock.c libHgfsServer_la_SOURCES += hgfsServerOplockLinux.c AM_CFLAGS = AM_CFLAGS += -DVMTOOLS_USE_GLIB AM_CFLAGS += @GLIB2_CPPFLAGS@ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsDirNotify.h000066400000000000000000000073351321503522500261220ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _HGFS_DIRNOTIFY_H #define _HGFS_DIRNOTIFY_H /* * hgfsDirNotify.h -- * * Function definitions for directory change notification. */ #include "hgfsServer.h" // for HgfsSharedFolderHandle #include "hgfsProto.h" // for HgfsSubscriberHandle #include "hgfsUtil.h" // for HgfsInternalStatus struct HgfsSessionInfo; /* * Activate and deactivate reason. * Currently, there are two scenarios: * 1) HGFS server is check point synchronizing: the file system event * generation is deactivated at the start and activated at the end. * 2) The client has added the first subscriber or removed the last * subscriber. The file system event generation is activated on the * addition of the first subscriber and deactivated on removal of * the last one. * * Note, in case 1 above, if there are no subscribers even at the end * of the HGFS server check point syncing, the activation will not * activate the file system events. */ typedef enum { HGFS_NOTIFY_REASON_SERVER_SYNC, HGFS_NOTIFY_REASON_SUBSCRIBERS, } HgfsNotifyActivateReason; /* These are the callbacks that are implemented in hgfsServer.c */ typedef void (*HgfsNotifyRegisterThreadCb)(struct HgfsSessionInfo *session); typedef void (*HgfsNotifyUnregisterThreadCb)(struct HgfsSessionInfo *session); typedef void (*HgfsNotifyEventReceiveCb)(HgfsSharedFolderHandle sharedFolder, HgfsSubscriberHandle subscriber, char *name, uint32 mask, struct HgfsSessionInfo *session); typedef struct HgfsServerNotifyCallbacks { HgfsNotifyRegisterThreadCb registerThread; HgfsNotifyUnregisterThreadCb unregisterThread; HgfsNotifyEventReceiveCb eventReceive; } HgfsServerNotifyCallbacks; HgfsInternalStatus HgfsNotify_Init(const HgfsServerNotifyCallbacks *serverCbData); void HgfsNotify_Exit(void); void HgfsNotify_Deactivate(HgfsNotifyActivateReason mode, struct HgfsSessionInfo *session); void HgfsNotify_Activate(HgfsNotifyActivateReason mode, struct HgfsSessionInfo *session); HgfsSharedFolderHandle HgfsNotify_AddSharedFolder(const char *path, const char *shareName); HgfsSubscriberHandle HgfsNotify_AddSubscriber(HgfsSharedFolderHandle sharedFolder, const char *path, uint32 eventFilter, uint32 recursive, struct HgfsSessionInfo *session); Bool HgfsNotify_RemoveSharedFolder(HgfsSharedFolderHandle sharedFolder); Bool HgfsNotify_RemoveSubscriber(HgfsSubscriberHandle subscriber); void HgfsNotify_RemoveSessionSubscribers(struct HgfsSessionInfo *session); #endif // _HGFS_DIRNOTIFY_H open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsDirNotifyStub.c000066400000000000000000000137071321503522500267530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsDirNotifyStub.c -- * * Stubs for directory notification support, used to build guest components. */ #include #include "vmware.h" #include "vm_basic_types.h" #include "hgfsProto.h" #include "hgfsServer.h" #include "hgfsUtil.h" #include "hgfsDirNotify.h" /* *----------------------------------------------------------------------------- * * HgfsNotify_Init -- * * Initialization for the notification component. * * Results: * Invalid value error. * * Side effects: * None. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsNotify_Init(const HgfsServerNotifyCallbacks *serverCbData) // IN: serverCbData unused { return HGFS_ERROR_NOT_SUPPORTED; } /* *----------------------------------------------------------------------------- * * HgfsNotify_Exit -- * * Exit for the notification component. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsNotify_Exit(void) { } /* *----------------------------------------------------------------------------- * * HgfsNotify_Activate -- * * Activates generating file system change notifications. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsNotify_Activate(HgfsNotifyActivateReason reason, // IN: reason struct HgfsSessionInfo *session) // IN: session { } /* *----------------------------------------------------------------------------- * * HgfsNotify_Deactivate -- * * Deactivates generating file system change notifications. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsNotify_Deactivate(HgfsNotifyActivateReason reason, // IN: reason struct HgfsSessionInfo *session) // IN: session { } /* *----------------------------------------------------------------------------- * * HgfsNotify_AddSharedFolder -- * * Allocates memory and initializes new shared folder structure. * * Results: * Opaque subscriber handle for the new subscriber or HGFS_INVALID_FOLDER_HANDLE * if adding shared folder fails. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsSharedFolderHandle HgfsNotify_AddSharedFolder(const char *path, // IN: path in the host const char *shareName) // IN: name of the shared folder { return HGFS_INVALID_FOLDER_HANDLE; } /* *----------------------------------------------------------------------------- * * HgfsNotify_AddSubscriber -- * * Allocates memory and initializes new subscriber structure. * Inserts allocated subscriber into corrspondent array. * * Results: * Opaque subscriber handle for the new subscriber or HGFS_INVALID_SUBSCRIBER_HANDLE * if adding subscriber fails. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsSubscriberHandle HgfsNotify_AddSubscriber(HgfsSharedFolderHandle sharedFolder, // IN: shared folder handle const char *path, // IN: relative path uint32 eventFilter, // IN: event filter uint32 recursive, // IN: look in subfolders struct HgfsSessionInfo *session) // IN: server context { return HGFS_INVALID_SUBSCRIBER_HANDLE; } /* *----------------------------------------------------------------------------- * * HgfsNotify_RemoveSharedFolder -- * * Deallcates memory used by shared folder and performs necessary cleanup. * Also deletes all subscribers that are defined for the shared folder. * * Results: * FALSE. * * Side effects: * Removes all subscribers that correspond to the shared folder and invalidates * thier handles. * *----------------------------------------------------------------------------- */ Bool HgfsNotify_RemoveSharedFolder(HgfsSharedFolderHandle sharedFolder) // IN { return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsNotify_RemoveSubscriber -- * * Deallcates memory used by NotificationSubscriber and performs necessary cleanup. * * Results: * FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsNotify_RemoveSubscriber(HgfsSubscriberHandle subscriber) // IN { return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsNotify_RemoveSessionSubscribers -- * * Removes all entries that are related to a particular session. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsNotify_RemoveSessionSubscribers(struct HgfsSessionInfo *session) // IN { } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServer.c000066400000000000000000011057531321503522500254600ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #if defined(__APPLE__) /* * DirectoryEntry type that is used in common code is * defined as dirent for Mac OS. * _DARWIN_USE_64_BIT_INODE definition is needed to make dirent * structure definitions in this file and in HgfsServerLinux.c * consistent. */ #define _DARWIN_USE_64_BIT_INODE #endif #include #include #include "vmware.h" #include "str.h" #include "cpName.h" #include "cpNameLite.h" #include "hgfsServerInt.h" #include "hgfsServerPolicy.h" #include "hgfsUtil.h" #include "hgfsVirtualDir.h" #include "codeset.h" #include "dbllnklst.h" #include "file.h" #include "util.h" #include "wiper.h" #include "hgfsServer.h" #include "hgfsServerParameters.h" #include "hgfsServerOplock.h" #include "hgfsDirNotify.h" #include "userlock.h" #include "poll.h" #include "mutexRankLib.h" #include "vm_basic_asm.h" #include "unicodeOperations.h" #if defined(_WIN32) #include #define HGFS_PARENT_DIR "..\\" #else #include #define stricmp strcasecmp #define HGFS_PARENT_DIR "../" #endif // _WIN32 #define HGFS_PARENT_DIR_LEN 3 /* * Define this to enable an ASSERT on HGFS_STATUS_PROTOCOL_ERROR. * This is useful if client is to be guaranteed to work with the server * without falling back to older protocol versions and to ensure that * clients don't send op value greater than HGFS_OP_MAX. * * NOTE: This flag is only meant to be used while testing. This should * _always_ be undefined when checking code in. */ #if 0 #define HGFS_ASSERT_CLIENT(op) \ do { \ LOG(4, ("%s: op: %u.\n", __FUNCTION__, op)); \ ASSERT(status != HGFS_STATUS_PROTOCOL_ERROR); \ } while(0) #else #define HGFS_ASSERT_CLIENT(op) #endif #define HGFS_ASSERT_INPUT(input) \ ASSERT(input && input->packet && input->request && \ ((!input->sessionEnabled && input->session) || \ (input->sessionEnabled && \ (input->op == HGFS_OP_CREATE_SESSION_V4 || input->session))) && \ (!input->payloadSize || input->payload)) /* * Define this to enable an ASSERT if server gets an op lower than * this value. This is useful if client is to be guaranteed to work with * the server without falling back to older protocol versions. * * NOTE: This flag is only meant to be used while testing. This should * _always_ be undefined when checking code in. */ #if 0 #define HGFS_ASSERT_MINIMUM_OP(op) \ do { \ LOG(4, ("%s: op received - %u.\n", __FUNCTION__, op)); \ ASSERT(op >= HGFS_OP_OPEN_V3); \ } while(0) #else #define HGFS_ASSERT_MINIMUM_OP(op) #endif /* * This ensures that the hgfs name conversion code never fails on long * filenames by using a buffer that is too small. If anything, we will * fail first elsewhere because the name is too big to fit in one hgfs * packet. [bac] */ #define HGFS_PATH_MAX HGFS_PACKET_MAX /* * Array of FileNodes for opening files. */ #define NUM_FILE_NODES 100 #define NUM_SEARCHES 100 /* Default maximun number of open nodes that have server locks. */ #define MAX_LOCKED_FILENODES 10 struct HgfsTransportSessionInfo { /* Default session id. */ uint64 defaultSessionId; /* Lock to manipulate the list of sessions */ MXUserExclLock *sessionArrayLock; /* List of sessions */ DblLnkLst_Links sessionArray; /* Max packet size that is supported by both client and server. */ uint32 maxPacketSize; /* Total number of sessions present this transport session*/ uint32 numSessions; /* Transport session context. */ void *transportData; /* Current state of the session. */ HgfsSessionInfoState state; /* Session is dynamic or internal. */ HgfsSessionInfoType type; /* Function callbacks into Hgfs Channels. */ HgfsServerChannelCallbacks *channelCbTable; Atomic_uint32 refCount; /* Reference count for session. */ HgfsServerChannelData channelCapabilities; }; /* The input request paramaters object. */ typedef struct HgfsInputParam { const void *request; /* Hgfs header followed by operation request */ size_t requestSize; /* Size of Hgfs header and operation request */ HgfsSessionInfo *session; /* Hgfs session data */ HgfsTransportSessionInfo *transportSession; HgfsPacket *packet; /* Public (server/transport) Hgfs packet */ const void *payload; /* Hgfs operation request */ uint32 payloadOffset; /* Offset to start of Hgfs operation request */ size_t payloadSize; /* Hgfs operation request size */ HgfsOp op; /* Hgfs operation command code */ uint32 id; /* Request ID to be matched with the reply */ Bool sessionEnabled; /* Requests have session enabled headers */ } HgfsInputParam; /* * The HGFS server configurable settings. * (Note: the guest sets these to all defaults only modifiable from the VMX.) */ static HgfsServerConfig gHgfsCfgSettings = { (HGFS_CONFIG_NOTIFY_ENABLED | HGFS_CONFIG_VOL_INFO_MIN), HGFS_MAX_CACHED_FILENODES }; /* * Monotonically increasing handle counter used to dish out HgfsHandles. * This value is checkpointed. */ static Atomic_uint32 hgfsHandleCounter = {0}; static HgfsServerMgrCallbacks *gHgfsMgrData = NULL; /* * Session usage and locking. * * The channel will serialize callbacks to connect, disconnect, close * and invalidate objects for sessions. * The receives will also be serialized with the above when received through * the backdoor channel. * However, when requests are received from a socket, they will be from a * worker thread. It is the responsibility of the socket channel to keep * the session alive when processing the receive request which it does by * an additional reference for the session. This means even if a disconnect * occurs and the socket is closed, the channel will not call the session * close until the hgfs server returns from the receive processing. Thus * the hgfs server session data will remain valid. * When the hgfs server processes requests asynchronously, or returns from * receive request prior to sending the reply to be done at a later time, * a reference on the session is taken out while processing the message, * and not removed until the reply is processed. This reference will ensure * the session is not torndown until the final reference is removed, even * if the close session is called from the channel. */ /* Session related callbacks. */ static void HgfsServerSessionReceive(HgfsPacket *packet, void *clientData); static Bool HgfsServerSessionConnect(void *transportData, HgfsServerChannelCallbacks *channelCbTable, HgfsServerChannelData *channelCapabililies, void **clientData); static void HgfsServerSessionDisconnect(void *clientData); static void HgfsServerSessionClose(void *clientData); static void HgfsServerSessionInvalidateObjects(void *clientData, DblLnkLst_Links *shares); static uint32 HgfsServerSessionInvalidateInactiveSessions(void *clientData); static void HgfsServerSessionSendComplete(HgfsPacket *packet, void *clientData); static void HgfsServerSessionQuiesce(void * clientData, HgfsQuiesceOp quiesceOp); /* * Callback table passed to transport and any channels. */ static const HgfsServerCallbacks gHgfsServerCBTable = { { HgfsServerSessionConnect, HgfsServerSessionDisconnect, HgfsServerSessionClose, HgfsServerSessionReceive, HgfsServerSessionInvalidateObjects, HgfsServerSessionInvalidateInactiveSessions, HgfsServerSessionSendComplete, HgfsServerSessionQuiesce, }, }; static void HgfsServerNotifyRegisterThreadCb(struct HgfsSessionInfo *session); static void HgfsServerNotifyUnregisterThreadCb(struct HgfsSessionInfo *session); static void HgfsServerNotifyReceiveEventCb(HgfsSharedFolderHandle sharedFolder, HgfsSubscriberHandle subscriber, char* fileName, uint32 mask, struct HgfsSessionInfo *session); /* * Callback table passed to the directory change notification component. */ static const HgfsServerNotifyCallbacks gHgfsServerNotifyCBTable = { HgfsServerNotifyRegisterThreadCb, HgfsServerNotifyUnregisterThreadCb, HgfsServerNotifyReceiveEventCb, }; /* Lock that protects shared folders list. */ static MXUserExclLock *gHgfsSharedFoldersLock = NULL; /* List of shared folders nodes. */ static DblLnkLst_Links gHgfsSharedFoldersList; /* * Number of active sessions that support change directory notification. HGFS server * needs to maintain up-to-date shared folders list when there is * at least one such session. */ static Bool gHgfsDirNotifyActive = FALSE; typedef struct HgfsSharedFolderProperties { DblLnkLst_Links links; char *name; /* Name of the share. */ HgfsSharedFolderHandle notificationHandle; /* Directory notification handle. */ } HgfsSharedFolderProperties; /* Allocate/Add sessions helper functions. */ #ifndef VMX86_TOOLS static void HgfsServerAsyncInfoIncCount(HgfsAsyncRequestInfo *info); #endif static Bool HgfsServerAllocateSession(HgfsTransportSessionInfo *transportSession, HgfsSessionInfo **sessionData); static HgfsInternalStatus HgfsServerTransportAddSessionToList(HgfsTransportSessionInfo *transportSession, HgfsSessionInfo *sessionInfo); static void HgfsServerTransportRemoveSessionFromList(HgfsTransportSessionInfo *transportSession, HgfsSessionInfo *sessionInfo); static HgfsSessionInfo * HgfsServerTransportGetSessionInfo(HgfsTransportSessionInfo *transportSession, uint64 sessionId); static HgfsTransportSessionInfo * HgfsServerTransportInit(void *transportData, HgfsServerChannelCallbacks *channelCbTable, HgfsServerChannelData *channelCapabilities); static void HgfsServerTransportExit(HgfsTransportSessionInfo *transportSession); /* Local functions. */ static void HgfsInvalidateSessionObjects(DblLnkLst_Links *shares, HgfsSessionInfo *session); static Bool HgfsAddToCacheInternal(HgfsHandle handle, HgfsSessionInfo *session); static Bool HgfsIsCachedInternal(HgfsHandle handle, HgfsSessionInfo *session); static Bool HgfsRemoveLruNode(HgfsSessionInfo *session); static Bool HgfsRemoveFromCacheInternal(HgfsHandle handle, HgfsSessionInfo *session); static void HgfsRemoveSearchInternal(HgfsSearch *search, HgfsSessionInfo *session); static HgfsSearch *HgfsSearchHandle2Search(HgfsHandle handle, HgfsSessionInfo *session); static HgfsHandle HgfsSearch2SearchHandle(HgfsSearch const *search); static HgfsSearch *HgfsAddNewSearch(char const *utf8Dir, DirectorySearchType type, char const *utf8ShareName, char const *rootDir, HgfsSessionInfo *session); static void HgfsDumpAllSearches(HgfsSessionInfo *session); static void HgfsDumpAllNodes(HgfsSessionInfo *session); static void HgfsFreeFileNode(HgfsHandle handle, HgfsSessionInfo *session); static void HgfsFreeFileNodeInternal(HgfsHandle handle, HgfsSessionInfo *session); static HgfsFileNode *HgfsAddNewFileNode(HgfsFileOpenInfo *openInfo, HgfsLocalId const *localId, fileDesc fileDesc, Bool append, size_t shareNameLen, char const *shareName, Bool sharedFolderOpen, HgfsSessionInfo *session); static void HgfsRemoveFileNode(HgfsFileNode *node, HgfsSessionInfo *session); static HgfsFileNode *HgfsGetNewNode(HgfsSessionInfo *session); static HgfsHandle HgfsFileNode2Handle(HgfsFileNode const *fileNode); static HgfsFileNode *HgfsHandle2FileNode(HgfsHandle handle, HgfsSessionInfo *session); static void HgfsServerExitSessionInternal(HgfsSessionInfo *session); static Bool HgfsIsShareRoot(char const *cpName, size_t cpNameSize); static void HgfsServerCompleteRequest(HgfsInternalStatus status, size_t replyPayloadSize, HgfsInputParam *input); static Bool HgfsHandle2NotifyInfo(HgfsHandle handle, HgfsSessionInfo *session, char **fileName, size_t *fileNameSize, HgfsSharedFolderHandle *folderHandle); static void HgfsFreeSearchDirents(HgfsSearch *search); static HgfsInternalStatus HgfsServerTransportGetDefaultSession(HgfsTransportSessionInfo *transportSession, HgfsSessionInfo **session); static Bool HgfsPacketSend(HgfsPacket *packet, HgfsTransportSessionInfo *transportSession, HgfsSessionInfo *session, HgfsSendFlags flags); /* * Opcode handlers */ static void HgfsServerOpen(HgfsInputParam *input); static void HgfsServerRead(HgfsInputParam *input); static void HgfsServerWrite(HgfsInputParam *input); static void HgfsServerSearchOpen(HgfsInputParam *input); static void HgfsServerSearchRead(HgfsInputParam *input); static void HgfsServerGetattr(HgfsInputParam *input); static void HgfsServerSetattr(HgfsInputParam *input); static void HgfsServerCreateDir(HgfsInputParam *input); static void HgfsServerDeleteFile(HgfsInputParam *input); static void HgfsServerDeleteDir(HgfsInputParam *input); static void HgfsServerRename(HgfsInputParam *input); static void HgfsServerQueryVolume(HgfsInputParam *input); static void HgfsServerSymlinkCreate(HgfsInputParam *input); static void HgfsServerServerLockChange(HgfsInputParam *input); static void HgfsServerWriteWin32Stream(HgfsInputParam *input); static void HgfsServerCreateSession(HgfsInputParam *input); static void HgfsServerDestroySession(HgfsInputParam *input); static void HgfsServerClose(HgfsInputParam *input); static void HgfsServerSearchClose(HgfsInputParam *input); static void HgfsServerSetDirNotifyWatch(HgfsInputParam *input); static void HgfsServerRemoveDirNotifyWatch(HgfsInputParam *input); /* *---------------------------------------------------------------------------- * * HgfsServerSessionGet -- * * Increment session reference count. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsServerSessionGet(HgfsSessionInfo *session) // IN: session context { ASSERT(session && Atomic_Read(&session->refCount) != 0); Atomic_Inc(&session->refCount); } /* *---------------------------------------------------------------------------- * * HgfsServerSessionPut -- * * Decrement session reference count. * * Free session info data if no reference. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsServerSessionPut(HgfsSessionInfo *session) // IN: session context { ASSERT(session); if (Atomic_ReadDec32(&session->refCount) == 1) { HgfsServerExitSessionInternal(session); } } /* *---------------------------------------------------------------------------- * * HgfsServerTransportSessionGet -- * * Increment transport session reference count. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ void HgfsServerTransportSessionGet(HgfsTransportSessionInfo *transportSession) // IN: session context { ASSERT(transportSession); Atomic_Inc(&transportSession->refCount); } /* *---------------------------------------------------------------------------- * * HgfsServerTransportSessionPut -- * * Decrement transport session reference count. * * Free session info data if no reference. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsServerTransportSessionPut(HgfsTransportSessionInfo *transportSession) // IN: transport session context { ASSERT(transportSession); if (Atomic_ReadDec32(&transportSession->refCount) == 1) { HgfsServerTransportExit(transportSession); } } /* *----------------------------------------------------------------------------- * * HgfsServerInitHandleCounter -- * * Initialize the file handle counter to the new value passed. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerInitHandleCounter(uint32 newHandleCounter) { Atomic_Write(&hgfsHandleCounter, newHandleCounter); } /* *----------------------------------------------------------------------------- * * HgfsServerGetHandleCounter -- * * Return file handle counter. This is used by the checkpointing code to * checkpoint this value so we avoid the risk of handle collision. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static uint32 HgfsServerGetHandleCounter(void) { return Atomic_Read(&hgfsHandleCounter); } /* *----------------------------------------------------------------------------- * * HgfsServerGetNextHandleCounter -- * * Return file handle counter. This is used by the checkpointing code to * checkpoint this value so we avoid the risk of handle collision. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static uint32 HgfsServerGetNextHandleCounter(void) { return Atomic_ReadInc32(&hgfsHandleCounter); } /* *----------------------------------------------------------------------------- * * HgfsHandle2FileNode -- * * Retrieve the file node a handle refers to. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * The file node if the handle is valid (i.e. it refers to an existing file * node that is currently in use). * NULL if the handle is invalid. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static HgfsFileNode * HgfsHandle2FileNode(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session) // IN: Session info { unsigned int i; HgfsFileNode *fileNode = NULL; ASSERT(session); ASSERT(session->nodeArray); /* XXX: This O(n) lookup can and should be optimized. */ for (i = 0; i < session->numNodes; i++) { if (session->nodeArray[i].state != FILENODE_STATE_UNUSED && session->nodeArray[i].handle == handle) { fileNode = &session->nodeArray[i]; break; } } return fileNode; } /* *----------------------------------------------------------------------------- * * HgfsFileNode2Handle -- * * Retrieve the handle that represents a file node outside of the server. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * The handle * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsHandle HgfsFileNode2Handle(HgfsFileNode const *fileNode) // IN { ASSERT(fileNode); return fileNode->handle; } /* *----------------------------------------------------------------------------- * * HgfsDumpAllNodes -- * * Debugging routine; print all nodes in the nodeArray. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsDumpAllNodes(HgfsSessionInfo *session) // IN: session info { unsigned int i; ASSERT(session); ASSERT(session->nodeArray); Log("Dumping all nodes\n"); for (i = 0; i < session->numNodes; i++) { Log("handle %u, name \"%s\", localdev %"FMT64"u, localInum %"FMT64"u %u\n", session->nodeArray[i].handle, session->nodeArray[i].utf8Name ? session->nodeArray[i].utf8Name : "NULL", session->nodeArray[i].localId.volumeId, session->nodeArray[i].localId.fileId, session->nodeArray[i].fileDesc); } Log("Done\n"); } /* *----------------------------------------------------------------------------- * * HgfsHandle2FileDesc -- * * Retrieve the file descriptor (host OS file handle) based on the hgfs * handle. * * Results: * TRUE if the handle is valid and the file desc was retrieved successfully. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsHandle2FileDesc(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info fileDesc *fd, // OUT: OS handle (file descriptor) void **fileCtx) // OUT: OS file context { Bool found = FALSE; HgfsFileNode *fileNode = NULL; MXUser_AcquireExclLock(session->nodeArrayLock); fileNode = HgfsHandle2FileNode(handle, session); if (fileNode == NULL) { goto exit; } *fd = fileNode->fileDesc; if (fileCtx) { *fileCtx = fileNode->fileCtx; } found = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return found; } /* *----------------------------------------------------------------------------- * * HgfsHandle2AppendFlag -- * * Retrieve the append flag for the file node that corresponds to * the specified hgfs handle. * * Results: * TRUE if the handle is valid and append flag was retrieved successfully. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsHandle2AppendFlag(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info Bool *appendFlag) // OUT: append flag { Bool found = FALSE; HgfsFileNode *fileNode = NULL; MXUser_AcquireExclLock(session->nodeArrayLock); fileNode = HgfsHandle2FileNode(handle, session); if (fileNode == NULL) { goto exit; } *appendFlag = fileNode->flags & HGFS_FILE_NODE_APPEND_FL; found = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return found; } /* *----------------------------------------------------------------------------- * * HgfsHandle2LocalId -- * * Retrieve the local id for the file node that corresponds to * the specified hgfs handle. * * Results: * TRUE if the hgfs handle is valid and local id was retrieved successfully. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsHandle2LocalId(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info HgfsLocalId *localId) // OUT: local id info { Bool found = FALSE; HgfsFileNode *fileNode = NULL; ASSERT(localId); MXUser_AcquireExclLock(session->nodeArrayLock); fileNode = HgfsHandle2FileNode(handle, session); if (fileNode == NULL) { goto exit; } localId->volumeId = fileNode->localId.volumeId; localId->fileId = fileNode->localId.fileId; found = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return found; } /* *----------------------------------------------------------------------------- * * HgfsFileDesc2Handle -- * * Given an OS handle/fd, return file's hgfs handle. * * Results: * TRUE if the node was found. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsFileDesc2Handle(fileDesc fd, // IN: OS handle (file descriptor) HgfsSessionInfo *session, // IN: Session info HgfsHandle *handle) // OUT: Hgfs file handle { unsigned int i; Bool found = FALSE; HgfsFileNode *existingFileNode = NULL; ASSERT(session); ASSERT(session->nodeArray); MXUser_AcquireExclLock(session->nodeArrayLock); for (i = 0; i < session->numNodes; i++) { existingFileNode = &session->nodeArray[i]; if ((existingFileNode->state == FILENODE_STATE_IN_USE_CACHED) && (existingFileNode->fileDesc == fd)) { *handle = HgfsFileNode2Handle(existingFileNode); found = TRUE; break; } } MXUser_ReleaseExclLock(session->nodeArrayLock); return found; } /* *----------------------------------------------------------------------------- * * HgfsHandle2ShareMode -- * * Given an OS handle/fd, return the share access mode. * * Results: * TRUE if the node was found. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsHandle2ShareMode(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info HgfsOpenMode *shareMode) // OUT:share access mode { Bool found = FALSE; HgfsFileNode *existingFileNode = NULL; HgfsNameStatus nameStatus; if (shareMode == NULL) { return found; } MXUser_AcquireExclLock(session->nodeArrayLock); existingFileNode = HgfsHandle2FileNode(handle, session); if (existingFileNode == NULL) { goto exit_unlock; } nameStatus = HgfsServerPolicy_GetShareMode(existingFileNode->shareName, existingFileNode->shareNameLen, shareMode); found = (nameStatus == HGFS_NAME_STATUS_COMPLETE); exit_unlock: MXUser_ReleaseExclLock(session->nodeArrayLock); return found; } /* *----------------------------------------------------------------------------- * * HgfsHandle2FileName -- * * Given an OS handle/fd, return file's hgfs name. * * Results: * TRUE if the node was found. * FALSE otherwise. * * Side effects: * Allocates memory and makes a copy of the file name. * *----------------------------------------------------------------------------- */ Bool HgfsHandle2FileName(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session,// IN: Session info char **fileName, // OUT: UTF8 file name size_t *fileNameSize) // OUT: UTF8 file name size { Bool unused1, unused2; return HgfsHandle2FileNameMode(handle, session, &unused1, &unused2, fileName, fileNameSize); } /* *----------------------------------------------------------------------------- * * HgfsHandle2FileNameMode -- * * Given an OS handle/fd, return file's hgfs name and permissions * associated with the corresponding shared folder. * * Results: * TRUE if the node was found. * FALSE otherwise. * * Side effects: * Allocates memory and makes a copy of the file name. * *----------------------------------------------------------------------------- */ Bool HgfsHandle2FileNameMode(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session,// IN: Session info Bool *readPermissions, // OUT: shared folder permissions Bool *writePermissions, // OUT: shared folder permissions char **fileName, // OUT: UTF8 file name size_t *fileNameSize) // OUT: UTF8 file name size { Bool found = FALSE; HgfsFileNode *existingFileNode = NULL; char *name = NULL; size_t nameSize = 0; if ((fileName == NULL) || (fileNameSize == NULL)) { return found; } MXUser_AcquireExclLock(session->nodeArrayLock); existingFileNode = HgfsHandle2FileNode(handle, session); if (existingFileNode == NULL) { goto exit_unlock; } name = malloc(existingFileNode->utf8NameLen + 1); if (name == NULL) { goto exit_unlock; } *readPermissions = existingFileNode->shareInfo.readPermissions; *writePermissions = existingFileNode->shareInfo.writePermissions; nameSize = existingFileNode->utf8NameLen; memcpy(name, existingFileNode->utf8Name, nameSize); name[nameSize] = '\0'; found = TRUE; exit_unlock: MXUser_ReleaseExclLock(session->nodeArrayLock); *fileName = name; *fileNameSize = nameSize; return found; } /* *----------------------------------------------------------------------------- * * HgfsHandle2FileNameMode -- * * Given an OS handle/fd, return information needed for directory * notification package: relative to the root share file name and * shared folder notification handle. * * Results: * TRUE if the node was found. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsHandle2NotifyInfo(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info char **fileName, // OUT: UTF8 file name size_t *fileNameSize, // OUT: UTF8 file name size HgfsSharedFolderHandle *folderHandle) // OUT: shared folder handle { Bool found = FALSE; HgfsFileNode *existingFileNode; char *name; size_t nameSize; ASSERT(fileName != NULL && fileNameSize != NULL); MXUser_AcquireExclLock(session->nodeArrayLock); existingFileNode = HgfsHandle2FileNode(handle, session); if (NULL != existingFileNode) { nameSize = existingFileNode->utf8NameLen - existingFileNode->shareInfo.rootDirLen; name = Util_SafeMalloc(nameSize + 1); *folderHandle = existingFileNode->shareInfo.handle; memcpy(name, existingFileNode->utf8Name, nameSize); name[nameSize] = '\0'; *fileName = name; *fileNameSize = nameSize; found = TRUE; } MXUser_ReleaseExclLock(session->nodeArrayLock); return found; } /* *----------------------------------------------------------------------------- * * HgfsGetNodeCopy -- * * Make a copy of the node. The node should not be kept around for long, as * the data might become stale. This is mostly a convenience function to get * node fields more efficiently. * * Results: * TRUE if the hgfs handle is valid and the copy was successful. * FALSE otherwise. * * Side effects: * Allocates memory for node.utf8Name if copyName was set to TRUE. * *----------------------------------------------------------------------------- */ Bool HgfsGetNodeCopy(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info Bool copyName, // IN: Should we copy the name? HgfsFileNode *copy) // IN/OUT: Copy of the node { HgfsFileNode *original = NULL; Bool found = FALSE; ASSERT(copy); MXUser_AcquireExclLock(session->nodeArrayLock); original = HgfsHandle2FileNode(handle, session); if (original == NULL) { goto exit; } if (copyName) { copy->utf8Name = malloc(original->utf8NameLen + 1); if (copy->utf8Name == NULL) { goto exit; } copy->utf8NameLen = original->utf8NameLen; memcpy(copy->utf8Name, original->utf8Name, copy->utf8NameLen); copy->utf8Name[copy->utf8NameLen] = '\0'; } else { copy->utf8Name = NULL; copy->utf8NameLen = 0; } copy->localId = original->localId; copy->fileDesc = original->fileDesc; copy->mode = original->mode; copy->shareAccess = original->shareAccess; copy->flags = original->flags; copy->state = original->state; copy->handle = original->handle; copy->fileCtx = original->fileCtx; found = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return found; } /* *---------------------------------------------------------------------------- * * HgfsHandleIsSequentialOpen -- * * Get the Hgfs open mode this handle was originally opened with. * * Results: * TRUE on success, FALSE on failure. sequentialOpen is filled in on * success. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool HgfsHandleIsSequentialOpen(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info Bool *sequentialOpen) // OUT: If open was sequential { HgfsFileNode *node; Bool success = FALSE; ASSERT(sequentialOpen); MXUser_AcquireExclLock(session->nodeArrayLock); node = HgfsHandle2FileNode(handle, session); if (node == NULL) { goto exit; } *sequentialOpen = node->flags & HGFS_FILE_NODE_SEQUENTIAL_FL; success = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return success; } /* *---------------------------------------------------------------------------- * * HgfsHandleIsSharedFolderOpen -- * * Find if this is a shared folder open. * * Results: * TRUE on success, FALSE on failure. sharedFolderOpen is filled in on * success. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool HgfsHandleIsSharedFolderOpen(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info Bool *sharedFolderOpen) // OUT: If shared folder { HgfsFileNode *node; Bool success = FALSE; ASSERT(sharedFolderOpen); MXUser_AcquireExclLock(session->nodeArrayLock); node = HgfsHandle2FileNode(handle, session); if (node == NULL) { goto exit; } *sharedFolderOpen = node->flags & HGFS_FILE_NODE_SHARED_FOLDER_OPEN_FL; success = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return success; } /* *----------------------------------------------------------------------------- * * HgfsUpdateNodeFileDesc -- * * Given a hgfs file handle, update the node with the new file desc (OS * handle) information. * * Results: * TRUE if the update is successful. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsUpdateNodeFileDesc(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info fileDesc fd, // IN: OS handle (file desc) void *fileCtx) // IN: OS file context { HgfsFileNode *node; Bool updated = FALSE; MXUser_AcquireExclLock(session->nodeArrayLock); node = HgfsHandle2FileNode(handle, session); if (node == NULL) { goto exit; } node->fileDesc = fd; node->fileCtx = fileCtx; updated = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return updated; } /* *----------------------------------------------------------------------------- * * HgfsUpdateNodeServerLock -- * * Given a file desc (OS handle), update the node with the new oplock * information. * * Results: * TRUE if the update is successful. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsUpdateNodeServerLock(fileDesc fd, // IN: OS handle HgfsSessionInfo *session, // IN: Session info HgfsLockType serverLock) // IN: new oplock { unsigned int i; HgfsFileNode *existingFileNode = NULL; Bool updated = FALSE; ASSERT(session); ASSERT(session->nodeArray); MXUser_AcquireExclLock(session->nodeArrayLock); for (i = 0; i < session->numNodes; i++) { existingFileNode = &session->nodeArray[i]; if (existingFileNode->state != FILENODE_STATE_UNUSED) { if (existingFileNode->fileDesc == fd) { existingFileNode->serverLock = serverLock; updated = TRUE; break; } } } MXUser_ReleaseExclLock(session->nodeArrayLock); return updated; } /* *----------------------------------------------------------------------------- * * HgfsUpdateNodeAppendFlag -- * * Given a hgfs file handle, update the node with the append flag info. * * Results: * TRUE if the update is successful. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsUpdateNodeAppendFlag(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info Bool appendFlag) // OUT: Append flag { HgfsFileNode *node; Bool updated = FALSE; MXUser_AcquireExclLock(session->nodeArrayLock); node = HgfsHandle2FileNode(handle, session); if (node == NULL) { goto exit; } if (appendFlag) { node->flags |= HGFS_FILE_NODE_APPEND_FL; } updated = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return updated; } /* *----------------------------------------------------------------------------- * * HgfsServerCheckOpenFlagsForShare -- * * Given an open mode check this is compatible with the mode for * the share upon which the open file resides. * * If the share is read only and mode is HGFS_OPEN_CREATE we remap * it to HGFS_OPEN which is allowed if the file exists. * * Results: * TRUE if the mode is compatible. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsServerCheckOpenFlagsForShare(HgfsFileOpenInfo *openInfo,// IN: Hgfs file handle HgfsOpenFlags *flags) // IN/OUT: open mode { Bool status = TRUE; HgfsNameStatus nameStatus; HgfsOpenMode shareMode; char const *inEnd; char const *next; int len; ASSERT(openInfo); ASSERT(flags); inEnd = openInfo->cpName + openInfo->cpNameSize; /* The share name is the first component of the cross-platform name. */ len = CPName_GetComponent(openInfo->cpName, inEnd, &next); if (len < 0) { LOG(4, ("%s: get first component failed\n", __FUNCTION__)); status = FALSE; goto exit; } nameStatus = HgfsServerPolicy_GetShareMode(openInfo->cpName, len, &shareMode); if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { status = FALSE; goto exit; } if (shareMode == HGFS_OPEN_MODE_READ_ONLY) { /* Read only share we may have work to do. */ if (*flags != HGFS_OPEN && *flags != HGFS_OPEN_CREATE) { status = FALSE; goto exit; } if (*flags == HGFS_OPEN_CREATE) { /* * Map open or create, to just open, which will fail if * if the file does not exist, which it is okay, as creating * a new file is not allowed and should be failed. */ *flags = HGFS_OPEN; } } exit: return status; } /* *----------------------------------------------------------------------------- * * HgfsDumpAllSearches -- * * Debugging routine; print all searches in the searchArray. * * Caller should hold the session's searchArrayLock. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsDumpAllSearches(HgfsSessionInfo *session) // IN: session info { unsigned int i; ASSERT(session); ASSERT(session->searchArray); Log("Dumping all searches\n"); for (i = 0; i < session->numSearches; i++) { Log("handle %u, baseDir \"%s\"\n", session->searchArray[i].handle, session->searchArray[i].utf8Dir ? session->searchArray[i].utf8Dir : "(NULL)"); } Log("Done\n"); } /* *----------------------------------------------------------------------------- * * HgfsGetNewNode -- * * Remove a node from the free list and return it. Nodes on * the free list should already be initialized. * * If the free list is empty, reallocates more memory, * initializes it appropriately, adds the new entries to the * free list, and then returns one off the free list. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * An unused file node on success * NULL on failure * * Side effects: * Memory allocation (potentially). * *----------------------------------------------------------------------------- */ static HgfsFileNode * HgfsGetNewNode(HgfsSessionInfo *session) // IN: session info { HgfsFileNode *node; HgfsFileNode *newMem; unsigned int newNumNodes; unsigned int i; ASSERT(session); ASSERT(session->nodeArray); LOG(4, ("%s: entered\n", __FUNCTION__)); if (!DblLnkLst_IsLinked(&session->nodeFreeList)) { /* * This has to be unsigned and with maximum bit length. This is * required to take care of "negative" differences as well. */ uintptr_t ptrDiff; if (DOLOG(4)) { Log("Dumping nodes before realloc\n"); HgfsDumpAllNodes(session); } /* Try to get twice as much memory as we had */ newNumNodes = 2 * session->numNodes; newMem = (HgfsFileNode *)realloc(session->nodeArray, newNumNodes * sizeof *(session->nodeArray)); if (!newMem) { LOG(4, ("%s: can't realloc more nodes\n", __FUNCTION__)); return NULL; } ptrDiff = (char *)newMem - (char *)session->nodeArray; if (ptrDiff) { size_t const oldSize = session->numNodes * sizeof *(session->nodeArray); /* * The portion of memory that contains all our file nodes moved. * All pointers that pointed inside the previous portion of memory * must be updated to point to the new portion of memory. * * We'll need to lock this if we multithread. */ LOG(4, ("Rebasing pointers, diff is %"FMTSZ"u, sizeof node is " "%"FMTSZ"u\n", ptrDiff, sizeof(HgfsFileNode))); LOG(4, ("old: %p new: %p\n", session->nodeArray, newMem)); ASSERT(newMem == (HgfsFileNode *)((char*)session->nodeArray + ptrDiff)); #define HgfsServerRebase(_ptr, _type) \ if ((size_t)((char *)_ptr - (char *)session->nodeArray) < oldSize) { \ _ptr = (_type *)((char *)_ptr + ptrDiff); \ } /* * Rebase the links of all file nodes */ for (i = 0; i < session->numNodes; i++) { HgfsServerRebase(newMem[i].links.prev, DblLnkLst_Links) HgfsServerRebase(newMem[i].links.next, DblLnkLst_Links) } /* * There is no need to rebase the anchor of the file node free list * because if we are here, it is empty. */ /* Rebase the anchor of the cached file nodes list. */ HgfsServerRebase(session->nodeCachedList.prev, DblLnkLst_Links) HgfsServerRebase(session->nodeCachedList.next, DblLnkLst_Links) #undef HgfsServerRebase } /* Initialize the new nodes */ LOG(4, ("numNodes was %u, now is %u\n", session->numNodes, newNumNodes)); for (i = session->numNodes; i < newNumNodes; i++) { DblLnkLst_Init(&newMem[i].links); newMem[i].state = FILENODE_STATE_UNUSED; newMem[i].utf8Name = NULL; newMem[i].utf8NameLen = 0; newMem[i].fileCtx = NULL; /* Append at the end of the list */ DblLnkLst_LinkLast(&session->nodeFreeList, &newMem[i].links); } session->nodeArray = newMem; session->numNodes = newNumNodes; if (DOLOG(4)) { Log("Dumping nodes after pointer changes\n"); HgfsDumpAllNodes(session); } } /* Remove the first item from the list */ node = DblLnkLst_Container(session->nodeFreeList.next, HgfsFileNode, links); DblLnkLst_Unlink1(&node->links); return node; } /* *----------------------------------------------------------------------------- * * HgfsRemoveFileNode -- * * Free its localname, clear its fields, return it to the free list. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * None * * Side effects: * node->utf8Name is freed. * node->state is set to FILENODE_STATE_UNUSED. * *----------------------------------------------------------------------------- */ static void HgfsRemoveFileNode(HgfsFileNode *node, // IN: file node HgfsSessionInfo *session) // IN: session info { ASSERT(node); LOG(4, ("%s: handle %u, name %s, fileId %"FMT64"u\n", __FUNCTION__, HgfsFileNode2Handle(node), node->utf8Name, node->localId.fileId)); if (node->shareName) { free(node->shareName); node->shareName = NULL; } if (node->utf8Name) { free(node->utf8Name); node->utf8Name = NULL; } node->state = FILENODE_STATE_UNUSED; ASSERT(node->fileCtx == NULL); node->fileCtx = NULL; if (node->shareInfo.rootDir) { free((void*)node->shareInfo.rootDir); node->shareInfo.rootDir = NULL; } /* Prepend at the beginning of the list */ DblLnkLst_LinkFirst(&session->nodeFreeList, &node->links); } /* *----------------------------------------------------------------------------- * * HgfsFreeFileNodeInternal -- * * Free its localname, clear its fields, return it to the free list. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * None * * Side effects: * node->utf8Name is freed. * node->state is set to FILENODE_STATE_UNUSED. * *----------------------------------------------------------------------------- */ static void HgfsFreeFileNodeInternal(HgfsHandle handle, // IN: Handle to free HgfsSessionInfo *session) // IN: Session info { HgfsFileNode *node = HgfsHandle2FileNode(handle, session); ASSERT(node); HgfsRemoveFileNode(node, session); } /* *----------------------------------------------------------------------------- * * HgfsFreeFileNode -- * * Free its localname, clear its fields, return it to the free list. * * Results: * None * * Side effects: * node->utf8Name is freed. * node->state is set to FILENODE_STATE_UNUSED. * *----------------------------------------------------------------------------- */ static void HgfsFreeFileNode(HgfsHandle handle, // IN: Handle to free HgfsSessionInfo *session) // IN: Session info { MXUser_AcquireExclLock(session->nodeArrayLock); HgfsFreeFileNodeInternal(handle, session); MXUser_ReleaseExclLock(session->nodeArrayLock); } /* *----------------------------------------------------------------------------- * * HgfsAddNewFileNode -- * * Gets a free node off the free list, sets its name, localId info, * file descriptor and permissions. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * A pointer to the newly added node on success * NULL on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsFileNode * HgfsAddNewFileNode(HgfsFileOpenInfo *openInfo, // IN: open info struct HgfsLocalId const *localId, // IN: Local unique file ID fileDesc fileDesc, // IN: File Handle Bool append, // IN: open with append flag size_t shareNameLen, // IN: share name byte length char const *shareName, // IN: share name Bool sharedFolderOpen, // IN: shared folder only open HgfsSessionInfo *session) // IN: session info { HgfsFileNode *newNode; char* rootDir; ASSERT(openInfo); ASSERT(localId); ASSERT(session); /* This was already verified in HgfsUnpackOpenRequest... */ ASSERT(openInfo->mask & HGFS_OPEN_VALID_FILE_NAME); /* Get an unused node */ newNode = HgfsGetNewNode(session); if (!newNode) { LOG(4, ("%s: out of memory\n", __FUNCTION__)); return NULL; } /* Set new node's fields */ if (!HgfsServerGetOpenMode(openInfo, &newNode->mode)) { HgfsRemoveFileNode(newNode, session); return NULL; } /* * Save a copy of the share name so we can look up its * access mode at various times over the node's lifecycle. */ newNode->shareName = malloc(shareNameLen + 1); if (newNode->shareName == NULL) { LOG(4, ("%s: out of memory\n", __FUNCTION__)); HgfsRemoveFileNode(newNode, session); return NULL; } memcpy(newNode->shareName, shareName, shareNameLen); newNode->shareName[shareNameLen] = '\0'; newNode->shareNameLen = shareNameLen; newNode->utf8NameLen = strlen(openInfo->utf8Name); newNode->utf8Name = malloc(newNode->utf8NameLen + 1); if (newNode->utf8Name == NULL) { LOG(4, ("%s: out of memory\n", __FUNCTION__)); HgfsRemoveFileNode(newNode, session); return NULL; } memcpy(newNode->utf8Name, openInfo->utf8Name, newNode->utf8NameLen); newNode->utf8Name[newNode->utf8NameLen] = '\0'; newNode->shareInfo.rootDirLen = strlen(openInfo->shareInfo.rootDir); rootDir = malloc(newNode->shareInfo.rootDirLen + 1); if (rootDir == NULL) { LOG(4, ("HgfsAddNewFileNode: out of memory\n")); HgfsRemoveFileNode(newNode, session); return NULL; } memcpy(rootDir, openInfo->shareInfo.rootDir, newNode->shareInfo.rootDirLen); rootDir[newNode->shareInfo.rootDirLen] = '\0'; newNode->shareInfo.rootDir = rootDir; newNode->handle = HgfsServerGetNextHandleCounter(); newNode->localId = *localId; newNode->fileDesc = fileDesc; newNode->shareAccess = (openInfo->mask & HGFS_OPEN_VALID_SHARE_ACCESS) ? openInfo->shareAccess : HGFS_DEFAULT_SHARE_ACCESS; newNode->flags = 0; if (append) { newNode->flags |= HGFS_FILE_NODE_APPEND_FL; } if (sharedFolderOpen) { newNode->flags |= HGFS_FILE_NODE_SHARED_FOLDER_OPEN_FL; } if (HGFS_OPEN_MODE_FLAGS(openInfo->mode) & HGFS_OPEN_SEQUENTIAL) { newNode->flags |= HGFS_FILE_NODE_SEQUENTIAL_FL; } newNode->serverLock = openInfo->acquiredLock; newNode->state = FILENODE_STATE_IN_USE_NOT_CACHED; newNode->shareInfo.readPermissions = openInfo->shareInfo.readPermissions; newNode->shareInfo.writePermissions = openInfo->shareInfo.writePermissions; newNode->shareInfo.handle = openInfo->shareInfo.handle; LOG(4, ("%s: got new node, handle %u\n", __FUNCTION__, HgfsFileNode2Handle(newNode))); return newNode; } /* *----------------------------------------------------------------------------- * * HgfsAddToCacheInternal -- * * Adds the node to cache. If the number of nodes in the cache exceed * the maximum number of entries then the first node is removed. The * first node should be the least recently used. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsAddToCacheInternal(HgfsHandle handle, // IN: HGFS file handle HgfsSessionInfo *session) // IN: Session info { HgfsFileNode *node; /* Check if the node is already cached. */ if (HgfsIsCachedInternal(handle, session)) { ASSERT((node = HgfsHandle2FileNode(handle, session)) && node->state == FILENODE_STATE_IN_USE_CACHED); return TRUE; } /* Remove the LRU node if the list is full. */ if (session->numCachedOpenNodes == gHgfsCfgSettings.maxCachedOpenNodes) { if (!HgfsRemoveLruNode(session)) { LOG(4, ("%s: Unable to remove LRU node from cache.\n", __FUNCTION__)); return FALSE; } } ASSERT(session->numCachedOpenNodes < gHgfsCfgSettings.maxCachedOpenNodes); node = HgfsHandle2FileNode(handle, session); ASSERT(node); /* Append at the end of the list. */ DblLnkLst_LinkLast(&session->nodeCachedList, &node->links); node->state = FILENODE_STATE_IN_USE_CACHED; session->numCachedOpenNodes++; /* * Keep track of how many open nodes we have with * server locks on them. The locked file should * always be present in the node cache. So we keep * the number of the files that have locks on them * limited, and smaller than the number of maximum * nodes in the cache. */ if (node->serverLock != HGFS_LOCK_NONE) { session->numCachedLockedNodes++; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsRemoveFromCacheInternal -- * * Remove the specified node from the cache and close the associated * file descriptor. If the node was not already in the cache then nothing * is done. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsRemoveFromCacheInternal(HgfsHandle handle, // IN: Hgfs handle to the node HgfsSessionInfo *session) // IN: Session info { HgfsFileNode *node; ASSERT(session); node = HgfsHandle2FileNode(handle, session); if (node == NULL) { LOG(4, ("%s: invalid handle.\n", __FUNCTION__)); return FALSE; } if (node->state == FILENODE_STATE_IN_USE_CACHED) { /* Unlink the node from the list of cached fileNodes. */ DblLnkLst_Unlink1(&node->links); node->state = FILENODE_STATE_IN_USE_NOT_CACHED; session->numCachedOpenNodes--; LOG(4, ("%s: cache entries %u remove node %s id %"FMT64"u fd %u .\n", __FUNCTION__, session->numCachedOpenNodes, node->utf8Name, node->localId.fileId, node->fileDesc)); /* * XXX: From this point and up in the call chain (i.e. this function and * all callers), Bool is returned instead of the HgfsInternalStatus. * HgfsPlatformCloseFile returns HgfsInternalStatus, which is far more granular, * but modifying this stack to use HgfsInternalStatus instead of Bool is * not worth it, as we'd have to #define per-platform error codes for * things like "ran out of memory", "bad file handle", etc. * * Instead, we'll just await the lobotomization of the node cache to * really fix this. */ if (HgfsPlatformCloseFile(node->fileDesc, node->fileCtx)) { LOG(4, ("%s: Could not close fd %u\n", __FUNCTION__, node->fileDesc)); return FALSE; } node->fileCtx = NULL; /* * If we have just removed the node then the number of used nodes better * be less than the max. If we didn't remove a node, it means the * node we tried to remove was not in the cache to begin with, and * we have a problem (see bug 36244). */ ASSERT(session->numCachedOpenNodes < gHgfsCfgSettings.maxCachedOpenNodes); } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsIsCachedInternal -- * * Check if the node exists in the cache. If the node is found in * the cache then move it to the end of the list. Most recently * used nodes move towards the end of the list. * * The session nodeArrayLock should be acquired prior to calling this * function. * * Results: * TRUE if the node is found in the cache. * FALSE if the node is not in the cache. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsIsCachedInternal(HgfsHandle handle, // IN: Structure representing file node HgfsSessionInfo *session) // IN: Session info { HgfsFileNode *node; ASSERT(session); node = HgfsHandle2FileNode(handle, session); if (node == NULL) { LOG(4, ("%s: invalid handle.\n", __FUNCTION__)); return FALSE; } if (node->state == FILENODE_STATE_IN_USE_CACHED) { /* * Move this node to the end of the list. */ DblLnkLst_Unlink1(&node->links); DblLnkLst_LinkLast(&session->nodeCachedList, &node->links); return TRUE; } return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsIsServerLockAllowed -- * * Check if there's room for another file node with the server lock. * If there's no room in the cache for the file with the server lock, * then the file will be opened without the lock even if the client * asked for the lock. * * * Results: * TRUE if the node is found in the cache. * FALSE if the node is not in the cache. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsIsServerLockAllowed(HgfsSessionInfo *session) // IN: session info { Bool allowed; MXUser_AcquireExclLock(session->nodeArrayLock); allowed = session->numCachedLockedNodes < MAX_LOCKED_FILENODES; MXUser_ReleaseExclLock(session->nodeArrayLock); return allowed; } /* *----------------------------------------------------------------------------- * * HgfsGetNewSearch -- * * Remove a search from the free list and return it. Searches on * the free list should already be initialized. * * If the free list is empty, reallocates more memory, * initializes it appropriately, adds the new entries to the * free list, and then returns one off the free list. * * Caller should hold the session's searchArrayLock. * * Results: * An unused search on success * NULL on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsSearch * HgfsGetNewSearch(HgfsSessionInfo *session) // IN: session info { HgfsSearch *search; HgfsSearch *newMem; unsigned int newNumSearches; unsigned int i; ASSERT(session); ASSERT(session->searchArray); LOG(4, ("%s: entered\n", __FUNCTION__)); if (!DblLnkLst_IsLinked(&session->searchFreeList)) { /* * This has to be unsigned and with maximum bit length. This is * required to take care of "negative" differences as well. */ uintptr_t ptrDiff; if (DOLOG(4)) { Log("Dumping searches before realloc\n"); HgfsDumpAllSearches(session); } /* Try to get twice as much memory as we had */ newNumSearches = 2 * session->numSearches; newMem = (HgfsSearch *)realloc(session->searchArray, newNumSearches * sizeof *(session->searchArray)); if (!newMem) { LOG(4, ("%s: can't realloc more searches\n", __FUNCTION__)); return NULL; } ptrDiff = (char *)newMem - (char *)session->searchArray; if (ptrDiff) { size_t const oldSize = session->numSearches * sizeof *(session->searchArray); /* * The portion of memory that contains all our searches moved. * All pointers that pointed inside the previous portion of memory * must be updated to point to the new portion of memory. */ LOG(4, ("Rebasing pointers, diff is %"FMTSZ"u, sizeof search is " "%"FMTSZ"u\n", ptrDiff, sizeof(HgfsSearch))); LOG(4, ("old: %p new: %p\n", session->searchArray, newMem)); ASSERT(newMem == (HgfsSearch*)((char*)session->searchArray + ptrDiff)); #define HgfsServerRebase(_ptr, _type) \ if ((size_t)((char *)_ptr - (char *)session->searchArray) < oldSize) { \ _ptr = (_type *)((char *)_ptr + ptrDiff); \ } /* * Rebase the links of all searches */ for (i = 0; i < session->numSearches; i++) { HgfsServerRebase(newMem[i].links.prev, DblLnkLst_Links) HgfsServerRebase(newMem[i].links.next, DblLnkLst_Links) } /* * There is no need to rebase the links of the search free list * because if we are here, it is empty */ #undef HgfsServerRebase } /* Initialize the new searches */ LOG(4, ("numSearches was %u, now is %u\n", session->numSearches, newNumSearches)); for (i = session->numSearches; i < newNumSearches; i++) { DblLnkLst_Init(&newMem[i].links); newMem[i].utf8Dir = NULL; newMem[i].utf8DirLen = 0; newMem[i].utf8ShareName = NULL; newMem[i].utf8ShareNameLen = 0; newMem[i].shareInfo.rootDir = NULL; newMem[i].shareInfo.rootDirLen = 0; newMem[i].dents = NULL; newMem[i].numDents = 0; /* Append at the end of the list */ DblLnkLst_LinkLast(&session->searchFreeList, &newMem[i].links); } session->searchArray = newMem; session->numSearches = newNumSearches; if (DOLOG(4)) { Log("Dumping searches after pointer changes\n"); HgfsDumpAllSearches(session); } } /* Remove the first item from the list */ search = DblLnkLst_Container(session->searchFreeList.next, HgfsSearch, links); DblLnkLst_Unlink1(&search->links); return search; } /* *----------------------------------------------------------------------------- * * HgfsSearch2SearchHandle -- * * Retrieve the handle that represents a search outside of the server. * * Caller should hold the session's searchArrayLock. * * Results: * The handle * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsHandle HgfsSearch2SearchHandle(HgfsSearch const *search) // IN { ASSERT(search); return search->handle; } /* *----------------------------------------------------------------------------- * * HgfsSearchIsBaseNameSpace -- * * Check if the search is the base of our name space, i.e. the dirents are * the shares themselves. * * Results: * TRUE if the search is the base of the name space, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsSearchIsBaseNameSpace(HgfsSearch const *search) // IN { ASSERT(search); return search->type == DIRECTORY_SEARCH_TYPE_BASE; } /* *----------------------------------------------------------------------------- * * HgfsGetSearchCopy -- * * Make a copy of the search. It should not be kept around for long, as the * data might become stale. This is mostly a convenience function to get * search fields more efficiently. * * Note that unlike HgfsGetNodeCopy, we always copy the name, and we never * copy the dents. * * Results: * TRUE if the hgfs handle is valid and the copy was successful. * FALSE otherwise. * * Side effects: * Allocates memory for search.utf8Dir * *----------------------------------------------------------------------------- */ Bool HgfsGetSearchCopy(HgfsHandle handle, // IN: Hgfs search handle HgfsSessionInfo *session, // IN: Session info HgfsSearch *copy) // IN/OUT: Copy of the search { HgfsSearch *original = NULL; Bool found = FALSE; ASSERT(copy); MXUser_AcquireExclLock(session->searchArrayLock); original = HgfsSearchHandle2Search(handle, session); if (original == NULL) { goto exit; } copy->utf8Dir = malloc(original->utf8DirLen + 1); if (copy->utf8Dir == NULL) { goto exit; } copy->utf8DirLen = original->utf8DirLen; memcpy(copy->utf8Dir, original->utf8Dir, copy->utf8DirLen); copy->utf8Dir[copy->utf8DirLen] = '\0'; copy->utf8ShareName = malloc(original->utf8ShareNameLen + 1); if (copy->utf8ShareName == NULL) { goto exit; } copy->utf8ShareNameLen = original->utf8ShareNameLen; memcpy(copy->utf8ShareName, original->utf8ShareName, copy->utf8ShareNameLen); copy->utf8ShareName[copy->utf8ShareNameLen] = '\0'; /* No dents for the copy, they consume too much memory and aren't needed. */ copy->dents = NULL; copy->numDents = 0; copy->handle = original->handle; copy->type = original->type; found = TRUE; exit: MXUser_ReleaseExclLock(session->searchArrayLock); return found; } /* *----------------------------------------------------------------------------- * * HgfsAddNewSearch -- * * Gets a free search off the free list, sets its base directory, dents, * and type. * * Caller should hold the session's searchArrayLock. * * Results: * A pointer to the newly added search on success * NULL on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsSearch * HgfsAddNewSearch(char const *utf8Dir, // IN: UTF8 name of dir to search in DirectorySearchType type, // IN: What kind of search is this? char const *utf8ShareName, // IN: Share name containing the directory char const *rootDir, // IN: Root directory for the share HgfsSessionInfo *session) // IN: Session info { HgfsSearch *newSearch; ASSERT(utf8Dir); /* Get an unused search */ newSearch = HgfsGetNewSearch(session); if (!newSearch) { LOG(4, ("%s: out of memory\n", __FUNCTION__)); return NULL; } newSearch->dents = NULL; newSearch->numDents = 0; newSearch->flags = 0; newSearch->type = type; newSearch->handle = HgfsServerGetNextHandleCounter(); newSearch->utf8DirLen = strlen(utf8Dir); newSearch->utf8Dir = Util_SafeStrdup(utf8Dir); newSearch->utf8ShareNameLen = strlen(utf8ShareName); newSearch->utf8ShareName = Util_SafeStrdup(utf8ShareName); newSearch->shareInfo.rootDirLen = strlen(rootDir); newSearch->shareInfo.rootDir = Util_SafeStrdup(rootDir); LOG(4, ("%s: got new search, handle %u\n", __FUNCTION__, HgfsSearch2SearchHandle(newSearch))); return newSearch; } /* *----------------------------------------------------------------------------- * * HgfsFreeSearchDirents -- * * Frees all dirents and dirents pointer array. * * Caller should hold the session's searchArrayLock. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsFreeSearchDirents(HgfsSearch *search) // IN/OUT: search { unsigned int i; if (NULL != search->dents) { for (i = 0; i < search->numDents; i++) { free(search->dents[i]); search->dents[i] = NULL; } free(search->dents); search->dents = NULL; } } /* *----------------------------------------------------------------------------- * * HgfsRemoveSearchInternal -- * * Destroy a search object and recycle it to the free list * * Caller should hold the session's searchArrayLock. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsRemoveSearchInternal(HgfsSearch *search, // IN: search HgfsSessionInfo *session) // IN: session info { ASSERT(search); ASSERT(session); LOG(4, ("%s: handle %u, dir %s\n", __FUNCTION__, HgfsSearch2SearchHandle(search), search->utf8Dir)); HgfsFreeSearchDirents(search); free(search->utf8Dir); free(search->utf8ShareName); free((char*)search->shareInfo.rootDir); search->utf8DirLen = 0; search->utf8Dir = NULL; search->utf8ShareNameLen = 0; search->utf8ShareName = NULL; search->shareInfo.rootDirLen = 0; search->shareInfo.rootDir = NULL; /* Prepend at the beginning of the list */ DblLnkLst_LinkFirst(&session->searchFreeList, &search->links); } /* *----------------------------------------------------------------------------- * * HgfsRemoveSearch -- * * Wrapper around HgfsRemoveSearchInternal that first takes the lock and * converts the handle to the search itself. * * Results: * TRUE if the search was freed successfully. * FALSE if the search could not be found. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsRemoveSearch(HgfsHandle handle, // IN: search HgfsSessionInfo *session) // IN: session info { HgfsSearch *search; Bool success = FALSE; MXUser_AcquireExclLock(session->searchArrayLock); search = HgfsSearchHandle2Search(handle, session); if (search != NULL) { HgfsRemoveSearchInternal(search, session); success = TRUE; } MXUser_ReleaseExclLock(session->searchArrayLock); return success; } /* *---------------------------------------------------------------------------- * * HgfsSearchHasReadAllEntries -- * * Return whether the client has read all the search entries or not. * * Results: * TRUE on success, FALSE on failure. readAllEntries is filled in on * success. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static Bool HgfsSearchHasReadAllEntries(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info Bool *readAllEntries) // OUT: If open was sequential { HgfsSearch *search; Bool success = FALSE; ASSERT(NULL != readAllEntries); MXUser_AcquireExclLock(session->searchArrayLock); search = HgfsSearchHandle2Search(handle, session); if (NULL == search) { goto exit; } *readAllEntries = search->flags & HGFS_SEARCH_FLAG_READ_ALL_ENTRIES; success = TRUE; exit: MXUser_ReleaseExclLock(session->searchArrayLock); return success; } /* *---------------------------------------------------------------------------- * * HgfsSearchSetReadAllEntries -- * * Set the flag to indicate the client has read all the search entries. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsSearchSetReadAllEntries(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session) // IN: Session info { HgfsSearch *search; MXUser_AcquireExclLock(session->searchArrayLock); search = HgfsSearchHandle2Search(handle, session); if (NULL == search) { goto exit; } search->flags |= HGFS_SEARCH_FLAG_READ_ALL_ENTRIES; exit: MXUser_ReleaseExclLock(session->searchArrayLock); } /* *----------------------------------------------------------------------------- * * HgfsServerGetDirEntry -- * * Returns a copy of the directory entry at the given index. If remove is set * to TRUE, the existing result is also pruned and the remaining results * are shifted up in the result array. * * Results: * NULL if there was an error or no search results were left. * Non-NULL if result was found. Caller must free it. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsServerGetDirEntry(HgfsHandle handle, // IN: Handle to search HgfsSessionInfo *session, // IN: Session info uint32 index, // IN: index to retrieve at Bool remove, // IN: If true, removes the result struct DirectoryEntry **dirEntry) // OUT: directory entry { HgfsSearch *search; struct DirectoryEntry *dent = NULL; HgfsInternalStatus status = HGFS_ERROR_SUCCESS; MXUser_AcquireExclLock(session->searchArrayLock); search = HgfsSearchHandle2Search(handle, session); if (search == NULL) { status = HGFS_ERROR_INVALID_HANDLE; goto out; } /* No more entries or none. */ if (search->dents == NULL) { goto out; } if (HGFS_SEARCH_LAST_ENTRY_INDEX == index) { /* Set the index to the final entry. */ index = search->numDents - 1; } status = HgfsPlatformGetDirEntry(search, session, index, remove, &dent); out: MXUser_ReleaseExclLock(session->searchArrayLock); *dirEntry = dent; return status; } /* *----------------------------------------------------------------------------- * * HgfsSearchHandle2Search -- * * Retrieve the search a handle refers to. * * Results: * The search if the handle is valid (i.e. it refers to an existing search * that is currently in use) * NULL if the handle is invalid * * Caller should hold the session's searchArrayLock. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsSearch * HgfsSearchHandle2Search(HgfsHandle handle, // IN: handle HgfsSessionInfo *session) // IN: session info { unsigned int i; HgfsSearch *search = NULL; ASSERT(session); ASSERT(session->searchArray); /* XXX: This O(n) lookup can and should be optimized. */ for (i = 0; i < session->numSearches; i++) { if (!DblLnkLst_IsLinked(&session->searchArray[i].links) && session->searchArray[i].handle == handle) { search = &session->searchArray[i]; break; } } return search; } /* *----------------------------------------------------------------------------- * * HgfsUpdateNodeNames -- * * Walk the node array and update all nodes that have the old file name to * store the new file name. * * Results: * None * * Side effects: * If there isnt enough memory to accomodate the new names, those file nodes * that couldnt be updated are deleted. * *----------------------------------------------------------------------------- */ void HgfsUpdateNodeNames(const char *oldLocalName, // IN: Name of file to look for const char *newLocalName, // IN: Name to replace with HgfsSessionInfo *session) // IN: Session info { HgfsFileNode *fileNode; unsigned int i; char *newBuffer; size_t newBufferLen; ASSERT(oldLocalName); ASSERT(newLocalName); ASSERT(session); ASSERT(session->nodeArray); newBufferLen = strlen(newLocalName); MXUser_AcquireExclLock(session->nodeArrayLock); for (i = 0; i < session->numNodes; i++) { fileNode = &session->nodeArray[i]; /* If the node is on the free list, skip it. */ if (fileNode->state == FILENODE_STATE_UNUSED) { continue; } if (strcmp(fileNode->utf8Name, oldLocalName) == 0) { newBuffer = malloc(newBufferLen + 1); if (!newBuffer) { LOG(4, ("%s: Failed to update a node name.\n", __FUNCTION__)); continue; } memcpy(newBuffer, newLocalName, newBufferLen); newBuffer[newBufferLen] = '\0'; /* Update this name to the new name. */ free(fileNode->utf8Name); fileNode->utf8Name = newBuffer; fileNode->utf8NameLen = newBufferLen; } } MXUser_ReleaseExclLock(session->nodeArrayLock); } /* *----------------------------------------------------------------------------- * * HgfsServerClose -- * * Handle a Close request. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerClose(HgfsInputParam *input) // IN: Input params { HgfsHandle file; HgfsInternalStatus status = HGFS_ERROR_SUCCESS; size_t replyPayloadSize = 0; HGFS_ASSERT_INPUT(input); if (HgfsUnpackCloseRequest(input->payload, input->payloadSize, input->op, &file)) { LOG(4, ("%s: close fh %u\n", __FUNCTION__, file)); if (!HgfsRemoveFromCache(file, input->session)) { LOG(4, ("%s: Could not remove the node from cache.\n", __FUNCTION__)); status = HGFS_ERROR_INVALID_HANDLE; } else { HgfsFreeFileNode(file, input->session); if (!HgfsPackCloseReply(input->packet, input->request, input->op, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else { status = HGFS_ERROR_INTERNAL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerSearchClose -- * * Handle a "Search Close" request. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerSearchClose(HgfsInputParam *input) // IN: Input params { HgfsHandle search; HgfsInternalStatus status; size_t replyPayloadSize = 0; HGFS_ASSERT_INPUT(input); if (HgfsUnpackSearchCloseRequest(input->payload, input->payloadSize, input->op, &search)) { LOG(4, ("%s: close search #%u\n", __FUNCTION__, search)); if (HgfsRemoveSearch(search, input->session)) { if (HgfsPackSearchCloseReply(input->packet, input->request, input->op, &replyPayloadSize, input->session)) { status = HGFS_ERROR_SUCCESS; } else { status = HGFS_ERROR_INTERNAL; } } else { /* Invalid handle */ LOG(4, ("%s: invalid handle %u\n", __FUNCTION__, search)); status = HGFS_ERROR_INVALID_HANDLE; } } else { status = HGFS_ERROR_INTERNAL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } #define HGFS_SIZEOF_OP(type) (sizeof (type) + sizeof (HgfsRequest)) /* Opcode handlers, indexed by opcode */ static struct { void (*handler)(HgfsInputParam *input); /* Minimal size of the request packet */ unsigned int minReqSize; /* How do you process the request {sync, async} ? */ RequestHint reqType; } const handlers[] = { { HgfsServerOpen, sizeof (HgfsRequestOpen), REQ_SYNC }, { HgfsServerRead, sizeof (HgfsRequestRead), REQ_SYNC }, { HgfsServerWrite, sizeof (HgfsRequestWrite), REQ_SYNC }, { HgfsServerClose, sizeof (HgfsRequestClose), REQ_SYNC }, { HgfsServerSearchOpen, sizeof (HgfsRequestSearchOpen), REQ_SYNC }, { HgfsServerSearchRead, sizeof (HgfsRequestSearchRead), REQ_SYNC }, { HgfsServerSearchClose, sizeof (HgfsRequestSearchClose), REQ_SYNC }, { HgfsServerGetattr, sizeof (HgfsRequestGetattr), REQ_SYNC }, { HgfsServerSetattr, sizeof (HgfsRequestSetattr), REQ_SYNC }, { HgfsServerCreateDir, sizeof (HgfsRequestCreateDir), REQ_SYNC }, { HgfsServerDeleteFile, sizeof (HgfsRequestDelete), REQ_SYNC }, { HgfsServerDeleteDir, sizeof (HgfsRequestDelete), REQ_SYNC }, { HgfsServerRename, sizeof (HgfsRequestRename), REQ_SYNC }, { HgfsServerQueryVolume, sizeof (HgfsRequestQueryVolume), REQ_SYNC }, { HgfsServerOpen, sizeof (HgfsRequestOpenV2), REQ_SYNC }, { HgfsServerGetattr, sizeof (HgfsRequestGetattrV2), REQ_SYNC }, { HgfsServerSetattr, sizeof (HgfsRequestSetattrV2), REQ_SYNC }, { HgfsServerSearchRead, sizeof (HgfsRequestSearchReadV2), REQ_SYNC }, { HgfsServerSymlinkCreate, sizeof (HgfsRequestSymlinkCreate), REQ_SYNC }, { HgfsServerServerLockChange, sizeof (HgfsRequestServerLockChange), REQ_SYNC }, { HgfsServerCreateDir, sizeof (HgfsRequestCreateDirV2), REQ_SYNC }, { HgfsServerDeleteFile, sizeof (HgfsRequestDeleteV2), REQ_SYNC }, { HgfsServerDeleteDir, sizeof (HgfsRequestDeleteV2), REQ_SYNC }, { HgfsServerRename, sizeof (HgfsRequestRenameV2), REQ_SYNC }, { HgfsServerOpen, HGFS_SIZEOF_OP(HgfsRequestOpenV3), REQ_SYNC }, { HgfsServerRead, HGFS_SIZEOF_OP(HgfsRequestReadV3), REQ_SYNC }, { HgfsServerWrite, HGFS_SIZEOF_OP(HgfsRequestWriteV3), REQ_SYNC }, { HgfsServerClose, HGFS_SIZEOF_OP(HgfsRequestCloseV3), REQ_SYNC }, { HgfsServerSearchOpen, HGFS_SIZEOF_OP(HgfsRequestSearchOpenV3), REQ_SYNC }, { HgfsServerSearchRead, HGFS_SIZEOF_OP(HgfsRequestSearchReadV3), REQ_SYNC }, { HgfsServerSearchClose, HGFS_SIZEOF_OP(HgfsRequestSearchCloseV3), REQ_SYNC }, { HgfsServerGetattr, HGFS_SIZEOF_OP(HgfsRequestGetattrV3), REQ_SYNC }, { HgfsServerSetattr, HGFS_SIZEOF_OP(HgfsRequestSetattrV3), REQ_SYNC }, { HgfsServerCreateDir, HGFS_SIZEOF_OP(HgfsRequestCreateDirV3), REQ_SYNC }, { HgfsServerDeleteFile, HGFS_SIZEOF_OP(HgfsRequestDeleteV3), REQ_SYNC }, { HgfsServerDeleteDir, HGFS_SIZEOF_OP(HgfsRequestDeleteV3), REQ_SYNC }, { HgfsServerRename, HGFS_SIZEOF_OP(HgfsRequestRenameV3), REQ_SYNC }, { HgfsServerQueryVolume, HGFS_SIZEOF_OP(HgfsRequestQueryVolumeV3), REQ_SYNC }, { HgfsServerSymlinkCreate, HGFS_SIZEOF_OP(HgfsRequestSymlinkCreateV3), REQ_SYNC }, { HgfsServerServerLockChange, sizeof (HgfsRequestServerLockChange), REQ_SYNC }, { HgfsServerWriteWin32Stream, HGFS_SIZEOF_OP(HgfsRequestWriteWin32StreamV3), REQ_SYNC }, /* * Starting from HGFS_OP_CREATE_SESSION_V4 (all V4 commands and above) the * second field is the minimum size for actual HGFS operational request * and not the minimum size of operational request with a header. */ { HgfsServerCreateSession, sizeof (HgfsRequestCreateSessionV4), REQ_SYNC}, { HgfsServerDestroySession, sizeof (HgfsRequestDestroySessionV4), REQ_SYNC}, { HgfsServerRead, sizeof (HgfsRequestReadV3), REQ_SYNC}, { HgfsServerWrite, sizeof (HgfsRequestWriteV3), REQ_SYNC}, { HgfsServerSetDirNotifyWatch, sizeof (HgfsRequestSetWatchV4), REQ_SYNC}, { HgfsServerRemoveDirNotifyWatch, sizeof (HgfsRequestRemoveWatchV4), REQ_SYNC}, { NULL, 0, REQ_SYNC}, // No Op notify { HgfsServerSearchRead, sizeof (HgfsRequestSearchReadV4), REQ_SYNC}, }; /* *----------------------------------------------------------------------------- * * HgfsServerInputAllocInit -- * * Allocates and initializes the input params object with the operation parameters. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerInputAllocInit(HgfsPacket *packet, // IN: packet HgfsTransportSessionInfo *transportSession,// IN: session HgfsSessionInfo *session, // IN: session Id const void *request, // IN: HGFS packet size_t requestSize, // IN: request packet size Bool sessionEnabled, // IN: session enabled request uint32 requestId, // IN: unique request id HgfsOp requestOp, // IN: op size_t requestOpArgsSize, // IN: op args size const void *requestOpArgs, // IN: op args HgfsInputParam **params) // OUT: parameters { HgfsInputParam *localParams; localParams = Util_SafeCalloc(1, sizeof *localParams); localParams->packet = packet; localParams->request = request; localParams->requestSize = requestSize; localParams->transportSession = transportSession; localParams->session = session; localParams->id = requestId; localParams->sessionEnabled = sessionEnabled; localParams->op = requestOp; localParams->payload = requestOpArgs; localParams->payloadSize = requestOpArgsSize; if (NULL != localParams->payload) { localParams->payloadOffset = (char *)localParams->payload - (char *)localParams->request; } *params = localParams; } /* *----------------------------------------------------------------------------- * * HgfsServerInputExit -- * * Tearsdown and frees the input params object with the operation parameters. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerInputExit(HgfsInputParam *params) // IN: packet { if (NULL != params->session) { HgfsServerSessionPut(params->session); } HgfsServerTransportSessionPut(params->transportSession); free(params); } /* *----------------------------------------------------------------------------- * * HgfsServerGetRequest -- * * Takes the Hgfs packet and extracts the operation parameters. * This validates the incoming packet as part of the processing. * * Results: * HGFS_ERROR_SUCCESS if all the request parameters are successfully extracted. * HGFS_ERROR_INTERNAL if an error occurs without sufficient request data to be * able to send a reply to the client. * Any other appropriate error if the incoming packet has errors and there is * sufficient information to send a response. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerGetRequest(HgfsPacket *packet, // IN: packet HgfsTransportSessionInfo *transportSession,// IN: session HgfsInputParam **input) // OUT: parameters { HgfsSessionInfo *session = NULL; uint64 sessionId = HGFS_INVALID_SESSION_ID; Bool sessionEnabled = FALSE; uint32 requestId; HgfsOp opcode; const void *request; size_t requestSize; const void *requestOpArgs; size_t requestOpArgsSize; HgfsInternalStatus parseStatus = HGFS_ERROR_SUCCESS; request = HSPU_GetMetaPacket(packet, &requestSize, transportSession->channelCbTable); if (NULL == request) { /* * How can I return error back to the client, clearly the client is either broken or * malicious? We cannot continue from here. */ parseStatus = HGFS_ERROR_INTERNAL; goto exit; } parseStatus = HgfsUnpackPacketParams(request, requestSize, &sessionEnabled, &sessionId, &requestId, &opcode, &requestOpArgsSize, &requestOpArgs); if (HGFS_ERROR_INTERNAL == parseStatus) { /* The packet was malformed and we cannot reply. */ goto exit; } /* * Every request must be processed within an HGFS session, except create session. * If we don't already have an HGFS session for processing this request, * then use or create the default session. */ if (sessionEnabled) { if (opcode != HGFS_OP_CREATE_SESSION_V4) { session = HgfsServerTransportGetSessionInfo(transportSession, sessionId); if (NULL == session || session->state != HGFS_SESSION_STATE_OPEN) { LOG(4, ("%s: HGFS packet with invalid session id!\n", __FUNCTION__)); parseStatus = HGFS_ERROR_STALE_SESSION; } } } else { parseStatus = HgfsServerTransportGetDefaultSession(transportSession, &session); } if (NULL != session) { session->isInactive = FALSE; } HgfsServerInputAllocInit(packet, transportSession, session, request, requestSize, sessionEnabled, requestId, opcode, requestOpArgsSize, requestOpArgs, input); exit: return parseStatus; } /* *----------------------------------------------------------------------------- * * HgfsServerGetHeaderSize -- * * Takes the Hgfs input and finds the size of the header component. * * Results: * Size of the HGFS protocol header used by this request or reply. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerGetHeaderSize(Bool sessionEnabled, // IN: session based request HgfsOp op, // IN: operation Bool request) // IN: TRUE for request, FALSE for reply { size_t headerSize; /* * If the HGFS request is session enabled we must have the new header. * Any V4 operation always must have the new header too. * Otherwise, starting from HGFS V3 the header is not included in the * request itself, so we must return the size of the separate header * structure, for requests this will be HgfsRequest and replies will be HgfsReply. * Prior to V3 (so V1 and V2) there was no separate header from the request * or reply structure for any given operation, so a zero size is returned for these. */ if (sessionEnabled) { headerSize = sizeof (HgfsHeader); } else if (op < HGFS_OP_CREATE_SESSION_V4 && op >= HGFS_OP_OPEN_V3) { headerSize = (request ? sizeof (HgfsRequest) : sizeof (HgfsReply)); } else { headerSize = 0; } return headerSize; } /* *----------------------------------------------------------------------------- * * HgfsServerGetRequestHeaderSize -- * * Takes the Hgfs request input and finds the size of the header component. * * Results: * Size of the HGFS protocol header used by this request and reply. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerGetRequestHeaderSize(Bool sessionEnabled, // IN: session based request HgfsOp op) // IN: operation { return HgfsServerGetHeaderSize(sessionEnabled, op, TRUE); } /* *----------------------------------------------------------------------------- * * HgfsServerGetReplyHeaderSize -- * * Takes the Hgfs reply input and finds the size of the header component. * * Results: * Size of the HGFS protocol header used by this reply. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerGetReplyHeaderSize(Bool sessionEnabled, // IN: session based request HgfsOp op) // IN: operation { return HgfsServerGetHeaderSize(sessionEnabled, op, FALSE); } /* *----------------------------------------------------------------------------- * * HgfsServerCompleteRequest -- * * Performs all necessary action which needed for completing HGFS request: * 1. Sends reply to the guest. * 2. Release allocated objects, mapped guest memory. * 3. Dereference objects that were referenced. * * Results: * None. * * Side effects: * Reference to Session is dropped. * *----------------------------------------------------------------------------- */ static void HgfsServerCompleteRequest(HgfsInternalStatus status, // IN: Status of the request size_t replyPayloadSize, // IN: sizeof the reply payload HgfsInputParam *input) // INOUT: request context { void *reply; size_t replySize; size_t replyTotalSize; size_t replyHeaderSize; uint64 replySessionId; if (HGFS_ERROR_SUCCESS == status) { HGFS_ASSERT_INPUT(input); } else { ASSERT(input); } replySessionId = (NULL != input->session) ? input->session->sessionId : HGFS_INVALID_SESSION_ID; replyHeaderSize = HgfsServerGetReplyHeaderSize(input->sessionEnabled, input->op); if (replyHeaderSize != 0) { replySize = replyHeaderSize + replyPayloadSize; } else { /* * For pre-V3 header is included in the payload size. * If we want to send just an error result then HgfsReply * only size is required. * * XXX - all callers should be verified that the reply payload * size for V1 and V2 should be correct (mininum HgfsReply size). */ replySize = MAX(replyPayloadSize, sizeof (HgfsReply)); } reply = HSPU_GetReplyPacket(input->packet, input->transportSession->channelCbTable, replySize, &replyTotalSize); ASSERT(reply && (replySize <= replyTotalSize)); if (!HgfsPackReplyHeader(status, replyPayloadSize, input->sessionEnabled, replySessionId, input->id, input->op, HGFS_PACKET_FLAG_REPLY, replyTotalSize, reply)) { Log("%s: Error packing header!\n", __FUNCTION__); goto exit; } if (!HgfsPacketSend(input->packet, input->transportSession, input->session, 0)) { /* Send failed. Drop the reply. */ Log("%s: Error sending reply\n", __FUNCTION__); } exit: HgfsServerInputExit(input); } /* *----------------------------------------------------------------------------- * * HgfsServerProcessRequest -- * * Dispatch an incoming packet (in packetIn) to a handler function. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerProcessRequest(void *context) { HgfsInputParam *input = (HgfsInputParam *)context; if (!input->request) { input->request = HSPU_GetMetaPacket(input->packet, &input->requestSize, input->transportSession->channelCbTable); } input->payload = (char *)input->request + input->payloadOffset; (*handlers[input->op].handler)(input); } /* *----------------------------------------------------------------------------- * * HgfsServerSessionReceive -- * * Dispatch an incoming packet (in packetIn) to a handler function. * * This function cannot fail; if something goes wrong, it returns * a packet containing only a reply header with error code. * * The handler function can send the reply packet either using * HgfsPacketSend helper functions. This function would return error * as a reply if the op handler do not return HGFS_ERROR_SUCCESS. * * NOTE: If any op handler needs to keep packetIn around for sending replies * at a later point (possibly in a different thread context), it should * make a copy of it. The validity of packetIn for the HGFS server is only * within the scope of this function. * * Definitions of Meta Packet, Data packet can be looked up in * hgfsChannelVmci.c * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerSessionReceive(HgfsPacket *packet, // IN: Hgfs Packet void *clientData) // IN: session info { HgfsTransportSessionInfo *transportSession = clientData; HgfsInternalStatus status; HgfsInputParam *input = NULL; ASSERT(transportSession); if (transportSession->state == HGFS_SESSION_STATE_CLOSED) { LOG(4, ("%s: %d: Received packet after disconnected.\n", __FUNCTION__, __LINE__)); return; } HgfsServerTransportSessionGet(transportSession); status = HgfsServerGetRequest(packet, transportSession, &input); if (HGFS_ERROR_INTERNAL == status) { LOG(4, ("%s: %d: Error: packet invalid and cannot reply %d.\n ", __FUNCTION__, __LINE__, status)); HgfsServerTransportSessionPut(transportSession); return; } HGFS_ASSERT_MINIMUM_OP(input->op); if (HGFS_ERROR_SUCCESS == status) { HGFS_ASSERT_INPUT(input); if ((input->op < ARRAYSIZE(handlers)) && (handlers[input->op].handler != NULL) && (input->requestSize >= handlers[input->op].minReqSize)) { /* Initial validation passed, process the client request now. */ if ((handlers[input->op].reqType == REQ_ASYNC) && (transportSession->channelCapabilities.flags & HGFS_CHANNEL_ASYNC)) { packet->state |= HGFS_STATE_ASYNC_REQUEST; } if (0 != (packet->state & HGFS_STATE_ASYNC_REQUEST)) { LOG(4, ("%s: %d: @@Async\n", __FUNCTION__, __LINE__)); #ifndef VMX86_TOOLS /* * Asynchronous processing is supported by the transport. * We can release mappings here and reacquire when needed. */ HSPU_PutMetaPacket(packet, transportSession->channelCbTable); input->request = NULL; HgfsServerAsyncInfoIncCount(&input->session->asyncRequestsInfo); /* Remove pending requests during poweroff. */ Poll_Callback(POLL_CS_MAIN, POLL_FLAG_REMOVE_AT_POWEROFF, HgfsServerProcessRequest, input, POLL_REALTIME, 1000, NULL); #else /* Tools code should never process request async. */ ASSERT(0); #endif } else { LOG(4, ("%s: %d: ##Sync\n", __FUNCTION__, __LINE__)); HgfsServerProcessRequest(input); } } else { /* * The input packet is smaller than the minimal size needed for the * operation. */ status = HGFS_ERROR_PROTOCOL; LOG(4, ("%s: %d: Possible BUG! Malformed packet.\n", __FUNCTION__, __LINE__)); } } HGFS_ASSERT_CLIENT(input->op); /* Send error if we fail to process the op. */ if (HGFS_ERROR_SUCCESS != status) { LOG(4, ("Error %d occured parsing the packet\n", (uint32)status)); HgfsServerCompleteRequest(status, 0, input); } } /* *----------------------------------------------------------------------------- * * HgfsServerTransportGetSessionInfo -- * * Scans the list of sessions and return the session with the specified * session id. * * Results: * A valid pointer to HgfsSessionInfo if there is a session with the * specified session id. NULL, otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsSessionInfo * HgfsServerTransportGetSessionInfo(HgfsTransportSessionInfo *transportSession, // IN: transport session info uint64 sessionId) // IN: session id { DblLnkLst_Links *curr; HgfsSessionInfo *session = NULL; ASSERT(transportSession); if (HGFS_INVALID_SESSION_ID == sessionId) { return NULL; } MXUser_AcquireExclLock(transportSession->sessionArrayLock); DblLnkLst_ForEach(curr, &transportSession->sessionArray) { session = DblLnkLst_Container(curr, HgfsSessionInfo, links); if (session->sessionId == sessionId) { HgfsServerSessionGet(session); break; } session = NULL; } MXUser_ReleaseExclLock(transportSession->sessionArrayLock); return session; } /* *----------------------------------------------------------------------------- * * HgfsServerTransportGetDefaultSession -- * * Returns default session if there is one, otherwise creates it. * XXX - this function should be moved to the HgfsServer file. * * Results: * HGFS_ERROR_SUCCESS and the session if found or created successfully * or an appropriate error if no memory or cannot add to the list of sessions. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerTransportGetDefaultSession(HgfsTransportSessionInfo *transportSession, // IN: transport HgfsSessionInfo **session) // OUT: session { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; HgfsSessionInfo *defaultSession; defaultSession = HgfsServerTransportGetSessionInfo(transportSession, transportSession->defaultSessionId); if (NULL != defaultSession) { /* The default session already exists, we are done. */ goto exit; } /* * Create a new session if the default session doesn't exist. */ if (!HgfsServerAllocateSession(transportSession, &defaultSession)) { status = HGFS_ERROR_NOT_ENOUGH_MEMORY; goto exit; } status = HgfsServerTransportAddSessionToList(transportSession, defaultSession); if (HGFS_ERROR_SUCCESS != status) { LOG(4, ("%s: Could not add session to the list.\n", __FUNCTION__)); HgfsServerSessionPut(defaultSession); defaultSession = NULL; goto exit; } transportSession->defaultSessionId = defaultSession->sessionId; HgfsServerSessionGet(defaultSession); exit: *session = defaultSession; return status; } /* *----------------------------------------------------------------------------- * * HgfsServerTransportRemoveSessionFromList -- * * Unlinks the specified session info from the list. * * Note: The caller must acquire the sessionArrayLock in transportSession * before calling this function. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsServerTransportRemoveSessionFromList(HgfsTransportSessionInfo *transportSession, // IN: transport session info HgfsSessionInfo *session) // IN: session info { ASSERT(transportSession); ASSERT(session); DblLnkLst_Unlink1(&session->links); transportSession->numSessions--; HgfsServerSessionPut(session); } /* *----------------------------------------------------------------------------- * * HgfsServerTransportAddSessionToList -- * * Links the specified session info to the list. * * Results: * HGFS_ERROR_SUCCESS if the session is successfully added to the list, * HGFS_ERROR_TOO_MANY_SESSIONS if maximum number of sessions were already * added to the list. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerTransportAddSessionToList(HgfsTransportSessionInfo *transportSession, // IN: transport session info HgfsSessionInfo *session) // IN: session info { HgfsInternalStatus status = HGFS_ERROR_TOO_MANY_SESSIONS; ASSERT(transportSession); ASSERT(session); MXUser_AcquireExclLock(transportSession->sessionArrayLock); if (transportSession->numSessions == MAX_SESSION_COUNT) { goto abort; } DblLnkLst_LinkLast(&transportSession->sessionArray, &session->links); transportSession->numSessions++; HgfsServerSessionGet(session); status = HGFS_ERROR_SUCCESS; abort: MXUser_ReleaseExclLock(transportSession->sessionArrayLock); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerSharesDeleteStale -- * * This function iterates through all shared folders and removes all * deleted shared folders, removes them from notification package and * from the folders list. * * Note: this assumes that the list lock is already acquired. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerSharesDeleteStale(DblLnkLst_Links *newSharesList) // IN: new list of shares { DblLnkLst_Links *link, *nextElem; DblLnkLst_ForEachSafe(link, nextElem, &gHgfsSharedFoldersList) { HgfsSharedFolderProperties *currentShare = DblLnkLst_Container(link, HgfsSharedFolderProperties, links); Bool staleShare = TRUE; DblLnkLst_Links *linkNewShare, *nextNewShare; DblLnkLst_ForEachSafe(linkNewShare, nextNewShare, newSharesList) { HgfsSharedFolder *newShare = DblLnkLst_Container(linkNewShare, HgfsSharedFolder, links); ASSERT(newShare); if (strcmp(currentShare->name, newShare->name) == 0) { LOG(4, ("%s: %s is still valid\n", __FUNCTION__, newShare->name)); staleShare = FALSE; break; } } if (staleShare) { LOG(8, ("%s: removing shared folder handle %#x\n", __FUNCTION__, currentShare->notificationHandle)); if (!HgfsNotify_RemoveSharedFolder(currentShare->notificationHandle)) { LOG(4, ("%s: Error: removing %d shared folder handle\n", __FUNCTION__, currentShare->notificationHandle)); } DblLnkLst_Unlink1(link); free(currentShare->name); free(currentShare); } } } /* *----------------------------------------------------------------------------- * * HgfsServerShareAddInternal -- * * Add a new shared folder property entry if it is not in the list of shares. * * Note: this assumes that the list lock is already acquired. * * Results: * The share handle if entry was found HGFS_INVALID_FOLDER_HANDLE if not. * * Side effects: * May add a shared folders entry for change notifications. * *----------------------------------------------------------------------------- */ static HgfsSharedFolderHandle HgfsServerShareAddInternal(const char *shareName, // IN: shared folder name const char *sharePath) // IN: shared folder path) { HgfsSharedFolderHandle handle = HGFS_INVALID_FOLDER_HANDLE; DblLnkLst_Links *link, *nextElem; DblLnkLst_ForEachSafe(link, nextElem, &gHgfsSharedFoldersList) { HgfsSharedFolderProperties *currentShare = DblLnkLst_Container(link, HgfsSharedFolderProperties, links); ASSERT(currentShare); if (strcmp(currentShare->name, shareName) == 0) { LOG(8, ("%s: Share is not new\n", __FUNCTION__)); handle = currentShare->notificationHandle; break; } } /* If the share is new then add it to the notification shares. */ if (handle == HGFS_INVALID_FOLDER_HANDLE) { handle = HgfsNotify_AddSharedFolder(sharePath, shareName); if (HGFS_INVALID_FOLDER_HANDLE != handle) { HgfsSharedFolderProperties *shareProps = (HgfsSharedFolderProperties *)Util_SafeMalloc(sizeof *shareProps); shareProps->notificationHandle = handle; shareProps->name = Util_SafeStrdup(shareName); DblLnkLst_Init(&shareProps->links); DblLnkLst_LinkLast(&gHgfsSharedFoldersList, &shareProps->links); } LOG(8, ("%s: %s, %s, add hnd %#x\n",__FUNCTION__, (shareName ? shareName : "NULL"), (sharePath ? sharePath : "NULL"), handle)); } return handle; } /* *----------------------------------------------------------------------------- * * HgfsServerShareAdd -- * * Add a new shared folder property entry if it is not in the list of shares. * * Note: this assumes that the list lock is already acquired. * * Results: * The shares handle if found or added. HGFS_INVALID_FOLDER_HANDLE otherwise. * * Side effects: * May add a shared folders entry for change notifications. * *----------------------------------------------------------------------------- */ static HgfsSharedFolderHandle HgfsServerShareAdd(const char *shareName, // IN: shared folder name const char *sharePath) // IN: shared folder path) // IN: List of new shares { HgfsSharedFolderHandle handle; LOG(8, ("%s: entered\n", __FUNCTION__)); if (!gHgfsDirNotifyActive) { LOG(8, ("%s: notification disabled\n", __FUNCTION__)); return HGFS_INVALID_FOLDER_HANDLE; } MXUser_AcquireExclLock(gHgfsSharedFoldersLock); handle = HgfsServerShareAddInternal(shareName, sharePath); MXUser_ReleaseExclLock(gHgfsSharedFoldersLock); LOG(8, ("%s: exit(%#x)\n", __FUNCTION__, handle)); return handle; } /* *----------------------------------------------------------------------------- * * HgfsServerSharesReset -- * * This is a callback function which is invoked by hgfsServerManagement * for every shared folder when something changed in shared folders * configuration. * The function any entries now not present as stale and removes them. * Any entries on the new list of shares not on the list of list of shares * will have new entries created and added to the list. * * Results: * None. * * Side effects: * May add an entry to known shared folders list. * *----------------------------------------------------------------------------- */ static void HgfsServerSharesReset(DblLnkLst_Links *newSharesList) // IN: List of new shares { DblLnkLst_Links *linkNewShare, *nextNewShare; LOG(8, ("%s: entered\n", __FUNCTION__)); if (!gHgfsDirNotifyActive) { LOG(8, ("%s: notification disabled\n", __FUNCTION__)); return; } MXUser_AcquireExclLock(gHgfsSharedFoldersLock); /* * Now we go through the shares properties list to * remove and delete those shares that are stale. */ HgfsServerSharesDeleteStale(newSharesList); /* * Iterate over the new shares and check for any not in the updated shares properties * list, as those will need a new share property created and added to the list. */ DblLnkLst_ForEachSafe(linkNewShare, nextNewShare, newSharesList) { HgfsSharedFolder *newShare = DblLnkLst_Container(linkNewShare, HgfsSharedFolder, links); ASSERT(newShare); HgfsServerShareAddInternal(newShare->name, newShare->path); } MXUser_ReleaseExclLock(gHgfsSharedFoldersLock); LOG(8, ("%s: exit\n", __FUNCTION__)); } /* *----------------------------------------------------------------------------- * * HgfsServerGetShareHandle -- * * The function returns shared folder notification handle for the specified * shared folder. * * Results: * HgfsSharedFolderHandle that corresponds to the shared folder. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static HgfsSharedFolderHandle HgfsServerGetShareHandle(const char *shareName) // IN: name of the shared folder { DblLnkLst_Links *link; HgfsSharedFolderHandle result = HGFS_INVALID_FOLDER_HANDLE; if (!gHgfsDirNotifyActive) { return HGFS_INVALID_FOLDER_HANDLE; } MXUser_AcquireExclLock(gHgfsSharedFoldersLock); DblLnkLst_ForEach(link, &gHgfsSharedFoldersList) { HgfsSharedFolderProperties *folder = DblLnkLst_Container(link, HgfsSharedFolderProperties, links); if (strcmp(folder->name, shareName) == 0) { result = folder->notificationHandle; break; } } MXUser_ReleaseExclLock(gHgfsSharedFoldersLock); return result; } /* *----------------------------------------------------------------------------- * * HgfsServerGetShareName -- * * Get the share name for a shared folder handle by looking at the * requested handle, finding the matching share (if any), and returning * the share's name. * * Results: * An Bool value indicating if the result is returned. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsServerGetShareName(HgfsSharedFolderHandle sharedFolder, // IN: Notify handle size_t *shareNameLen, // OUT: Name length char **shareName) // OUT: Share name { Bool result = FALSE; DblLnkLst_Links *link; if (!gHgfsDirNotifyActive) { return FALSE; } MXUser_AcquireExclLock(gHgfsSharedFoldersLock); DblLnkLst_ForEach(link, &gHgfsSharedFoldersList) { HgfsSharedFolderProperties *folder = DblLnkLst_Container(link, HgfsSharedFolderProperties, links); if (folder->notificationHandle == sharedFolder) { *shareName = Util_SafeStrdup(folder->name); result = TRUE; *shareNameLen = strlen(*shareName); break; } } MXUser_ReleaseExclLock(gHgfsSharedFoldersLock); return result; } /* *----------------------------------------------------------------------------- * * HgfsServer_InitState -- * * Initialize the global server state * * Results: * TRUE if succeeded, FALSE if failed. * * Side effects: * Memory allocation. * *----------------------------------------------------------------------------- */ Bool HgfsServer_InitState(const HgfsServerCallbacks **callbackTable, // IN/OUT: our callbacks HgfsServerConfig *serverCfgData, // IN: configurable settings HgfsServerMgrCallbacks *serverMgrData) // IN: mgr callback { Bool result = TRUE; ASSERT(callbackTable); /* Save any server manager data for logging state updates.*/ gHgfsMgrData = serverMgrData; if (NULL != serverCfgData) { gHgfsCfgSettings = *serverCfgData; } /* * Initialize the globals for handling the active shared folders. */ DblLnkLst_Init(&gHgfsSharedFoldersList); gHgfsSharedFoldersLock = MXUser_CreateExclLock("sharedFoldersLock", RANK_hgfsSharedFolders); if (!HgfsPlatformInit()) { LOG(4, ("Could not initialize server platform specific \n")); result = FALSE; } if (result) { *callbackTable = &gHgfsServerCBTable; if (0 != (gHgfsCfgSettings.flags & HGFS_CONFIG_NOTIFY_ENABLED)) { gHgfsDirNotifyActive = HgfsNotify_Init(&gHgfsServerNotifyCBTable) == HGFS_STATUS_SUCCESS; Log("%s: initialized notification %s.\n", __FUNCTION__, (gHgfsDirNotifyActive ? "active" : "inactive")); } if (0 != (gHgfsCfgSettings.flags & HGFS_CONFIG_OPLOCK_ENABLED)) { if (!HgfsServerOplockInit()) { gHgfsCfgSettings.flags &= ~HGFS_CONFIG_OPLOCK_ENABLED; } } } else { HgfsServer_ExitState(); // Cleanup partially initialized state } return result; } /* *----------------------------------------------------------------------------- * * HgfsServer_ExitState -- * * Cleanup the global server state. * * This function should be called when all other HGFS threads stopped * running. Otherwise we'll be in trouble because this is where we delete * the node array lock. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsServer_ExitState(void) { if (0 != (gHgfsCfgSettings.flags & HGFS_CONFIG_OPLOCK_ENABLED)) { HgfsServerOplockDestroy(); } if (gHgfsDirNotifyActive) { DblLnkLst_Links emptySharesList; DblLnkLst_Init(&emptySharesList); /* Make all existing shared folders stale and delete them. */ HgfsServerSharesReset(&emptySharesList); HgfsNotify_Exit(); gHgfsDirNotifyActive = FALSE; Log("%s: exit notification - inactive.\n", __FUNCTION__); } if (NULL != gHgfsSharedFoldersLock) { MXUser_DestroyExclLock(gHgfsSharedFoldersLock); gHgfsSharedFoldersLock = NULL; } HgfsPlatformDestroy(); /* * Reset the server manager callbacks. */ gHgfsMgrData = NULL; } /* *----------------------------------------------------------------------------- * * HgfsServer_ShareAccessCheck -- * * Checks if the requested mode may be granted depending on read/write * permissions. * * Results: * An HgfsNameStatus value indicating the result is returned. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsServer_ShareAccessCheck(HgfsOpenMode accessMode, // IN: open mode to check Bool shareWriteable, // IN: share is writable Bool shareReadable) // IN: share is readable { /* * See if access is allowed in the requested mode. * * XXX We should be using bits instead of an enum for HgfsOpenMode. * Add it to the todo list. [bac] */ switch (HGFS_OPEN_MODE_ACCMODE(accessMode)) { case HGFS_OPEN_MODE_READ_ONLY: if (!shareReadable) { LOG(4, ("%s: Read access denied\n", __FUNCTION__)); return FALSE; } break; case HGFS_OPEN_MODE_WRITE_ONLY: if (!shareWriteable) { LOG(4, ("%s: Write access denied\n", __FUNCTION__)); return FALSE; } break; case HGFS_OPEN_MODE_READ_WRITE: if (!shareReadable || !shareWriteable) { LOG(4, ("%s: Read/write access denied\n", __FUNCTION__)); return FALSE; } break; default: LOG(0, ("%s: Invalid mode %d\n", __FUNCTION__, accessMode)); ASSERT(FALSE); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsGenerateSessionId -- * * Generates unique session id. * * Results: * Unique 64-bit value. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static uint64 HgfsGenerateSessionId(void) { return RDTSC(); } /* *----------------------------------------------------------------------------- * * HgfsServerSetSessionCapability -- * * Sets session capability for a specific operation code. * * Results: * TRUE is the capability for the operation has been changed. * FALSE if the operation is not represented in the capabilities array. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsServerSetSessionCapability(HgfsOp op, // IN: operation code uint32 flags, // IN: flags that describe level of support HgfsSessionInfo *session) // INOUT: session to update { int i; Bool result = FALSE; for ( i = 0; i < ARRAYSIZE(session->hgfsSessionCapabilities); i++) { if (session->hgfsSessionCapabilities[i].op == op) { session->hgfsSessionCapabilities[i].flags = flags; result = TRUE; } } LOG(4, ("%s: Setting capabilitiy flags %x for op code %d %s\n", __FUNCTION__, flags, op, result ? "succeeded" : "failed")); return result; } /* *----------------------------------------------------------------------------- * * HgfsServerResEnumInit -- * * Initialize an enumeration of all exisitng resources. * * Results: * The enumeration state object. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void * HgfsServerResEnumInit(void) { void *enumState = NULL; if (gHgfsMgrData != NULL && gHgfsMgrData->enumResources.init != NULL) { enumState = gHgfsMgrData->enumResources.init(); } return enumState; } /* *----------------------------------------------------------------------------- * * HgfsServerResEnumGet -- * * Enumerates the next resource associated with the enumeration state. * * Results: * TRUE on success and . * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsServerResEnumGet(void *enumState, // IN/OUT: enumeration state char const **enumResName, // OUT: enumerated resource name size_t *enumResNameLen, // OUT: enumerated resource name len Bool *enumResDone) // OUT: enumerated resources done { Bool success = FALSE; if (gHgfsMgrData != NULL && gHgfsMgrData->enumResources.get != NULL) { success = gHgfsMgrData->enumResources.get(enumState, enumResName, enumResNameLen, enumResDone); } return success; } /* *----------------------------------------------------------------------------- * * HgfsServerResEnumExit -- * * Exit the enumeration of all existing resources. * * Results: * TRUE on success, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsServerResEnumExit(void *enumState) // IN/OUT: enumeration state { Bool success = FALSE; if (gHgfsMgrData != NULL && gHgfsMgrData->enumResources.exit != NULL) { success = gHgfsMgrData->enumResources.exit(enumState); } return success; } /* *----------------------------------------------------------------------------- * * HgfsServerEnumerateSharedFolders -- * * Enumerates all exisitng shared folders and registers shared folders with * directory notification package. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsServerEnumerateSharedFolders(void) { void *state; Bool success = FALSE; LOG(8, ("%s: entered\n", __FUNCTION__)); state = HgfsServerResEnumInit(); if (NULL != state) { Bool done; do { char const *shareName; size_t len; success = HgfsServerResEnumGet(state, &shareName, &len, &done); if (success && !done) { HgfsSharedFolderHandle handle; char const *sharePath; size_t sharePathLen; HgfsNameStatus nameStatus; nameStatus = HgfsServerPolicy_GetSharePath(shareName, len, HGFS_OPEN_MODE_READ_ONLY, &sharePathLen, &sharePath); if (HGFS_NAME_STATUS_COMPLETE == nameStatus) { LOG(8, ("%s: registering share %s path %s\n", __FUNCTION__, shareName, sharePath)); handle = HgfsServerShareAdd(shareName, sharePath); success = handle != HGFS_INVALID_FOLDER_HANDLE; LOG(8, ("%s: registering share %s hnd %#x\n", __FUNCTION__, shareName, handle)); } } } while (!done && success); HgfsServerResEnumExit(state); } LOG(8, ("%s: exit %d\n", __FUNCTION__, success)); return success; } /* *----------------------------------------------------------------------------- * * HgfsServerSessionConnect -- * * Initialize a new client session. * * Allocate HgfsTransportSessionInfo and initialize it. * * Results: * TRUE always. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsServerSessionConnect(void *transportData, // IN: transport session context HgfsServerChannelCallbacks *channelCbTable, // IN: Channel callbacks HgfsServerChannelData *channelCapabilities, // IN: channel capabilities void **transportSessionData) // OUT: server session context { ASSERT(transportSessionData); LOG(4, ("%s: initting.\n", __FUNCTION__)); *transportSessionData = HgfsServerTransportInit(transportData, channelCbTable, channelCapabilities); return TRUE; } /* *---------------------------------------------------------------------------- * * HgfsServerTransportInit -- * * Init a transport session. * * Allocated and initialize the transport session. * * Results: * The initialized transport session object. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static HgfsTransportSessionInfo * HgfsServerTransportInit(void *transportData, // IN: transport session context HgfsServerChannelCallbacks *channelCbTable, // IN: Channel callbacks HgfsServerChannelData *channelCapabilities) // IN: channel capabilities { HgfsTransportSessionInfo *transportSession; transportSession = Util_SafeCalloc(1, sizeof *transportSession); transportSession->transportData = transportData; transportSession->channelCbTable = channelCbTable; transportSession->type = HGFS_SESSION_TYPE_REGULAR; transportSession->state = HGFS_SESSION_STATE_OPEN; transportSession->channelCapabilities = *channelCapabilities; transportSession->numSessions = 0; transportSession->sessionArrayLock = MXUser_CreateExclLock("HgfsSessionArrayLock", RANK_hgfsSessionArrayLock); DblLnkLst_Init(&transportSession->sessionArray); transportSession->defaultSessionId = HGFS_INVALID_SESSION_ID; Atomic_Write(&transportSession->refCount, 0); /* Give our session a reference to hold while we are open. */ HgfsServerTransportSessionGet(transportSession); return transportSession; } /* *---------------------------------------------------------------------------- * * HgfsServerTransportExit -- * * Exit by destroying the transport session. * * Free session info data if no reference. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsServerTransportExit(HgfsTransportSessionInfo *transportSession) // IN: transport session context { DblLnkLst_Links *curr, *next; ASSERT(Atomic_Read(&transportSession->refCount) == 0); DblLnkLst_ForEachSafe(curr, next, &transportSession->sessionArray) { HgfsSessionInfo *session = DblLnkLst_Container(curr, HgfsSessionInfo, links); HgfsServerTransportRemoveSessionFromList(transportSession, session); HgfsServerSessionPut(session); } MXUser_DestroyExclLock(transportSession->sessionArrayLock); free(transportSession); } /* *----------------------------------------------------------------------------- * * HgfsServerAsyncInfoInit -- * * Initialize the async request info for a session. * * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerAsyncInfoInit(HgfsAsyncRequestInfo *info) // IN/OUT: info { Atomic_Write(&info->requestCount, 0); info->lock = MXUser_CreateExclLock("asyncLock", RANK_hgfsSharedFolders); info->requestCountIsZero = MXUser_CreateCondVarExclLock(info->lock); } /* *----------------------------------------------------------------------------- * * HgfsServerAsyncInfoExit -- * * Destroy the async request info for a session session. * * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerAsyncInfoExit(HgfsAsyncRequestInfo *info) // IN/OUT: info { ASSERT(Atomic_Read(&info->requestCount) == 0); if (NULL != info->lock) { MXUser_DestroyExclLock(info->lock); info->lock = NULL; } if (NULL != info->requestCountIsZero) { MXUser_DestroyCondVar(info->requestCountIsZero); info->requestCountIsZero = NULL; } } /* *----------------------------------------------------------------------------- * * HgfsServerAsyncWaitForAllRequestsDone -- * * Wait for all the async info requests to be done. * * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerAsyncWaitForAllRequestsDone(HgfsAsyncRequestInfo *info) // IN: info { MXUser_AcquireExclLock(info->lock); while (Atomic_Read(&info->requestCount)) { MXUser_WaitCondVarExclLock(info->lock, info->requestCountIsZero); } MXUser_ReleaseExclLock(info->lock); } /* *----------------------------------------------------------------------------- * * HgfsServerAsyncSignalAllRequestsDone -- * * Signal that all the async info requests are done. * * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerAsyncSignalAllRequestsDone(HgfsAsyncRequestInfo *info) // IN: info { MXUser_AcquireExclLock(info->lock); MXUser_BroadcastCondVar(info->requestCountIsZero); MXUser_ReleaseExclLock(info->lock); } /* *----------------------------------------------------------------------------- * * HgfsServerAsyncInfoDecCount -- * * Decrement the async info request count for a session. * * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerAsyncInfoDecCount(HgfsAsyncRequestInfo *info) // IN/OUT: info { if (Atomic_ReadDec32(&info->requestCount) == 1) { HgfsServerAsyncSignalAllRequestsDone(info); } } #ifndef VMX86_TOOLS /* *----------------------------------------------------------------------------- * * HgfsServerAsyncInfoIncCount -- * * Increment the async info request count for a session. * * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerAsyncInfoIncCount(HgfsAsyncRequestInfo *info) // IN/OUT: info { Atomic_Inc(&info->requestCount); } #endif // VMX86_TOOLS /* *----------------------------------------------------------------------------- * * HgfsServerAllocateSession -- * * Initialize a new Hgfs session. * * Allocate HgfsSessionInfo and initialize it. Create the nodeArray and * searchArray for the session. * * Results: * TRUE on success, FALSE otherwise. * * Side effects: * Allocates and initializes new session info. * *----------------------------------------------------------------------------- */ static Bool HgfsServerAllocateSession(HgfsTransportSessionInfo *transportSession, // IN: HgfsSessionInfo **sessionData) // OUT: { int i; HgfsSessionInfo *session; LOG(8, ("%s: entered\n", __FUNCTION__)); ASSERT(transportSession); session = Util_SafeCalloc(1, sizeof *session); /* * Initialize all our locks first as these can fail. */ session->fileIOLock = MXUser_CreateExclLock("HgfsFileIOLock", RANK_hgfsFileIOLock); session->nodeArrayLock = MXUser_CreateExclLock("HgfsNodeArrayLock", RANK_hgfsNodeArrayLock); session->searchArrayLock = MXUser_CreateExclLock("HgfsSearchArrayLock", RANK_hgfsSearchArrayLock); session->sessionId = HgfsGenerateSessionId(); session->state = HGFS_SESSION_STATE_OPEN; DblLnkLst_Init(&session->links); session->maxPacketSize = transportSession->channelCapabilities.maxPacketSize; session->flags |= HGFS_SESSION_MAXPACKETSIZE_VALID; session->isInactive = TRUE; session->transportSession = transportSession; session->numInvalidationAttempts = 0; /* * Initialize the node handling components. */ DblLnkLst_Init(&session->nodeFreeList); DblLnkLst_Init(&session->nodeCachedList); /* Allocate array of FileNodes and add them to free list. */ session->numNodes = NUM_FILE_NODES; session->nodeArray = Util_SafeCalloc(session->numNodes, sizeof (HgfsFileNode)); session->numCachedOpenNodes = 0; session->numCachedLockedNodes = 0; for (i = 0; i < session->numNodes; i++) { DblLnkLst_Init(&session->nodeArray[i].links); /* Append at the end of the list. */ DblLnkLst_LinkLast(&session->nodeFreeList, &session->nodeArray[i].links); } /* * Initialize the search handling components. */ /* Initialize search freelist. */ DblLnkLst_Init(&session->searchFreeList); /* Give our session a reference to hold while we are open. */ Atomic_Write(&session->refCount, 1); /* Allocate array of searches and add them to free list. */ session->numSearches = NUM_SEARCHES; session->searchArray = Util_SafeCalloc(session->numSearches, sizeof (HgfsSearch)); for (i = 0; i < session->numSearches; i++) { DblLnkLst_Init(&session->searchArray[i].links); /* Append at the end of the list. */ DblLnkLst_LinkLast(&session->searchFreeList, &session->searchArray[i].links); } /* Initialize the async request info.*/ HgfsServerAsyncInfoInit(&session->asyncRequestsInfo); /* Get common to all sessions capabiities. */ HgfsServerGetDefaultCapabilities(session->hgfsSessionCapabilities, &session->numberOfCapabilities); if (transportSession->channelCapabilities.flags & HGFS_CHANNEL_SHARED_MEM) { HgfsServerSetSessionCapability(HGFS_OP_READ_FAST_V4, HGFS_REQUEST_SUPPORTED, session); HgfsServerSetSessionCapability(HGFS_OP_WRITE_FAST_V4, HGFS_REQUEST_SUPPORTED, session); if (gHgfsDirNotifyActive) { LOG(8, ("%s: notify is enabled\n", __FUNCTION__)); if (HgfsServerEnumerateSharedFolders()) { HgfsServerSetSessionCapability(HGFS_OP_SET_WATCH_V4, HGFS_REQUEST_SUPPORTED, session); HgfsServerSetSessionCapability(HGFS_OP_REMOVE_WATCH_V4, HGFS_REQUEST_SUPPORTED, session); session->flags |= HGFS_SESSION_CHANGENOTIFY_ENABLED; } else { HgfsServerSetSessionCapability(HGFS_OP_SET_WATCH_V4, HGFS_REQUEST_NOT_SUPPORTED, session); HgfsServerSetSessionCapability(HGFS_OP_REMOVE_WATCH_V4, HGFS_REQUEST_NOT_SUPPORTED, session); } LOG(8, ("%s: session notify capability is %s\n", __FUNCTION__, (session->flags & HGFS_SESSION_CHANGENOTIFY_ENABLED ? "enabled" : "disabled"))); } HgfsServerSetSessionCapability(HGFS_OP_SEARCH_READ_V4, HGFS_REQUEST_SUPPORTED, session); } *sessionData = session; Log("%s: init session %p id %"FMT64"x\n", __FUNCTION__, session, session->sessionId); return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsDisconnectSessionInt -- * * Disconnect a client session. * * Mark the session as closed as we are in the process of teardown * of the session. No more new requests should be processed. We would * start draining any outstanding pending operations at this point. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsDisconnectSessionInt(HgfsSessionInfo *session) // IN: session context { LOG(8, ("%s: entered\n", __FUNCTION__)); ASSERT(session); ASSERT(session->nodeArray); ASSERT(session->searchArray); session->state = HGFS_SESSION_STATE_CLOSED; LOG(8, ("%s: exit\n", __FUNCTION__)); } /* *----------------------------------------------------------------------------- * * HgfsServerSessionDisconnect -- * * Disconnect a client session. * * Mark the session as closed as we are in the process of teardown * of the session. No more new requests should be processed. We would * start draining any outstanding pending operations at this point. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerSessionDisconnect(void *clientData) // IN: session context { HgfsTransportSessionInfo *transportSession = clientData; DblLnkLst_Links *curr, *next; LOG(8, ("%s: entered\n", __FUNCTION__)); ASSERT(transportSession); MXUser_AcquireExclLock(transportSession->sessionArrayLock); DblLnkLst_ForEachSafe(curr, next, &transportSession->sessionArray) { HgfsSessionInfo *session = DblLnkLst_Container(curr, HgfsSessionInfo, links); HgfsDisconnectSessionInt(session); } MXUser_ReleaseExclLock(transportSession->sessionArrayLock); transportSession->state = HGFS_SESSION_STATE_CLOSED; LOG(8, ("%s: exit\n", __FUNCTION__)); } /* *----------------------------------------------------------------------------- * * HgfsServerSessionClose -- * * Closes a client session. * * Remvoing the final reference will free the session's nodeArray * and seachArrary, and finally free the session object. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerSessionClose(void *clientData) // IN: session context { HgfsTransportSessionInfo *transportSession = clientData; LOG(8, ("%s: entered\n", __FUNCTION__)); ASSERT(transportSession); ASSERT(transportSession->state == HGFS_SESSION_STATE_CLOSED); /* Remove, typically, the last reference, will teardown everything. */ HgfsServerTransportSessionPut(transportSession); LOG(8, ("%s: exit\n", __FUNCTION__)); } /* *----------------------------------------------------------------------------- * * HgfsServerExitSessionInternal -- * * Destroys a session. * * Free the session's nodeArray and seachArrary. Free the session. * * The caller must have previously acquired the global sessions lock. * * Results: * TRUE on success, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerExitSessionInternal(HgfsSessionInfo *session) // IN: session context { int i; ASSERT(session); ASSERT(session->nodeArray); ASSERT(session->searchArray); ASSERT(session->state == HGFS_SESSION_STATE_CLOSED); /* Check and remove any notification handles we have for this session. */ if (session->flags & HGFS_SESSION_CHANGENOTIFY_ENABLED) { LOG(8, ("%s: calling notify component to disconnect\n", __FUNCTION__)); /* * This routine will synchronize itself with notification generator. * Therefore, it will remove subscribers and prevent the event generator * from generating any new events while it locks the subscribers lists. * New events will continue once more but with the updated subscriber list * that will not contain this session. */ HgfsNotify_RemoveSessionSubscribers(session); } MXUser_AcquireExclLock(session->nodeArrayLock); Log("%s: teardown session %p id 0x%"FMT64"x\n", __FUNCTION__, session, session->sessionId); /* Recycle all nodes that are still in use, then destroy the node pool. */ for (i = 0; i < session->numNodes; i++) { HgfsHandle handle; if (session->nodeArray[i].state == FILENODE_STATE_UNUSED) { continue; } handle = HgfsFileNode2Handle(&session->nodeArray[i]); HgfsRemoveFromCacheInternal(handle, session); HgfsFreeFileNodeInternal(handle, session); } free(session->nodeArray); session->nodeArray = NULL; MXUser_ReleaseExclLock(session->nodeArrayLock); /* * Recycle all searches that are still in use, then destroy the * search pool. */ MXUser_AcquireExclLock(session->searchArrayLock); for (i = 0; i < session->numSearches; i++) { if (DblLnkLst_IsLinked(&session->searchArray[i].links)) { continue; } HgfsRemoveSearchInternal(&session->searchArray[i], session); } free(session->searchArray); session->searchArray = NULL; MXUser_ReleaseExclLock(session->searchArrayLock); /* Teardown the locks for the sessions and destroy itself. */ MXUser_DestroyExclLock(session->nodeArrayLock); MXUser_DestroyExclLock(session->searchArrayLock); MXUser_DestroyExclLock(session->fileIOLock); /* Teardown the async request info.*/ HgfsServerAsyncInfoExit(&session->asyncRequestsInfo); free(session); } /* *----------------------------------------------------------------------------- * * HgfsServer_GetHandleCounter -- * * Return file handle counter. This is used by the checkpointing code to * checkpoint this value so we avoid the risk of handle collision. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ uint32 HgfsServer_GetHandleCounter(void) { return HgfsServerGetHandleCounter(); } /* *----------------------------------------------------------------------------- * * HgfsServer_SetHandleCounter -- * * Set the file handle counter. This is used by the checkpointing code to * restore this value so we avoid the risk of handle collision. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsServer_SetHandleCounter(uint32 newHandleCounter) { HgfsServerInitHandleCounter(newHandleCounter); } /* *---------------------------------------------------------------------------- * * HgfsServerSessionSendComplete -- * * This is called by the Transport when it is done sending the packet. * Free the buffer. If we allocate buffers per session we have the session * that the buffer belongs too. * * Results: * None. * * Side effects: * Frees the packet buffer. * *--------------------------------------------------------------------------- */ void HgfsServerSessionSendComplete(HgfsPacket *packet, // IN/OUT: Hgfs packet void *clientData) // IN: session info { HgfsTransportSessionInfo *transportSession = clientData; if (0 != (packet->state & HGFS_STATE_CLIENT_REQUEST)) { HSPU_PutMetaPacket(packet, transportSession->channelCbTable); HSPU_PutReplyPacket(packet, transportSession->channelCbTable); HSPU_PutDataPacketBuf(packet, transportSession->channelCbTable); } else { if (packet->metaPacketIsAllocated) { free(packet->metaPacket); } free(packet); } } /* *---------------------------------------------------------------------------- * * HgfsServerSessionQuiesce -- * * The function is called when VM is about to take a snapshot and * when creation of the snapshot completed. When the freeze is TRUE the * function quiesces all asynchronous and background activity to prevent * interactions with snapshots and waits until there is no such activity. * When freeze is FALSE the function restarts background activity that * has been suspended previously. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsServerSessionQuiesce(void *clientData, // IN: transport and session HgfsQuiesceOp quiesceOp) // IN: operation { HgfsTransportSessionInfo *transportSession = clientData; DblLnkLst_Links *curr; LOG(4, ("%s: Beginning\n", __FUNCTION__)); MXUser_AcquireExclLock(transportSession->sessionArrayLock); DblLnkLst_ForEach(curr, &transportSession->sessionArray) { HgfsSessionInfo *session = DblLnkLst_Container(curr, HgfsSessionInfo, links); switch(quiesceOp) { case HGFS_QUIESCE_FREEZE: /* Suspend background activity. */ LOG(8, ("%s: Halt file system activity for session %p\n", __FUNCTION__, session)); if (gHgfsDirNotifyActive) { HgfsNotify_Deactivate(HGFS_NOTIFY_REASON_SERVER_SYNC, session); } HgfsServerAsyncWaitForAllRequestsDone(&session->asyncRequestsInfo); break; case HGFS_QUIESCE_THAW: /* Resume background activity. */ LOG(8, ("%s: Resume file system activity for session %p\n", __FUNCTION__, session)); if (gHgfsDirNotifyActive) { HgfsNotify_Activate(HGFS_NOTIFY_REASON_SERVER_SYNC, session); } break; default: NOT_REACHED(); } } MXUser_ReleaseExclLock(transportSession->sessionArrayLock); LOG(4, ("%s: Ending\n", __FUNCTION__)); } /* *---------------------------------------------------------------------------- * * HgfsPacketSend -- * * Send the packet. * * Results: * TRUE on success, FALSE on error. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static Bool HgfsPacketSend(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsTransportSessionInfo *transportSession, // IN: transport HgfsSessionInfo *session, // IN: session info HgfsSendFlags flags) // IN: send flags { Bool result = FALSE; Bool asyncClientRequest = (0 != (packet->state & HGFS_STATE_CLIENT_REQUEST) && 0 != (packet->state & HGFS_STATE_ASYNC_REQUEST)); ASSERT(packet); ASSERT(transportSession); if (transportSession->state == HGFS_SESSION_STATE_OPEN) { ASSERT(transportSession->type == HGFS_SESSION_TYPE_REGULAR); result = transportSession->channelCbTable->send(transportSession->transportData, packet, flags); } if (asyncClientRequest) { ASSERT(session); HgfsServerAsyncInfoDecCount(&session->asyncRequestsInfo); } return result; } /* *----------------------------------------------------------------------------- * * HgfsInvalidateSessionObjects -- * * Iterates over all nodes and searches, invalidating and removing those * that are no longer within a share. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsInvalidateSessionObjects(DblLnkLst_Links *shares, // IN: List of new shares HgfsSessionInfo *session) // IN: Session info { unsigned int i; ASSERT(shares); ASSERT(session); ASSERT(session->nodeArray); ASSERT(session->searchArray); LOG(4, ("%s: Beginning\n", __FUNCTION__)); MXUser_AcquireExclLock(session->nodeArrayLock); /* * Iterate over each node, skipping those that are unused. For each node, * if its filename is no longer within a share, remove it. */ for (i = 0; i < session->numNodes; i++) { HgfsHandle handle; DblLnkLst_Links *l; if (session->nodeArray[i].state == FILENODE_STATE_UNUSED) { continue; } handle = HgfsFileNode2Handle(&session->nodeArray[i]); LOG(4, ("%s: Examining node with fd %d (%s)\n", __FUNCTION__, handle, session->nodeArray[i].utf8Name)); /* For each share, is the node within the share? */ for (l = shares->next; l != shares; l = l->next) { HgfsSharedFolder *share; share = DblLnkLst_Container(l, HgfsSharedFolder, links); ASSERT(share); if (strcmp(session->nodeArray[i].shareInfo.rootDir, share->path) == 0) { LOG(4, ("%s: Node is still valid\n", __FUNCTION__)); break; } } /* If the node wasn't found in any share, remove it. */ if (l == shares) { LOG(4, ("%s: Node is invalid, removing\n", __FUNCTION__)); if (!HgfsRemoveFromCacheInternal(handle, session)) { LOG(4, ("%s: Could not remove node with " "fh %d from the cache.\n", __FUNCTION__, handle)); } else { HgfsFreeFileNodeInternal(handle, session); } } } MXUser_ReleaseExclLock(session->nodeArrayLock); MXUser_AcquireExclLock(session->searchArrayLock); /* * Iterate over each search, skipping those that are on the free list. For * each search, if its base name is no longer within a share, remove it. */ for (i = 0; i < session->numSearches; i++) { DblLnkLst_Links *l; if (DblLnkLst_IsLinked(&session->searchArray[i].links)) { continue; } if (HgfsSearchIsBaseNameSpace(&session->searchArray[i])) { /* Skip search of the base name space. Maybe stale but it is okay. */ continue; } LOG(4, ("%s: Examining search (%s)\n", __FUNCTION__, session->searchArray[i].utf8Dir)); /* For each share, is the search within the share? */ for (l = shares->next; l != shares; l = l->next) { HgfsSharedFolder *share; share = DblLnkLst_Container(l, HgfsSharedFolder, links); ASSERT(share); if (strcmp(session->searchArray[i].shareInfo.rootDir, share->path) == 0) { LOG(4, ("%s: Search is still valid\n", __FUNCTION__)); break; } } /* If the node wasn't found in any share, remove it. */ if (l == shares) { LOG(4, ("%s: Search is invalid, removing\n", __FUNCTION__)); HgfsRemoveSearchInternal(&session->searchArray[i], session); } } MXUser_ReleaseExclLock(session->searchArrayLock); LOG(4, ("%s: Ending\n", __FUNCTION__)); } /* *----------------------------------------------------------------------------- * * HgfsServerSessionInvalidateObjects -- * * Iterates over all sessions and invalidate session objects for the shares * removed. * * Caller guarantees that the sessions won't go away under us, so no locks * needed. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsServerSessionInvalidateObjects(void *clientData, // IN: DblLnkLst_Links *shares) // IN: List of new shares { HgfsTransportSessionInfo *transportSession = clientData; DblLnkLst_Links *curr; LOG(4, ("%s: Beginning\n", __FUNCTION__)); ASSERT(transportSession); MXUser_AcquireExclLock(transportSession->sessionArrayLock); DblLnkLst_ForEach(curr, &transportSession->sessionArray) { HgfsSessionInfo *session = DblLnkLst_Container(curr, HgfsSessionInfo, links); HgfsServerSessionGet(session); HgfsInvalidateSessionObjects(shares, session); HgfsServerSessionPut(session); } MXUser_ReleaseExclLock(transportSession->sessionArrayLock); /* Now invalidate any stale shares and add any new ones. */ HgfsServerSharesReset(shares); LOG(4, ("%s: Ending\n", __FUNCTION__)); } /* *----------------------------------------------------------------------------- * * HgfsServerSessionInvalidateInactiveSessions -- * * Iterates over all sessions and invalidate all inactive session objects. * * Following clock algorithm is used to determine whether the session object * is inactive or not. * * When this function is called, the HGFS server manager will iterate * over all the sessions belonging to this manager. Each session is marked * as inactive. Whenever a message is processed for a session, that * session is marked as active. When this function is called the next time, * any sessions that are still inactive will be invalidated. * * Caller guarantees that the sessions won't go away under us, so no locks * needed. * * Results: * Number of active sessions remaining inside the HGFS server. * * Side effects: * None * *----------------------------------------------------------------------------- */ uint32 HgfsServerSessionInvalidateInactiveSessions(void *clientData) // IN: { HgfsTransportSessionInfo *transportSession = clientData; uint32 numActiveSessionsLeft = 0; DblLnkLst_Links shares, *curr, *next; ASSERT(transportSession); MXUser_AcquireExclLock(transportSession->sessionArrayLock); DblLnkLst_Init(&shares); DblLnkLst_ForEachSafe(curr, next, &transportSession->sessionArray) { HgfsSessionInfo *session = DblLnkLst_Container(curr, HgfsSessionInfo, links); HgfsServerSessionGet(session); session->numInvalidationAttempts++; numActiveSessionsLeft++; /* * Check if the session is inactive. If the session is inactive, then * invalidate the session objects. */ if (session->isInactive) { if (session->numInvalidationAttempts == MAX_SESSION_INVALIDATION_ATTEMPTS) { LOG(4, ("%s: closing inactive session %"FMT64"x\n", __FUNCTION__, session->sessionId)); session->state = HGFS_SESSION_STATE_CLOSED; HgfsServerTransportRemoveSessionFromList(transportSession, session); /* * We need to reduce the refcount by 1 since we want to * destroy the session. */ numActiveSessionsLeft--; HgfsServerSessionPut(session); } else { HgfsInvalidateSessionObjects(&shares, session); } } else { session->isInactive = TRUE; session->numInvalidationAttempts = 0; } HgfsServerSessionPut(session); } MXUser_ReleaseExclLock(transportSession->sessionArrayLock); return numActiveSessionsLeft; } /* *----------------------------------------------------------------------------- * * HgfsServerStatFs -- * * Calls on the wiper library to return the number of free bytes and * total bytes on the filesystem underlying the given pathname. * * Results: * TRUE if successful: freeBytes and totalBytes have been written to. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsServerStatFs(const char *pathName, // IN: Path we're interested in size_t pathLength, // IN: Length of path uint64 *freeBytes, // OUT: Free bytes on volume uint64 *totalBytes) // OUT: Total bytes on volume { WiperPartition p; unsigned char *wiperError; ASSERT(pathName); ASSERT(freeBytes); ASSERT(totalBytes); Wiper_Init(NULL); /* * Sanity checks. If length is good, assume well-formed drive path * (i.e. "C:\..." or "\\abc..."). Note that we throw out shares that * exactly equal p.mountPoint's size because we won't have room for a null * delimiter on copy. Allow 0 length drives so that hidden feature "" can * work. */ if (pathLength >= sizeof p.mountPoint) { LOG(4, ("%s: could not get the volume name\n", __FUNCTION__)); return FALSE; } /* Now call the wiper lib to get space information. */ Str_Strcpy(p.mountPoint, pathName, sizeof p.mountPoint); wiperError = WiperSinglePartition_GetSpace(&p, NULL, freeBytes, totalBytes); if (strlen(wiperError) > 0) { LOG(4, ("%s: error using wiper lib: %s\n", __FUNCTION__, wiperError)); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsServerGetLocalNameInfo -- * * Construct local name based on the crossplatform CPName for the file and the * share information. * * The name returned is allocated and must be freed by the caller. * The name length is optionally returned. * * Results: * A status code indicating either success (correspondent share exists) or * a failure status. * * Side effects: * Memory allocation in the success case * *----------------------------------------------------------------------------- */ static HgfsNameStatus HgfsServerGetLocalNameInfo(const char *cpName, // IN: Cross-platform filename to check size_t cpNameSize, // IN: Size of name cpName uint32 caseFlags, // IN: Case-sensitivity flags HgfsShareInfo *shareInfo,// OUT: properties of the shared folder char **bufOut, // OUT: File name in local fs size_t *outLen) // OUT: Length of name out optional { HgfsNameStatus nameStatus; const char *inEnd; const char *next; char *myBufOut; char *convertedMyBufOut; char *out; size_t outSize; size_t myBufOutLen; size_t convertedMyBufOutLen; int len; uint32 pathNameLen; char tempBuf[HGFS_PATH_MAX]; size_t tempSize; char *tempPtr; uint32 startIndex = 0; HgfsShareOptions shareOptions; ASSERT(cpName); ASSERT(bufOut); inEnd = cpName + cpNameSize; if (!Unicode_IsBufferValid(cpName, cpNameSize, STRING_ENCODING_UTF8)) { LOG(4, ("%s: invalid UTF8 string @ %p\n", __FUNCTION__, cpName)); return HGFS_NAME_STATUS_FAILURE; } /* * Get first component. */ len = CPName_GetComponent(cpName, inEnd, &next); if (len < 0) { LOG(4, ("%s: get first component failed\n", __FUNCTION__)); return HGFS_NAME_STATUS_FAILURE; } /* See if we are dealing with the base of the namespace */ if (!len) { return HGFS_NAME_STATUS_INCOMPLETE_BASE; } /* Check permission on the share and get the share path */ nameStatus = HgfsServerPolicy_ProcessCPName(cpName, len, &shareInfo->readPermissions, &shareInfo->writePermissions, &shareInfo->handle, // XXX: to be deleted. &shareInfo->rootDir); if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { LOG(4, ("%s: No such share (%s)\n", __FUNCTION__, cpName)); return nameStatus; } shareInfo->rootDirLen = strlen(shareInfo->rootDir); /* * XXX: The handle is now NOT propagated back and held in the policy but only in the * table of share properties. * * Get shareInfo handle returns a valid handle only if we have change * notification active. * Note: cpName begins with the share name. */ shareInfo->handle = HgfsServerGetShareHandle(cpName); /* Get the config options. */ nameStatus = HgfsServerPolicy_GetShareOptions(cpName, len, &shareOptions); if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { LOG(4, ("%s: no matching share: %s.\n", __FUNCTION__, cpName)); return nameStatus; } /* Point to the next component, if any */ cpNameSize -= next - cpName; cpName = next; /* * Allocate space for the string. We trim the unused space later. */ outSize = HGFS_PATH_MAX; myBufOut = (char *) malloc(outSize * sizeof *myBufOut); if (!myBufOut) { LOG(4, ("%s: out of memory allocating string\n", __FUNCTION__)); return HGFS_NAME_STATUS_OUT_OF_MEMORY; } out = myBufOut; /* * See if we are dealing with a "root" share or regular share */ if (shareInfo->rootDirLen == 0) { size_t prefixLen; /* Are root shares allowed? If not, we exit with an error. */ if (0 == (gHgfsCfgSettings.flags & HGFS_CONFIG_SHARE_ALL_HOST_DRIVES_ENABLED)) { LOG(4, ("%s: Root share being used\n", __FUNCTION__)); nameStatus = HGFS_NAME_STATUS_ACCESS_DENIED; goto error; } /* * This is a "root" share. Interpret the input appropriately as * either a drive letter or UNC name and append it to the output * buffer (for Win32) or simply get the prefix for root (for * linux). */ tempSize = sizeof tempBuf; tempPtr = tempBuf; nameStatus = CPName_ConvertFromRoot(&cpName, &cpNameSize, &tempSize, &tempPtr); if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { LOG(4, ("%s: ConvertFromRoot not complete\n", __FUNCTION__)); goto error; } prefixLen = tempPtr - tempBuf; /* Copy the UTF8 prefix to the output buffer. */ if (prefixLen >= HGFS_PATH_MAX) { Log("%s: error: prefix too long\n", __FUNCTION__); nameStatus = HGFS_NAME_STATUS_TOO_LONG; goto error; } memcpy(out, tempBuf, prefixLen); out += prefixLen; *out = 0; outSize -= prefixLen; } else { /* * This is a regular share. Append the path to the out buffer. */ if (outSize < shareInfo->rootDirLen + 1) { LOG(4, ("%s: share path too big\n", __FUNCTION__)); nameStatus = HGFS_NAME_STATUS_TOO_LONG; goto error; } memcpy(out, shareInfo->rootDir, shareInfo->rootDirLen + 1); out += shareInfo->rootDirLen; outSize -= shareInfo->rootDirLen; } /* Convert the rest of the input name (if any) to a local name */ tempSize = sizeof tempBuf; tempPtr = tempBuf; if (CPName_ConvertFrom(&cpName, &cpNameSize, &tempSize, &tempPtr) < 0) { LOG(4, ("%s: CP name conversion failed\n", __FUNCTION__)); nameStatus = HGFS_NAME_STATUS_FAILURE; goto error; } /* * For volume root directory shares the prefix will have a trailing * separator and since our remaining paths start with a separator, we * will skip over the second separator for this case. Bug 166755. */ if ((out != myBufOut) && (*(out - 1) == DIRSEPC) && (tempBuf[0] == DIRSEPC)) { startIndex++; } pathNameLen = tempPtr - &tempBuf[startIndex]; /* Copy UTF8 to the output buffer. */ if (pathNameLen >= outSize) { LOG(4, ("%s: pathname too long\n", __FUNCTION__)); nameStatus = HGFS_NAME_STATUS_TOO_LONG; goto error; } memcpy(out, &tempBuf[startIndex], pathNameLen); outSize -= pathNameLen; out += pathNameLen; *out = 0; myBufOutLen = out - myBufOut; #if defined(__APPLE__) { size_t nameLen; /* * For Mac hosts the unicode format is decomposed (form D) * so there is a need to convert the incoming name from HGFS clients * which is assumed to be in the normalized form C (precomposed). */ if (!CodeSet_Utf8FormCToUtf8FormD(myBufOut, myBufOutLen, &tempPtr, &nameLen)) { LOG(4, ("%s: unicode conversion to form D failed.\n", __FUNCTION__)); nameStatus = HGFS_NAME_STATUS_FAILURE; goto error; } free(myBufOut); LOG(4, ("%s: name is \"%s\"\n", __FUNCTION__, tempPtr)); /* Save returned pointers, update buffer length. */ myBufOut = tempPtr; out = tempPtr + nameLen; myBufOutLen = nameLen; } #endif /* defined(__APPLE__) */ /* * Look up the file name using the proper case if the config option is not set * to use the host default and lookup is supported for this platform. */ if (!HgfsServerPolicy_IsShareOptionSet(shareOptions, HGFS_SHARE_HOST_DEFAULT_CASE) && HgfsPlatformDoFilenameLookup()) { nameStatus = HgfsPlatformFilenameLookup(shareInfo->rootDir, shareInfo->rootDirLen, myBufOut, myBufOutLen, caseFlags, &convertedMyBufOut, &convertedMyBufOutLen); /* * On successful lookup, use the found matching file name for further operations. */ if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { LOG(4, ("%s: HgfsPlatformFilenameLookup failed.\n", __FUNCTION__)); goto error; } free(myBufOut); myBufOut = convertedMyBufOut; myBufOutLen = convertedMyBufOutLen; ASSERT(myBufOut); } /* Check for symlinks if the followSymlinks option is not set. */ if (!HgfsServerPolicy_IsShareOptionSet(shareOptions, HGFS_SHARE_FOLLOW_SYMLINKS)) { /* * Verify that either the path is same as share path or the path until the * parent directory is within the share. * * XXX: Symlink check could become susceptible to TOCTOU (time-of-check, * time-of-use) attack when we move to asynchrounous HGFS operations. * We should use the resolved file path for further file system * operations, instead of using the one passed from the client. */ nameStatus = HgfsPlatformPathHasSymlink(myBufOut, myBufOutLen, shareInfo->rootDir, shareInfo->rootDirLen); if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { LOG(4, ("%s: parent path failed to be resolved: %d\n", __FUNCTION__, nameStatus)); goto error; } } { char *p; /* Trim unused memory */ /* Enough space for resulting string + NUL termination */ p = realloc(myBufOut, (myBufOutLen + 1) * sizeof *p); if (!p) { LOG(4, ("%s: failed to trim memory\n", __FUNCTION__)); } else { myBufOut = p; } if (outLen) { *outLen = myBufOutLen; } } LOG(4, ("%s: name is \"%s\"\n", __FUNCTION__, myBufOut)); *bufOut = myBufOut; return HGFS_NAME_STATUS_COMPLETE; error: free(myBufOut); return nameStatus; } /* *----------------------------------------------------------------------------- * * HgfsServerIsSharedFolderOnly -- * * Test a name if it is a shared folder only or not * * This function assumes that CPName_GetComponent() will always succeed * with a size greater than 0, so it must ONLY be called after a call to * HgfsServerGetLocalNameInfo() that returns HGFS_NAME_STATUS_COMPLETE. * * Results: * True if it is a shared folder only, otherwise false * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsServerIsSharedFolderOnly(char const *cpName,// IN: Cross-platform filename to check size_t cpNameSize) // IN: Size of name cpName { char const *inEnd; char const *next; int len; ASSERT(cpName); inEnd = cpName + cpNameSize; len = CPName_GetComponent(cpName, inEnd, &next); ASSERT(len > 0); (void) len; /* Shuts up gcc's -Werror=unused-but-set-variable. */ return (next == inEnd); } #ifdef VMX86_LOG /* *----------------------------------------------------------------------------- * * HgfsServerDirDumpDents -- * * Dump a set of directory entries (debugging code) * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsServerDirDumpDents(HgfsHandle searchHandle, // IN: Handle to dump dents from HgfsSessionInfo *session) // IN: Session info { HgfsSearch *search; MXUser_AcquireExclLock(session->searchArrayLock); search = HgfsSearchHandle2Search(searchHandle, session); if (search != NULL) { HgfsPlatformDirDumpDents(search); } MXUser_ReleaseExclLock(session->searchArrayLock); } #endif /* *----------------------------------------------------------------------------- * * HgfsServerSearchRealDir -- * * Handle a search on a real directory. Takes a pointer to an enumerator * for the directory's contents and returns a handle to a search that is * correctly set up with the real directory's entries. * * The casual reader will notice that the "type" of this search is obviously * always DIRECTORY_SEARCH_TYPE_DIR, but the caller is nonetheless required * to pass it in, for completeness' sake with respect to * HgfsServerSearchVirtualDir. * * Results: * Zero on success, returns a handle to the created search. * Non-zero on failure. * * Side effects: * Memory allocation on success * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsServerSearchRealDir(char const *baseDir, // IN: Directory to search size_t baseDirLen, // IN: Length of directory char const *shareName, // IN: Share name containing the directory char const *rootDir, // IN: Shared folder root directory HgfsSessionInfo *session, // IN: Session info HgfsHandle *handle) // OUT: Search handle { HgfsSearch *search = NULL; HgfsInternalStatus status = 0; HgfsNameStatus nameStatus; Bool followSymlinks; HgfsShareOptions configOptions; ASSERT(baseDir); ASSERT(handle); ASSERT(shareName); MXUser_AcquireExclLock(session->searchArrayLock); search = HgfsAddNewSearch(baseDir, DIRECTORY_SEARCH_TYPE_DIR, shareName, rootDir, session); if (!search) { LOG(4, ("%s: failed to get new search\n", __FUNCTION__)); status = HGFS_ERROR_INTERNAL; goto out; } /* Get the config options. */ nameStatus = HgfsServerPolicy_GetShareOptions(shareName, strlen(shareName), &configOptions); if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { LOG(4, ("%s: no matching share: %s.\n", __FUNCTION__, shareName)); status = HGFS_ERROR_INTERNAL; HgfsRemoveSearchInternal(search, session); goto out; } followSymlinks = HgfsServerPolicy_IsShareOptionSet(configOptions, HGFS_SHARE_FOLLOW_SYMLINKS); status = HgfsPlatformScandir(baseDir, baseDirLen, followSymlinks, &search->dents, &search->numDents); if (HGFS_ERROR_SUCCESS != status) { LOG(4, ("%s: couldn't scandir\n", __FUNCTION__)); HgfsRemoveSearchInternal(search, session); goto out; } *handle = HgfsSearch2SearchHandle(search); out: MXUser_ReleaseExclLock(session->searchArrayLock); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerSearchVirtualDir -- * * Handle a search on a virtual directory (i.e. one that does not * really exist on the server). Takes a pointer to an enumerator * for the directory's contents and returns a handle to a search that is * correctly set up with the virtual directory's entries. * * Results: * Zero on success, returns a handle to the created search. * Non-zero on failure. * * Side effects: * Memory allocation on success * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsServerSearchVirtualDir(HgfsServerResEnumGetFunc getName, // IN: Name enumerator HgfsServerResEnumInitFunc initName, // IN: Init function HgfsServerResEnumExitFunc cleanupName, // IN: Cleanup function DirectorySearchType type, // IN: Kind of search HgfsSessionInfo *session, // IN: Session info HgfsHandle *handle) // OUT: Search handle { HgfsInternalStatus status = 0; HgfsSearch *search = NULL; ASSERT(getName); ASSERT(initName); ASSERT(cleanupName); ASSERT(handle); MXUser_AcquireExclLock(session->searchArrayLock); search = HgfsAddNewSearch("", type, "", "", session); if (!search) { LOG(4, ("%s: failed to get new search\n", __FUNCTION__)); status = HGFS_ERROR_INTERNAL; goto out; } status = HgfsPlatformScanvdir(getName, initName, cleanupName, type, &search->dents, &search->numDents); if (HGFS_ERROR_SUCCESS != status) { LOG(4, ("%s: couldn't get dents\n", __FUNCTION__)); HgfsRemoveSearchInternal(search, session); goto out; } *handle = HgfsSearch2SearchHandle(search); out: MXUser_ReleaseExclLock(session->searchArrayLock); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerRestartSearchVirtualDir -- * * Restart a search on a virtual directory (i.e. one that does not * really exist on the server). Takes a pointer to an enumerator * for the directory's contents and returns a handle to a search that is * correctly set up with the virtual directory's entries. * * Results: * Zero on success, returns a handle to the created search. * Non-zero on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsServerRestartSearchVirtualDir(HgfsServerResEnumGetFunc getName, // IN: Name enumerator HgfsServerResEnumInitFunc initName, // IN: Init function HgfsServerResEnumExitFunc cleanupName, // IN: Cleanup function HgfsSessionInfo *session, // IN: Session info HgfsHandle searchHandle) // IN: search to restart { HgfsInternalStatus status = 0; HgfsSearch *vdirSearch; ASSERT(getName); ASSERT(initName); ASSERT(cleanupName); ASSERT(searchHandle); MXUser_AcquireExclLock(session->searchArrayLock); vdirSearch = HgfsSearchHandle2Search(searchHandle, session); if (NULL == vdirSearch) { status = HGFS_ERROR_INVALID_HANDLE; goto exit; } /* Release the virtual directory's old set of entries. */ HgfsFreeSearchDirents(vdirSearch); /* Restart by rescanning the virtual directory. */ status = HgfsPlatformScanvdir(getName, initName, cleanupName, vdirSearch->type, &vdirSearch->dents, &vdirSearch->numDents); if (HGFS_ERROR_SUCCESS != status) { LOG(4, ("%s: couldn't get root dents %u\n", __FUNCTION__, status)); goto exit; } /* Clear the flag to indicate that the client has read the entries. */ vdirSearch->flags &= ~HGFS_SEARCH_FLAG_READ_ALL_ENTRIES; exit: MXUser_ReleaseExclLock(session->searchArrayLock); LOG(4, ("%s: refreshing dents return %d\n", __FUNCTION__, status)); return status; } /* *----------------------------------------------------------------------------- * * HgfsRemoveFromCache -- * * Grab a node cache lock and call HgfsRemoveFromCacheInternal. * * If the node was not already in the cache then nothing is done. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsRemoveFromCache(HgfsHandle handle, // IN: Hgfs handle to the node HgfsSessionInfo *session) // IN: Session info { Bool removed = FALSE; MXUser_AcquireExclLock(session->nodeArrayLock); removed = HgfsRemoveFromCacheInternal(handle, session); MXUser_ReleaseExclLock(session->nodeArrayLock); return removed; } /* *----------------------------------------------------------------------------- * * HgfsIsCached -- * * Grab a lock and call HgfsIsCachedInternal. * * Results: * TRUE if the node is found in the cache. * FALSE if the node is not in the cache. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsIsCached(HgfsHandle handle, // IN: Structure representing file node HgfsSessionInfo *session) // IN: Session info { Bool cached = FALSE; MXUser_AcquireExclLock(session->nodeArrayLock); cached = HgfsIsCachedInternal(handle, session); MXUser_ReleaseExclLock(session->nodeArrayLock); return cached; } /* *----------------------------------------------------------------------------- * * HgfsRemoveLruNode-- * * Removes the least recently used node in the cache. The first node is * removed since most recently used nodes are moved to the end of the * list. * * XXX: Right now we do not remove nodes that have server locks on them * This is not correct and should be fixed before the release. * Instead we should cancel the server lock (by calling IoCancel) * notify client of the lock break, and close the file. * * Assumes that there is at least one node in the cache. * * The session's nodeArrayLock should be acquired prior to calling this * function. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsRemoveLruNode(HgfsSessionInfo *session) // IN: session info { HgfsFileNode *lruNode = NULL; HgfsHandle handle; Bool found = FALSE; uint32 numOpenNodes = session->numCachedOpenNodes; ASSERT(session); ASSERT(session->numCachedOpenNodes > 0); /* * Remove the first item from the list that does not have a server lock, * file context or is open in sequential mode. */ while (!found && (numOpenNodes-- > 0)) { lruNode = DblLnkLst_Container(session->nodeCachedList.next, HgfsFileNode, links); ASSERT(lruNode->state == FILENODE_STATE_IN_USE_CACHED); if (lruNode->serverLock != HGFS_LOCK_NONE || lruNode->fileCtx != NULL || (lruNode->flags & HGFS_FILE_NODE_SEQUENTIAL_FL) != 0) { /* * Move this node with the server lock to the beginning of the list. * Also, prevent files opened in HGFS_FILE_NODE_SEQUENTIAL_FL mode * from being closed. -- On some platforms, this mode does not * allow files to be closed/re-opened (eg: When restoring a file * into a Windows guest you cannot use BackupWrite, then close and * re-open the file and continue to use BackupWrite. */ DblLnkLst_Unlink1(&lruNode->links); DblLnkLst_LinkLast(&session->nodeCachedList, &lruNode->links); } else { found = TRUE; } } if (found) { handle = HgfsFileNode2Handle(lruNode); if (!HgfsRemoveFromCacheInternal(handle, session)) { LOG(4, ("%s: Could not remove the node from cache.\n", __FUNCTION__)); return FALSE; } } else { LOG(4, ("%s: Could not find a node to remove from cache.\n", __FUNCTION__)); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsAddToCache -- * * Grabs the cache lock and calls HgfsAddToCacheInternal. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsAddToCache(HgfsHandle handle, // IN: HGFS file handle HgfsSessionInfo *session) // IN: Session info { Bool added = FALSE; MXUser_AcquireExclLock(session->nodeArrayLock); added = HgfsAddToCacheInternal(handle, session); MXUser_ReleaseExclLock(session->nodeArrayLock); return added; } /* *----------------------------------------------------------------------------- * * HgfsCreateAndCacheFileNode -- * * Get a node from the free node list and cache it. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsCreateAndCacheFileNode(HgfsFileOpenInfo *openInfo, // IN: Open info struct HgfsLocalId const *localId, // IN: Local unique file ID fileDesc fileDesc, // IN: Handle to the fileopenInfo, Bool append, // IN: flag to append HgfsSessionInfo *session) // IN: session info { HgfsHandle handle; HgfsFileNode *node = NULL; char const *inEnd; char const *next; int len; Bool sharedFolderOpen = FALSE; ASSERT(openInfo); ASSERT(localId); ASSERT(session); inEnd = openInfo->cpName + openInfo->cpNameSize; /* * Get first component. */ len = CPName_GetComponent(openInfo->cpName, inEnd, &next); if (len < 0) { LOG(4, ("%s: get first component failed\n", __FUNCTION__)); HgfsPlatformCloseFile(fileDesc, NULL); return FALSE; } /* See if we are dealing with the base of the namespace */ if (!len) { HgfsPlatformCloseFile(fileDesc, NULL); return FALSE; } if (!next) { sharedFolderOpen = TRUE; } MXUser_AcquireExclLock(session->nodeArrayLock); node = HgfsAddNewFileNode(openInfo, localId, fileDesc, append, len, openInfo->cpName, sharedFolderOpen, session); if (node == NULL) { LOG(4, ("%s: Failed to add new node.\n", __FUNCTION__)); MXUser_ReleaseExclLock(session->nodeArrayLock); HgfsPlatformCloseFile(fileDesc, NULL); return FALSE; } handle = HgfsFileNode2Handle(node); if (!HgfsAddToCacheInternal(handle, session)) { HgfsFreeFileNodeInternal(handle, session); HgfsPlatformCloseFile(fileDesc, NULL); LOG(4, ("%s: Failed to add node to the cache.\n", __FUNCTION__)); MXUser_ReleaseExclLock(session->nodeArrayLock); return FALSE; } MXUser_ReleaseExclLock(session->nodeArrayLock); /* Only after everything is successful, save the handle in the open info. */ openInfo->file = handle; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsAllocInitReply -- * * Retrieves the hgfs protocol reply data buffer that follows the reply header. * * Results: * Cannot fail, returns the protocol reply data buffer for the corresponding * processed protocol request. * * Side effects: * None * *----------------------------------------------------------------------------- */ void * HgfsAllocInitReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header size_t replyDataSize, // IN: replyDataSize size HgfsSessionInfo *session) // IN: Session Info { const HgfsRequest *request = packetHeader; size_t replyPacketSize; size_t headerSize = 0; /* Replies prior to V3 do not have a header. */ void *replyHeader; void *replyData; /* * XXX - this should be modified to use the common HgfsServerGetReplyHeaderSize * so that all requests and replies are handled consistently. */ if (HGFS_OP_NEW_HEADER == request->op) { headerSize = sizeof(HgfsHeader); } else if (request->op < HGFS_OP_CREATE_SESSION_V4 && request->op > HGFS_OP_RENAME_V2) { headerSize = sizeof(HgfsReply); } replyHeader = HSPU_GetReplyPacket(packet, session->transportSession->channelCbTable, headerSize + replyDataSize, &replyPacketSize); ASSERT(replyHeader && (replyPacketSize >= headerSize + replyDataSize)); memset(replyHeader, 0, headerSize + replyDataSize); if (replyDataSize > 0) { replyData = (char *)replyHeader + headerSize; } else { replyData = NULL; ASSERT(FALSE); } return replyData; } /* *----------------------------------------------------------------------------- * * HgfsServerValidateRead -- * * Validate a Read request's arguments. * * Note, the readOffset is ignored here but is checked in the platform specific * read handler. * * Results: * HGFS_ERROR_SUCCESS on success. * HGFS error code on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerValidateRead(HgfsInputParam *input, // IN: Input params HgfsHandle readHandle, // IN: read Handle uint32 readSize, // IN: size to read uint64 readOffset, // IN: offset to read unused fileDesc *readfd, // OUT: read file descriptor size_t *readReplySize, // OUT: read reply size size_t *readDataSize) // OUT: read data size { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; size_t replyReadHeaderSize; size_t replyReadResultSize = 0; size_t replyReadResultDataSize = 0; size_t replyReadDataSize = 0; fileDesc readFileDesc = 0; Bool useMappedBuffer; useMappedBuffer = (input->transportSession->channelCbTable->getWriteVa != NULL); replyReadHeaderSize = HgfsServerGetReplyHeaderSize(input->sessionEnabled, input->op); switch (input->op) { case HGFS_OP_READ_FAST_V4: /* Data is packed into a separate buffer from the read results. */ replyReadResultSize = sizeof (HgfsReplyReadV3); replyReadResultDataSize = 0; replyReadDataSize = readSize; break; case HGFS_OP_READ_V3: /* Data is packed as a part of the read results. */ replyReadResultSize = sizeof (HgfsReplyReadV3); replyReadResultDataSize = readSize; replyReadDataSize = 0; break; case HGFS_OP_READ: /* Data is packed as a part of the read results. */ replyReadResultSize = sizeof (HgfsReplyRead); replyReadResultDataSize = readSize; replyReadDataSize = 0; break; default: status = HGFS_ERROR_PROTOCOL; LOG(4, ("%s: Unsupported protocol version passed %d -> PROTOCOL_ERROR.\n", __FUNCTION__, input->op)); NOT_IMPLEMENTED(); goto exit; } if (!HSPU_ValidateDataPacketSize(input->packet, replyReadDataSize) || !HSPU_ValidateReplyPacketSize(input->packet, replyReadHeaderSize, replyReadResultSize, replyReadResultDataSize, useMappedBuffer)) { status = HGFS_ERROR_INVALID_PARAMETER; LOG(4, ("%s: Error: arg validation read size -> %d.\n", __FUNCTION__, status)); goto exit; } /* Validate the file handle by retrieving it possibly from the cache. */ status = HgfsPlatformGetFd(readHandle, input->session, FALSE, &readFileDesc); if (status != HGFS_ERROR_SUCCESS) { LOG(4, ("%s: Error: arg validation handle -> %d.\n", __FUNCTION__, status)); goto exit; } exit: *readDataSize = replyReadDataSize; *readReplySize = replyReadResultSize + replyReadResultDataSize; *readfd = readFileDesc; LOG(4, ("%s: arg validation check return (%"FMTSZ"u) %d.\n", __FUNCTION__, replyReadDataSize, status)); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerRead -- * * Handle a Read request. * * Results: * HGFS_ERROR_SUCCESS on success. * HGFS error code on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerRead(HgfsInputParam *input) // IN: Input params { HgfsInternalStatus status; HgfsHandle file; fileDesc readFd; uint64 offset; uint32 requiredSize; size_t replyPayloadSize = 0; size_t replyReadSize = 0; size_t replyReadDataSize = 0; void *replyRead; HGFS_ASSERT_INPUT(input); if (!HgfsUnpackReadRequest(input->payload, input->payloadSize, input->op, &file, &offset, &requiredSize)) { LOG(4, ("%s: Failed to unpack a valid packet -> PROTOCOL_ERROR.\n", __FUNCTION__)); status = HGFS_ERROR_PROTOCOL; goto exit; } /* * Validate the read arguments with the data and reply buffers to ensure * there isn't a malformed request or we read more data than the buffer can * hold. */ status = HgfsServerValidateRead(input, file, requiredSize, offset, &readFd, &replyReadSize, &replyReadDataSize); if (status != HGFS_ERROR_SUCCESS) { LOG(4, ("%s: Error: validate args %u.\n", __FUNCTION__, status)); goto exit; } replyRead = HgfsAllocInitReply(input->packet, input->request, replyReadSize, input->session); switch (input->op) { case HGFS_OP_READ_FAST_V4: case HGFS_OP_READ_V3: { HgfsReplyReadV3 *reply = replyRead; void *payload; Bool readUseDataBuffer = replyReadDataSize != 0; /* * The read data size holds the size of the data to read which will be read * into the separate data packet buffer. Zero indicates data is read into the * same buffer as the reply arguments. */ if (readUseDataBuffer) { payload = HSPU_GetDataPacketBuf(input->packet, BUF_WRITEABLE, input->transportSession->channelCbTable); } else { payload = &reply->payload[0]; } if (payload) { status = HgfsPlatformReadFile(readFd, input->session, offset, requiredSize, payload, &reply->actualSize); if (HGFS_ERROR_SUCCESS == status) { reply->reserved = 0; replyPayloadSize = sizeof *reply; if (readUseDataBuffer) { HSPU_SetDataPacketSize(input->packet, reply->actualSize); } else { replyPayloadSize += reply->actualSize; } } } else { status = HGFS_ERROR_PROTOCOL; LOG(4, ("%s: V3/V4 Failed to get payload -> PROTOCOL_ERROR.\n", __FUNCTION__)); } break; } case HGFS_OP_READ: { HgfsReplyRead *reply = replyRead; status = HgfsPlatformReadFile(readFd, input->session, offset, requiredSize, reply->payload, &reply->actualSize); if (HGFS_ERROR_SUCCESS == status) { replyPayloadSize = sizeof *reply + reply->actualSize; } else { LOG(4, ("%s: V1 Failed to read-> %d.\n", __FUNCTION__, status)); } break; } default: NOT_REACHED(); break; } exit: HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerValidateWrite -- * * Validate a write request's arguments. * * The HGFS Packet stored in the following possible formats as follows: * * Protocol V4 versions: * In the HgfsPacket metaPacket buffer * [HgfsHeader][HgfsRequestWriteV3] * In the HgfsPacket dataPacket buffer * [Variable length data to write] * * Protocol V3 versions: * In the HgfsPacket metaPacket buffer * [HgfsHeader][HgfsRequestWriteV3][Variable length data to write] * [HgfsRequest][HgfsRequestWriteV3][Variable length data to write] * * Protocol V2 versions: * Does not exist * * Protocol V1 versions: * In the HgfsPacket metaPacket buffer * [HgfsRequestWrite][Variable length data to write] * (Note, the HgfsRequestWrite contains an HgfsRequest within it.) * * Note, the writeOffset is ignored here but is checked in the platform specific * write handler. * * Results: * HGFS_ERROR_SUCCESS on success. * HGFS error code on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerValidateWrite(HgfsInputParam *input, // IN: Input params HgfsHandle writeHandle, // IN: write Handle uint64 writeOffset, // IN: write offset of file uint32 writeSize, // IN: size to write HgfsWriteFlags flags, // IN: write flags fileDesc *writefd, // OUT: write file descriptor Bool *writeSequential, // OUT: write is sequential Bool *writeAppend) // OUT: write is append { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; size_t requestWriteHeaderSize; size_t requestWritePacketSize = 0; size_t requestWritePacketDataSize = 0; size_t requestWriteDataSize = 0; fileDesc writeFileDesc = 0; Bool sequentialHandle = FALSE; Bool appendHandle = FALSE; requestWriteHeaderSize = HgfsServerGetRequestHeaderSize(input->sessionEnabled, input->op); switch (input->op) { case HGFS_OP_WRITE_FAST_V4: /* * For this the operation data is in the shared memory, * which depends on the mapping functions from the transport. */ ASSERT(input->transportSession->channelCbTable->getReadVa != NULL); /* * The write data is packed in a separate buffer to the write request. * Note, for size we **include** the 1 byte placeholder payload that was not * counted in earlier versions of the write request. Sigh. See below. */ requestWritePacketSize = sizeof (HgfsRequestWriteV3); requestWritePacketDataSize = 0; requestWriteDataSize = writeSize; break; case HGFS_OP_WRITE_V3: /* * Data is packed as a part of the write request. * Note, for size we remove the 1 byte placeholder payload * so it isn't counted twice. */ requestWritePacketSize = sizeof (HgfsRequestWriteV3) - 1; requestWritePacketDataSize = writeSize; requestWriteDataSize = 0; break; case HGFS_OP_WRITE: /* * Data is packed as a part of the write request. * Note, for size we remove the 1 byte placeholder payload * so it isn't counted twice. */ requestWritePacketSize = sizeof (HgfsRequestWrite) - 1; requestWritePacketDataSize = writeSize; requestWriteDataSize = 0; break; default: status = HGFS_ERROR_PROTOCOL; LOG(4, ("%s: Unsupported protocol version passed %d -> PROTOCOL_ERROR.\n", __FUNCTION__, input->op)); NOT_IMPLEMENTED(); goto exit; } /* * Validate the packet size with the header, write request and write data. */ if (!HSPU_ValidateDataPacketSize(input->packet, requestWriteDataSize) || !HSPU_ValidateRequestPacketSize(input->packet, requestWriteHeaderSize, requestWritePacketSize, requestWritePacketDataSize)) { status = HGFS_ERROR_INVALID_PARAMETER; LOG(4, ("%s: Error: write data size pkt %"FMTSZ"u data %"FMTSZ"u\n", __FUNCTION__, requestWritePacketDataSize, requestWriteDataSize)); goto exit; } /* * Now map the file handle, and extract the details of the write e.g. writing * sequentially or appending * * Validate the file handle by retrieving it possibly from the cache. */ status = HgfsPlatformGetFd(writeHandle, input->session, ((flags & HGFS_WRITE_APPEND) ? TRUE : FALSE), &writeFileDesc); if (status != HGFS_ERROR_SUCCESS) { LOG(4, ("%s: Error: arg validation handle -> %d.\n", __FUNCTION__, status)); goto exit; } if (!HgfsHandleIsSequentialOpen(writeHandle, input->session, &sequentialHandle)) { status = HGFS_ERROR_INVALID_HANDLE; LOG(4, ("%s: Could not get sequential open status\n", __FUNCTION__)); goto exit; } #if defined(__APPLE__) if (!HgfsHandle2AppendFlag(writeHandle, input->session, &appendHandle)) { status = HGFS_ERROR_INVALID_HANDLE; LOG(4, ("%s: Could not get append mode\n", __FUNCTION__)); goto exit; } #endif exit: *writefd = writeFileDesc; *writeSequential = sequentialHandle; *writeAppend = appendHandle; LOG(4, ("%s: arg validation check return (file %u data size %u) %u.\n", __FUNCTION__, writeHandle, writeSize, status)); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerWrite -- * * Handle a Write request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerWrite(HgfsInputParam *input) // IN: Input params { uint64 writeOffset; uint32 writeSize; uint32 writtenSize = 0; HgfsInternalStatus status = HGFS_ERROR_SUCCESS; HgfsWriteFlags writeFlags; const void *writeData; size_t writeReplySize = 0; HgfsHandle writeFile; fileDesc writeFd; Bool writeSequential; Bool writeAppend; HGFS_ASSERT_INPUT(input); if (!HgfsUnpackWriteRequest(input->payload, input->payloadSize, input->op, &writeFile, &writeOffset, &writeSize, &writeFlags, &writeData)) { LOG(4, ("%s: Error: Op %d unpack write request arguments\n", __FUNCTION__, input->op)); status = HGFS_ERROR_PROTOCOL; goto exit; } /* * Validate the write arguments with the data and request buffers to ensure * there isn't a malformed request or we try to write more data than is in the buffer. */ status = HgfsServerValidateWrite(input, writeFile, writeOffset, writeSize, writeFlags, &writeFd, &writeSequential, &writeAppend); if (status != HGFS_ERROR_SUCCESS) { LOG(4, ("%s: Error: validate args %u.\n", __FUNCTION__, status)); goto exit; } if (writeSize > 0) { if (NULL == writeData) { /* No inline data to write, get it from the transport shared memory. */ HSPU_SetDataPacketSize(input->packet, writeSize); writeData = HSPU_GetDataPacketBuf(input->packet, BUF_READABLE, input->transportSession->channelCbTable); if (NULL == writeData) { LOG(4, ("%s: Error: Op %d mapping write data buffer\n", __FUNCTION__, input->op)); status = HGFS_ERROR_PROTOCOL; goto exit; } } status = HgfsPlatformWriteFile(writeFd, input->session, writeOffset, writeSize, writeFlags, writeSequential, writeAppend, writeData, &writtenSize); if (HGFS_ERROR_SUCCESS != status) { goto exit; } } if (!HgfsPackWriteReply(input->packet, input->request, input->op, writtenSize, &writeReplySize, input->session)) { status = HGFS_ERROR_INTERNAL; } exit: HgfsServerCompleteRequest(status, writeReplySize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerQueryVolInt -- * * Internal function to query the volume's free space and capacity. * The volume queried can be: * - real taken from the file path of a real file or folder * - virtual taken from one of the HGFS virtual folders which can span * multiple volumes. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerQueryVolInt(HgfsSessionInfo *session, // IN: session info const char *fileName, // IN: cpName for the volume size_t fileNameLength, // IN: cpName length uint32 caseFlags, // IN: case sensitive/insensitive name uint64 *freeBytes, // OUT: free space in bytes uint64 *totalBytes) // OUT: capacity in bytes { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; uint64 outFreeBytes = 0; uint64 outTotalBytes = 0; char *utf8Name = NULL; size_t utf8NameLen; HgfsNameStatus nameStatus; HgfsShareInfo shareInfo; VolumeInfoType infoType; /* * XXX - make the filename const! * It is now safe to read the file name field. */ nameStatus = HgfsServerGetLocalNameInfo(fileName, fileNameLength, caseFlags, &shareInfo, &utf8Name, &utf8NameLen); /* Check if we have a real path and if so handle it here. */ if (nameStatus == HGFS_NAME_STATUS_COMPLETE) { Bool success; ASSERT(utf8Name); LOG(4,("%s: querying path %s\n", __FUNCTION__, utf8Name)); success = HgfsServerStatFs(utf8Name, utf8NameLen, &outFreeBytes, &outTotalBytes); free(utf8Name); if (!success) { LOG(4, ("%s: error getting volume information\n", __FUNCTION__)); status = HGFS_ERROR_IO; } goto exit; } /* * If we're outside the Tools, find out if we're to compute the minimum * values across all shares, or the maximum values. */ infoType = VOLUME_INFO_TYPE_MIN; /* We have a virtual folder path and if so pass it over to the platform code. */ if (0 == (gHgfsCfgSettings.flags & HGFS_CONFIG_VOL_INFO_MIN)) { /* Using the maximum volume size and space values. */ infoType = VOLUME_INFO_TYPE_MAX; } status = HgfsPlatformVDirStatsFs(session, nameStatus, infoType, &outFreeBytes, &outTotalBytes); exit: *freeBytes = outFreeBytes; *totalBytes = outTotalBytes; LOG(4, ("%s: return %"FMT64"u bytes Free %"FMT64"u bytes\n", __FUNCTION__, outTotalBytes, outFreeBytes)); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerQueryVolume -- * * Handle a Query Volume request. * * Right now we only handle the volume space request. Call Wiper library * to get the volume information. * It is possible that shared folders can belong to different volumes on * the server. If this is the case, default to return the space information * of the volume that has the least amount of the available space, but it's * configurable with a config option (tools.hgfs.volumeInfoType). 2 possible * options, min and max. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerQueryVolume(HgfsInputParam *input) // IN: Input params { HgfsInternalStatus status; size_t replyPayloadSize = 0; HgfsHandle file; const char *fileName; size_t fileNameLength; uint32 caseFlags; Bool useHandle; uint64 freeBytes; uint64 totalBytes; HGFS_ASSERT_INPUT(input); if (HgfsUnpackQueryVolumeRequest(input->payload, input->payloadSize, input->op, &useHandle, &fileName, &fileNameLength, &caseFlags, &file)) { /* * We don't yet support file handle for this operation. * Clients should retry using the file name. */ if (useHandle) { LOG(4, ("%s: Doesn't support file handle.\n", __FUNCTION__)); status = HGFS_ERROR_INVALID_PARAMETER; } else { status = HgfsServerQueryVolInt(input->session, fileName, fileNameLength, caseFlags, &freeBytes, &totalBytes); if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackQueryVolumeReply(input->packet, input->request, input->op, freeBytes, totalBytes, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsSymlinkCreate -- * * Platform independent function that verifies whether symbolic link creation * is allowed for the specific shared folder and then calls platform specific * HgfsPlatformSymlinkCreate to do the actual job. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsSymlinkCreate(HgfsSessionInfo *session, // IN: session info, const char *srcFileName, // IN: symbolic link file name uint32 srcFileNameLength, // IN: symbolic link name length uint32 srcCaseFlags, // IN: symlink case flags const char *trgFileName, // IN: symbolic link target name uint32 trgFileNameLength, // IN: target name length uint32 trgCaseFlags) // IN: target case flags { HgfsShareInfo shareInfo; HgfsInternalStatus status = 0; HgfsNameStatus nameStatus; HgfsShareOptions configOptions; char *localSymlinkName = NULL; size_t localSymlinkNameLen; char localTargetName[HGFS_PACKET_MAX]; /* * It is now safe to read the symlink file name and the * "targetName" field */ nameStatus = HgfsServerGetLocalNameInfo(srcFileName, srcFileNameLength, srcCaseFlags, &shareInfo, &localSymlinkName, &localSymlinkNameLen); if (nameStatus == HGFS_NAME_STATUS_COMPLETE) { if (shareInfo.writePermissions ) { /* Get the config options. */ nameStatus = HgfsServerPolicy_GetShareOptions(srcFileName, srcFileNameLength, &configOptions); if (nameStatus == HGFS_NAME_STATUS_COMPLETE) { /* Prohibit symlink ceation if symlink following is enabled. */ if (HgfsServerPolicy_IsShareOptionSet(configOptions, HGFS_SHARE_FOLLOW_SYMLINKS)) { status = HGFS_ERROR_ACCESS_DENIED; } } else { LOG(4, ("%s: no matching share: %s.\n", __FUNCTION__, srcFileName)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } } else { status = HgfsPlatformFileExists(localSymlinkName); if (status != 0) { if (status == HGFS_ERROR_FILE_NOT_FOUND) { status = HGFS_ERROR_ACCESS_DENIED; } } else { status = HGFS_ERROR_FILE_EXIST; } LOG(4, ("%s: failed access check, error %d\n", __FUNCTION__, status)); } } else { LOG(4, ("%s: symlink name access check failed\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } if (HGFS_ERROR_SUCCESS == status) { /* Convert from CPName-lite to normal and NUL-terminate. */ memcpy(localTargetName, trgFileName, trgFileNameLength); CPNameLite_ConvertFrom(localTargetName, trgFileNameLength, DIRSEPC); localTargetName[trgFileNameLength] = '\0'; status = HgfsPlatformSymlinkCreate(localSymlinkName, localTargetName); } free(localSymlinkName); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerSymlinkCreate -- * * Handle a SymlinkCreate request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerSymlinkCreate(HgfsInputParam *input) // IN: Input params { HgfsInternalStatus status; HgfsHandle srcFile; const char *srcFileName; size_t srcFileNameLength; uint32 srcCaseFlags; Bool srcUseHandle; HgfsHandle trgFile; const char *trgFileName; size_t trgFileNameLength; uint32 trgCaseFlags; Bool trgUseHandle; size_t replyPayloadSize = 0; HGFS_ASSERT_INPUT(input); if (HgfsUnpackSymlinkCreateRequest(input->payload, input->payloadSize, input->op, &srcUseHandle, &srcFileName, &srcFileNameLength, &srcCaseFlags, &srcFile, &trgUseHandle, &trgFileName, &trgFileNameLength, &trgCaseFlags, &trgFile)) { /* * We don't yet support file handle for this operation. * Clients should retry using the file name. */ if (srcUseHandle || trgUseHandle) { LOG(4, ("%s: Doesn't support file handle.\n", __FUNCTION__)); status = HGFS_ERROR_INVALID_PARAMETER; } else { status = HgfsSymlinkCreate(input->session, srcFileName, srcFileNameLength, srcCaseFlags, trgFileName, trgFileNameLength, trgCaseFlags); if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackSymlinkCreateReply(input->packet, input->request, input->op, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerSearchOpen -- * * Handle a search open request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerSearchOpen(HgfsInputParam *input) // IN: Input params { HgfsInternalStatus status; size_t replyPayloadSize = 0; const char *dirName; size_t dirNameLength; uint32 caseFlags = HGFS_FILE_NAME_DEFAULT_CASE; HgfsHandle search; HgfsNameStatus nameStatus; HgfsShareInfo shareInfo; char *baseDir = NULL; size_t baseDirLen; HGFS_ASSERT_INPUT(input); if (HgfsUnpackSearchOpenRequest(input->payload, input->payloadSize, input->op, &dirName, &dirNameLength, &caseFlags)) { nameStatus = HgfsServerGetLocalNameInfo(dirName, dirNameLength, caseFlags, &shareInfo, &baseDir, &baseDirLen); status = HgfsPlatformSearchDir(nameStatus, dirName, dirNameLength, caseFlags, &shareInfo, baseDir, baseDirLen, input->session, &search); if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackSearchOpenReply(input->packet, input->request, input->op, search, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); free(baseDir); } /* *----------------------------------------------------------------------------- * * HgfsValidateRenameFile -- * * Validates if the file can can participate in rename process either as * as a source or as a target. * * Results: * HGFS_ERROR_SUCCESS if rename operation is allowed. * Appropriate error code otherwise. * * Side effects: * Allcates locaFileName which must be freed by the caller. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsValidateRenameFile(Bool useHandle, // IN: HgfsHandle fileHandle, // IN: const char *cpName, // IN: size_t cpNameLength, // IN: uint32 caseFlags, // IN: HgfsSessionInfo *session, // IN: Session info fileDesc* descr, // OUT: HgfsShareInfo *shareInfo, // OUT: char **localFileName, // OUT: size_t *localNameLength) // OUT: { HgfsInternalStatus status; Bool sharedFolderOpen = FALSE; HgfsLockType serverLock = HGFS_LOCK_NONE; HgfsNameStatus nameStatus; if (useHandle) { status = HgfsPlatformGetFd(fileHandle, session, FALSE, descr); if (HGFS_ERROR_SUCCESS != status) { LOG(4, ("%s: could not map cached handle %d, error %u\n", __FUNCTION__, fileHandle, status)); } else if (!HgfsHandle2FileNameMode(fileHandle, session, &shareInfo->writePermissions, &shareInfo->readPermissions, localFileName, localNameLength)) { /* * HgfsPlatformRename requires valid source file name even when file handle * is specified. * Also the name will be required to update the nodes on a successful * rename operation. */ LOG(4, ("%s: could not get file name for fd %d\n", __FUNCTION__, *descr)); status = HGFS_ERROR_INVALID_HANDLE; } else if (HgfsHandleIsSharedFolderOpen(fileHandle, session, &sharedFolderOpen) && sharedFolderOpen) { LOG(4, ("%s: Cannot rename shared folder\n", __FUNCTION__)); status = HGFS_ERROR_ACCESS_DENIED; } } else { nameStatus = HgfsServerGetLocalNameInfo(cpName, cpNameLength, caseFlags, shareInfo, localFileName, localNameLength); if (HGFS_NAME_STATUS_COMPLETE != nameStatus) { LOG(4, ("%s: access check failed\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } else if (HgfsServerIsSharedFolderOnly(cpName, cpNameLength)) { /* Guest OS is not allowed to rename shared folder. */ LOG(4, ("%s: Cannot rename shared folder\n", __FUNCTION__)); status = HGFS_ERROR_ACCESS_DENIED; } else { status = HGFS_ERROR_SUCCESS; } } ASSERT(*localFileName != NULL || HGFS_ERROR_SUCCESS != status); if (HGFS_ERROR_SUCCESS == status) { if (HgfsFileHasServerLock(*localFileName, session, &serverLock, descr)) { /* * XXX: Before renaming the file, check to see if we are holding * an oplock on both the old and new files. If one of them is oplocked, and * we commence with the rename, we'll trigger an oplock break that'll * deadlock us. The client should be smart enough to break necessary oplocks * on the source and target files before calling rename, so we'll return * an error. */ LOG (4, ("%s: File has an outstanding oplock. Client " "should remove this oplock and try again.\n", __FUNCTION__)); status = HGFS_ERROR_PATH_BUSY; } } return status; } /* *----------------------------------------------------------------------------- * * HgfsServerRename -- * * Handle a Rename request. * * Simply converts the new and old names to local filenames, calls * platform specific function to rename/move the file, and returns an * appropriate response to the driver. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerRename(HgfsInputParam *input) // IN: Input params { char *utf8OldName = NULL; size_t utf8OldNameLen; char *utf8NewName = NULL; size_t utf8NewNameLen; const char *cpOldName; size_t cpOldNameLen; const char *cpNewName; size_t cpNewNameLen; HgfsInternalStatus status; fileDesc srcFileDesc; fileDesc targetFileDesc; HgfsHandle srcFile; HgfsHandle targetFile; HgfsRenameHint hints; uint32 oldCaseFlags; uint32 newCaseFlags; HgfsShareInfo shareInfo; size_t replyPayloadSize = 0; HGFS_ASSERT_INPUT(input); if (HgfsUnpackRenameRequest(input->payload, input->payloadSize, input->op, &cpOldName, &cpOldNameLen, &cpNewName, &cpNewNameLen, &hints, &srcFile, &targetFile, &oldCaseFlags, &newCaseFlags)) { status = HgfsValidateRenameFile((hints & HGFS_RENAME_HINT_USE_SRCFILE_DESC) != 0, srcFile, cpOldName, cpOldNameLen, oldCaseFlags, input->session, &srcFileDesc, &shareInfo, &utf8OldName, &utf8OldNameLen); if (HGFS_ERROR_SUCCESS == status) { /* * Renaming a file requires both read and write permssions for the * original file. * However the error code must be different depending on the existence * of the file with the same name. */ if (!shareInfo.writePermissions || !shareInfo.readPermissions) { status = HgfsPlatformFileExists(utf8OldName); if (HGFS_ERROR_SUCCESS == status) { status = HGFS_ERROR_ACCESS_DENIED; } LOG(4, ("HgfsServerRename: failed access check, error %d\n", status)); } else { status = HgfsValidateRenameFile((hints & HGFS_RENAME_HINT_USE_TARGETFILE_DESC) != 0, targetFile, cpNewName, cpNewNameLen, newCaseFlags, input->session, &targetFileDesc, &shareInfo, &utf8NewName, &utf8NewNameLen); if (HGFS_ERROR_SUCCESS == status) { /* * Renaming a file requires both read and write permssions for * the target directory. * However the error code must be different depending on the existence * of the target directory - if the destination directory exists then * ERROR_ACCESS_DENIED should be returned regardless if the destination * file exists. */ if (!shareInfo.writePermissions || !shareInfo.readPermissions) { status = HgfsPlatformFileExists(utf8NewName); if (HGFS_ERROR_SUCCESS == status || HGFS_ERROR_FILE_NOT_FOUND == status) { status = HGFS_ERROR_ACCESS_DENIED; } LOG(4, ("HgfsServerRename: failed access check, error %d\n", status)); } } } } } else { status = HGFS_ERROR_PROTOCOL; } /* If all pre-conditions are met go ahead with actual rename. */ if (HGFS_ERROR_SUCCESS == status) { status = HgfsPlatformRename(utf8OldName, srcFileDesc, utf8NewName, targetFileDesc, hints); if (HGFS_ERROR_SUCCESS == status) { /* Update all file nodes that refer to this file to contain the new name. */ HgfsUpdateNodeNames(utf8OldName, utf8NewName, input->session); if (!HgfsPackRenameReply(input->packet, input->request, input->op, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } free(utf8OldName); free(utf8NewName); HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerCreateDir -- * * Handle a CreateDir request. * * Simply converts to the local filename, calls platform specific * code to create a directory, and returns an appropriate response to the driver. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerCreateDir(HgfsInputParam *input) // IN: Input params { HgfsInternalStatus status; HgfsNameStatus nameStatus; HgfsCreateDirInfo info; char *utf8Name = NULL; size_t utf8NameLen; size_t replyPayloadSize = 0; HgfsShareInfo shareInfo; HGFS_ASSERT_INPUT(input); if (HgfsUnpackCreateDirRequest(input->payload, input->payloadSize, input->op, &info)) { nameStatus = HgfsServerGetLocalNameInfo(info.cpName, info.cpNameSize, info.caseFlags, &shareInfo, &utf8Name, &utf8NameLen); if (HGFS_NAME_STATUS_COMPLETE == nameStatus) { ASSERT(utf8Name); LOG(4, ("%s: making dir \"%s\"", __FUNCTION__, utf8Name)); /* * For read-only shares we must never attempt to create a directory. * However the error code must be different depending on the existence * of the file with the same name. */ if (shareInfo.writePermissions) { status = HgfsPlatformCreateDir(&info, utf8Name); if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackCreateDirReply(input->packet, input->request, info.requestType, &replyPayloadSize, input->session)) { status = HGFS_ERROR_PROTOCOL; } } } else { status = HgfsPlatformFileExists(utf8Name); if (HGFS_ERROR_SUCCESS == status) { status = HGFS_ERROR_FILE_EXIST; } else if (HGFS_ERROR_FILE_NOT_FOUND == status) { status = HGFS_ERROR_ACCESS_DENIED; } } } else { /* * Check if the name does not exist - the share was not found. * Then it could one of two things: the share was removed/disabled; * or we could be in the root share itself and have a new name. * To return the correct error, if we are in the root share, * we must check the open mode too - creation of new files/folders * should fail access denied, for anything else "not found" is acceptable. */ if (nameStatus == HGFS_NAME_STATUS_DOES_NOT_EXIST) { if (HgfsServerIsSharedFolderOnly(info.cpName, info.cpNameSize)) { nameStatus = HGFS_NAME_STATUS_ACCESS_DENIED; LOG(4, ("%s: New file creation in share root not allowed\n", __FUNCTION__)); } else { LOG(4, ("%s: Shared folder not found\n", __FUNCTION__)); } } else { LOG(4, ("%s: Shared folder access error %u\n", __FUNCTION__, nameStatus)); } status = HgfsPlatformConvertFromNameStatus(nameStatus); } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); free(utf8Name); } /* *----------------------------------------------------------------------------- * * HgfsServerDeleteFile -- * * Handle a Delete File request. * * Simply converts to the local filename, calls DeleteFile on the * file or calls the Windows native API Delete, and returns an * appropriate response to the driver. * * Enforcing read-only shares restrictions * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerDeleteFile(HgfsInputParam *input) // IN: Input params { const char *cpName; size_t cpNameSize; HgfsLockType serverLock = HGFS_LOCK_NONE; fileDesc fileDesc; HgfsHandle file; HgfsDeleteHint hints = 0; HgfsInternalStatus status; HgfsNameStatus nameStatus; uint32 caseFlags; size_t replyPayloadSize = 0; HgfsShareInfo shareInfo; HGFS_ASSERT_INPUT(input); if (HgfsUnpackDeleteRequest(input->payload, input->payloadSize, input->op, &cpName, &cpNameSize, &hints, &file, &caseFlags)) { if (hints & HGFS_DELETE_HINT_USE_FILE_DESC) { status = HgfsPlatformDeleteFileByHandle(file, input->session); } else { char *utf8Name = NULL; size_t utf8NameLen; nameStatus = HgfsServerGetLocalNameInfo(cpName, cpNameSize, caseFlags, &shareInfo, &utf8Name, &utf8NameLen); if (nameStatus == HGFS_NAME_STATUS_COMPLETE) { /* * Deleting a file needs both read and write permssions. * However the error code must be different depending on the existence * of the file with the same name. */ if (!shareInfo.writePermissions || !shareInfo.readPermissions) { status = HgfsPlatformFileExists(utf8Name); if (HGFS_ERROR_SUCCESS == status) { status = HGFS_ERROR_ACCESS_DENIED; } LOG(4, ("HgfsServerDeleteFile: failed access check, error %d\n", status)); } else if (HgfsFileHasServerLock(utf8Name, input->session, &serverLock, &fileDesc)) { /* * XXX: If the file has an oplock, the client should have broken it on * its own by now. Sorry! */ LOG (4, ("%s: File has an outstanding oplock. Client should " "remove this oplock and try again.\n", __FUNCTION__)); status = HGFS_ERROR_PATH_BUSY; } else { LOG(4, ("%s: deleting \"%s\"\n", __FUNCTION__, utf8Name)); status = HgfsPlatformDeleteFileByName(utf8Name); } free(utf8Name); } else { LOG(4, ("%s: Shared folder does not exist.\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } } if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackDeleteReply(input->packet, input->request, input->op, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerDeleteDir -- * * Handle a Delete Dir request. * * Simply converts to the local filename, calls RemoveDirectory on the * directory or Windows native API delete if we have a valid handle, * and returns an appropriate response to the driver. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerDeleteDir(HgfsInputParam *input) // IN: Input params { const char *cpName; size_t cpNameSize; HgfsInternalStatus status; HgfsNameStatus nameStatus; HgfsHandle file; HgfsDeleteHint hints = 0; fileDesc fileDesc; Bool sharedFolderOpen = FALSE; uint32 caseFlags; size_t replyPayloadSize = 0; HgfsShareInfo shareInfo; HGFS_ASSERT_INPUT(input); if (HgfsUnpackDeleteRequest(input->payload, input->payloadSize, input->op, &cpName, &cpNameSize, &hints, &file, &caseFlags)) { if (hints & HGFS_DELETE_HINT_USE_FILE_DESC) { status = HgfsPlatformGetFd(file, input->session, FALSE, &fileDesc); if (HGFS_ERROR_SUCCESS == status) { if (HgfsHandleIsSharedFolderOpen(file, input->session, &sharedFolderOpen) && sharedFolderOpen) { LOG(4, ("%s: Cannot delete shared folder\n", __FUNCTION__)); status = HGFS_ERROR_ACCESS_DENIED; } else { status = HgfsPlatformDeleteDirByHandle(file, input->session); if (HGFS_ERROR_SUCCESS != status) { LOG(4, ("%s: error deleting directory %d: %d\n", __FUNCTION__, file, status)); } } } else { LOG(4, ("%s: could not map cached handle %u, error %u\n", __FUNCTION__, file, status)); } } else { char *utf8Name = NULL; size_t utf8NameLen; nameStatus = HgfsServerGetLocalNameInfo(cpName, cpNameSize, caseFlags, &shareInfo, &utf8Name, &utf8NameLen); if (HGFS_NAME_STATUS_COMPLETE == nameStatus) { ASSERT(utf8Name); /* Guest OS is not allowed to delete shared folder. */ if (HgfsServerIsSharedFolderOnly(cpName, cpNameSize)){ LOG(4, ("%s: Cannot delete shared folder\n", __FUNCTION__)); status = HGFS_ERROR_ACCESS_DENIED; } else if (!shareInfo.writePermissions || !shareInfo.readPermissions) { /* * Deleting a directory requires both read and write permissions. * However the error code must be different depending on the existence * of the file with the same name. */ status = HgfsPlatformFileExists(utf8Name); if (HGFS_ERROR_SUCCESS == status) { status = HGFS_ERROR_ACCESS_DENIED; } LOG(4, ("HgfsServerDeleteDir: failed access check, error %d\n", status)); } else { LOG(4, ("%s: removing \"%s\"\n", __FUNCTION__, utf8Name)); status = HgfsPlatformDeleteDirByName(utf8Name); } free(utf8Name); } else { LOG(4, ("%s: access check failed\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } } if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackDeleteReply(input->packet, input->request, input->op, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerServerLockChange -- * * Called by the client when it wants to either acquire an oplock on a file * that was previously opened, or when it wants to release/downgrade an * oplock on a file that was previously oplocked. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerServerLockChange(HgfsInputParam *input) // IN: Input params { HGFS_ASSERT_INPUT(input); HgfsServerCompleteRequest(HGFS_ERROR_NOT_SUPPORTED, 0, input); } /* *----------------------------------------------------------------------------- * * HgfsServerWriteWin32Stream -- * * Handle a write request in the WIN32_STREAM_ID format. * * Results: * ERROR_SUCCESS or an appropriate Win32 error code. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerWriteWin32Stream(HgfsInputParam *input) // IN: Input params { uint32 actualSize; HgfsInternalStatus status; HgfsHandle file; const char *dataToWrite; Bool doSecurity; size_t replyPayloadSize = 0; size_t requiredSize; HGFS_ASSERT_INPUT(input); if (HgfsUnpackWriteWin32StreamRequest(input->payload, input->payloadSize, input->op, &file, &dataToWrite, &requiredSize, &doSecurity)) { status = HgfsPlatformWriteWin32Stream(file, (char *)dataToWrite, (uint32)requiredSize, doSecurity, &actualSize, input->session); if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackWriteWin32StreamReply(input->packet, input->request, input->op, actualSize, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerSetDirWatchByHandle -- * * Sets directory notification watch request using directory handle. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerSetDirWatchByHandle(HgfsInputParam *input, // IN: Input params HgfsHandle dir, // IN: directory handle uint32 events, // IN: event types to report Bool watchTree, // IN: recursive watch HgfsSubscriberHandle *watchId) // OUT: watch id { HgfsInternalStatus status; char *fileName = NULL; size_t fileNameSize; HgfsSharedFolderHandle sharedFolder = HGFS_INVALID_FOLDER_HANDLE; LOG(8, ("%s: entered\n", __FUNCTION__)); ASSERT(watchId != NULL); if (HgfsHandle2NotifyInfo(dir, input->session, &fileName, &fileNameSize, &sharedFolder)) { LOG(4, ("%s: adding a subscriber on shared folder handle %#x\n", __FUNCTION__, sharedFolder)); *watchId = HgfsNotify_AddSubscriber(sharedFolder, fileName, events, watchTree, input->session); status = (HGFS_INVALID_SUBSCRIBER_HANDLE == *watchId) ? HGFS_ERROR_INTERNAL : HGFS_ERROR_SUCCESS; LOG(4, ("%s: result of add subscriber id %"FMT64"x status %u\n", __FUNCTION__, *watchId, status)); } else { status = HGFS_ERROR_INTERNAL; } free(fileName); LOG(8, ("%s: exit %u\n", __FUNCTION__, status)); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerSetDirWatchByName -- * * Sets directory notification watch request using directory name. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerSetDirWatchByName(HgfsInputParam *input, // IN: Input params const char *cpName, // IN: directory name uint32 cpNameSize, // IN: directory name length uint32 caseFlags, // IN: case flags uint32 events, // IN: event types to report Bool watchTree, // IN: recursive watch HgfsSubscriberHandle *watchId) // OUT: watch id { HgfsInternalStatus status; HgfsNameStatus nameStatus; char *utf8Name = NULL; size_t utf8NameLen; HgfsShareInfo shareInfo; HgfsSharedFolderHandle sharedFolder = HGFS_INVALID_FOLDER_HANDLE; ASSERT(cpName != NULL); ASSERT(watchId != NULL); LOG(8, ("%s: entered\n",__FUNCTION__)); nameStatus = HgfsServerGetLocalNameInfo(cpName, cpNameSize, caseFlags, &shareInfo, &utf8Name, &utf8NameLen); if (HGFS_NAME_STATUS_COMPLETE == nameStatus) { char const *inEnd = cpName + cpNameSize; char const *next; int len; ASSERT(utf8Name); /* * Get first component. */ len = CPName_GetComponent(cpName, inEnd, (char const **) &next); if (len < 0) { LOG(4, ("%s: get first component failed\n", __FUNCTION__)); nameStatus = HGFS_NAME_STATUS_FAILURE; } else if (0 == len) { /* See if we are dealing with the base of the namespace */ nameStatus = HGFS_NAME_STATUS_INCOMPLETE_BASE; } else { sharedFolder = shareInfo.handle; } if (HGFS_NAME_STATUS_COMPLETE == nameStatus && HGFS_INVALID_FOLDER_HANDLE != sharedFolder) { if (cpNameSize > len + 1) { size_t nameSize = cpNameSize - len - 1; char tempBuf[HGFS_PATH_MAX]; char *tempPtr = tempBuf; size_t tempSize = sizeof tempBuf; nameStatus = CPName_ConvertFrom((char const **) &next, &nameSize, &tempSize, &tempPtr); if (HGFS_NAME_STATUS_COMPLETE == nameStatus) { LOG(8, ("%s: session %p id %"FMT64"x on share hnd %#x\n", __FUNCTION__, input->session, input->session->sessionId, sharedFolder)); *watchId = HgfsNotify_AddSubscriber(sharedFolder, tempBuf, events, watchTree, input->session); status = (HGFS_INVALID_SUBSCRIBER_HANDLE == *watchId) ? HGFS_ERROR_INTERNAL : HGFS_ERROR_SUCCESS; LOG(8, ("%s: watchId %"FMT64"x result %u\n", __FUNCTION__, *watchId, status)); } else { LOG(4, ("%s: Conversion to platform specific name failed\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } } else { LOG(8, ("%s: adding subscriber on share hnd %#x\n", __FUNCTION__, sharedFolder)); *watchId = HgfsNotify_AddSubscriber(sharedFolder, "", events, watchTree, input->session); status = (HGFS_INVALID_SUBSCRIBER_HANDLE == *watchId) ? HGFS_ERROR_INTERNAL : HGFS_ERROR_SUCCESS; LOG(8, ("%s: adding subscriber on share hnd %#x watchId %"FMT64"x result %u\n", __FUNCTION__, sharedFolder, *watchId, status)); } } else if (HGFS_NAME_STATUS_INCOMPLETE_BASE == nameStatus) { LOG(4, ("%s: Notification for root share is not supported yet\n", __FUNCTION__)); status = HGFS_ERROR_INVALID_PARAMETER; } else { LOG(4, ("%s: file not found.\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } } else { LOG(4, ("%s: file not found.\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } free(utf8Name); LOG(8, ("%s: exit %u\n",__FUNCTION__, status)); return status; } /* *----------------------------------------------------------------------------- * * HgfsServerSetDirNotifyWatch -- * * Handle a set directory notification watch request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerSetDirNotifyWatch(HgfsInputParam *input) // IN: Input params { const char *cpName; size_t cpNameSize; HgfsInternalStatus status; HgfsHandle dir; uint32 caseFlags; size_t replyPayloadSize = 0; uint32 flags; uint32 events; HgfsSubscriberHandle watchId = HGFS_INVALID_SUBSCRIBER_HANDLE; Bool useHandle; HGFS_ASSERT_INPUT(input); LOG(8, ("%s: entered\n", __FUNCTION__)); /* * If the active session does not support directory change notification - bail out * with an error immediately. * Clients are expected to check the session capabilities and flags but a malicious * or broken client could still issue this to us. */ if (0 == (input->session->flags & HGFS_SESSION_CHANGENOTIFY_ENABLED)) { HgfsServerCompleteRequest(HGFS_ERROR_PROTOCOL, 0, input); return; } if (HgfsUnpackSetWatchRequest(input->payload, input->payloadSize, input->op, &useHandle, &cpName, &cpNameSize, &flags, &events, &dir, &caseFlags)) { Bool watchTree = 0 != (flags & HGFS_NOTIFY_FLAG_WATCH_TREE); if (useHandle) { status = HgfsServerSetDirWatchByHandle(input, dir, events, watchTree, &watchId); } else { status = HgfsServerSetDirWatchByName(input, cpName, cpNameSize, caseFlags, events, watchTree, &watchId); } if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackSetWatchReply(input->packet, input->request, input->op, watchId, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); LOG(8, ("%s: exit %u\n", __FUNCTION__, status)); } /* *----------------------------------------------------------------------------- * * HgfsServerRemoveDirNotifyWatch -- * * Handle a remove directory notification watch request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerRemoveDirNotifyWatch(HgfsInputParam *input) // IN: Input params { HgfsSubscriberHandle watchId; HgfsInternalStatus status; size_t replyPayloadSize = 0; LOG(8, ("%s: entered\n", __FUNCTION__)); HGFS_ASSERT_INPUT(input); /* * If the active session does not support directory change notification - bail out * with an error immediately. * Clients are expected to check the session capabilities and flags but a malicious * or broken client could still issue this to us. */ if (0 == (input->session->flags & HGFS_SESSION_CHANGENOTIFY_ENABLED)) { HgfsServerCompleteRequest(HGFS_ERROR_PROTOCOL, 0, input); return; } if (HgfsUnpackRemoveWatchRequest(input->payload, input->payloadSize, input->op, &watchId)) { LOG(8, ("%s: remove subscriber on subscr id %"FMT64"x\n", __FUNCTION__, watchId)); if (HgfsNotify_RemoveSubscriber(watchId)) { status = HGFS_ERROR_SUCCESS; } else { status = HGFS_ERROR_INTERNAL; } LOG(8, ("%s: remove subscriber on subscr id %"FMT64"x result %u\n", __FUNCTION__, watchId, status)); } else { status = HGFS_ERROR_PROTOCOL; } if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackRemoveWatchReply(input->packet, input->request, input->op, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } HgfsServerCompleteRequest(status, replyPayloadSize, input); LOG(8, ("%s: exit result %u\n", __FUNCTION__, status)); } /* *----------------------------------------------------------------------------- * * HgfsServerGetattr -- * * Handle a Getattr request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerGetattr(HgfsInputParam *input) // IN: Input params { char *localName = NULL; HgfsAttrHint hints = 0; HgfsFileAttrInfo attr; HgfsInternalStatus status = 0; HgfsNameStatus nameStatus; const char *cpName; size_t cpNameSize; char *targetName = NULL; uint32 targetNameLen = 0; HgfsHandle file; /* file handle from driver */ uint32 caseFlags = 0; HgfsShareOptions configOptions; size_t localNameLen; HgfsShareInfo shareInfo; size_t replyPayloadSize = 0; HGFS_ASSERT_INPUT(input); if (HgfsUnpackGetattrRequest(input->payload, input->payloadSize, input->op, &attr, &hints, &cpName, &cpNameSize, &file, &caseFlags)) { /* Client wants us to reuse an existing handle. */ if (hints & HGFS_ATTR_HINT_USE_FILE_DESC) { fileDesc fd; targetNameLen = 0; status = HgfsPlatformGetFd(file, input->session, FALSE, &fd); if (HGFS_ERROR_SUCCESS == status) { status = HgfsPlatformGetattrFromFd(fd, input->session, &attr); } else { LOG(4, ("%s: Could not get file descriptor\n", __FUNCTION__)); } } else { /* * Depending on whether this file/dir is real or virtual, either * forge its attributes or look them up in the actual filesystem. */ nameStatus = HgfsServerGetLocalNameInfo(cpName, cpNameSize, caseFlags, &shareInfo, &localName, &localNameLen); switch (nameStatus) { case HGFS_NAME_STATUS_INCOMPLETE_BASE: /* * This is the base of our namespace; make up fake status for * this directory. */ LOG(4, ("%s: getting attrs for base dir\n", __FUNCTION__)); HgfsPlatformGetDefaultDirAttrs(&attr); break; case HGFS_NAME_STATUS_COMPLETE: /* This is a regular lookup; proceed as usual */ ASSERT(localName); /* Get the config options. */ nameStatus = HgfsServerPolicy_GetShareOptions(cpName, cpNameSize, &configOptions); if (HGFS_NAME_STATUS_COMPLETE == nameStatus) { status = HgfsPlatformGetattrFromName(localName, configOptions, (char *)cpName, &attr, &targetName); } else { LOG(4, ("%s: no matching share: %s.\n", __FUNCTION__, cpName)); status = HGFS_ERROR_FILE_NOT_FOUND; } if (HGFS_ERROR_SUCCESS == status && !HgfsServer_ShareAccessCheck(HGFS_OPEN_MODE_READ_ONLY, shareInfo.writePermissions, shareInfo.readPermissions)) { status = HGFS_ERROR_ACCESS_DENIED; } else if (status != HGFS_ERROR_SUCCESS) { /* * If it is a dangling share server should not return * HGFS_ERROR_FILE_NOT_FOUND * to the client because it causes confusion: a name that is returned * by directory enumeration should not produce "name not found" * error. * Replace it with a more appropriate error code: no such device. */ if (status == HGFS_ERROR_FILE_NOT_FOUND && HgfsIsShareRoot(cpName, cpNameSize)) { status = HGFS_ERROR_IO; } } break; default: status = HgfsPlatformHandleIncompleteName(nameStatus, &attr); } targetNameLen = targetName ? strlen(targetName) : 0; } if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackGetattrReply(input->packet, input->request, &attr, targetName, targetNameLen, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else { status = HGFS_ERROR_PROTOCOL; } free(targetName); free(localName); HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerSetattr -- * * Handle a Setattr request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerSetattr(HgfsInputParam *input) // IN: Input params { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; HgfsNameStatus nameStatus; HgfsFileAttrInfo attr; const char *cpName; size_t cpNameSize = 0; HgfsAttrHint hints = 0; HgfsOpenMode shareMode; uint32 caseFlags = 0; HgfsShareInfo shareInfo; HgfsHandle file; size_t replyPayloadSize = 0; HGFS_ASSERT_INPUT(input); if (HgfsUnpackSetattrRequest(input->payload, input->payloadSize, input->op, &attr, &hints, &cpName, &cpNameSize, &file, &caseFlags)) { Bool useHostTime = 0 != (gHgfsCfgSettings.flags & HGFS_CONFIG_USE_HOST_TIME); /* Client wants us to reuse an existing handle. */ if (hints & HGFS_ATTR_HINT_USE_FILE_DESC) { if (HgfsHandle2ShareMode(file, input->session, &shareMode)) { if (HGFS_OPEN_MODE_READ_ONLY != shareMode) { status = HgfsPlatformSetattrFromFd(file, input->session, &attr, hints, useHostTime); } else { status = HGFS_ERROR_ACCESS_DENIED; } } else { LOG(4, ("%s: could not get share mode fd %d\n", __FUNCTION__, file)); status = HGFS_ERROR_INVALID_HANDLE; } } else { /* Client wants us to open a new handle for this operation. */ char *utf8Name = NULL; size_t utf8NameLen; nameStatus = HgfsServerGetLocalNameInfo(cpName, cpNameSize, caseFlags, &shareInfo, &utf8Name, &utf8NameLen); if (HGFS_NAME_STATUS_COMPLETE == nameStatus) { fileDesc hFile; HgfsLockType serverLock = HGFS_LOCK_NONE; HgfsShareOptions configOptions; /* * XXX: If the client has an oplock on this file, it must reuse the * handle for the oplocked node (or break the oplock) prior to making * a setattr request. Fail this request. */ if (!HgfsServer_ShareAccessCheck(HGFS_OPEN_MODE_WRITE_ONLY, shareInfo.writePermissions, shareInfo.readPermissions)) { status = HGFS_ERROR_ACCESS_DENIED; } else if (HGFS_NAME_STATUS_COMPLETE != HgfsServerPolicy_GetShareOptions(cpName, cpNameSize, &configOptions)) { LOG(4, ("%s: no matching share: %s.\n", __FUNCTION__, cpName)); status = HGFS_ERROR_FILE_NOT_FOUND; } else if (HgfsFileHasServerLock(utf8Name, input->session, &serverLock, &hFile)) { LOG(4, ("%s: An open, oplocked handle exists for " "this file. The client should retry with that handle\n", __FUNCTION__)); status = HGFS_ERROR_PATH_BUSY; } else { status = HgfsPlatformSetattrFromName(utf8Name, &attr, configOptions, hints, useHostTime); } free(utf8Name); } else { LOG(4, ("%s: file not found.\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } } if (HGFS_ERROR_SUCCESS == status) { if (!HgfsPackSetattrReply(input->packet, input->request, attr.requestType, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerValidateOpenParameters -- * * Performs sanity check of the input parameters. * * Results: * HGFS_ERROR_SUCCESS if the parameters are valid. * Appropriate error code otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsServerValidateOpenParameters(HgfsFileOpenInfo *openInfo, // IN/OUT: openfile info Bool *denyCreatingFile, // OUT: No new files int *followSymlinks) // OUT: Host resolves link { size_t utf8NameLen; HgfsInternalStatus status; *followSymlinks = 0; *denyCreatingFile = FALSE; if ((openInfo->mask & HGFS_OPEN_VALID_MODE)) { HgfsNameStatus nameStatus; /* It is now safe to read the file name. */ nameStatus = HgfsServerGetLocalNameInfo(openInfo->cpName, openInfo->cpNameSize, openInfo->caseFlags, &openInfo->shareInfo, &openInfo->utf8Name, &utf8NameLen); if (HGFS_NAME_STATUS_COMPLETE == nameStatus) { if (openInfo->mask & HGFS_OPEN_VALID_FLAGS) { HgfsOpenFlags savedOpenFlags = openInfo->flags; if (HgfsServerCheckOpenFlagsForShare(openInfo, &openInfo->flags)) { HgfsShareOptions configOptions; /* Get the config options. */ nameStatus = HgfsServerPolicy_GetShareOptions(openInfo->cpName, openInfo->cpNameSize, &configOptions); if (nameStatus == HGFS_NAME_STATUS_COMPLETE) { *followSymlinks = HgfsServerPolicy_IsShareOptionSet(configOptions, HGFS_SHARE_FOLLOW_SYMLINKS); *denyCreatingFile = savedOpenFlags != openInfo->flags; status = HGFS_ERROR_SUCCESS; } else { LOG(4, ("%s: no matching share: %s.\n", __FUNCTION__, openInfo->cpName)); *denyCreatingFile = TRUE; status = HGFS_ERROR_FILE_NOT_FOUND; } } else { /* Incompatible open mode with share mode. */ status = HGFS_STATUS_ACCESS_DENIED; } } else { status = HGFS_ERROR_PROTOCOL; } } else { /* * Check if the name does not exist - the share was not found. * Then it could one of two things: the share was removed/disabled; * or we could be in the root share itself and have a new name. * To return the correct error, if we are in the root share, * we must check the open mode too - creation of new files/folders * should fail access denied, for anything else "not found" is acceptable. */ if (nameStatus == HGFS_NAME_STATUS_DOES_NOT_EXIST) { if ((openInfo->mask & HGFS_OPEN_VALID_FLAGS && (openInfo->flags == HGFS_OPEN_CREATE || openInfo->flags == HGFS_OPEN_CREATE_SAFE || openInfo->flags == HGFS_OPEN_CREATE_EMPTY)) && HgfsServerIsSharedFolderOnly(openInfo->cpName, openInfo->cpNameSize)) { nameStatus = HGFS_NAME_STATUS_ACCESS_DENIED; LOG(4, ("%s: New file creation in share root not allowed\n", __FUNCTION__)); } else { LOG(4, ("%s: Shared folder not found\n", __FUNCTION__)); } } else { LOG(4, ("%s: Shared folder access error %u\n", __FUNCTION__, nameStatus)); } status = HgfsPlatformConvertFromNameStatus(nameStatus); } } else { LOG(4, ("%s: filename or mode not provided\n", __FUNCTION__)); status = HGFS_ERROR_PROTOCOL; } return status; } /* *----------------------------------------------------------------------------- * * HgfsServerOpen -- * * Handle an Open request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerOpen(HgfsInputParam *input) // IN: Input params { HgfsInternalStatus status; fileDesc newHandle; HgfsLocalId localId; HgfsFileOpenInfo openInfo; fileDesc fileDesc; HgfsLockType serverLock = HGFS_LOCK_NONE; size_t replyPayloadSize = 0; HGFS_ASSERT_INPUT(input); if (HgfsUnpackOpenRequest(input->payload, input->payloadSize, input->op, &openInfo)) { int followSymlinks; Bool denyCreatingFile; status = HgfsServerValidateOpenParameters(&openInfo, &denyCreatingFile, &followSymlinks); if (HGFS_ERROR_SUCCESS == status) { ASSERT(openInfo.utf8Name); LOG(4, ("%s: opening \"%s\", mode %u, flags %u, perms %u%u%u%u attr %u\n", __FUNCTION__, openInfo.utf8Name, openInfo.mode, openInfo.mask & HGFS_OPEN_VALID_FLAGS ? openInfo.flags : 0, (openInfo.mask & HGFS_OPEN_VALID_SPECIAL_PERMS) ? openInfo.specialPerms : 0, (openInfo.mask & HGFS_OPEN_VALID_OWNER_PERMS) ? openInfo.ownerPerms : 0, (openInfo.mask & HGFS_OPEN_VALID_GROUP_PERMS) ? openInfo.groupPerms : 0, (openInfo.mask & HGFS_OPEN_VALID_OTHER_PERMS) ? openInfo.otherPerms : 0, openInfo.mask & HGFS_OPEN_VALID_FILE_ATTR ? (uint32)openInfo.attr : 0)); /* * XXX: Before opening the file, see if we already have this file opened on * the server with an oplock on it. If we do, we must fail the new open * request, otherwise we will trigger an oplock break that the guest cannot * handle at this time (since the HGFS server is running in the context of * the vcpu thread), and we'll deadlock. * * Until we overcome this limitation via Crosstalk, we will be extra smart * in the client drivers so as to prevent open requests on handles that * already have an oplock. And the server will protect itself like so. * * XXX: With some extra effort, we could allow a second open for read here, * since that won't break a shared oplock, but the clients should already * realize that the second open can be avoided via sharing handles, too. */ if (!HgfsFileHasServerLock(openInfo.utf8Name, input->session, &serverLock, &fileDesc)) { /* See if the name is valid, and if so add it and return the handle. */ status = HgfsPlatformValidateOpen(&openInfo, followSymlinks, input->session, &localId, &newHandle); if (status == HGFS_ERROR_SUCCESS) { ASSERT(newHandle >= 0); /* * Open succeeded, so make new node and return its handle. If we fail, * it's almost certainly an internal server error. */ if (HgfsCreateAndCacheFileNode(&openInfo, &localId, newHandle, FALSE, input->session)) { if (!HgfsPackOpenReply(input->packet, input->request, &openInfo, &replyPayloadSize, input->session)) { status = HGFS_ERROR_INTERNAL; } } } else if (denyCreatingFile && HGFS_ERROR_FILE_NOT_FOUND == status) { status = HGFS_ERROR_ACCESS_DENIED; } } else { status = HGFS_ERROR_PATH_BUSY; } free(openInfo.utf8Name); } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerSearchReadAttrToMask -- * * Sets a search read information mask from the retrieved attribute * information. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerSearchReadAttrToMask(HgfsFileAttrInfo *attr, // IN/OUT: attributes for entry HgfsSearchReadMask *mask) // IN/OUT: what info is required/returned { if (0 != (attr->mask & HGFS_ATTR_VALID_TYPE)) { *mask |= (HGFS_SEARCH_READ_FILE_NODE_TYPE); } if (0 != (attr->mask & HGFS_ATTR_VALID_SIZE)) { *mask |= (HGFS_SEARCH_READ_FILE_SIZE); } if (0 != (attr->mask & HGFS_ATTR_VALID_ALLOCATION_SIZE)) { *mask |= (HGFS_SEARCH_READ_ALLOCATION_SIZE); } if (0 != (attr->mask & (HGFS_ATTR_VALID_CREATE_TIME | HGFS_ATTR_VALID_ACCESS_TIME | HGFS_ATTR_VALID_WRITE_TIME | HGFS_ATTR_VALID_CHANGE_TIME))) { *mask |= (HGFS_SEARCH_READ_TIME_STAMP); } if (0 != (attr->mask & (HGFS_ATTR_VALID_FLAGS | HGFS_ATTR_VALID_OWNER_PERMS | HGFS_ATTR_VALID_GROUP_PERMS | HGFS_ATTR_VALID_OTHER_PERMS))) { Bool isReadOnly = TRUE; *mask |= (HGFS_SEARCH_READ_FILE_ATTRIBUTES); /* * For V4 we don't return the permissions as they are really not * used. Only used to see if the entry is read only. So set the * attribute flag if the entry is read only. */ if (attr->mask & HGFS_ATTR_VALID_OWNER_PERMS && attr->ownerPerms & HGFS_PERM_WRITE) { isReadOnly = FALSE; } if (attr->mask & HGFS_ATTR_VALID_GROUP_PERMS && attr->groupPerms & HGFS_PERM_WRITE) { isReadOnly = FALSE; } if (attr->mask & HGFS_ATTR_VALID_OTHER_PERMS && attr->otherPerms & HGFS_PERM_WRITE) { isReadOnly = FALSE; } if (isReadOnly) { attr->flags |= HGFS_ATTR_READONLY; attr->mask |= HGFS_ATTR_VALID_FLAGS; } } if (0 != (attr->mask & (HGFS_ATTR_VALID_FILEID | HGFS_ATTR_VALID_NON_STATIC_FILEID))) { *mask |= (HGFS_SEARCH_READ_FILE_ID); } } /* *----------------------------------------------------------------------------- * * HgfsGetDirEntry -- * * Gets a directory entry at specified index. * * Results: * A platform specific error or success. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsGetDirEntry(HgfsHandle hgfsSearchHandle, // IN: ID for search data HgfsSearch *search, // IN: search data HgfsShareOptions configOptions, // IN: share configuration settings HgfsSessionInfo *session, // IN: session we are called in HgfsSearchReadInfo *info, // IN/OUT: request details HgfsSearchReadEntry *entry, // OUT: directory entry Bool *moreEntries) // OUT: any more entries { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; struct DirectoryEntry *dent; HgfsSearchReadMask infoRetrieved; HgfsSearchReadMask infoRequested; HgfsFileAttrInfo *entryAttr; char **entryName; uint32 *entryNameLength; Bool getAttrs; uint32 requestedIndex; infoRequested = info->requestedMask; entryAttr = &entry->attr; entryName = &entry->name; entryNameLength = &entry->nameLength; requestedIndex = info->currentIndex; getAttrs = (0 != (infoRequested & (HGFS_SEARCH_READ_FILE_SIZE | HGFS_SEARCH_READ_ALLOCATION_SIZE | HGFS_SEARCH_READ_TIME_STAMP | HGFS_SEARCH_READ_FILE_ATTRIBUTES | HGFS_SEARCH_READ_FILE_ID | HGFS_SEARCH_READ_FILE_NODE_TYPE))); /* Clear out what we will return. */ infoRetrieved = 0; memset(entryAttr, 0, sizeof *entryAttr); *moreEntries = FALSE; *entryName = NULL; *entryNameLength = 0; status = HgfsServerGetDirEntry(hgfsSearchHandle, session, requestedIndex, FALSE, &dent); if (HGFS_ERROR_SUCCESS != status) { goto exit; } if (NULL == dent) { /* End of directory entries marker. */ info->replyFlags |= HGFS_SEARCH_READ_REPLY_FINAL_ENTRY; HgfsSearchSetReadAllEntries(hgfsSearchHandle, session); goto exit; } status = HgfsPlatformSetDirEntry(search, configOptions, session, dent, getAttrs, entryAttr, entryName, entryNameLength); if (HGFS_ERROR_SUCCESS != status) { goto exit; } if (getAttrs) { /* * Update the search read mask for the attributes information. */ HgfsServerSearchReadAttrToMask(entryAttr, &infoRetrieved); } infoRetrieved |= HGFS_SEARCH_READ_NAME; /* Update the entry fields for valid data and index for the dent. */ entry->mask = infoRetrieved; entry->fileIndex = requestedIndex; *moreEntries = TRUE; exit: free(dent); return status; } /* *----------------------------------------------------------------------------- * * HgfsDoSearchRead -- * * Gets all the directory entries that remain or as many that will * fit into the reply buffer from the specified index. Fill in the * reply with the records and complete the reply details. * * Results: * A platform specific error or success. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsDoSearchRead(HgfsHandle hgfsSearchHandle, // IN: ID for search data HgfsSearch *search, // IN: search data HgfsShareOptions configOptions, // IN: share configuration settings HgfsSessionInfo *session, // IN: session we are called in HgfsSearchReadInfo *info, // IN/OUT: request details size_t *replyHeaderSize, // OUT: reply info written size size_t *replyDirentSize) // OUT: reply dirent written size { HgfsSearchReadEntry entry; size_t bytesWritten = 0; size_t bytesRemaining = 0; char *currentSearchReadRecord = NULL; char *lastSearchReadRecord = NULL; Bool moreEntries = TRUE; HgfsInternalStatus status = HGFS_ERROR_SUCCESS; info->currentIndex = info->startIndex; *replyHeaderSize = 0; *replyDirentSize = 0; while (moreEntries) { size_t offsetInBuffer = ROUNDUP(*replyDirentSize, sizeof (uint64)); if (info->payloadSize <= offsetInBuffer) { break; } memset(&entry, 0, sizeof entry); currentSearchReadRecord = (char*)info->replyPayload + offsetInBuffer; bytesRemaining = info->payloadSize - offsetInBuffer; bytesWritten = 0; status = HgfsGetDirEntry(hgfsSearchHandle, search, configOptions, session, info, &entry, &moreEntries); if (HGFS_ERROR_SUCCESS != status) { /* Failed to retrieve an entry record, bail. */ break; } if (!HgfsPackSearchReadReplyRecord(info->requestType, &entry, bytesRemaining, lastSearchReadRecord, currentSearchReadRecord, &bytesWritten)) { /* * The current entry is too large to be contained in the reply. * If this is the first entry returned then we have an error. * Otherwise, we return success for what is already in the reply. */ if (0 == info->numberRecordsWritten) { status = HGFS_ERROR_INTERNAL; } moreEntries = FALSE; } if (NULL != entry.name) { free(entry.name); } if (HGFS_ERROR_SUCCESS != status) { /* Failed to pack any entry records, bail. */ break; } /* * Only count records actually written to the reply. * (The final, empty record is not written for all protocol versions.) */ if (0 < bytesWritten) { if (0 != (info->flags & HGFS_SEARCH_READ_SINGLE_ENTRY)) { moreEntries = FALSE; } *replyDirentSize = ROUNDUP(*replyDirentSize, sizeof (uint64)) + bytesWritten; lastSearchReadRecord = currentSearchReadRecord; info->currentIndex++; info->numberRecordsWritten++; } } /* Now pack the search read reply common reply part. */ if (HgfsPackSearchReadReplyHeader(info, &bytesWritten)) { /* The search read reply common reply part size was already done so should be 0. */ *replyHeaderSize = bytesWritten; } else { status = HGFS_ERROR_PROTOCOL; } return status; } /* *----------------------------------------------------------------------------- * * HgfsServerSearchRead -- * * Handle a "Search Read" request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerSearchRead(HgfsInputParam *input) // IN: Input params { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; HgfsNameStatus nameStatus; HgfsHandle hgfsSearchHandle; HgfsSearch search; HgfsShareOptions configOptions = 0; size_t replyInfoSize = 0; size_t replyDirentSize = 0; size_t replyPayloadSize = 0; size_t inlineDataSize = 0; size_t baseReplySize; HgfsSearchReadInfo info; HGFS_ASSERT_INPUT(input); memset(&info, 0, sizeof info); /* * For search read V4 we use the whole packet buffer available to pack * as many replies as can fit into that size. For all previous versions * only one record is going to be returned, so we allow the old packet * max for the reply. */ if (HgfsUnpackSearchReadRequest(input->payload, input->payloadSize, input->op, &info, &baseReplySize, &inlineDataSize, &hgfsSearchHandle)) { LOG(4, ("%s: read search #%u, offset %u\n", __FUNCTION__, hgfsSearchHandle, info.startIndex)); info.reply = HgfsAllocInitReply(input->packet, input->request, baseReplySize + inlineDataSize, input->session); if (inlineDataSize == 0) { info.replyPayload = HSPU_GetDataPacketBuf(input->packet, BUF_WRITEABLE, input->transportSession->channelCbTable); } else { info.replyPayload = (char *)info.reply + baseReplySize; } if (info.replyPayload == NULL) { LOG(4, ("%s: Op %d reply buffer failure\n", __FUNCTION__, input->op)); status = HGFS_ERROR_PROTOCOL; } else { if (HgfsGetSearchCopy(hgfsSearchHandle, input->session, &search)) { /* Get the config options. */ if (search.utf8ShareNameLen != 0) { nameStatus = HgfsServerPolicy_GetShareOptions(search.utf8ShareName, search.utf8ShareNameLen, &configOptions); if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { LOG(4, ("%s: no matching share: %s.\n", __FUNCTION__, search.utf8ShareName)); status = HGFS_ERROR_FILE_NOT_FOUND; } } else if (0 == info.startIndex) { Bool readAllEntries = FALSE; /* * Reading the first entry, we check if this is a second scan * of the directory. If so, in some cases we restart the scan * by refreshing the entries first. */ if (!HgfsSearchHasReadAllEntries(hgfsSearchHandle, input->session, &readAllEntries)) { status = HGFS_ERROR_INTERNAL; } if (readAllEntries) { /* * XXX - a hack that is now required until Fusion 5.0 end * of lifes see bug 710697. * The coder modified the server instead of the OS X client * for the shares directory refresh needed by OS X clients in * order to work around handles remaining open by Finder. * This was fixed CLN 1988575 in the OS X client for 5.0.2. * However, Fusion 4.0 and Fusion 5.0 tools will rely on this hack. * At least now it works correctly without breaking everything * else. */ status = HgfsPlatformRestartSearchDir(hgfsSearchHandle, input->session, search.type); } } if (HGFS_ERROR_SUCCESS == status) { status = HgfsDoSearchRead(hgfsSearchHandle, &search, configOptions, input->session, &info, &replyInfoSize, &replyDirentSize); } if (HGFS_ERROR_SUCCESS == status) { replyPayloadSize = replyInfoSize + ((inlineDataSize == 0) ? 0 : replyDirentSize); if (0 == inlineDataSize) { HSPU_SetDataPacketSize(input->packet, replyDirentSize); } } free(search.utf8Dir); free(search.utf8ShareName); } else { LOG(4, ("%s: handle %u is invalid\n", __FUNCTION__, hgfsSearchHandle)); status = HGFS_ERROR_INVALID_HANDLE; } } } else { status = HGFS_ERROR_PROTOCOL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerCreateSession -- * * Handle a "Create session" request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerCreateSession(HgfsInputParam *input) // IN: Input params { size_t replyPayloadSize = 0; HgfsCreateSessionInfo info; HgfsInternalStatus status; HGFS_ASSERT_INPUT(input); if (HgfsUnpackCreateSessionRequest(input->payload, input->payloadSize, input->op, &info)) { HgfsSessionInfo *session; LOG(4, ("%s: create session\n", __FUNCTION__)); if (!HgfsServerAllocateSession(input->transportSession, &session)) { status = HGFS_ERROR_NOT_ENOUGH_MEMORY; goto abort; } else { status = HgfsServerTransportAddSessionToList(input->transportSession, session); if (HGFS_ERROR_SUCCESS != status) { LOG(4, ("%s: Could not add session to the list.\n", __FUNCTION__)); HgfsServerSessionPut(session); goto abort; } } if (info.maxPacketSize < session->maxPacketSize) { session->maxPacketSize = info.maxPacketSize; } /* * If the server is enabled for processing oplocks and the client * is requesting to use them, then report back to the client oplocks * are enabled by propagating the session flag. */ if ((0 != (info.flags & HGFS_SESSION_OPLOCK_ENABLED)) && (0 != (gHgfsCfgSettings.flags & HGFS_CONFIG_OPLOCK_ENABLED))) { session->flags |= HGFS_SESSION_OPLOCK_ENABLED; } if (HgfsPackCreateSessionReply(input->packet, input->request, &replyPayloadSize, session)) { status = HGFS_ERROR_SUCCESS; } else { status = HGFS_ERROR_INTERNAL; } } else { status = HGFS_ERROR_PROTOCOL; } abort: HgfsServerCompleteRequest(status, replyPayloadSize, input); } /* *----------------------------------------------------------------------------- * * HgfsServerDestroySession -- * * Handle a "Destroy session" request. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerDestroySession(HgfsInputParam *input) // IN: Input params { HgfsTransportSessionInfo *transportSession; HgfsSessionInfo *session; size_t replyPayloadSize = 0; HgfsInternalStatus status; HGFS_ASSERT_INPUT(input); transportSession = input->transportSession; session = input->session; session->state = HGFS_SESSION_STATE_CLOSED; if (session->sessionId == transportSession->defaultSessionId) { transportSession->defaultSessionId = HGFS_INVALID_SESSION_ID; } /* * Remove the session from the list. By doing that, the refcount of * the session will be decremented. Later, we will be invoking * HgfsServerCompleteRequest which will decrement the session's * refcount and cleanup the session */ MXUser_AcquireExclLock(transportSession->sessionArrayLock); HgfsServerTransportRemoveSessionFromList(transportSession, session); MXUser_ReleaseExclLock(transportSession->sessionArrayLock); if (HgfsPackDestroySessionReply(input->packet, input->request, &replyPayloadSize, session)) { status = HGFS_ERROR_SUCCESS; } else { status = HGFS_ERROR_INTERNAL; } HgfsServerCompleteRequest(status, replyPayloadSize, input); HgfsServerSessionPut(session); } /* *----------------------------------------------------------------------------- * * HgfsServerGetTargetRelativePath -- * * Generates relative file path which need to be used a symbolic link * target which would generate target name defined in "target" if the path * to symbolic link file defined in the "source". * Both source and target parameters represent absolute paths. * * Results: * Allocated path that caller must free. * NULL if there is a low memory condition. * * Side effects: * None * *----------------------------------------------------------------------------- */ char* HgfsServerGetTargetRelativePath(const char* source, // IN: source file name const char* target) // IN: target file name { const char *relativeSource = source; const char *relativeTarget = target; const char* sourceSep; const char* targetSep; int level = 0; size_t targetSize; char *result; char *currentPosition; /* * First remove the part of the path which is common between source and * target */ while (*relativeSource != '\0' && *relativeTarget != '\0') { sourceSep = strchr(relativeSource, DIRSEPC); targetSep = strchr(relativeTarget, DIRSEPC); if (sourceSep == NULL || targetSep == NULL) { break; } if ((sourceSep - relativeSource) != (targetSep - relativeTarget)) { break; } if (strncmp(relativeSource, relativeTarget, (targetSep - relativeTarget)) != 0) { break; } relativeSource = sourceSep + 1; relativeTarget = targetSep + 1; }; /* * Find out how many directories deep the source file is from the common * part of the path. */ while(*relativeSource != '\0') { sourceSep = strchr(relativeSource, DIRSEPC); if (sourceSep != NULL) { /* Several consecutive separators mean only one level. */ while (*sourceSep == DIRSEPC) { sourceSep++; } if (*sourceSep != '\0') { level++; relativeSource = sourceSep; } else { break; } } else { break; } } /* * Consruct relative path by adding level number of "../" * to the relative target path. */ targetSize = level * HGFS_PARENT_DIR_LEN + strlen(relativeTarget) + sizeof '\0'; result = malloc(targetSize); currentPosition = result; if (result != NULL) { while (level != 0) { memcpy(currentPosition, HGFS_PARENT_DIR, HGFS_PARENT_DIR_LEN); level--; currentPosition += HGFS_PARENT_DIR_LEN; } memcpy(currentPosition, relativeTarget, strlen(relativeTarget) + sizeof '\0'); } return result; } /* *----------------------------------------------------------------------------- * * HgfsServerNotifyRegisterThreadCb -- * * The callback is invoked by the file system change notification component * thread for generating change notification events. * This simply calls back to the channel's register thread function, if present, * which does the actual work. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerNotifyRegisterThreadCb(struct HgfsSessionInfo *session) // IN: session info { HgfsTransportSessionInfo *transportSession; ASSERT(session); transportSession = session->transportSession; LOG(4, ("%s: Registering thread on session %"FMT64"x\n", __FUNCTION__, session->sessionId)); if (transportSession->channelCbTable->registerThread != NULL) { transportSession->channelCbTable->registerThread(); } } /* *----------------------------------------------------------------------------- * * HgfsServerNotifyUnregisterThreadCb -- * * The callback is invoked by the file system change notification component * thread for generating change notification events. * This simply calls back to the channel's unregister thread function, if present, * which does the actual work. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerNotifyUnregisterThreadCb(struct HgfsSessionInfo *session) // IN: session info { HgfsTransportSessionInfo *transportSession; ASSERT(session); transportSession = session->transportSession; LOG(4, ("%s: Unregistering thread on session %"FMT64"x\n", __FUNCTION__, session->sessionId)); if (transportSession->channelCbTable->unregisterThread != NULL) { transportSession->channelCbTable->unregisterThread(); } } /* *----------------------------------------------------------------------------- * * HgfsServerNotifyReceiveEventCb -- * * The callback is invoked by the file system change notification component * in response to a change event when the client has set at least one watch * on a directory. * * The function builds directory notification packet and queues it to be sent * to the client. It processes one notification at a time. Any consolidation of * packets is expected to occur at the transport layer. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerNotifyReceiveEventCb(HgfsSharedFolderHandle sharedFolder, // IN: shared folder HgfsSubscriberHandle subscriber, // IN: subsciber char* fileName, // IN: name of the file uint32 mask, // IN: event type struct HgfsSessionInfo *session) // IN: session info { HgfsPacket *packet = NULL; HgfsHeader *packetHeader = NULL; char *shareName = NULL; size_t shareNameLen; size_t sizeNeeded; uint32 notifyFlags; LOG(4, ("%s:Entered shr hnd %u hnd %"FMT64"x file %s mask %u\n", __FUNCTION__, sharedFolder, subscriber, fileName, mask)); if (session->state == HGFS_SESSION_STATE_CLOSED) { LOG(4, ("%s: session has been closed drop the notification %"FMT64"x\n", __FUNCTION__, session->sessionId)); goto exit; } if (!HgfsServerGetShareName(sharedFolder, &shareNameLen, &shareName)) { LOG(4, ("%s: failed to find shared folder for a handle %x\n", __FUNCTION__, sharedFolder)); goto exit; } sizeNeeded = HgfsPackCalculateNotificationSize(shareName, fileName); /* * Use a single buffer zero'd out, as the packet and metapacket have the same * lifespan which is ended at the send complete callback (HgfsServerSessionSendComplete). */ packet = Util_SafeCalloc(1, sizeof *packet + sizeNeeded); packetHeader = (HgfsHeader *)((char *)packet + sizeof *packet); /* * The buffer is zero'd out, so no need to set the following explicitly: * packet->metaPacketIsAllocated = FALSE; * packet->state &= ~HGFS_STATE_CLIENT_REQUEST; */ packet->metaPacketSize = sizeNeeded; packet->metaPacketDataSize = packet->metaPacketSize; packet->metaPacket = packetHeader; notifyFlags = 0; if (mask & HGFS_NOTIFY_EVENTS_DROPPED) { notifyFlags |= HGFS_NOTIFY_FLAG_OVERFLOW; } if (!HgfsPackChangeNotificationRequest(packetHeader, subscriber, shareName, fileName, mask, notifyFlags, session, &sizeNeeded)) { LOG(4, ("%s: failed to pack notification request\n", __FUNCTION__)); goto exit; } if (!HgfsPacketSend(packet, session->transportSession, session, 0)) { LOG(4, ("%s: failed to send notification to the host\n", __FUNCTION__)); goto exit; } /* The transport will call the server send complete callback to release the packets. */ packet = NULL; LOG(4, ("%s: Sent notify for: %u index: %"FMT64"u file name %s mask %x\n", __FUNCTION__, sharedFolder, subscriber, fileName, mask)); exit: if (shareName) { free(shareName); } if (packet) { free(packet); } } /* *----------------------------------------------------------------------------- * * HgfsIsShareRoot -- * * Checks if the cpName represents the root directory for a share. * Components in CPName format are separated by NUL characters. * CPName for the root of a share contains only one component thus * it does not have any embedded '\0' characters in the name. * * Results: * TRUE if it is the root directory, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsIsShareRoot(char const *cpName, // IN: name to test size_t cpNameSize) // IN: length of the name { size_t i; for (i = 0; i < cpNameSize; i++) { if (cpName[i] == '\0') { return FALSE; } } return TRUE; } /* * more testing */ #if 0 void TestNodeFreeList(void) { HgfsHandle array[10 * NUM_FILE_NODES]; HgfsFileNode *node; unsigned int i; printf("%s: begin >>>>>>>>>>>>>>>>>>>>>>>>>>>\n", __FUNCTION__); for (i = 0; i < sizeof array / sizeof array[0]; i++) { char tempName[20]; HgfsLocalId localId; Str_Sprintf(tempName, sizeof tempName, "name%u", i); printf("\nadding node with name: %s\n", tempName); localId.volumeId = 0; localId.fileId = i + 1000; node = HgfsAddNewFileNode(Util_SafeStrdup(tempName), &localId); array[i] = HgfsFileNode2Handle(node); } HgfsDumpAllNodes(); printf("done getting nodes, now freeing\n"); for (i = 0; i < sizeof array / sizeof array[0]; i++) { printf("removing node #%u\n", i); HgfsRemoveFileNode(&nodeArray[array[i]]); } HgfsDumpAllNodes(); printf("%s: end <<<<<<<<<<<<<<<<<<<<<<<<<< \n", __FUNCTION__); } void TestSearchFreeList(void) { HgfsHandle array[10 * NUM_SEARCHES]; HgfsSearch *search; unsigned int i; printf("%s: begin >>>>>>>>>>>>>>>>>>>>>>>>>>>\n", __FUNCTION__); for (i = 0; i < sizeof array / sizeof array[0]; i++) { char tempName[20]; Str_Sprintf(tempName, sizeof tempName, "baseDir%u", i); printf("\nadding search with baseDir: \"%s\"\n", tempName); search = HgfsAddNewSearch(Util_SafeStrdup(tempName)); array[i] = HgfsSearch2SearchHandle(search); } HgfsDumpAllSearches(); printf("done getting searches, now freeing\n"); for (i = 0; i < sizeof array / sizeof array[0]; i++) { printf("removing search #%u\n", i); HgfsRemoveSearch(&searchArray[array[i]]); } HgfsDumpAllSearches(); printf("%s: end <<<<<<<<<<<<<<<<<<<<<<<<<< \n", __FUNCTION__); } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerInt.h000066400000000000000000001163611321503522500261340ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef __HGFS_SERVER_INT_H__ # define __HGFS_SERVER_INT_H__ #include "vm_basic_types.h" struct DirectoryEntry; #ifndef _WIN32 typedef int fileDesc; #else # include typedef HANDLE fileDesc; #endif #include "dbllnklst.h" #include "hgfsProto.h" #include "cpName.h" // for HgfsNameStatus #include "hgfsServerPolicy.h" #include "hgfsUtil.h" // for HgfsInternalStatus #include "vm_atomic.h" #include "userlock.h" #include "hgfsServer.h" // for the server public types #ifndef VMX86_TOOLS #define LOGLEVEL_MODULE hgfsServer #include "loglevel_user.h" #else // VMX86_TOOLS #undef DOLOG #undef LOG /* * Map all LOG statements to a Debug or g_debug tools log. * Set the level to a default log level of 10 so that we will * capture everything if tools logging is set to debug. * * Note, for future work would be to go through the log * statements and set the levels correctly so that we can * map to info, error and warnings. */ #define LGLEVEL (10) #define LGPFX_FMT "%s:%s:" #define LGPFX "hgfsServer" #if defined VMTOOLS_USE_GLIB #define Debug g_debug #define Warning g_warning #define G_LOG_DOMAIN LGPFX #include "vmware/tools/utils.h" #include "vmware/tools/log.h" #else // VMTOOLS_USE_GLIB #include "debug.h" #endif // VMTOOLS_USE_GLIB #define DOLOG(_min) ((_min) <= LGLEVEL) #define LOG(_level, args) \ do { \ if (DOLOG(_level)) { \ Debug(LGPFX_FMT, LGPFX, __FUNCTION__); \ Debug args; \ } \ } while (0) #endif // VNMX86_TOOLS #define HGFS_DEBUG_ASYNC (0) typedef struct HgfsTransportSessionInfo HgfsTransportSessionInfo; /* Identifier for a local file */ typedef struct HgfsLocalId { uint64 volumeId; uint64 fileId; } HgfsLocalId; typedef enum { REQ_ASYNC, /* Hint that request should be processed Async. */ REQ_SYNC, /* " Sync. */ } RequestHint; /* Three possible filenode states */ typedef enum { FILENODE_STATE_UNUSED, /* Linked on the free list */ FILENODE_STATE_IN_USE_CACHED, /* Linked on the cached nodes list */ FILENODE_STATE_IN_USE_NOT_CACHED, /* Not linked on any list */ } FileNodeState; /* Three possible search types */ typedef enum { DIRECTORY_SEARCH_TYPE_DIR, /* Objects are files and subdirectories */ DIRECTORY_SEARCH_TYPE_BASE, /* Objects are shares */ DIRECTORY_SEARCH_TYPE_OTHER, /* Objects are the contents of "root/drive" or contents of "root" */ } DirectorySearchType; #define HGFS_SEARCH_LAST_ENTRY_INDEX ((uint32)~((uint32)0)) /* Two possible volume info type */ typedef enum { VOLUME_INFO_TYPE_MIN, VOLUME_INFO_TYPE_MAX, } VolumeInfoType; /* * The "default" share access is used in cross-platform code, so it's helpful * to have a single macro for accessing it. */ #ifdef _WIN32 # define HGFS_DEFAULT_SHARE_ACCESS (FILE_SHARE_READ | FILE_SHARE_WRITE | \ FILE_SHARE_DELETE) #else # define HGFS_DEFAULT_SHARE_ACCESS 0 #endif // _WIN32 typedef struct HgfsShareInfo { /* Filename of the root directory for the shared folder */ const char *rootDir; /* Length of the root directory filename (does not include nul terminator) */ size_t rootDirLen; /* Read permissions for the shared folder, needed for handle => name conversions. */ Bool readPermissions; /* Write permissions for the shared folder, needed for handle => name conversions. */ Bool writePermissions; /* * Shared folder handle used by change directory notification code to identify * shared folder. */ HgfsSharedFolderHandle handle; } HgfsShareInfo; /* * This struct represents a file on the local filesystem that has been * opened by a remote client. We store the name of the local file and * enough state to keep track of whether the file has changed locally * between remote accesses. None of the fields contain cross-platform * types; everything has been converted for the local filesystem. * * A file node object can only be in 1 of these 3 states: * 1) FILENODE_STATE_UNUSED: linked on the free list * 2) FILENODE_STATE_IN_USE_CACHED: Linked on the cached nodes list * 3) FILENODE_STATE_IN_USE_NOT_CACHED: Linked on neither of the above two lists. */ typedef struct HgfsFileNode { /* Links to place the object on various lists */ DblLnkLst_Links links; /* HGFS handle uniquely identifying this node. */ HgfsHandle handle; /* Local filename (in UTF8) */ char *utf8Name; /* Length of filename (does not include nul terminator) */ size_t utf8NameLen; /* share name */ char *shareName; /* Length of share name (does not include nul terminator) */ size_t shareNameLen; /* ID of file in local filesystem */ HgfsLocalId localId; /* File descriptor */ fileDesc fileDesc; /* On POSIX, access mode. On Windows, desired access */ uint32 mode; /* Share access to open with (Windows only) */ uint32 shareAccess; /* The server lock that the node currently has. */ HgfsLockType serverLock; /* File node state on lists */ FileNodeState state; /* File flags - see below. */ uint32 flags; /* * Context as required by some file operations. Eg: BackupWrite on * Windows: BackupWrite requires the caller to hold on to a pointer * to a Windows internal data structure between subsequent calls to * BackupWrite while restoring a file. */ void *fileCtx; /* Parameters associated with the share. */ HgfsShareInfo shareInfo; } HgfsFileNode; /* HgfsFileNode flags. */ /* TRUE if opened in append mode */ #define HGFS_FILE_NODE_APPEND_FL (1 << 0) /* Whether this file was opened in sequential mode. */ #define HGFS_FILE_NODE_SEQUENTIAL_FL (1 << 1) /* Whether this a shared folder open. */ #define HGFS_FILE_NODE_SHARED_FOLDER_OPEN_FL (1 << 2) /* * This struct represents a file search that a client initiated. * * A search object can only be in 1 of these 2 states: * 1) Unused: linked on the free list * 2) In use: unlinked */ typedef struct HgfsSearch { /* Links to place the object on various lists */ DblLnkLst_Links links; /* Flags to track state and information: see below. */ uint32 flags; /* HGFS handle uniquely identifying this search. */ HgfsHandle handle; /* Local directory name (in UTF8) */ char *utf8Dir; /* Length of directory name (does not include nul terminator) */ size_t utf8DirLen; /* Share name. */ char *utf8ShareName; /* Share name length. */ size_t utf8ShareNameLen; /* Directory entries for this search */ struct DirectoryEntry **dents; /* Number of dents */ uint32 numDents; /* * What type of search is this (what objects does it track)? This is * important to know so we can do the right kind of stat operation later * when we want to retrieve the attributes for each dent. */ DirectorySearchType type; /* Parameters associated with the share. */ HgfsShareInfo shareInfo; } HgfsSearch; /* HgfsSearch flags. */ /* TRUE if opened in append mode */ #define HGFS_SEARCH_FLAG_READ_ALL_ENTRIES (1 << 0) /* HgfsSessionInfo flags. */ typedef enum { HGFS_SESSION_TYPE_REGULAR, /* Dynamic session, created by the HgfsTransport. */ HGFS_SESSION_TYPE_INTERNAL, /* This is a static session. */ } HgfsSessionInfoType; /* HgfsSessionState, used for session status. */ typedef enum { HGFS_SESSION_STATE_OPEN, HGFS_SESSION_STATE_CLOSED, } HgfsSessionInfoState; typedef struct HgfsAsyncRequestInfo { /* Asynchronous request handling. */ Atomic_uint32 requestCount; MXUserExclLock *lock; MXUserCondVar *requestCountIsZero; } HgfsAsyncRequestInfo; typedef struct HgfsSessionInfo { DblLnkLst_Links links; Bool isInactive; /* The sessions state and capabilities. */ HgfsSessionFlags flags; /* Unique session id. */ uint64 sessionId; /* Max packet size that is supported by both client and server. */ uint32 maxPacketSize; /* Transport session context. */ HgfsTransportSessionInfo *transportSession; /* Current state of the session. */ HgfsSessionInfoState state; /* Lock to ensure some fileIO requests are atomic for a handle. */ MXUserExclLock *fileIOLock; int numInvalidationAttempts; Atomic_uint32 refCount; /* Reference count for session. */ /* ** START NODE ARRAY ************************************************** * * Lock for the following 6 fields: the node array, * counters and lists for this session. */ MXUserExclLock *nodeArrayLock; /* Open file nodes of this session. */ HgfsFileNode *nodeArray; /* Number of nodes in the nodeArray. */ uint32 numNodes; /* Free list of file nodes. LIFO to be cache-friendly. */ DblLnkLst_Links nodeFreeList; /* List of cached open nodes. */ DblLnkLst_Links nodeCachedList; /* Current number of open nodes. */ unsigned int numCachedOpenNodes; /* Number of open nodes having server locks. */ unsigned int numCachedLockedNodes; /** END NODE ARRAY ****************************************************/ /* ** START SEARCH ARRAY ************************************************ * * Lock for the following three fields: for the search array * and it's counter and list, for this session. */ MXUserExclLock *searchArrayLock; /* Directory entry cache for this session. */ HgfsSearch *searchArray; /* Number of entries in searchArray. */ uint32 numSearches; /* Free list of searches. LIFO. */ DblLnkLst_Links searchFreeList; /** END SEARCH ARRAY ****************************************************/ /* Array of session specific capabiities. */ HgfsCapability hgfsSessionCapabilities[HGFS_OP_MAX]; uint32 numberOfCapabilities; /* Asynchronous request handling. */ HgfsAsyncRequestInfo asyncRequestsInfo; } HgfsSessionInfo; /* * This represents the maximum number of HGFS sessions that can be * created in a HGFS transport session. We picked a random value * for this variable. There is no specific reason behind picking * this value. */ #define MAX_SESSION_COUNT 1024 /* * This represents the maximum number attempts made by the HGFS * invalidator before completely destroying the HGFS session. We * picked a random value and there is no specific reason behind * the value 4 for thie variable. */ #define MAX_SESSION_INVALIDATION_ATTEMPTS 4 /* * These structs represent information about file open requests, file * attributes, and directory creation requests. * * The main reason for these structs is data abstraction -- we pass * a struct around instead of the individual parameters. This way * as more parameters are implemented, we don't have to add more * parameters to the functions, instead just extend the structs. */ typedef struct HgfsFileOpenInfo { HgfsOp requestType; HgfsHandle file; /* Opaque file ID used by the server */ HgfsOpenValid mask; /* Bitmask that specified which fields are valid. */ HgfsOpenMode mode; /* Which type of access requested. See desiredAccess */ HgfsOpenFlags flags; /* Which flags to open the file with */ HgfsPermissions specialPerms; /* Desired 'special' permissions for file creation */ HgfsPermissions ownerPerms; /* Desired 'owner' permissions for file creation */ HgfsPermissions groupPerms; /* Desired 'group' permissions for file creation */ HgfsPermissions otherPerms; /* Desired 'other' permissions for file creation */ HgfsAttrFlags attr; /* Attributes, if any, for file creation */ uint64 allocationSize; /* How much space to pre-allocate during creation */ uint32 desiredAccess; /* Extended support for windows access modes */ uint32 shareAccess; /* Windows only, share access modes */ HgfsLockType desiredLock; /* The type of lock desired by the client */ HgfsLockType acquiredLock; /* The type of lock acquired by the server */ uint32 cpNameSize; const char *cpName; char *utf8Name; uint32 caseFlags; /* Case-sensitivity flags. */ HgfsShareInfo shareInfo; /* Parameters associated with the share. */ } HgfsFileOpenInfo; typedef struct HgfsFileAttrInfo { HgfsOp requestType; HgfsAttrValid mask; HgfsFileType type; /* File type */ uint64 size; /* File size (in bytes) */ uint64 creationTime; /* Creation time. Ignored by POSIX */ uint64 accessTime; /* Time of last access */ uint64 writeTime; /* Time of last write */ uint64 attrChangeTime; /* Time file attributes were last * changed. Ignored by Windows */ HgfsPermissions specialPerms; /* Special permissions bits. Ignored by Windows */ HgfsPermissions ownerPerms; /* Owner permissions bits */ HgfsPermissions groupPerms; /* Group permissions bits. Ignored by Windows */ HgfsPermissions otherPerms; /* Other permissions bits. Ignored by Windows */ HgfsAttrFlags flags; /* Various flags and Windows 'attributes' */ uint64 allocationSize; /* Actual size of file on disk */ uint32 userId; /* User identifier, ignored by Windows */ uint32 groupId; /* group identifier, ignored by Windows */ uint64 hostFileId; /* File Id of the file on host: inode_t on Linux */ uint32 volumeId; /* Volume Id of the volune on which the file resides */ uint32 effectivePerms; /* Permissions in effect for the current user */ uint32 eaSize; /* Extended attribute data size */ uint32 reparseTag; /* Windows reparse point tag, valid by attr flag */ HgfsShortFileName shortName; /* Windows DOS 8 dot 3 name for long names */ } HgfsFileAttrInfo; typedef struct HgfsSearchReadEntry { HgfsSearchReadMask mask; /* Info returned mask */ HgfsFileAttrInfo attr; /* Attributes of entry */ uint32 fileIndex; /* Entry directory index */ char *name; /* Name */ uint32 nameLength; /* Name byte length */ } HgfsSearchReadEntry; typedef struct HgfsSearchReadInfo { HgfsOp requestType; /* HGFS request version */ HgfsSearchReadMask requestedMask; /* Entry info requested mask */ HgfsSearchReadFlags flags; /* Request specific flags */ HgfsSearchReadFlags replyFlags; /* Reply specific flags */ char *searchPattern; /* Search pattern to match entries with */ uint32 searchPatternLength; /* Byte length of search pattern */ uint32 startIndex; /* Starting index for entries */ uint32 currentIndex; /* Current index for entries */ uint32 numberRecordsWritten; /* Number of entries written */ void *reply; /* Fixed part of search read reply */ void *replyPayload; /* Variable part (dirent records) of reply */ size_t payloadSize; /* Remaining bytes in reply payload. */ } HgfsSearchReadInfo; typedef struct HgfsCreateDirInfo { HgfsOp requestType; HgfsCreateDirValid mask; HgfsPermissions specialPerms; /* Special permissions bits. Ignored by Windows */ HgfsPermissions ownerPerms; /* Owner permissions bits */ HgfsPermissions groupPerms; /* Group permissions bits. Ignored by Windows */ HgfsPermissions otherPerms; /* Other permissions bits. Ignored by Windows */ uint32 cpNameSize; const char *cpName; uint32 caseFlags; /* Case-sensitivity flags. */ HgfsAttrFlags fileAttr; /* Various flags and Windows 'attributes' */ } HgfsCreateDirInfo; typedef struct HgfsCreateSessionInfo { uint32 maxPacketSize; HgfsSessionFlags flags; /* Session capability flags. */ } HgfsCreateSessionInfo; Bool HgfsCreateAndCacheFileNode(HgfsFileOpenInfo *openInfo, // IN: Open info struct HgfsLocalId const *localId, // IN: Local unique file ID fileDesc fileDesc, // IN: OS file handle Bool append, // IN: Open with append flag HgfsSessionInfo *session); // IN: Session info Bool HgfsSearchHandle2FileName(HgfsHandle handle, // IN: Hgfs search handle char **fileName, // OUT: cp file name uint32 *fileNameSize); // OUT: cp file name size void HgfsUpdateNodeNames(const char *oldLocalName, // IN: Name of file to look for const char *newLocalName, // IN: Name to replace with HgfsSessionInfo *session); // IN: Session info Bool HgfsRemoveSearch(HgfsHandle searchHandle, HgfsSessionInfo *session); #ifdef VMX86_LOG #define HGFS_SERVER_DIR_DUMP_DENTS(_searchHandle, _session) do { \ if (DOLOG(4)) { \ HgfsServerDirDumpDents(_searchHandle, _session); \ } \ } while (0) void HgfsServerDirDumpDents(HgfsHandle searchHandle, // IN: Handle to dump dents from HgfsSessionInfo *session); // IN: Session info #else #define HGFS_SERVER_DIR_DUMP_DENTS(_searchHandle, _session) do {} while (0) #endif struct DirectoryEntry * HgfsGetSearchResult(HgfsHandle handle, // IN: Handle to search HgfsSessionInfo *session, // IN: Session info uint32 offset, // IN: Offset to retrieve at Bool remove); // IN: If true, removes the result Bool HgfsServerStatFs(const char *pathName, // IN: Path we're interested in size_t pathLength, // IN: Length of path uint64 *freeBytes, // OUT: Free bytes on volume uint64 *totalBytes); // OUT: Total bytes on volume HgfsNameStatus HgfsServerGetAccess(char *in, // IN: CP filename to check size_t inSize, // IN: Size of name in HgfsOpenMode mode, // IN: Requested access mode uint32 caseFlags, // IN: Case-sensitivity flags char **bufOut, // OUT: File name in local fs size_t *outLen); // OUT: Length of name out Bool HgfsServerIsSharedFolderOnly(char const *in, // IN: CP filename to check size_t inSize); // IN: Size of name in void * HgfsServerResEnumInit(void); Bool HgfsServerResEnumGet(void *enumState, char const **enumResName, size_t *enumResNameLen, Bool *enumResDone); Bool HgfsServerResEnumExit(void *enumState); HgfsInternalStatus HgfsServerGetDirEntry(HgfsHandle handle, // IN: Handle to search HgfsSessionInfo *session, // IN: Session info uint32 index, // IN: index to retrieve at Bool remove, // IN: If true, removes the result struct DirectoryEntry **dirEntry);// OUT: directory entry HgfsInternalStatus HgfsServerSearchRealDir(char const *baseDir, // IN: Directory to search size_t baseDirLen, // IN: Length of directory char const *shareName, // IN: Share name char const *rootDir, // IN: Root directory for the share HgfsSessionInfo *session, // IN: Session info HgfsHandle *handle); // OUT: Search handle HgfsInternalStatus HgfsServerSearchVirtualDir(HgfsServerResEnumGetFunc getName, // IN: Name enumerator HgfsServerResEnumInitFunc initName, // IN: Init function HgfsServerResEnumExitFunc cleanupName, // IN: Cleanup function DirectorySearchType type, // IN: Kind of search HgfsSessionInfo *session, // IN: Session info HgfsHandle *handle); // OUT: Search handle HgfsInternalStatus HgfsServerRestartSearchVirtualDir(HgfsServerResEnumGetFunc getName, // IN: Name enumerator HgfsServerResEnumInitFunc initName, // IN: Init function HgfsServerResEnumExitFunc cleanupName, // IN: Cleanup function HgfsSessionInfo *session, // IN: Session info HgfsHandle searchHandle); // IN: search to restart void * HgfsAllocInitReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: incoming packet header size_t replyDataSize, // IN: payload size HgfsSessionInfo *session); // IN: Session Info /* Node cache functions. */ Bool HgfsRemoveFromCache(HgfsHandle handle, // IN: Hgfs handle of the node HgfsSessionInfo *session); // IN: Session info Bool HgfsAddToCache(HgfsHandle handle, // IN: Hgfs handle of the node HgfsSessionInfo *session); // IN: Session info Bool HgfsIsCached(HgfsHandle handle, // IN: Hgfs handle of the node HgfsSessionInfo *session); // IN: Session info Bool HgfsIsServerLockAllowed(HgfsSessionInfo *session); // IN: session info Bool HgfsHandle2FileDesc(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info fileDesc *fd, // OUT: OS handle (file descriptor) void **fileCtx); // OUT: OS file context Bool HgfsFileDesc2Handle(fileDesc fd, // IN: OS handle (file descriptor) HgfsSessionInfo *session, // IN: session info HgfsHandle *handle); // OUT: Hgfs file handle Bool HgfsHandle2ShareMode(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info HgfsOpenMode *shareMode); // OUT: UTF8 file name size Bool HgfsHandle2FileName(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info char **fileName, // OUT: CP file name size_t *fileNameSize); // OUT: CP file name size Bool HgfsHandle2FileNameMode(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session,// IN: Session info Bool *readPermissions, // OUT: shared folder permissions Bool *writePermissions, // OUT: shared folder permissions char **fileName, // OUT: UTF8 file name size_t *fileNameSize); // OUT: UTF8 file name size Bool HgfsHandle2AppendFlag(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info Bool *appendFlag); // OUT: Append flag Bool HgfsHandle2LocalId(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info HgfsLocalId *localId); // OUT: Local id info Bool HgfsUpdateNodeFileDesc(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info fileDesc fd, // IN: OS handle (file desc void *fileCtx); // IN: OS file context Bool HgfsUpdateNodeServerLock(fileDesc fd, // IN: OS handle HgfsSessionInfo *session, // IN: session info HgfsLockType serverLock); // IN: new oplock Bool HgfsUpdateNodeAppendFlag(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info Bool appendFlag); // OUT: Append flag Bool HgfsGetNodeCopy(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info Bool copyName, // IN: Should we copy the name? HgfsFileNode *copy); // IN/OUT: Copy of the node Bool HgfsHandleIsSequentialOpen(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info Bool *sequentialOpen); // OUT: If open was sequential Bool HgfsHandleIsSharedFolderOpen(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: session info Bool *sharedFolderOpen); // OUT: If shared folder Bool HgfsGetSearchCopy(HgfsHandle handle, // IN: Hgfs search handle HgfsSessionInfo *session, // IN: Session info HgfsSearch *copy); // IN/OUT: Copy of the search Bool HgfsServerGetOpenMode(HgfsFileOpenInfo *openInfo, // IN: Open info to examine uint32 *modeOut); // OUT: Local mode char* HgfsServerGetTargetRelativePath(const char* source, // IN: source file name const char* target); // IN: target file name Bool HgfsServerCheckOpenFlagsForShare(HgfsFileOpenInfo *openInfo, // IN: Hgfs file handle HgfsOpenFlags *flags); // IN/OUT: open mode /* Platform specific exports. */ Bool HgfsPlatformInit(void); void HgfsPlatformDestroy(void); HgfsInternalStatus HgfsPlatformCloseFile(fileDesc fileDesc, // IN: OS handle of the file void *fileCtx); // IN: file context Bool HgfsPlatformDoFilenameLookup(void); HgfsNameStatus HgfsPlatformFilenameLookup(const char *sharePath, // IN: share path in question size_t sharePathLength, // IN char *fileName, // IN: filename to be looked up size_t fileNameLength, // IN uint32 caseFlags, // IN: case-sensitivity flags char **convertedFileName, // OUT: case-converted filename size_t *convertedFileNameLength); // OUT HgfsInternalStatus HgfsPlatformConvertFromNameStatus(HgfsNameStatus status); // IN: name status HgfsNameStatus HgfsPlatformPathHasSymlink(const char *fileName, // IN: fileName to be checked size_t fileNameLength, // IN const char *sharePath, // IN: share path in question size_t sharePathLen); // IN HgfsInternalStatus HgfsPlatformSymlinkCreate(char *localSymlinkName, // IN: symbolic link file name char *localTargetName); // IN: symlink target name HgfsInternalStatus HgfsPlatformGetattrFromName(char *fileName, // IN: file name HgfsShareOptions configOptions, // IN: configuration options char *shareName, // IN: share name HgfsFileAttrInfo *attr, // OUT: file attributes char **targetName); // OUT: Symlink target HgfsInternalStatus HgfsPlatformGetDirEntry(HgfsSearch *search, // IN: search HgfsSessionInfo *session, // IN: Session info uint32 offset, // IN: Offset to retrieve at Bool remove, // IN: If true, removes the result struct DirectoryEntry **dirEntry); // OUT: dirent HgfsInternalStatus HgfsPlatformSetDirEntry(HgfsSearch *search, // IN: search HgfsShareOptions configOptions, // IN: share configuration settings HgfsSessionInfo *session, // IN: session info struct DirectoryEntry *dirEntry, // IN: the indexed dirent Bool getAttr, // IN: get the entry attributes HgfsFileAttrInfo *entryAttr, // OUT: entry attributes, optional char **entryName, // OUT: entry name uint32 *entryNameLength); // OUT: entry name length HgfsInternalStatus HgfsPlatformScandir(char const *baseDir, // IN: Directory to search in size_t baseDirLen, // IN: Length of directory Bool followSymlinks, // IN: followSymlinks config option struct DirectoryEntry ***dents, // OUT: Array of DirectoryEntrys int *numDents); // OUT: Number of DirectoryEntrys HgfsInternalStatus HgfsPlatformScanvdir(HgfsServerResEnumGetFunc enumNamesGet, // IN: Function to get name HgfsServerResEnumInitFunc enumNamesInit, // IN: Setup function HgfsServerResEnumExitFunc enumNamesExit, // IN: Cleanup function DirectorySearchType type, // IN: Kind of search struct DirectoryEntry ***dents, // OUT: Array of DirectoryEntrys uint32 *numDents); // OUT: total number of directory entrys HgfsInternalStatus HgfsPlatformSearchDir(HgfsNameStatus nameStatus, // IN: name status const char *dirName, // IN: relative directory name size_t dirNameLength, // IN: length of dirName uint32 caseFlags, // IN: case flags HgfsShareInfo *shareInfo, // IN: sharfed folder information char *baseDir, // IN: name of the shared directory uint32 baseDirLen, // IN: length of the baseDir HgfsSessionInfo *session, // IN: session info HgfsHandle *handle); // OUT: search handle HgfsInternalStatus HgfsPlatformRestartSearchDir(HgfsHandle handle, // IN: search handle HgfsSessionInfo *session, // IN: session info DirectorySearchType searchType); // IN: Kind of search #ifdef VMX86_LOG void HgfsPlatformDirDumpDents(HgfsSearch *search); // IN: search #endif HgfsInternalStatus HgfsPlatformReadFile(fileDesc readFile, // IN: file descriptor HgfsSessionInfo *session, // IN: session info uint64 offset, // IN: file offset to read from uint32 requiredSize, // IN: length of data to read void* payload, // OUT: buffer for the read data uint32 *actualSize); // OUT: actual length read HgfsInternalStatus HgfsPlatformWriteFile(fileDesc writeFile, // IN: file descriptor HgfsSessionInfo *session, // IN: session info uint64 writeOffset, // IN: file offset to write to uint32 writeDataSize, // IN: length of data to write HgfsWriteFlags writeFlags, // IN: write flags Bool writeSequential, // IN: write is sequential Bool writeAppend, // IN: write is appended const void *writeData, // IN: data to be written uint32 *writtenSize); // OUT: byte length written HgfsInternalStatus HgfsPlatformWriteWin32Stream(HgfsHandle file, // IN: packet header char *dataToWrite, // IN: data to write size_t requiredSize, // IN: data size Bool doSecurity, // IN: write ACL uint32 *actualSize, // OUT: written data size HgfsSessionInfo *session); // IN: session info HgfsInternalStatus HgfsPlatformVDirStatsFs(HgfsSessionInfo *session, // IN: session info HgfsNameStatus nameStatus, // IN: VolumeInfoType infoType, // IN: uint64 *outFreeBytes, // OUT: uint64 *outTotalBytes); // OUT: HgfsInternalStatus HgfsPlatformGetFd(HgfsHandle hgfsHandle, // IN: HGFS file handle HgfsSessionInfo *session, // IN: Session info Bool append, // IN: Open with append flag fileDesc *fd); // OUT: Opened file descriptor HgfsInternalStatus HgfsPlatformFileExists(char *utf8LocalName); // IN: Full file path utf8 encoding /* * NOTE. * This function requires valid localSrcName and localTargetName even when * srcFile and targetFile are specified. * Depending on some various conditions it may fall back on using file names * instead of file handles. */ HgfsInternalStatus HgfsPlatformRename(char *localSrcName, // IN: local path to source file fileDesc srcFile, // IN: source file handle char *localTargetName, // IN: local path to target file fileDesc targetFile, // IN: target file handle HgfsRenameHint hints); // IN: rename hints HgfsInternalStatus HgfsPlatformCreateDir(HgfsCreateDirInfo *info, // IN: direcotry properties char *utf8Name); // IN: full path for the new directory HgfsInternalStatus HgfsPlatformDeleteFileByHandle(HgfsHandle file, // IN: file being deleted HgfsSessionInfo *session); // IN: session info HgfsInternalStatus HgfsPlatformDeleteFileByName(char const *utf8Name); // IN: full file path in utf8 encoding HgfsInternalStatus HgfsPlatformDeleteDirByHandle(HgfsHandle dir, // IN: directory being deleted HgfsSessionInfo *session); // IN: session info HgfsInternalStatus HgfsPlatformDeleteDirByName(char const *utf8Name); // IN: full file path in utf8 encoding HgfsInternalStatus HgfsPlatformHandleIncompleteName(HgfsNameStatus nameStatus, // IN: name status HgfsFileAttrInfo *attr); // OUT: attributes void HgfsPlatformGetDefaultDirAttrs(HgfsFileAttrInfo *attr); // OUT: attributes HgfsInternalStatus HgfsPlatformGetattrFromFd(fileDesc fileDesc, // IN: file descriptor to query HgfsSessionInfo *session, // IN: session info HgfsFileAttrInfo *attr); // OUT: file attributes HgfsInternalStatus HgfsPlatformSetattrFromFd(HgfsHandle file, // IN: file descriptor HgfsSessionInfo *session, // IN: session info HgfsFileAttrInfo *attr, // IN: attrs to set HgfsAttrHint hints, // IN: attr hints Bool useHostTime); // IN: use current host time HgfsInternalStatus HgfsPlatformSetattrFromName(char *utf8Name, // IN: local file path HgfsFileAttrInfo *attr, // IN: attrs to set HgfsShareOptions configOptions, // IN: share options HgfsAttrHint hints, // IN: attr hints Bool useHostTime); // IN: use current host time HgfsInternalStatus HgfsPlatformValidateOpen(HgfsFileOpenInfo *openInfo, // IN: Open info struct Bool followLinks, // IN: follow symlinks on the host HgfsSessionInfo *session, // IN: Session info HgfsLocalId *localId, // OUT: Local unique file ID fileDesc *newHandle); // OUT: Handle to the file void * HSPU_GetMetaPacket(HgfsPacket *packet, // IN/OUT: Hgfs Packet size_t *metaPacketSize, // OUT: Size of metaPacket HgfsServerChannelCallbacks *chanCb); // IN: Channel callbacks Bool HSPU_ValidateDataPacketSize(HgfsPacket *packet, // IN: Hgfs Packet size_t dataSize); // IN: data size void * HSPU_GetDataPacketBuf(HgfsPacket *packet, // IN/OUT: Hgfs Packet MappingType mappingType, // IN: Readable/ Writeable ? HgfsServerChannelCallbacks *chanCb); // IN: Channel callbacks void HSPU_SetDataPacketSize(HgfsPacket *packet, // IN/OUT: Hgfs Packet size_t dataSize); // IN: data size void HSPU_PutDataPacketBuf(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsServerChannelCallbacks *chanCb); // IN: Channel callbacks void HSPU_PutMetaPacket(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsServerChannelCallbacks *chanCb); // IN: Channel callbacks Bool HSPU_ValidateRequestPacketSize(HgfsPacket *packet, // IN: Hgfs Packet size_t requestHeaderSize, // IN: request header size size_t requestOpSize, // IN: request packet size size_t requestOpDataSize); // IN: request packet data size Bool HSPU_ValidateReplyPacketSize(HgfsPacket *packet, // IN: Hgfs Packet size_t replyHeaderSize, // IN: reply header size size_t replyResultSize, // IN: reply result size size_t replyResultDataSize, // IN: reply result data size Bool useMappedMetaPacket); // IN: using meta buffer void * HSPU_GetReplyPacket(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsServerChannelCallbacks *chanCb, // IN: Channel callbacks size_t replyDataSize, // IN: Size of reply data size_t *replyPacketSize); // OUT: Size of reply Packet void HSPU_PutReplyPacket(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsServerChannelCallbacks *chanCb); // IN: Channel callbacks #endif /* __HGFS_SERVER_INT_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerLinux.c000066400000000000000000005102661321503522500264760ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerLinux.c -- * * This file contains the linux implementation of the server half * of the Host/Guest File System (hgfs), a.k.a. "Shared Folder". * * The hgfs server carries out filesystem requests that it receives * over the backdoor from a driver in the other world. */ #define _GNU_SOURCE // for O_NOFOLLOW #if defined(__APPLE__) #define _DARWIN_USE_64_BIT_INODE #endif #include #include #include #include #include #include #include // for utimes(2) #include #include #include #include #include // for getrlimit #if defined(__FreeBSD__) # include #else # include # include #endif #include "vmware.h" #include "hgfsServerPolicy.h" // for security policy #include "hgfsServerInt.h" #include "hgfsServerOplock.h" #include "hgfsEscape.h" #include "err.h" #include "str.h" #include "cpNameLite.h" #include "hgfsUtil.h" // for cross-platform time conversion #include "posix.h" #include "file.h" #include "util.h" #include "su.h" #include "codeset.h" #include "unicodeOperations.h" #include "userlock.h" #if defined(__linux__) && !defined(SYS_getdents64) /* For DT_UNKNOWN */ # include #endif #ifndef VMX86_TOOLS # include "config.h" #endif #if defined(__APPLE__) #include // for the alias manager #include // for CFString and CFURL #include // for getattrlist #include // for VERG / VDIR #endif #ifdef linux typedef struct DirectoryEntry { uint64 d_ino; uint64 d_off; uint16 d_reclen; uint8 d_type; char d_name[256]; } DirectoryEntry; #else #include typedef struct DirectoryEntry { uint64 d_ino; uint16 d_reclen; uint16 d_namlen; uint8 d_type; char d_name[1024]; } DirectoryEntry; #endif /* * ALLPERMS (mode 07777) and ACCESSPERMS (mode 0777) are not defined in the * Solaris version of . */ #ifdef sun # define ACCESSPERMS (S_IRWXU|S_IRWXG|S_IRWXO) # define ALLPERMS (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO) #endif /* * On Linux, we must wrap getdents64, as glibc does not wrap it for us. We use getdents64 * (rather than getdents) because with the latter, we'll get 64-bit offsets and inode * numbers. Note that getdents64 isn't supported everywhere, in particular, kernels older * than 2.4.1 do not implement it. On those older guests, we try using getdents(), and * translating the results to our DirectoryEntry structure... * * On FreeBSD and Mac platforms, getdents is implemented as getdirentries, and takes an * additional parameter which returns the position of the block read, which we don't care * about. */ #if defined(__linux__) static INLINE int getdents_linux(unsigned int fd, DirectoryEntry *dirp, unsigned int count) { # if defined(SYS_getdents64) return syscall(SYS_getdents64, fd, dirp, count); # else /* * Fall back to regular getdents on older Linux systems that don't have * getdents64. Because glibc does translation between the kernel's "struct dirent" and * the libc "struct dirent", this structure matches the one in linux/dirent.h, rather * than us using the libc 'struct dirent' directly */ struct linux_dirent { long d_ino; long d_off; /* __kernel_off_t expands to long on RHL 6.2 */ unsigned short d_reclen; char d_name[NAME_MAX]; } *dirp_temp; int retval; dirp_temp = alloca((sizeof *dirp_temp) * count); retval = syscall(SYS_getdents, fd, dirp_temp, count); if (retval > 0) { int i; /* * Translate from the Linux 'struct dirent' to the hgfs DirectoryEntry, since * they're not always the same layout. */ for (i = 0; i < count; i++) { dirp[i].d_ino = dirp_temp[i].d_ino; dirp[i].d_off = dirp_temp[i].d_off; dirp[i].d_reclen = dirp_temp[i].d_reclen; dirp[i].d_type = DT_UNKNOWN; memset(dirp[i].d_name, 0, sizeof dirp->d_name); memcpy(dirp[i].d_name, dirp_temp[i].d_name, ((sizeof dirp->d_name) < (sizeof dirp_temp->d_name)) ? (sizeof dirp->d_name) : (sizeof dirp_temp->d_name)); } } return retval; # endif } # define getdents getdents_linux #elif defined(__FreeBSD__) #if defined(__INO64) typedef off_t BASEPTYPE; #else typedef long BASEPTYPE; #endif #define getdents_freebsd(fd, dirp, count) \ ({ \ BASEPTYPE basep; \ getdirentries(fd, dirp, count, &basep); \ }) # define getdents getdents_freebsd #elif defined(__APPLE__) static INLINE int getdents_apple(DIR *fd, // IN DirectoryEntry *dirp, // OUT unsigned int count) // IN: ignored { int res = 0; struct dirent *dirEntry; dirEntry = readdir(fd); if (NULL != dirEntry) { /* * Assert that the hgfs DirectoryEntry version and system dirent * name fields are of the same size. Since that is where it was taken from. */ ASSERT_ON_COMPILE(sizeof dirp->d_name == sizeof dirEntry->d_name); dirp->d_ino = dirEntry->d_ino; dirp->d_type = dirEntry->d_type; dirp->d_namlen = dirEntry->d_namlen; memcpy(dirp->d_name, dirEntry->d_name, dirEntry->d_namlen + 1); dirp->d_reclen = offsetof(DirectoryEntry, d_name) + dirp->d_namlen + 1; res = dirp->d_reclen; } return res; } # define getdents getdents_apple #endif /* * O_DIRECTORY is only relevant on Linux. For other platforms, we'll hope that * the kernel is smart enough to deny getdents(2) (or getdirentries(2)) on * files which aren't directories. * * Likewise, O_NOFOLLOW doesn't exist on Solaris 9. Oh well. */ #ifndef O_DIRECTORY #define O_DIRECTORY 0 #endif #ifndef O_NOFOLLOW #define O_NOFOLLOW 0 #endif #if defined(sun) || defined(__linux__) || \ (defined(__FreeBSD_version) && __FreeBSD_version < 490000) /* * Implements futimes(), which was introduced in glibc 2.3.3. FreeBSD 3.2 * doesn't have it, but 4.9 does. Unfortunately, these early FreeBSD versions * don't have /proc/self, so futimes() will simply fail. For now the only * caller to futimes() is HgfsServerSetattr which doesn't get invoked at all * in the HGFS server which runs in the Tools, so it's OK. */ #define PROC_SELF_FD "/proc/self/fd/" #define STRLEN_OF_MAXINT_AS_STRING 10 int futimes(int fd, const struct timeval times[2]) { #ifndef sun /* * Hack to allow the timevals in futimes() to be const even when utimes() * expects non-const timevals. This is the case on glibc up to 2.3 or * thereabouts. */ struct timeval mytimes[2]; /* Maximum size of "/proc/self/fd/" as a string. Accounts for nul. */ char nameBuffer[sizeof PROC_SELF_FD + STRLEN_OF_MAXINT_AS_STRING]; mytimes[0] = times[0]; mytimes[1] = times[1]; if (snprintf(nameBuffer, sizeof nameBuffer, PROC_SELF_FD "%d", fd) < 0) { return -1; } return Posix_Utimes(nameBuffer, mytimes); #else /* !sun */ return futimesat(fd, NULL, times); #endif /* !sun */ } #undef PROC_SELF_FD #undef STRLEN_OF_MAXINT_AS_STRING #endif #if defined(__APPLE__) struct FInfoAttrBuf { uint32 length; fsobj_type_t objType; char finderInfo[32]; }; #endif /* * Taken from WinNT.h. * For verifying the Windows client which can ask for delete access as well as the * standard read, write, execute permissions. * XXX - should probably be moved into a header file and may need to be expanded if * Posix looks at the access mode more thoroughly or we expand the set of cross-platform * access mode flags. */ #define DELETE (0x00010000L) /* * Server open flags, indexed by HgfsOpenFlags. Stolen from * lib/fileIOPosix.c * * Using O_NOFOLLOW will allow us to forgo a (racy) symlink check just * before opening the file. * * Using O_NONBLOCK will prevent us from blocking the HGFS server if * we open a FIFO. */ static const int HgfsServerOpenFlags[] = { O_NONBLOCK | O_NOFOLLOW, O_NONBLOCK | O_NOFOLLOW | O_TRUNC, O_NONBLOCK | O_NOFOLLOW | O_CREAT, O_NONBLOCK | O_NOFOLLOW | O_CREAT | O_EXCL, O_NONBLOCK | O_NOFOLLOW | O_CREAT | O_TRUNC, }; /* * Server open mode, indexed by HgfsOpenMode. */ static const int HgfsServerOpenMode[] = { O_RDONLY, O_WRONLY, O_RDWR, }; /* Local functions. */ static HgfsInternalStatus HgfsGetattrResolveAlias(char const *fileName, char **targetName); static void HgfsStatToFileAttr(struct stat *stats, uint64 *creationTime, HgfsFileAttrInfo *attr); static int HgfsStat(const char* fileName, Bool followLink, struct stat *stats, uint64 *creationTime); static int HgfsFStat(int fd, struct stat *stats, uint64 *creationTime); static void HgfsGetSequentialOnlyFlagFromName(const char *fileName, Bool followSymlinks, HgfsFileAttrInfo *attr); static void HgfsGetSequentialOnlyFlagFromFd(int fd, HgfsFileAttrInfo *attr); static int HgfsConvertComponentCase(char *currentComponent, const char *dirPath, const char **convertedComponent, size_t *convertedComponentSize); static int HgfsConstructConvertedPath(char **path, size_t *pathSize, char *convertedPath, size_t convertedPathSize); static int HgfsCaseInsensitiveLookup(const char *sharePath, size_t sharePathLength, char *fileName, size_t fileNameLength, char **convertedFileName, size_t *convertedFileNameLength); static Bool HgfsSetattrMode(struct stat *statBuf, HgfsFileAttrInfo *attr, mode_t *newPermissions); static Bool HgfsSetattrOwnership(HgfsFileAttrInfo *attr, uid_t *newUid, gid_t *newGid); static HgfsInternalStatus HgfsSetattrTimes(struct stat *statBuf, HgfsFileAttrInfo *attr, HgfsAttrHint hints, Bool useHostTime, struct timeval *accessTime, struct timeval *modTime, Bool *timesChanged); static HgfsInternalStatus HgfsGetHiddenXAttr(char const *fileName, Bool *attribute); static HgfsInternalStatus HgfsSetHiddenXAttr(char const *fileName, Bool value, mode_t permissions); static HgfsInternalStatus HgfsEffectivePermissions(char *fileName, Bool readOnlyShare, uint32 *permissions); static uint64 HgfsGetCreationTime(const struct stat *stats); #if !defined(sun) static HgfsInternalStatus HgfsWriteCheckIORange(off_t offset, uint32 bytesToWrite); #endif /* *----------------------------------------------------------------------------- * * HgfsPlatformConvertFromNameStatus -- * * This function converts between a status code used in processing a cross * platform filename, and a platform-specific status code. * * Because the two status codes never go down the wire, there is no danger * of backwards compatibility here, and we should ASSERT if we encounter * an status code that we're not familiar with. * * Results: * Converted status code. * * Side effects: * None. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformConvertFromNameStatus(HgfsNameStatus status) // IN { switch(status) { case HGFS_NAME_STATUS_COMPLETE: return 0; case HGFS_NAME_STATUS_FAILURE: case HGFS_NAME_STATUS_INCOMPLETE_BASE: case HGFS_NAME_STATUS_INCOMPLETE_ROOT: case HGFS_NAME_STATUS_INCOMPLETE_DRIVE: case HGFS_NAME_STATUS_INCOMPLETE_UNC: case HGFS_NAME_STATUS_INCOMPLETE_UNC_MACH: return EINVAL; case HGFS_NAME_STATUS_DOES_NOT_EXIST: return ENOENT; case HGFS_NAME_STATUS_ACCESS_DENIED: return EACCES; case HGFS_NAME_STATUS_SYMBOLIC_LINK: return ELOOP; case HGFS_NAME_STATUS_OUT_OF_MEMORY: return ENOMEM; case HGFS_NAME_STATUS_TOO_LONG: return ENAMETOOLONG; case HGFS_NAME_STATUS_NOT_A_DIRECTORY: return ENOTDIR; default: NOT_IMPLEMENTED(); } } /* *----------------------------------------------------------------------------- * * HgfsPlatformGetDefaultDirAttrs -- * * Get default directory attributes. Permissions are Read and * Execute permission only. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsPlatformGetDefaultDirAttrs(HgfsFileAttrInfo *attr) // OUT { struct timeval tv; uint64 hgfsTime; ASSERT(attr); attr->type = HGFS_FILE_TYPE_DIRECTORY; attr->size = 4192; /* * Linux and friends are OK with receiving timestamps of 0, but just * for consistency with the Windows server, we'll pass back the * host's time in a virtual directory's timestamps. */ if (gettimeofday(&tv, NULL) != 0) { hgfsTime = 0; } else { hgfsTime = HgfsConvertToNtTime(tv.tv_sec, tv.tv_usec * 1000); } attr->creationTime = hgfsTime; attr->accessTime = hgfsTime; attr->writeTime = hgfsTime; attr->attrChangeTime = hgfsTime; attr->specialPerms = 0; attr->ownerPerms = HGFS_PERM_READ | HGFS_PERM_EXEC; attr->groupPerms = HGFS_PERM_READ | HGFS_PERM_EXEC; attr->otherPerms = HGFS_PERM_READ | HGFS_PERM_EXEC; attr->mask = HGFS_ATTR_VALID_TYPE | HGFS_ATTR_VALID_SIZE | HGFS_ATTR_VALID_CREATE_TIME | HGFS_ATTR_VALID_ACCESS_TIME | HGFS_ATTR_VALID_WRITE_TIME | HGFS_ATTR_VALID_CHANGE_TIME | HGFS_ATTR_VALID_SPECIAL_PERMS | HGFS_ATTR_VALID_OWNER_PERMS | HGFS_ATTR_VALID_GROUP_PERMS | HGFS_ATTR_VALID_OTHER_PERMS; } /* *----------------------------------------------------------------------------- * * HgfsServerGetOpenFlags -- * * Retrieve system open flags from HgfsOpenFlags. * * Does the correct bounds checking on the HgfsOpenFlags before * indexing into the array of flags to use. See bug 54429. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsServerGetOpenFlags(HgfsOpenFlags flagsIn, // IN int *flagsOut) // OUT { unsigned int arraySize; ASSERT(flagsOut); arraySize = ARRAYSIZE(HgfsServerOpenFlags); if ((unsigned int)flagsIn >= arraySize) { Log("%s: Invalid HgfsOpenFlags %d\n", __FUNCTION__, flagsIn); return FALSE; } *flagsOut = HgfsServerOpenFlags[flagsIn]; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPlatformInit -- * * Set up any state needed to start Linux HGFS server. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsPlatformInit(void) { return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPlatformDestroy -- * * Tear down any state used for Linux HGFS server. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsPlatformDestroy(void) { } /* *----------------------------------------------------------------------------- * * HgfsServerGetOpenMode -- * * Retrieve system open mode from HgfsOpenMode. * * Does the correct bounds checking on the HgfsOpenMode before * indexing into the array of modes to use. See bug 54429. * * This is just the POSIX implementation; the Windows implementation is * more complicated, hence the need for the HgfsFileOpenInfo as an * argument. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsServerGetOpenMode(HgfsFileOpenInfo *openInfo, // IN: Open info to examine uint32 *modeOut) // OUT: Local mode { ASSERT(modeOut); /* * If we didn't get the mode in the open request, we'll return a mode of 0. * This has the effect of failing the call to open(2) later, which is * exactly what we want. */ if ((openInfo->mask & HGFS_OPEN_VALID_MODE) == 0) { *modeOut = 0; return TRUE; } if (!HGFS_OPEN_MODE_IS_VALID_MODE(openInfo->mode)) { Log("%s: Invalid HgfsOpenMode %d\n", __FUNCTION__, openInfo->mode); return FALSE; } *modeOut = HgfsServerOpenMode[HGFS_OPEN_MODE_ACCMODE(openInfo->mode)]; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPlatformCloseFile -- * * Closes the file descriptor and release the file context. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformCloseFile(fileDesc fileDesc, // IN: File descriptor void *fileCtx) // IN: File context { if (close(fileDesc) != 0) { int error = errno; LOG(4, ("%s: Could not close fd %d: %s\n", __FUNCTION__, fileDesc, Err_Errno2String(error))); return error; } return 0; } /* *----------------------------------------------------------------------------- * * HgfsCheckFileNode -- * * Check if a file node is still valid (i.e. if the file name stored in the * file node still refers to the same file) * * Results: * Zero if the file node is valid * Non-zero if the file node is stale * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsCheckFileNode(char const *localName, // IN HgfsLocalId const *localId) // IN { struct stat nodeStat; ASSERT(localName); ASSERT(localId); /* * A file is uniquely identified by a (device; inode) pair. Check that the * file name still refers to the same pair */ #if defined(__APPLE__) /* * Can't use Posix_Stat because of inconsistent definition * of _DARWIN_USE_64_BIT_INODE in this file and in other libraries. */ if (stat(localName, &nodeStat) < 0) { #else if (Posix_Stat(localName, &nodeStat) < 0) { #endif int error = errno; LOG(4, ("%s: couldn't stat local file \"%s\": %s\n", __FUNCTION__, localName, Err_Errno2String(error))); return error; } if (nodeStat.st_dev != localId->volumeId || nodeStat.st_ino != localId->fileId) { LOG(4, ("%s: local Id mismatch\n", __FUNCTION__)); return ENOENT; } return 0; } /* *----------------------------------------------------------------------------- * * HgfsPlatformGetFd -- * * Returns the file descriptor associated with the node. If the node is * cached then it just returns the cached file descriptor (checking for * correct write flags). Otherwise, it opens a new file, caches the node * and returns the file desriptor. * * Results: * Zero on success. fd contains the opened file descriptor. * Non-zero on error. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformGetFd(HgfsHandle hgfsHandle, // IN: HGFS file handle HgfsSessionInfo *session, // IN: Session info Bool append, // IN: Open with append flag fileDesc *fd) // OUT: Opened file descriptor { int newFd = -1, openFlags = 0; HgfsFileNode node; HgfsInternalStatus status = 0; ASSERT(fd); ASSERT(session); /* * Use node copy convenience function to get the node information. * Note that we shouldn't keep this node around for too long because * the information can become stale. However, it's ok to get all the * fields in one step, instead of getting them all separate. * * XXX: It would be better if we didn't do this node copy on the fast * path. Unfortuntely, even the fast path may need to look at the node's * append flag. */ node.utf8Name = NULL; if (!HgfsGetNodeCopy(hgfsHandle, session, TRUE, &node)) { /* XXX: Technically, this can also fail if we're out of memory. */ LOG(4, ("%s: Invalid hgfs handle.\n", __FUNCTION__)); status = EBADF; goto exit; } /* If the node is found in the cache */ if (HgfsIsCached(hgfsHandle, session)) { /* * If the append flag is set check to see if the file was opened * in append mode. If not, close the file and reopen it in append * mode. */ if (append && !(node.flags & HGFS_FILE_NODE_APPEND_FL)) { status = HgfsPlatformCloseFile(node.fileDesc, node.fileCtx); if (status != 0) { LOG(4, ("%s: Couldn't close file \"%s\" for reopening\n", __FUNCTION__, node.utf8Name)); goto exit; } /* * Update the node in the cache with the new value of the append * flag. */ if (!HgfsUpdateNodeAppendFlag(hgfsHandle, session, TRUE)) { LOG(4, ("%s: Could not update the node in the cache\n", __FUNCTION__)); status = EBADF; goto exit; } } else { newFd = node.fileDesc; goto exit; } } /* * If we got here then the file was either not in the cache or needs * reopening. This means we need to open a file. But first, verify * that the file we intend to open isn't stale. */ status = HgfsCheckFileNode(node.utf8Name, &node.localId); if (status != 0) { goto exit; } /* * We're not interested in creating a new file. So let's just get the * flags for a simple open request. This really should always work. */ HgfsServerGetOpenFlags(0, &openFlags); /* * We don't need to specify open permissions here because we're only * reopening an existing file, not creating a new one. * * XXX: We should use O_LARGEFILE, see lib/file/fileIOPosix.c --hpreg */ newFd = Posix_Open(node.utf8Name, node.mode | openFlags | (append ? O_APPEND : 0)); if (newFd < 0) { int error = errno; LOG(4, ("%s: Couldn't open file \"%s\": %s\n", __FUNCTION__, node.utf8Name, Err_Errno2String(errno))); status = error; goto exit; } /* * Update the original node with the new value of the file desc. * This call might fail if the node is not used anymore. */ if (!HgfsUpdateNodeFileDesc(hgfsHandle, session, newFd, NULL)) { LOG(4, ("%s: Could not update the node -- node is not used.\n", __FUNCTION__)); status = EBADF; goto exit; } /* Add the node to the cache. */ if (!HgfsAddToCache(hgfsHandle, session)) { LOG(4, ("%s: Could not add node to the cache\n", __FUNCTION__)); status = EBADF; goto exit; } exit: if (status == 0) { *fd = newFd; } free(node.utf8Name); return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformValidateOpen -- * * Verify that the file with the given local name exists in the * local filesystem by trying to open the file with the requested * mode and permissions. If the open succeeds we stat the file * and fill in the volumeId and fileId with the file's local * filesystem device and inode number, respectively. * * Results: * Zero on success * Non-zero on failure. * * Side effects: * File with name "localName" may be created or truncated. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformValidateOpen(HgfsFileOpenInfo *openInfo, // IN: Open info struct Bool followSymlinks, // IN: followSymlinks config option HgfsSessionInfo *session, // IN: session info HgfsLocalId *localId, // OUT: Local unique file ID fileDesc *fileDesc) // OUT: Handle to the file { struct stat fileStat; int fd; int openMode = 0, openFlags = 0; mode_t openPerms; HgfsLockType serverLock; HgfsInternalStatus status = 0; Bool needToSetAttribute = FALSE; ASSERT(openInfo); ASSERT(localId); ASSERT(fileDesc); ASSERT(session); /* * Get correct system flags and mode from the HgfsOpenFlags and * HgfsOpenMode. This is related to bug 54429. */ if (!HgfsServerGetOpenFlags(openInfo->mask & HGFS_OPEN_VALID_FLAGS ? openInfo->flags : 0, &openFlags) || !HgfsServerGetOpenMode(openInfo, &openMode)) { status = EPROTO; goto exit; } /* * Create mode_t for use in open(). If owner permissions are missing, use * read/write for the owner permissions. If group or other permissions * are missing, use the owner permissions. * * This sort of makes sense. If the Windows driver wants to make a file * read-only, it probably intended for the file to be 555. Since creating * a file requires a valid mode, it's highly unlikely that we'll ever * be creating a file without owner permissions. */ openPerms = 0; openPerms |= openInfo->mask & HGFS_OPEN_VALID_SPECIAL_PERMS ? openInfo->specialPerms << 9 : 0; openPerms |= openInfo->mask & HGFS_OPEN_VALID_OWNER_PERMS ? openInfo->ownerPerms << 6 : S_IWUSR | S_IRUSR; openPerms |= openInfo->mask & HGFS_OPEN_VALID_GROUP_PERMS ? openInfo->groupPerms << 3 : (openPerms & S_IRWXU) >> 3; openPerms |= openInfo->mask & HGFS_OPEN_VALID_OTHER_PERMS ? openInfo->otherPerms : (openPerms & S_IRWXU) >> 6; /* * By default we don't follow symlinks, O_NOFOLLOW is always set. * Unset it if followSymlinks config option is specified. */ if (followSymlinks) { openFlags &= ~O_NOFOLLOW; } /* * Need to validate that open does not change the file for read * only shared folders. */ status = 0; if (!openInfo->shareInfo.writePermissions) { Bool deleteAccess = FALSE; /* * If a valid desiredAccess field specified by the Windows client, we use that * as the desiredAccess field has more data such as delete than is contained * in the mode. */ if ((0 != (openInfo->mask & HGFS_OPEN_VALID_DESIRED_ACCESS)) && (0 != (openInfo->desiredAccess & DELETE))) { deleteAccess = TRUE; } if ((openFlags & (O_APPEND | O_CREAT | O_TRUNC)) || (openMode & (O_WRONLY | O_RDWR)) || deleteAccess) { status = Posix_Access(openInfo->utf8Name, F_OK); if (status < 0) { status = errno; if (status == ENOENT && (openFlags & O_CREAT) != 0) { status = EACCES; } } else { /* * Handle the case when the file already exists: * If there is an attempt to createa new file, fail with "EEXIST" * error, otherwise set error to "EACCES". */ if ((openFlags & O_CREAT) && (openFlags & O_EXCL)) { status = EEXIST; } else { status = EACCES; } } } if (status != 0) { LOG(4, ("%s: Error: Unwritable share mode %u flags %u file \"%s\": %d %s\n", __FUNCTION__, openMode, openFlags, openInfo->utf8Name, status, Err_Errno2String(status))); goto exit; } } if (!openInfo->shareInfo.readPermissions) { /* * "Drop Box" / "FTP incoming" type of shared folders. * Allow creating a new file. Deny opening exisitng file. */ status = Posix_Access(openInfo->utf8Name, F_OK); if (status < 0) { status = errno; if (status != ENOENT || (openFlags & O_CREAT) == 0) { status = EACCES; } } else { status = EACCES; } if (status != 0) { LOG(4, ("%s: Error: Unreadable share flags %u file \"%s\": %d %s\n", __FUNCTION__, openFlags, openInfo->utf8Name, status, Err_Errno2String(status))); goto exit; } } /* * Determine if hidden attribute needs to be updated. * It needs to be updated if a new file is created or an existing file is truncated. * Since Posix_Open does not tell us if a new file has been created when O_CREAT is * specified we need to find out if the file exists before an open that may create * it. */ if (openInfo->mask & HGFS_OPEN_VALID_FILE_ATTR) { if ((openFlags & O_TRUNC) || ((openFlags & O_CREAT) && (openFlags & O_EXCL))) { needToSetAttribute = TRUE; } else if (openFlags & O_CREAT) { int err = Posix_Access(openInfo->utf8Name, F_OK); needToSetAttribute = (err != 0) && (errno == ENOENT); } } /* * Try to open the file with the requested mode, flags and permissions. */ fd = Posix_Open(openInfo->utf8Name, openMode | openFlags, openPerms); if (fd < 0) { status = errno; if (status == EAGAIN) { /* * We have tried opening with O_NONBLOCK but looks like an incompatible * lease may be held on the file. Tell the client that this access mode * is not allowed currently. */ status = EACCES; } LOG(4, ("%s: Error: open file \"%s\": %d %s\n", __FUNCTION__, openInfo->utf8Name, status, Err_Errno2String(status))); goto exit; } /* Stat file to get its volume and file info */ if (fstat(fd, &fileStat) < 0) { status = errno; LOG(4, ("%s: Error: stat file\"%s\": %d %s\n", __FUNCTION__, openInfo->utf8Name, status, Err_Errno2String(status))); close(fd); goto exit; } /* Set the rest of the Windows specific attributes if necessary. */ if (needToSetAttribute) { HgfsSetHiddenXAttr(openInfo->utf8Name, (openInfo->attr & HGFS_ATTR_HIDDEN) != 0, fileStat.st_mode); } /* Try to acquire an oplock. */ if (openInfo->mask & HGFS_OPEN_VALID_SERVER_LOCK) { serverLock = openInfo->desiredLock; if (!HgfsAcquireServerLock(fd, session, &serverLock)) { openInfo->acquiredLock = HGFS_LOCK_NONE; } else { openInfo->acquiredLock = serverLock; } } else { openInfo->acquiredLock = HGFS_LOCK_NONE; } *fileDesc = fd; /* Set volume and file ids from stat results */ localId->volumeId = fileStat.st_dev; localId->fileId = fileStat.st_ino; exit: return status; } /* *----------------------------------------------------------------------------- * * HgfsGetattrResolveAlias -- * * Mac OS defines a special file type known as an alias which behaves like a * symlink when viewed through the Finder, but is actually a regular file * otherwise. * * If the given filename is (or contains) an alias, this function will * resolve it completely and set targetName to something non-NULL. * * Results: * Zero on success. targetName is allocated if the file was an alias, and * NULL otherwise. * Non-zero on failure. targetName is unmodified. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsGetattrResolveAlias(char const *fileName, // IN: Input filename char **targetName) // OUT: Target filename { #ifndef __APPLE__ *targetName = NULL; return 0; #else // __APPLE__ HgfsInternalStatus status = HGFS_INTERNAL_STATUS_ERROR; Boolean success; CFURLRef resolvedURL = NULL; CFStringRef resolvedString = NULL; CFIndex maxPath; *targetName = NULL; if (CFURLCreateBookmarkDataFromFile != NULL) { /* We are running on Mac OS 10.6 or later. */ CFURLRef fileURL; CFBooleanRef isAlias = NULL; CFDataRef bookmarkData = NULL; CFURLBookmarkResolutionOptions resolutionOptions; Boolean isStale; fileURL = CFURLCreateFromFileSystemRepresentation(NULL, fileName, strlen(fileName), FALSE); if (!fileURL) { Log("%s: could not create CFURL for file.\n", __FUNCTION__); goto newExit; } success = CFURLCopyResourcePropertyForKey(fileURL, kCFURLIsAliasFileKey, &isAlias, NULL); if (!success) { Log("%s: could not copy IsAlias property key for file.\n", __FUNCTION__); goto newExit; } if (!CFBooleanGetValue(isAlias)) { status = 0; LOG(4, ("%s: file was not an alias\n", __FUNCTION__)); goto newExit; } LOG(4, ("%s: file was an alias\n", __FUNCTION__)); bookmarkData = CFURLCreateBookmarkDataFromFile(NULL, fileURL, NULL); if (!bookmarkData) { Log("%s: could not retrieve bookmark data for file.\n", __FUNCTION__); goto newExit; } /* * Don't show any UI during alias resolution and don't mount volumes * containing the alias target. This avoids blocking the current process * and/or Finder while trying to mount unreachable hosts (bug 1396411). */ resolutionOptions = kCFBookmarkResolutionWithoutUIMask | kCFBookmarkResolutionWithoutMountingMask; resolvedURL = CFURLCreateByResolvingBookmarkData(NULL, bookmarkData, resolutionOptions, NULL, NULL, &isStale, NULL); if (!resolvedURL) { Log("%s: could not resolve bookmark data for file.\n", __FUNCTION__); goto newExit; } newExit: if (fileURL) { CFRelease(fileURL); } if (isAlias) { CFRelease(isAlias); } if (bookmarkData) { CFRelease(bookmarkData); } } else { /* We are running on Mac OS 10.5 or earlier. */ #if __MAC_OS_X_VERSION_MIN_REQUIRED < 1060 /* * Mac OS 10.5 used a type of alias which appears on disk as a 0-byte * file but stores its linking data in a resource fork. The APIs for * interacting with this type of alias are deprecated when targetting * 10.8+. */ FSRef fileRef; Boolean isAlias; Boolean targetIsFolder; OSStatus osStatus; ASSERT_ON_COMPILE(sizeof osStatus == sizeof (int32)); osStatus = FSPathMakeRef(fileName, &fileRef, NULL); if (osStatus != noErr) { Log("%s: could not create file reference: error %d\n", __FUNCTION__, (int32)osStatus); goto oldExit; } osStatus = FSIsAliasFile(&fileRef, &isAlias, &targetIsFolder); if (osStatus != noErr) { Log("%s: could not detect if file is an old style alias: error %d\n", __FUNCTION__, (int32)osStatus); goto oldExit; } if (!isAlias) { status = 0; LOG(4, ("%s: file was not an alias\n", __FUNCTION__)); goto oldExit; } LOG(4, ("%s: file was an alias\n", __FUNCTION__)); /* * Create and resolve an FSRef of the desired path. We pass FALSE to * resolveAliasChains because aliases to aliases should behave as * symlinks to symlinks. * * If alias points to an unmounted volume, the volume needs to be * explicitly mounted. Mount flag kResolveAliasFileNoUI prevents the user * from being prompted about mounting. * * Caution: Mac OS 10.10.2 will attempt to mount volumes silently, * unlike the earlier behavior of only resolving within existing mounts. * The new CFURLCreateByResolvingBookmarkData API must be used to avoid * mounting the alias target. * * XXX: This function returns fnfErr (file not found) if it encounters a * broken alias. Perhaps we should make that look like a dangling symlink * instead of returning an error? */ osStatus = FSResolveAliasFileWithMountFlags(&fileRef, FALSE, &targetIsFolder, &isAlias, kResolveAliasFileNoUI); if (osStatus != noErr) { Log("%s: could not resolve reference: error %d\n", __FUNCTION__, (int32)osStatus); goto oldExit; } resolvedURL = CFURLCreateFromFSRef(NULL, &fileRef); if (!resolvedURL) { Log("%s: could not create resolved URL reference from " "resolved filesystem reference\n", __FUNCTION__); goto oldExit; } oldExit: (void)0; // Need a statement for the label. #else // __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 // We are running on 10.5 but the build was targetting 10.6+. Eject! NOT_IMPLEMENTED(); #endif // __MAC_OS_X_VERSION_MIN_REQUIRED } if (resolvedURL) { /* * This is somewhat convoluted. We want to call * CFURLGetFileSystemRepresentation() to get a UTF-8 string representing * the target of the alias. But to call * CFStringGetMaximumSizeOfFileSystemRepresentation(), we need a CFString, * so we make one from the CFURL. Once we've got the max number of bytes * for a filename on the filesystem, we allocate some memory and convert * the CFURL to a basic UTF-8 string using a call to * CFURLGetFileSystemRepresentation(). */ resolvedString = CFURLGetString(resolvedURL); if (!resolvedString) { Log("%s: could not create resolved string reference from " "resolved URL reference\n", __FUNCTION__); goto exit; } maxPath = CFStringGetMaximumSizeOfFileSystemRepresentation(resolvedString); *targetName = malloc(maxPath); if (*targetName == NULL) { Log("%s: could not allocate %"FMTSZ"d bytes of memory for " "target name storage\n", __FUNCTION__, maxPath); goto exit; } success = CFURLGetFileSystemRepresentation(resolvedURL, FALSE, *targetName, maxPath); if (!success) { Log("%s: could not convert and copy resolved URL reference " "into allocated buffer\n", __FUNCTION__); goto exit; } status = 0; } exit: if (resolvedURL) { CFRelease(resolvedURL); } if (status != 0) { free(*targetName); *targetName = NULL; } return status; #endif // __APPLE__ } /* *----------------------------------------------------------------------------- * * HgfsGetHiddenAttr -- * * For Mac hosts and Linux hosts, if a guest is Windows we force the "dot", * files to be treated as hidden too in the Windows client by always setting * the hidden attribute flag. * Currently, this flag cannot be removed by Windows clients. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsGetHiddenAttr(char const *fileName, // IN: Input filename HgfsFileAttrInfo *attr) // OUT: Struct to copy into { char *baseName; ASSERT(fileName); ASSERT(attr); baseName = strrchr(fileName, DIRSEPC); if ((baseName != NULL) && (baseName[1] == '.') && (strcmp(&baseName[1], ".") != 0) && (strcmp(&baseName[1], "..") != 0)) { attr->mask |= HGFS_ATTR_VALID_FLAGS; attr->flags |= HGFS_ATTR_HIDDEN; /* * The request sets the forced flag so the client knows it is simulated * and is not a real attribute, which can only happen on a Windows server. * This allows the client to enforce some checks correctly if the flag * is real or not. * This replicates SMB behavior see bug 292189. */ attr->flags |= HGFS_ATTR_HIDDEN_FORCED; } else { Bool isHidden = FALSE; /* * Do not propagate any error returned from HgfsGetHiddenXAttr. * Consider that the file is not hidden if can't get hidden attribute for * whatever reason; most likely it fails because hidden attribute is not supported * by the OS or file system. */ HgfsGetHiddenXAttr(fileName, &isHidden); if (isHidden) { attr->mask |= HGFS_ATTR_VALID_FLAGS; attr->flags |= HGFS_ATTR_HIDDEN; } } } /* *----------------------------------------------------------------------------- * * HgfsConvertComponentCase -- * * Do a case insensitive search of a directory for the specified entry. If * a matching entry is found, return it in the convertedComponent argument. * * Results: * On Success: * Returns 0 and the converted component name in the argument convertedComponent. * The length for the convertedComponent is returned in convertedComponentSize. * * On Failure: * Non-zero errno return, with convertedComponent and convertedComponentSize * set to NULL and 0 respectively. * * Side effects: * On success, allocated memory is returned in convertedComponent and needs * to be freed. * *----------------------------------------------------------------------------- */ static int HgfsConvertComponentCase(char *currentComponent, // IN const char *dirPath, // IN const char **convertedComponent, // OUT size_t *convertedComponentSize) // OUT { struct dirent *dirent; DIR *dir = NULL; char *dentryName; size_t dentryNameLen; char *myConvertedComponent = NULL; size_t myConvertedComponentSize; int ret; ASSERT(currentComponent); ASSERT(dirPath); ASSERT(convertedComponent); ASSERT(convertedComponentSize); /* Open the specified directory. */ dir = Posix_OpenDir(dirPath); if (!dir) { ret = errno; goto exit; } /* * Unicode_CompareIgnoreCase crashes with invalid unicode strings, * validate it before passing it to Unicode_* functions. */ if (!Unicode_IsBufferValid(currentComponent, -1, STRING_ENCODING_UTF8)) { /* Invalid unicode string, return failure. */ ret = EINVAL; goto exit; } /* * Read all of the directory entries. For each one, convert the name * to lower case and then compare it to the lower case component. */ while ((dirent = readdir(dir))) { char *dentryNameU; int cmpResult; dentryName = dirent->d_name; dentryNameLen = strlen(dentryName); /* * Unicode_CompareIgnoreCase crashes with invalid unicode strings, * validate and convert it appropriately before passing it to Unicode_* * functions. */ if (!Unicode_IsBufferValid(dentryName, dentryNameLen, STRING_ENCODING_DEFAULT)) { /* Invalid unicode string, skip the entry. */ continue; } dentryNameU = Unicode_Alloc(dentryName, STRING_ENCODING_DEFAULT); cmpResult = Unicode_CompareIgnoreCase(currentComponent, dentryNameU); free(dentryNameU); if (cmpResult == 0) { /* * The current directory entry is a case insensitive match to * the specified component. Malloc and copy the current directory entry. */ myConvertedComponentSize = dentryNameLen + 1; myConvertedComponent = malloc(myConvertedComponentSize); if (myConvertedComponent == NULL) { ret = errno; LOG(4, ("%s: failed to malloc myConvertedComponent.\n", __FUNCTION__)); goto exit; } Str_Strcpy(myConvertedComponent, dentryName, myConvertedComponentSize); /* Success. Cleanup and exit. */ ret = 0; *convertedComponentSize = myConvertedComponentSize; *convertedComponent = myConvertedComponent; goto exit; } } /* We didn't find a match. Failure. */ ret = ENOENT; exit: if (dir) { closedir(dir); } if (ret) { *convertedComponent = NULL; *convertedComponentSize = 0; } return ret; } /* *----------------------------------------------------------------------------- * * HgfsConstructConvertedPath -- * * Expand the passed string and append the converted path. * * Results: * Returns 0 if successful, errno on failure. Note that this * function cannot return ENOENT. * * Side effects: * Reallocs the path. * *----------------------------------------------------------------------------- */ static int HgfsConstructConvertedPath(char **path, // IN/OUT size_t *pathSize, // IN/OUT char *convertedPath, // IN size_t convertedPathSize) // IN { char *p; size_t convertedPathLen = convertedPathSize - 1; ASSERT(path); ASSERT(*path); ASSERT(convertedPath); ASSERT(pathSize); p = realloc(*path, *pathSize + convertedPathLen + sizeof (DIRSEPC)); if (!p) { int error = errno; LOG(4, ("%s: failed to realloc.\n", __FUNCTION__)); return error; } *path = p; *pathSize += convertedPathLen + sizeof (DIRSEPC); /* Copy out the converted component to curDir, and free it. */ Str_Strncat(p, *pathSize, DIRSEPS, sizeof (DIRSEPS)); Str_Strncat(p, *pathSize, convertedPath, convertedPathLen); return 0; } /* *----------------------------------------------------------------------------- * * HgfsCaseInsensitiveLookup -- * * Do a case insensitive lookup for fileName. Each component past sharePath is * looked-up case-insensitively. Expensive! * * NOTE: * shareName is always expected to be a prefix of fileName. * * Results: * Returns 0 if successful and resolved path for fileName is returned in * convertedFileName and its length (without nul) in convertedFileNameLength. * Otherwise returns non-zero errno with convertedFileName and * convertedFileNameLength set to NULL and 0 respectively. * * Side effects: * On success, allocated memory is returned in convertedFileName and needs * to be freed. * *----------------------------------------------------------------------------- */ static int HgfsCaseInsensitiveLookup(const char *sharePath, // IN size_t sharePathLength, // IN char *fileName, // IN size_t fileNameLength, // IN char **convertedFileName, // OUT size_t *convertedFileNameLength) // OUT { char *currentComponent; char *nextComponent; char *curDir; size_t curDirSize; char *convertedComponent = NULL; size_t convertedComponentSize = 0; int error = 0; ASSERT(sharePath); ASSERT(fileName); ASSERT(convertedFileName); ASSERT(fileNameLength >= sharePathLength); curDirSize = sharePathLength + 1; curDir = malloc(curDirSize); if (!curDir) { error = errno; LOG(4, ("%s: failed to allocate for curDir\n", __FUNCTION__)); goto exit; } Str_Strcpy(curDir, sharePath, curDirSize); currentComponent = fileName + sharePathLength; /* Check there is something beyond the share name. */ if (*currentComponent == '\0') { /* * The fileName is the same as sharePath. Nothing else to do. * Return the duplicated sharePath string and return. */ goto exit; } /* Skip a component separator if not in the share path. */ if (*currentComponent == DIRSEPC) { currentComponent += 1; } while (TRUE) { /* Get the next component. */ nextComponent = strchr(currentComponent, DIRSEPC); if (nextComponent != NULL) { *nextComponent = '\0'; } /* * Try to match the current component against the one in curDir. * HgfsConvertComponentCase may return ENOENT. In that case return * the path case-converted uptil now (curDir) and append to it the * rest of the unconverted path. */ error = HgfsConvertComponentCase(currentComponent, curDir, (const char **)&convertedComponent, &convertedComponentSize); /* Restore the path separator if we removed it earlier. */ if (nextComponent != NULL) { *nextComponent = DIRSEPC; } if (error) { if (error == ENOENT) { /* * We could not find the current component so no need to convert it. * So it most likely a new path is to be created or an ENOENT genuine error. * Copy out the components starting from currentComponent. We do this * after replacing DIRSEPC, so all the components following * currentComponent gets copied. */ error = HgfsConstructConvertedPath(&curDir, &curDirSize, currentComponent, strlen(currentComponent) + 1); } break; } /* Expand curDir and copy out the converted component. */ error = HgfsConstructConvertedPath(&curDir, &curDirSize, convertedComponent, convertedComponentSize); if (error) { break; } /* Free the converted component. */ free(convertedComponent); convertedComponent = NULL; /* If there is no component after the current one then we are done. */ if (nextComponent == NULL) { /* Set success. */ error = 0; break; } /* * Set the current component pointer to point at the start of the next * component. */ currentComponent = nextComponent + 1; } exit: /* * If the conversion was successful, return the result. * The length does NOT include the nul terminator. */ if (error == 0) { *convertedFileName = curDir; *convertedFileNameLength = curDirSize - 1; } else { *convertedFileName = NULL; *convertedFileNameLength = 0; free(curDir); } free(convertedComponent); return error; } /* *----------------------------------------------------------------------------- * * HgfsPlatformFilenameLookup -- * * Perform a fileName lookup of the fileName if requested. * * The type of lookup depends on the flags passed. Currently, * case insensitive is checked and if set we lookup the file name. * Otherwise this function assumes the file system is the default * of case sensitive and returns a copy of the passed name. * * Results: * Returns HGFS_NAME_STATUS_COMPLETE if successful and converted * path for fileName is returned in convertedFileName and it length in * convertedFileNameLength. * * Otherwise returns non-zero integer without affecting fileName with * convertedFileName and convertedFileNameLength set to NULL and 0 * respectively. * * Side effects: * On success, allocated memory is returned in convertedFileName and needs * to be freed. * *----------------------------------------------------------------------------- */ HgfsNameStatus HgfsPlatformFilenameLookup(const char *sharePath, // IN size_t sharePathLength, // IN char *fileName, // IN size_t fileNameLength, // IN uint32 caseFlags, // IN char **convertedFileName, // OUT size_t *convertedFileNameLength) // OUT { int error = 0; HgfsNameStatus nameStatus = HGFS_NAME_STATUS_COMPLETE; ASSERT(sharePath); ASSERT(fileName); ASSERT(convertedFileName); ASSERT(convertedFileNameLength); *convertedFileName = NULL; *convertedFileNameLength = 0; /* * Case-insensitive lookup is expensive, do it only if the flag is set * and file is inaccessible using the case passed to us. We use access(2) * call to check if the passed case of the file name is correct. */ if (caseFlags == HGFS_FILE_NAME_CASE_INSENSITIVE && Posix_Access(fileName, F_OK) == -1) { LOG(4, ("%s: Case insensitive lookup, fileName: %s, flags: %u.\n", __FUNCTION__, fileName, caseFlags)); error = HgfsCaseInsensitiveLookup(sharePath, sharePathLength, fileName, fileNameLength, convertedFileName, convertedFileNameLength); /* * Map the success or an error code. */ switch (error) { /* * 0 means that HgfsCaseInsensitiveLookup completed * successfully built the converted name thus we return * HGFS_NAME_STATUS_COMPLETE in this case. */ case 0: nameStatus = HGFS_NAME_STATUS_COMPLETE; break; case ENOTDIR: nameStatus = HGFS_NAME_STATUS_NOT_A_DIRECTORY; break; default: nameStatus = HGFS_NAME_STATUS_FAILURE; break; } return nameStatus; } *convertedFileName = strdup(fileName); if (!*convertedFileName) { nameStatus = HGFS_NAME_STATUS_OUT_OF_MEMORY; LOG(4, ("%s: strdup on fileName failed.\n", __FUNCTION__)); } else { *convertedFileNameLength = fileNameLength; } return nameStatus; } /* *----------------------------------------------------------------------------- * * HgfsPlatformDoFilenameLookup -- * * Determines if the file name lookup depending on case flags is required. * * Results: * TRUE on Linux / Apple. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsPlatformDoFilenameLookup(void) { return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsEffectivePermissions -- * * Get permissions that are in efffect for the current user. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsEffectivePermissions(char *fileName, // IN: Input filename Bool readOnlyShare, // IN: Share name uint32 *permissions) // OUT: Effective permissions { *permissions = 0; if (Posix_Access(fileName, R_OK) == 0) { *permissions |= HGFS_PERM_READ; } if (Posix_Access(fileName, X_OK) == 0) { *permissions |= HGFS_PERM_EXEC; } if (!readOnlyShare && (Posix_Access(fileName, W_OK) == 0)) { *permissions |= HGFS_PERM_WRITE; } return 0; } /* *----------------------------------------------------------------------------- * * HgfsGetCreationTime -- * * Calculates actual or emulated file creation time from stat structure. * Definition of stat structure are different on diferent platforms. * This function hides away all these differences and produces 64 bit value * which should be reported to the client. * * Results: * Value that should be used as a file creation time stamp. * The resulting timestamp is in platform independent HGFS format. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static uint64 HgfsGetCreationTime(const struct stat *stats) { uint64 creationTime; /* * Linux and FreeBSD before v5 doesn't know about creation time; we just use the time * of last data modification for the creation time. * FreeBSD 5+ supprots file creation time. * * Using mtime when creation time is unavailable to be consistent with SAMBA. */ #ifdef __FreeBSD__ /* * FreeBSD: All supported versions have timestamps with nanosecond resolution. * FreeBSD 5+ has also file creation time. */ # if __IS_FREEBSD_VER__(500043) creationTime = HgfsConvertTimeSpecToNtTime(&stats->st_birthtimespec); # else creationTime = HgfsConvertTimeSpecToNtTime(&stats->st_mtimespec); # endif #elif defined(__linux__) /* * Linux: Glibc 2.3+ has st_Xtim. Glibc 2.1/2.2 has st_Xtime/__unusedX on * same place (see below). We do not support Glibc 2.0 or older. */ # if (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 3) && !defined(__UCLIBC__) /* * stat structure is same between glibc 2.3 and older glibcs, just * these __unused fields are always zero. If we'll use __unused* * instead of zeroes, we get automatically nanosecond timestamps * when running on host which provides them. */ creationTime = HgfsConvertToNtTime(stats->st_mtime, stats->__unused2); # else creationTime = HgfsConvertTimeSpecToNtTime(&stats->st_mtim); # endif #elif defined(__APPLE__) creationTime = HgfsConvertTimeSpecToNtTime(&stats->st_birthtimespec); #else /* * Solaris: No nanosecond timestamps, no file create timestamp. */ creationTime = HgfsConvertToNtTime(stats->st_mtime, 0); #endif return creationTime; } /* *----------------------------------------------------------------------------- * * HgfsStat -- * * Wrapper function that invokes stat on Mac OS and on Linux. * * Returns filled stat structure and a file creation time. File creation time is * the birthday time for Mac OS and last write time for Linux (which does not support * file creation time). * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static int HgfsStat(const char* fileName, // IN: file name Bool followLink, // IN: If true then follow symlink struct stat *stats, // OUT: file attributes uint64 *creationTime) // OUT: file creation time { int error; #if defined(__APPLE__) if (followLink) { error = stat(fileName, stats); } else { error = lstat(fileName, stats); } #else if (followLink) { error = Posix_Stat(fileName, stats); } else { error = Posix_Lstat(fileName, stats); } #endif *creationTime = HgfsGetCreationTime(stats); return error; } /* *----------------------------------------------------------------------------- * * HgfsFStat -- * * Wrapper function that invokes fstat. * * Returns filled stat structure and a file creation time. File creation time is * the birthday time for Mac OS and last write time for Linux (which does not support * file creation time). * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static int HgfsFStat(int fd, // IN: file descriptor struct stat *stats, // OUT: file attributes uint64 *creationTime) // OUT: file creation time { int error = 0; if (fstat(fd, stats) < 0) { error = errno; } *creationTime = HgfsGetCreationTime(stats); return error; } /* *---------------------------------------------------------------------------- * * HgfsGetSequentialOnlyFlagFromName -- * * Certain files like 'kallsyms' residing in /proc/ filesystem can be * copied only if they are opened in sequential mode. Check for such files * and set the 'sequential only' flag. This is done by trying to read the file * content using 'pread'. If 'pread' fails with ESPIPE then they are * tagged as 'sequential only' files. * * Results: * None. * * Side effects: * None * *---------------------------------------------------------------------------- */ static void HgfsGetSequentialOnlyFlagFromName(const char *fileName, // IN Bool followSymlinks, // IN: If true then follow symlink HgfsFileAttrInfo *attr) // IN/OUT { #if defined(__linux) || defined(__APPLE__) int fd; int openFlags; if ((NULL == fileName) || (NULL == attr)) { return; } /* * We're not interested in creating a new file. So let's just get the * flags for a simple open request. This really should always work. */ HgfsServerGetOpenFlags(0, &openFlags); /* * By default we don't follow symlinks, O_NOFOLLOW is always set. * Unset it if followSymlinks config option is specified. */ if (followSymlinks) { openFlags &= ~O_NOFOLLOW; } /* * Checking for a FIFO we open in nonblocking mode. In this case, opening for * read only will succeed even if no-one has opened on the write side yet, * opening for write only will fail with ENXIO (no such device or address) * unless the other end has already been opened. * Note, Under Linux, opening a FIFO for read and write will succeed both * in blocking and nonblocking mode. POSIX leaves this behavior undefined. */ fd = Posix_Open(fileName, openFlags | O_RDONLY); if (fd < 0) { LOG(4, ("%s: Couldn't open the file \"%s\"\n", __FUNCTION__, fileName)); return; } HgfsGetSequentialOnlyFlagFromFd(fd, attr); close(fd); return; #endif } /* *---------------------------------------------------------------------------- * * HgfsGetSequentialOnlyFlagFromFd -- * * Certain files like 'kallsyms' residing in /proc/ filesystem can be * copied only if they are opened in sequential mode. Check for such files * and set the 'sequential only' flag. This is done by trying to read the file * content using 'pread'. If 'pread' fails with ESPIPE then they are * tagged as 'sequential only' files. * * Results: * None. * * Side effects: * None * *---------------------------------------------------------------------------- */ static void HgfsGetSequentialOnlyFlagFromFd(int fd, // IN HgfsFileAttrInfo *attr) // IN/OUT { #if defined(__linux) || defined(__APPLE__) int error; char buffer[2]; struct stat stats; if (NULL == attr) { return; } if (fstat(fd, &stats) < 0) { return; } if (S_ISDIR(stats.st_mode) || S_ISLNK(stats.st_mode)) { return; } /* * At this point in the code, we are not reading any amount of data from the * file. We just want to check the behavior of pread. Since we are not * reading any data, we can call pread with size specified as 0. */ error = pread(fd, buffer, 0, 0); LOG(4, ("%s: pread returned %d, errno %d\n", __FUNCTION__, error, errno)); if ((-1 == error) && (ESPIPE == errno)) { LOG(4, ("%s: Marking the file as 'Sequential only' file\n", __FUNCTION__)); attr->flags |= HGFS_ATTR_SEQUENTIAL_ONLY; } return; #endif } /* *----------------------------------------------------------------------------- * * HgfsPlatformGetattrFromName -- * * Performs a stat operation on the given filename, and, if it is a symlink, * allocates the target filename on behalf of the caller and performs a * readlink to get it. If not a symlink, the targetName argument is * untouched. Does necessary translation between Unix file stats and the * HgfsFileAttrInfo formats. * NOTE: The function is different from HgfsGetAttrFromId: this function returns * effectve permissions while HgfsGetAttrFromId does not. * The reason for this asymmetry is that effective permissions are needed * to get a new handle. If the file is already opened then * getting effective permissions does not have any value. However getting * effective permissions would hurt perfomance and should be avoided. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformGetattrFromName(char *fileName, // IN/OUT: Input filename HgfsShareOptions configOptions, // IN: Share config options char *shareName, // IN: Share name HgfsFileAttrInfo *attr, // OUT: Struct to copy into char **targetName) // OUT: Symlink target { HgfsInternalStatus status = 0; struct stat stats; int error; char *myTargetName = NULL; uint64 creationTime; Bool followSymlinks; ASSERT(fileName); ASSERT(attr); LOG(4, ("%s: getting attrs for \"%s\"\n", __FUNCTION__, fileName)); followSymlinks = HgfsServerPolicy_IsShareOptionSet(configOptions, HGFS_SHARE_FOLLOW_SYMLINKS), error = HgfsStat(fileName, followSymlinks, &stats, &creationTime); if (error) { status = errno; LOG(4, ("%s: error stating file: %s\n", __FUNCTION__, Err_Errno2String(status))); goto exit; } /* * Deal with the file type returned from lstat(2). We currently support * regular files, directories, and symlinks. On Mac OS, we'll additionally * treat finder aliases as symlinks. */ if (S_ISDIR(stats.st_mode)) { attr->type = HGFS_FILE_TYPE_DIRECTORY; LOG(4, ("%s: is a directory\n", __FUNCTION__)); } else if (S_ISLNK(stats.st_mode)) { attr->type = HGFS_FILE_TYPE_SYMLINK; LOG(4, ("%s: is a symlink\n", __FUNCTION__)); /* * In the case of a symlink, we should populate targetName if the * caller asked. Use st_size and readlink() to do so. */ if (targetName != NULL) { myTargetName = Posix_ReadLink(fileName); if (myTargetName == NULL) { error = errno; LOG(4, ("%s: readlink returned wrong size\n", __FUNCTION__)); /* * Because of an unavoidable race between the lstat(2) and the * readlink(2), the symlink target may have lengthened and we may * not have read the entire link. If that happens, just return * "out of memory". */ status = error ? error : ENOMEM; goto exit; } } } else { /* * Now is a good time to check if the file was an alias. If so, we'll * treat it as a symlink. * * XXX: If HgfsGetattrResolveAlias fails, we'll treat the file as a * regular file. This isn't completely correct (the function may have * failed because we're out of memory), but it's better than having to * call LScopyItemInfoForRef for each file, which may negatively affect * performance. See: * * http://lists.apple.com/archives/carbon-development/2001/Nov/msg00007.html */ LOG(4, ("%s: NOT a directory or symlink\n", __FUNCTION__)); if (HgfsGetattrResolveAlias(fileName, &myTargetName)) { LOG(4, ("%s: could not resolve file aliases\n", __FUNCTION__)); } attr->type = HGFS_FILE_TYPE_REGULAR; if (myTargetName != NULL) { /* * At this point the alias target has been successfully resolved. If * the alias target is inside the same shared folder then convert it * to relative path. Converting to a relative path produces a symlink * that points to the target file in the guest OS. If the target lies * outside the shared folder then treat it the same way as if alias * has not been resolved - we drop the error and treat as a regular file! */ HgfsNameStatus nameStatus; size_t sharePathLen; const char* sharePath; nameStatus = HgfsServerPolicy_GetSharePath(shareName, strlen(shareName), HGFS_OPEN_MODE_READ_ONLY, &sharePathLen, &sharePath); if (nameStatus == HGFS_NAME_STATUS_COMPLETE && sharePathLen < strlen(myTargetName) && Str_Strncmp(sharePath, myTargetName, sharePathLen) == 0) { char *relativeName; relativeName = HgfsServerGetTargetRelativePath(fileName, myTargetName); free(myTargetName); myTargetName = relativeName; if (myTargetName != NULL) { /* * Let's mangle the permissions and size of the file so that * it more closely resembles a symlink. The size should be * the length of the target name (not including the * nul-terminator), and the permissions should be 777. */ stats.st_size = strlen(myTargetName); stats.st_mode |= ACCESSPERMS; attr->type = HGFS_FILE_TYPE_SYMLINK; } else { LOG(4, ("%s: out of memory\n", __FUNCTION__)); } } else { LOG(4, ("%s: alias target is outside shared folder\n", __FUNCTION__)); } } } if (myTargetName != NULL && targetName != NULL) { #if defined(__APPLE__) /* * HGFS clients will expect filenames in unicode normal form C * (precomposed) so Mac hosts must convert from normal form D * (decomposed). */ if (!CodeSet_Utf8FormDToUtf8FormC(myTargetName, strlen(myTargetName), targetName, NULL)) { LOG(4, ("%s: Unable to normalize form C \"%s\"\n", __FUNCTION__, myTargetName)); status = HgfsPlatformConvertFromNameStatus(HGFS_NAME_STATUS_FAILURE); goto exit; } #else *targetName = myTargetName; myTargetName = NULL; #endif LOG(4, ("%s: symlink target \"%s\"\n", __FUNCTION__, *targetName)); } HgfsStatToFileAttr(&stats, &creationTime, attr); /* * In the case we have a Windows client, force the hidden flag. * This will be ignored by Linux, Solaris clients. */ HgfsGetHiddenAttr(fileName, attr); HgfsGetSequentialOnlyFlagFromName(fileName, followSymlinks, attr); /* Get effective permissions if we can */ if (!(S_ISLNK(stats.st_mode))) { HgfsOpenMode shareMode; uint32 permissions; HgfsNameStatus nameStatus; nameStatus = HgfsServerPolicy_GetShareMode(shareName, strlen(shareName), &shareMode); if (nameStatus == HGFS_NAME_STATUS_COMPLETE && HgfsEffectivePermissions(fileName, shareMode == HGFS_OPEN_MODE_READ_ONLY, &permissions) == 0) { attr->mask |= HGFS_ATTR_VALID_EFFECTIVE_PERMS; attr->effectivePerms = permissions; } } exit: free(myTargetName); return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformGetattrFromFd -- * * Performs a stat operation on the given file desc. * Does necessary translation between Unix file stats and the * HgfsFileAttrInfo formats. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformGetattrFromFd(fileDesc fileDesc, // IN: file descriptor HgfsSessionInfo *session, // IN: session info HgfsFileAttrInfo *attr) // OUT: FileAttrInfo to copy into { HgfsInternalStatus status = 0; struct stat stats; int error; HgfsOpenMode shareMode; HgfsHandle handle = HGFS_INVALID_HANDLE; char *fileName = NULL; size_t fileNameLen; uint64 creationTime; ASSERT(attr); ASSERT(session); LOG(4, ("%s: getting attrs for %u\n", __FUNCTION__, fileDesc)); error = HgfsFStat(fileDesc, &stats, &creationTime); if (error) { LOG(4, ("%s: error stating file: %s\n", __FUNCTION__, Err_Errno2String(error))); status = error; goto exit; } /* * For now, everything that isn't a directory or symlink is a regular * file. */ if (S_ISDIR(stats.st_mode)) { attr->type = HGFS_FILE_TYPE_DIRECTORY; LOG(4, ("%s: is a directory\n", __FUNCTION__)); } else if (S_ISLNK(stats.st_mode)) { attr->type = HGFS_FILE_TYPE_SYMLINK; LOG(4, ("%s: is a symlink\n", __FUNCTION__)); } else { attr->type = HGFS_FILE_TYPE_REGULAR; LOG(4, ("%s: NOT a directory or symlink\n", __FUNCTION__)); } HgfsStatToFileAttr(&stats, &creationTime, attr); /* * XXX - Correct share mode checking should be fully implemented. * * For now, we must ensure that the client only sees read only * attributes when the share is read only. This allows the client * to make decisions to fail write/delete operations. * It is required by clients who use file handles that * are cached, for setting attributes, renaming and deletion. */ if (!HgfsFileDesc2Handle(fileDesc, session, &handle)) { LOG(4, ("%s: could not get HGFS handle for fd %u\n", __FUNCTION__, fileDesc)); status = EBADF; goto exit; } if (!HgfsHandle2ShareMode(handle, session, &shareMode)) { LOG(4, ("%s: could not get share mode fd %u\n", __FUNCTION__, fileDesc)); status = EBADF; goto exit; } if (!HgfsHandle2FileName(handle, session, &fileName, &fileNameLen)) { LOG(4, ("%s: could not map cached target file handle %u\n", __FUNCTION__, handle)); status = EBADF; goto exit; } /* * In the case we have a Windows client, force the hidden flag. * This will be ignored by Linux, Solaris clients. */ HgfsGetHiddenAttr(fileName, attr); HgfsGetSequentialOnlyFlagFromFd(fileDesc, attr); if (shareMode == HGFS_OPEN_MODE_READ_ONLY) { /* * Share does not allow write, so tell the client * everything is read only. */ if (attr->mask & HGFS_ATTR_VALID_OWNER_PERMS) { attr->ownerPerms &= ~HGFS_PERM_WRITE; } if (attr->mask & HGFS_ATTR_VALID_GROUP_PERMS) { attr->groupPerms &= ~HGFS_PERM_WRITE; } if (attr->mask & HGFS_ATTR_VALID_OTHER_PERMS) { attr->otherPerms &= ~HGFS_PERM_WRITE; } } exit: free(fileName); return status; } /* *----------------------------------------------------------------------------- * * HgfsStatToFileAttr -- * * Does necessary translation between Unix file stats and the * HgfsFileAttrInfo formats. * It expects creationTime to be in platform-independent HGFS format and * stats in a platform-specific stat format. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsStatToFileAttr(struct stat *stats, // IN: stat information uint64 *creationTime, // IN: file creation time HgfsFileAttrInfo *attr) // OUT: FileAttrInfo to copy into { attr->size = stats->st_size; attr->allocationSize = stats->st_blocks * 512; attr->creationTime = *creationTime; #ifdef __FreeBSD__ /* * FreeBSD: All supported versions have timestamps with nanosecond resolution. * FreeBSD 5+ has also file creation time. */ attr->accessTime = HgfsConvertTimeSpecToNtTime(&stats->st_atimespec); attr->writeTime = HgfsConvertTimeSpecToNtTime(&stats->st_mtimespec); attr->attrChangeTime = HgfsConvertTimeSpecToNtTime(&stats->st_ctimespec); #elif defined(__linux__) /* * Linux: Glibc 2.3+ has st_Xtim. Glibc 2.1/2.2 has st_Xtime/__unusedX on * same place (see below). We do not support Glibc 2.0 or older. */ # if (__GLIBC__ == 2) && (__GLIBC_MINOR__ < 3) && !defined(__UCLIBC__) /* * stat structure is same between glibc 2.3 and older glibcs, just * these __unused fields are always zero. If we'll use __unused* * instead of zeroes, we get automatically nanosecond timestamps * when running on host which provides them. */ attr->accessTime = HgfsConvertToNtTime(stats->st_atime, stats->__unused1); attr->writeTime = HgfsConvertToNtTime(stats->st_mtime, stats->__unused2); attr->attrChangeTime = HgfsConvertToNtTime(stats->st_ctime, stats->__unused3); # else attr->accessTime = HgfsConvertTimeSpecToNtTime(&stats->st_atim); attr->writeTime = HgfsConvertTimeSpecToNtTime(&stats->st_mtim); attr->attrChangeTime = HgfsConvertTimeSpecToNtTime(&stats->st_ctim); # endif #else /* * Solaris, Mac OS: No nanosecond timestamps. */ attr->accessTime = HgfsConvertToNtTime(stats->st_atime, 0); attr->writeTime = HgfsConvertToNtTime(stats->st_mtime, 0); attr->attrChangeTime = HgfsConvertToNtTime(stats->st_ctime, 0); #endif attr->specialPerms = (stats->st_mode & (S_ISUID | S_ISGID | S_ISVTX)) >> 9; attr->ownerPerms = (stats->st_mode & S_IRWXU) >> 6; attr->groupPerms = (stats->st_mode & S_IRWXG) >> 3; attr->otherPerms = stats->st_mode & S_IRWXO; LOG(4, ("%s: done, permissions %o%o%o%o, size %"FMT64"u\n", __FUNCTION__, attr->specialPerms, attr->ownerPerms, attr->groupPerms, attr->otherPerms, attr->size)); #ifdef __FreeBSD__ # if !defined(VM_X86_64) && __FreeBSD_version >= 500043 # define FMTTIMET "" # else # define FMTTIMET "l" # endif #else # define FMTTIMET "l" #endif LOG(4, ("access: %"FMTTIMET"d/%"FMT64"u \nwrite: %"FMTTIMET"d/%"FMT64"u \n" "attr: %"FMTTIMET"d/%"FMT64"u\n", stats->st_atime, attr->accessTime, stats->st_mtime, attr->writeTime, stats->st_ctime, attr->attrChangeTime)); #undef FMTTIMET attr->userId = stats->st_uid; attr->groupId = stats->st_gid; attr->hostFileId = stats->st_ino; attr->volumeId = stats->st_dev; attr->mask = HGFS_ATTR_VALID_TYPE | HGFS_ATTR_VALID_SIZE | HGFS_ATTR_VALID_ALLOCATION_SIZE | HGFS_ATTR_VALID_CREATE_TIME | HGFS_ATTR_VALID_ACCESS_TIME | HGFS_ATTR_VALID_WRITE_TIME | HGFS_ATTR_VALID_CHANGE_TIME | HGFS_ATTR_VALID_SPECIAL_PERMS | HGFS_ATTR_VALID_OWNER_PERMS | HGFS_ATTR_VALID_GROUP_PERMS | HGFS_ATTR_VALID_OTHER_PERMS | HGFS_ATTR_VALID_USERID | HGFS_ATTR_VALID_GROUPID | HGFS_ATTR_VALID_FILEID | HGFS_ATTR_VALID_VOLID; } /* *----------------------------------------------------------------------------- * * HgfsSetattrMode -- * * Set the permissions based on stat and attributes. * * Results: * TRUE if permissions have changed. * FALSE otherwise. * * Note that newPermissions is always set. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsSetattrMode(struct stat *statBuf, // IN: stat info HgfsFileAttrInfo *attr, // IN: attrs to set mode_t *newPermissions) // OUT: new perms { Bool permsChanged = FALSE; ASSERT(statBuf); ASSERT(attr); ASSERT(newPermissions); *newPermissions = 0; if (attr->mask & HGFS_ATTR_VALID_SPECIAL_PERMS) { *newPermissions |= attr->specialPerms << 9; permsChanged = TRUE; } else { *newPermissions |= statBuf->st_mode & (S_ISUID | S_ISGID | S_ISVTX); } if (attr->mask & HGFS_ATTR_VALID_OWNER_PERMS) { *newPermissions |= attr->ownerPerms << 6; permsChanged = TRUE; } else { *newPermissions |= statBuf->st_mode & S_IRWXU; } if (attr->mask & HGFS_ATTR_VALID_GROUP_PERMS) { *newPermissions |= attr->groupPerms << 3; permsChanged = TRUE; } else { *newPermissions |= statBuf->st_mode & S_IRWXG; } if (attr->mask & HGFS_ATTR_VALID_OTHER_PERMS) { *newPermissions |= attr->otherPerms; permsChanged = TRUE; } else { *newPermissions |= statBuf->st_mode & S_IRWXO; } return permsChanged; } /* *----------------------------------------------------------------------------- * * HgfsSetattrOwnership -- * * Set the user and group ID based the attributes. * * Results: * TRUE if ownership has changed. * FALSE otherwise. * * Note that newUid/newGid are always set. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsSetattrOwnership(HgfsFileAttrInfo *attr, // IN: attrs to set uid_t *newUid, // OUT: new user ID gid_t *newGid) // OUT: new group ID { Bool idChanged = FALSE; ASSERT(attr); ASSERT(newUid); ASSERT(newGid); *newUid = *newGid = -1; if (attr->mask & HGFS_ATTR_VALID_USERID) { *newUid = attr->userId; idChanged = TRUE; } if (attr->mask & HGFS_ATTR_VALID_GROUPID) { *newGid = attr->groupId; idChanged = TRUE; } return idChanged; } /* *----------------------------------------------------------------------------- * * HgfsSetattrTimes -- * * Set the time stamps based on stat and attributes. * * Results: * Zero on success. accessTime/modTime contain new times. * Non-zero on failure. * * Note that timesChanged is always set. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsSetattrTimes(struct stat *statBuf, // IN: stat info HgfsFileAttrInfo *attr, // IN: attrs to set HgfsAttrHint hints, // IN: attr hints Bool useHostTime, // IN: use the current host time struct timeval *accessTime, // OUT: access time struct timeval *modTime, // OUT: modification time Bool *timesChanged) // OUT: times changed { HgfsInternalStatus status = 0; int error; ASSERT(statBuf); ASSERT(attr); ASSERT(accessTime); ASSERT(modTime); ASSERT(timesChanged); *timesChanged = FALSE; if (attr->mask & (HGFS_ATTR_VALID_ACCESS_TIME | HGFS_ATTR_VALID_WRITE_TIME)) { /* * utime(2) only lets you update both atime and mtime at once, so * if either one needs updating, first we get the current times * and call utime with some combination of the current and new * times. This is a bit racy because someone else could update * one of them in between, but this seems to be how "touch" does * things, so we'll go with it. [bac] */ if ((attr->mask & (HGFS_ATTR_VALID_ACCESS_TIME | HGFS_ATTR_VALID_WRITE_TIME)) != (HGFS_ATTR_VALID_ACCESS_TIME | HGFS_ATTR_VALID_WRITE_TIME)) { /* * XXX Set also usec from nsec stat fields. */ accessTime->tv_sec = statBuf->st_atime; accessTime->tv_usec = 0; modTime->tv_sec = statBuf->st_mtime; modTime->tv_usec = 0; } /* * If times need updating, we either use the guest-provided time or the * host time. HGFS_ATTR_HINT_SET_x_TIME_ will be set if we should use * the guest time, and useHostTime will be TRUE if the config * option to always use host time is set. */ if (attr->mask & HGFS_ATTR_VALID_ACCESS_TIME) { if (!useHostTime && (hints & HGFS_ATTR_HINT_SET_ACCESS_TIME)) { /* Use the guest-provided time */ struct timespec ts; HgfsConvertFromNtTimeNsec(&ts, attr->accessTime); accessTime->tv_sec = ts.tv_sec; accessTime->tv_usec = ts.tv_nsec / 1000; } else { /* Use the host's time */ struct timeval tv; if (gettimeofday(&tv, NULL) != 0) { error = errno; LOG(4, ("%s: gettimeofday error: %s\n", __FUNCTION__, Err_Errno2String(error))); status = error; goto exit; } accessTime->tv_sec = tv.tv_sec; accessTime->tv_usec = tv.tv_usec; } } if (attr->mask & HGFS_ATTR_VALID_WRITE_TIME) { if (!useHostTime && (hints & HGFS_ATTR_HINT_SET_WRITE_TIME)) { struct timespec ts; HgfsConvertFromNtTimeNsec(&ts, attr->writeTime); modTime->tv_sec = ts.tv_sec; modTime->tv_usec = ts.tv_nsec / 1000; } else { struct timeval tv; if (gettimeofday(&tv, NULL) != 0) { error = errno; LOG(4, ("%s: gettimeofday error: %s\n", __FUNCTION__, Err_Errno2String(error))); status = error; goto exit; } modTime->tv_sec = tv.tv_sec; modTime->tv_usec = tv.tv_usec; } } *timesChanged = TRUE; } exit: return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformSetattrFromFd -- * * Handle a Setattr request by file descriptor. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformSetattrFromFd(HgfsHandle file, // IN: file descriptor HgfsSessionInfo *session, // IN: session info HgfsFileAttrInfo *attr, // OUT: attrs to set HgfsAttrHint hints, // IN: attr hints Bool useHostTime) // IN: use current host time { HgfsInternalStatus status = 0, timesStatus; int error; struct stat statBuf; struct timeval times[2]; mode_t newPermissions; uid_t newUid = -1; gid_t newGid = -1; Bool permsChanged = FALSE; Bool timesChanged = FALSE; Bool idChanged = FALSE; int fd; HgfsLockType serverLock; ASSERT(session); ASSERT(file != HGFS_INVALID_HANDLE); status = HgfsPlatformGetFd(file, session, FALSE, &fd); if (status != 0) { LOG(4, ("%s: Could not get file descriptor\n", __FUNCTION__)); goto exit; } /* We need the old stats so that we can preserve times. */ if (fstat(fd, &statBuf) == -1) { error = errno; LOG(4, ("%s: error stating file %u: %s\n", __FUNCTION__, fd, Err_Errno2String(error))); status = error; goto exit; } /* * Try to make each requested attribute change. In the event that * one operation fails, we still attempt to perform any other * operations that the driver requested. We return success only * if all operations succeeded. */ idChanged = HgfsSetattrOwnership(attr, &newUid, &newGid); if (idChanged) { LOG(4, ("%s: set uid %"FMTUID" and gid %"FMTUID"\n", __FUNCTION__, newUid, newGid)); if (fchown(fd, newUid, newGid) < 0) { error = errno; LOG(4, ("%s: error chowning file %u: %s\n", __FUNCTION__, fd, Err_Errno2String(error))); status = error; } } /* * Set permissions based on what we got in the packet. If we didn't get * a particular bit, use the existing permissions. In that case we don't * toggle permsChanged since it should not influence our decision of * whether to actually call chmod or not. * * NOTE: Setting ownership clears SUID and SGID bits, therefore set the * file permissions after setting ownership. */ permsChanged = HgfsSetattrMode(&statBuf, attr, &newPermissions); if (permsChanged) { LOG(4, ("%s: set mode %o\n", __FUNCTION__, (unsigned)newPermissions)); if (fchmod(fd, newPermissions) < 0) { error = errno; LOG(4, ("%s: error chmoding file %u: %s\n", __FUNCTION__, fd, Err_Errno2String(error))); status = error; } } if (attr->mask & HGFS_ATTR_VALID_SIZE) { /* * XXX: Truncating the file will trigger an oplock break. The client * should have predicted this and removed the oplock prior to sending * the truncate request. At this point, the server must safeguard itself * against deadlock. */ if (!HgfsHandle2ServerLock(file, session, &serverLock)) { LOG(4, ("%s: File handle is no longer valid.\n", __FUNCTION__)); status = EBADF; } else if (serverLock != HGFS_LOCK_NONE) { LOG(4, ("%s: Client attempted to truncate an oplocked file\n", __FUNCTION__)); status = EBUSY; } else if (ftruncate(fd, attr->size) < 0) { error = errno; LOG(4, ("%s: error truncating file %u: %s\n", __FUNCTION__, fd, Err_Errno2String(error))); status = error; } else { LOG(4, ("%s: set size %"FMT64"u\n", __FUNCTION__, attr->size)); } } /* Setting hidden attribute for symlink itself is not supported. */ if ((attr->mask & HGFS_ATTR_VALID_FLAGS) && !S_ISLNK(statBuf.st_mode)) { char *localName; size_t localNameSize; if (HgfsHandle2FileName(file, session, &localName, &localNameSize)) { status = HgfsSetHiddenXAttr(localName, (attr->flags & HGFS_ATTR_HIDDEN) != 0, newPermissions); free(localName); } } timesStatus = HgfsSetattrTimes(&statBuf, attr, hints, useHostTime, ×[0], ×[1], ×Changed); if (timesStatus == 0 && timesChanged) { uid_t uid = (uid_t)-1; Bool switchToSuperUser = FALSE; LOG(4, ("%s: setting new times\n", __FUNCTION__)); /* * If the VMX is neither the file owner nor running as root, return an error. * Otherwise if we are not the file owner switch to superuser briefly * to set the files times using futimes. */ if (geteuid() != statBuf.st_uid) { /* We are not the file owner. Check if we are running as root. */ if (!Id_IsSuperUser()) { LOG(4, ("%s: only owner of file %u or root can call futimes\n", __FUNCTION__, fd)); /* XXX: Linux kernel says both EPERM and EACCES are valid here. */ status = EPERM; goto exit; } uid = Id_BeginSuperUser(); switchToSuperUser = TRUE; } /* * XXX Newer glibc provide also lutimes() and futimes() * when we politely ask with -D_GNU_SOURCE -D_BSD_SOURCE */ if (futimes(fd, times) < 0) { if (!switchToSuperUser) { /* * Check bug 718252. If futimes() fails, switch to * superuser briefly and try futimes() one more time. */ uid = Id_BeginSuperUser(); switchToSuperUser = TRUE; if (futimes(fd, times) < 0) { error = errno; LOG(4, ("%s: Executing futimes as owner on file: %u " "failed with error: %s\n", __FUNCTION__, fd, Err_Errno2String(error))); status = error; } } else { error = errno; LOG(4, ("%s: Executing futimes as superuser on file: %u " "failed with error: %s\n", __FUNCTION__, fd, Err_Errno2String(error))); status = error; } } if (switchToSuperUser) { Id_EndSuperUser(uid); } } else if (timesStatus != 0) { status = timesStatus; } exit: return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformSetattrFromName -- * * Handle a Setattr request by name. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformSetattrFromName(char *localName, // IN: Name HgfsFileAttrInfo *attr, // IN: attrs to set HgfsShareOptions configOptions, // IN: share options HgfsAttrHint hints, // IN: attr hints Bool useHostTime) // IN: use current host time { HgfsInternalStatus status = 0, timesStatus; struct stat statBuf; struct timeval times[2]; mode_t newPermissions; uid_t newUid = -1; gid_t newGid = -1; Bool permsChanged = FALSE; Bool timesChanged = FALSE; Bool idChanged = FALSE; int error; ASSERT(localName); if (!HgfsServerPolicy_IsShareOptionSet(configOptions, HGFS_SHARE_FOLLOW_SYMLINKS)) { /* * If followSymlink option is not set, verify that the pathname isn't a * symlink. Some of the following syscalls (chmod, for example) will * follow a link. So we need to verify the final component too. The * parent has already been verified in HgfsServerGetAccess. * * XXX: This is racy. But clients interested in preventing a race should * have sent us a Setattr packet with a valid HGFS handle. */ if (File_IsSymLink(localName)) { LOG(4, ("%s: pathname contains a symlink\n", __FUNCTION__)); status = EINVAL; goto exit; } } LOG(4, ("%s: setting attrs for \"%s\"\n", __FUNCTION__, localName)); /* We need the old stats so that we can preserve times. */ if (Posix_Lstat(localName, &statBuf) == -1) { error = errno; LOG(4, ("%s: error stating file \"%s\": %s\n", __FUNCTION__, localName, Err_Errno2String(error))); status = error; goto exit; } /* * Try to make each requested attribute change. In the event that * one operation fails, we still attempt to perform any other * operations that the driver requested. We return success only * if all operations succeeded. */ idChanged = HgfsSetattrOwnership(attr, &newUid, &newGid); /* * Chown changes the uid and gid together. If one of them should * not be changed, we pass in -1. */ if (idChanged) { if (Posix_Lchown(localName, newUid, newGid) < 0) { error = errno; LOG(4, ("%s: error chowning file \"%s\": %s\n", __FUNCTION__, localName, Err_Errno2String(error))); status = error; } } /* * Set permissions based on what we got in the packet. If we didn't get * a particular bit, use the existing permissions. In that case we don't * toggle permsChanged since it should not influence our decision of * whether to actually call chmod or not. * * NOTE: Setting ownership clears SUID and SGID bits, therefore set the * file permissions after setting ownership. */ permsChanged = HgfsSetattrMode(&statBuf, attr, &newPermissions); if (permsChanged) { LOG(4, ("%s: set mode %o\n", __FUNCTION__, (unsigned)newPermissions)); if (Posix_Chmod(localName, newPermissions) < 0) { error = errno; LOG(4, ("%s: error chmoding file \"%s\": %s\n", __FUNCTION__, localName, Err_Errno2String(error))); status = error; } } if (attr->mask & HGFS_ATTR_VALID_SIZE) { if (Posix_Truncate(localName, attr->size) < 0) { error = errno; LOG(4, ("%s: error truncating file \"%s\": %s\n", __FUNCTION__, localName, Err_Errno2String(error))); status = error; } else { LOG(4, ("%s: set size %"FMT64"u\n", __FUNCTION__, attr->size)); } } if (attr->mask & HGFS_ATTR_VALID_FLAGS) { status = HgfsSetHiddenXAttr(localName, (attr->flags & HGFS_ATTR_HIDDEN) != 0, newPermissions); } timesStatus = HgfsSetattrTimes(&statBuf, attr, hints, useHostTime, ×[0], ×[1], ×Changed); if (timesStatus == 0 && timesChanged) { /* * XXX Newer glibc provide also lutimes() and futimes() * when we politely ask with -D_GNU_SOURCE -D_BSD_SOURCE */ if (Posix_Utimes(localName, times) < 0) { error = errno; LOG(4, ("%s: utimes error on file \"%s\": %s\n", __FUNCTION__, localName, Err_Errno2String(error))); status = error; } } else if (timesStatus != 0) { status = timesStatus; } exit: return status; } HgfsInternalStatus HgfsPlatformWriteWin32Stream(HgfsHandle file, // IN: packet header char *dataToWrite, // IN: request type size_t requiredSize, Bool doSecurity, uint32 *actualSize, HgfsSessionInfo *session) { return EPROTO; } /* *----------------------------------------------------------------------------- * * HgfsPlatformVDirStatsFs -- * * Handle a statfs (query volume information) request for a virtual folder. * * Results: * HGFS_ERROR_SUCCESS or an appropriate error code. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformVDirStatsFs(HgfsSessionInfo *session, // IN: session info HgfsNameStatus nameStatus, // IN: VolumeInfoType infoType, // IN: uint64 *outFreeBytes, // OUT: uint64 *outTotalBytes) // OUT: { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; HgfsInternalStatus firstErr = HGFS_ERROR_SUCCESS; Bool firstShare = TRUE; size_t failed = 0; size_t shares = 0; DirectoryEntry *dent; HgfsHandle handle; ASSERT(nameStatus != HGFS_NAME_STATUS_COMPLETE); switch (nameStatus) { case HGFS_NAME_STATUS_INCOMPLETE_BASE: /* * This is the base of our namespace. Clients can request a * QueryVolumeInfo on it, on individual shares, or on just about * any pathname. */ LOG(4,("%s: opened search on base\n", __FUNCTION__)); status = HgfsServerSearchVirtualDir(HgfsServerResEnumGet, HgfsServerResEnumInit, HgfsServerResEnumExit, DIRECTORY_SEARCH_TYPE_BASE, session, &handle); if (status != HGFS_ERROR_SUCCESS) { break; } /* * Now go through all shares and get share paths on the server. * Then retrieve space info for each share's volume. */ while ((status = HgfsServerGetDirEntry(handle, session, HGFS_SEARCH_LAST_ENTRY_INDEX, TRUE, &dent)) == HGFS_ERROR_SUCCESS) { char const *sharePath; size_t sharePathLen; uint64 currentFreeBytes = 0; uint64 currentTotalBytes = 0; size_t length; if (NULL == dent) { break; } length = strlen(dent->d_name); /* * Now that the server is passing '.' and ".." around as dents, we * need to make sure to handle them properly. In particular, they * should be ignored within QueryVolume, as they're not real shares. */ if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) { LOG(4, ("%s: Skipping fake share %s\n", __FUNCTION__, dent->d_name)); free(dent); continue; } /* * The above check ignores '.' and '..' so we do not include them in * the share count here. */ shares++; /* * Check permission on the share and get the share path. It is not * fatal if these do not succeed. Instead we ignore the failures * (apart from logging them) until we have processed all shares. Only * then do we check if there were any failures; if all shares failed * to process then we bail out with an error code. */ nameStatus = HgfsServerPolicy_GetSharePath(dent->d_name, length, HGFS_OPEN_MODE_READ_ONLY, &sharePathLen, &sharePath); free(dent); if (nameStatus != HGFS_NAME_STATUS_COMPLETE) { LOG(4, ("%s: No such share or access denied\n", __FUNCTION__)); if (0 == firstErr) { firstErr = HgfsPlatformConvertFromNameStatus(nameStatus); } failed++; continue; } /* * Pick the drive with amount of space available and return that * according to different volume info type. */ if (!HgfsServerStatFs(sharePath, sharePathLen, ¤tFreeBytes, ¤tTotalBytes)) { LOG(4, ("%s: error getting volume information\n", __FUNCTION__)); if (0 == firstErr) { firstErr = HGFS_ERROR_IO; } failed++; continue; } /* * Pick the drive with amount of space available and return that * according to different volume info type. */ switch (infoType) { case VOLUME_INFO_TYPE_MIN: if ((*outFreeBytes > currentFreeBytes) || firstShare) { firstShare = FALSE; *outFreeBytes = currentFreeBytes; *outTotalBytes = currentTotalBytes; } break; case VOLUME_INFO_TYPE_MAX: if ((*outFreeBytes < currentFreeBytes)) { *outFreeBytes = currentFreeBytes; *outTotalBytes = currentTotalBytes; } break; default: NOT_IMPLEMENTED(); } } if (!HgfsRemoveSearch(handle, session)) { LOG(4, ("%s: could not close search on base\n", __FUNCTION__)); } if (shares == failed) { if (firstErr != 0) { /* * We failed to query any of the shares. We return the error] * from the first share failure. */ status = firstErr; } /* No shares but no error, return zero for sizes and success. */ } break; default: LOG(4,("%s: file access check failed\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } return status; } #ifdef VMX86_LOG /* *----------------------------------------------------------------------------- * * HgfsPlatformDirDumpDents -- * * Dump a set of directory entries (debugging code). * Note: this must be called with the session search lock acquired. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsPlatformDirDumpDents(HgfsSearch *search) // IN: search { unsigned int i; ASSERT(search != NULL); Log("%s: %u dents in \"%s\"\n", __FUNCTION__, search->numDents, search->utf8Dir); for (i = 0; i < search->numDents; i++) { Log("\"%s\"\n", search->dents[i]->d_name); } } #endif /* *----------------------------------------------------------------------------- * * HgfsConvertToUtf8FormC -- * * Converts file name coming from OS to Utf8 form C. * The function NOOP on Linux where the name is already in correct * encoding. * On Mac OS the default encoding is Utf8 form D thus a convertion to * Utf8 for C is required. * * Results: * TRUE on success. Buffer has name in Utf8 form C encoding. * FALSE on error. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsConvertToUtf8FormC(char *buffer, // IN/OUT: name to normalize size_t bufferSize) // IN: size of the name buffer { #if defined(__APPLE__) size_t entryNameLen; char *entryName = NULL; Bool result; /* * HGFS clients receive names in unicode normal form C, * (precomposed) so Mac hosts must convert from normal form D * (decomposed). */ if (CodeSet_Utf8FormDToUtf8FormC(buffer, bufferSize, &entryName, &entryNameLen)) { result = entryNameLen < bufferSize; if (result) { memcpy(buffer, entryName, entryNameLen + 1); } free(entryName); } else { LOG(4, ("%s: Unable to normalize form C \"%s\"\n", __FUNCTION__, buffer)); result = FALSE; } return result; #else size_t size; /* * Buffer may contain invalid data after the null terminating character. * We need to check the validity of the buffer only till the null * terminating character (if any). Calculate the real size of the * string before calling Unicode_IsBufferValid(). */ for (size = 0; size < bufferSize ; size++) { if ('\0' == buffer[size]) { break; } } return Unicode_IsBufferValid(buffer, size, STRING_ENCODING_UTF8); #endif /* defined(__APPLE__) */ } /* *----------------------------------------------------------------------------- * * HgfsPlatformGetDirEntry -- * * Returns the directory entry (or a copy) at the given index. If remove is set * to TRUE, the existing result is also pruned and the remaining results * are shifted up in the result array. * * Results: * HGFS_ERROR_SUCCESS or an appropriate error code. * * Side effects: * None. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformGetDirEntry(HgfsSearch *search, // IN: search HgfsSessionInfo *session, // IN: Session info uint32 index, // IN: Offset to retrieve at Bool remove, // IN: If true, removes the result struct DirectoryEntry **dirEntry) // OUT: dirent { DirectoryEntry *dent = NULL; HgfsInternalStatus status = HGFS_ERROR_SUCCESS; if (index >= search->numDents) { goto out; } /* If we're not removing the result, we need to make a copy of it. */ if (remove) { /* * We're going to shift the dents array, overwriting the dent pointer at * offset, so first we need to save said pointer so that we can return it * later to the caller. */ dent = search->dents[index]; if (index < search->numDents - 1) { /* Shift up the remaining results */ memmove(&search->dents[index], &search->dents[index + 1], (search->numDents - (index + 1)) * sizeof search->dents[0]); } /* Decrement the number of results */ search->numDents--; } else { DirectoryEntry *originalDent; size_t nameLen; originalDent = search->dents[index]; ASSERT(originalDent); nameLen = strlen(originalDent->d_name); /* * Make sure the name will not overrun the d_name buffer, the end of * which is also the end of the DirectoryEntry. */ ASSERT(offsetof(DirectoryEntry, d_name) + nameLen < originalDent->d_reclen); dent = malloc(originalDent->d_reclen); if (dent == NULL) { status = HGFS_ERROR_NOT_ENOUGH_MEMORY; goto out; } /* * Yes, there are more members than this in a dirent. But if you look * at the top of hgfsServerInt.h, you'll see that on Windows we only * define d_reclen and d_name, as those are the only fields we need. */ dent->d_reclen = originalDent->d_reclen; memcpy(dent->d_name, originalDent->d_name, nameLen); dent->d_name[nameLen] = 0; } out: if (status == HGFS_ERROR_SUCCESS) { *dirEntry = dent; } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformSetDirEntry -- * * Sets the directory entry into the search read information. * * Results: * HGFS_ERROR_SUCCESS or an appropriate error code. * * Side effects: * None. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformSetDirEntry(HgfsSearch *search, // IN: partially valid search HgfsShareOptions configOptions, // IN: share configuration settings HgfsSessionInfo *session, // IN: session info struct DirectoryEntry *dirEntry, // IN: the indexed dirent Bool getAttr, // IN: get the entry attributes HgfsFileAttrInfo *entryAttr, // OUT: entry attributes, optional char **entryName, // OUT: entry name uint32 *entryNameLength) // OUT: entry name length { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; unsigned int length; char *fullName; char *sharePath; size_t sharePathLen; size_t fullNameLen; HgfsLockType serverLock = HGFS_LOCK_NONE; fileDesc fileDesc; Bool unescapeName = TRUE; length = strlen(dirEntry->d_name); /* Each type of search gets a dent's attributes in a different way. */ switch (search->type) { case DIRECTORY_SEARCH_TYPE_DIR: /* * Construct the UTF8 version of the full path to the file, and call * HgfsGetattrFromName to get the attributes of the file. */ fullNameLen = search->utf8DirLen + 1 + length; fullName = (char *)malloc(fullNameLen + 1); if (fullName) { memcpy(fullName, search->utf8Dir, search->utf8DirLen); fullName[search->utf8DirLen] = DIRSEPC; memcpy(&fullName[search->utf8DirLen + 1], dirEntry->d_name, length + 1); LOG(4, ("%s: about to stat \"%s\"\n", __FUNCTION__, fullName)); /* Do we need to query the attributes information? */ if (getAttr) { /* * XXX: It is unreasonable to make the caller either 1) pass existing * handles for directory objects as part of the SearchRead, or 2) * prior to calling SearchRead on a directory, break all oplocks on * that directory's objects. * * To compensate for that, if we detect that this directory object * has an oplock, we'll quietly reuse the handle. Note that this * requires clients who take out an exclusive oplock to open a * handle with read as well as write access, otherwise we'll fail * further down in HgfsStat. * * XXX: We could open a new handle safely if its a shared oplock. * But isn't this handle sharing always desirable? */ if (HgfsFileHasServerLock(fullName, session, &serverLock, &fileDesc)) { LOG(4, ("%s: Reusing existing oplocked handle " "to avoid oplock break deadlock\n", __FUNCTION__)); status = HgfsPlatformGetattrFromFd(fileDesc, session, entryAttr); } else { status = HgfsPlatformGetattrFromName(fullName, configOptions, search->utf8ShareName, entryAttr, NULL); } if (HGFS_ERROR_SUCCESS != status) { HgfsOp savedOp = entryAttr->requestType; LOG(4, ("%s: stat FAILED %s (%d)\n", __FUNCTION__, fullName, status)); memset(entryAttr, 0, sizeof *entryAttr); entryAttr->requestType = savedOp; entryAttr->type = HGFS_FILE_TYPE_REGULAR; entryAttr->mask = HGFS_ATTR_VALID_TYPE; status = HGFS_ERROR_SUCCESS; } } free(fullName); } else { LOG(4, ("%s: could not allocate space for \"%s\\%s\"\n", __FUNCTION__, search->utf8Dir, dirEntry->d_name)); status = HGFS_ERROR_NOT_ENOUGH_MEMORY; } break; case DIRECTORY_SEARCH_TYPE_BASE: /* * We only want to unescape names that we could have escaped. * This cannot apply to our shares since they are created by the user. * The client will take care of escaping anything it requires. */ unescapeName = FALSE; if (getAttr) { /* * For a search enumerating all shares, give the default attributes * for '.' and ".." (which aren't really shares anyway). Each real * share gets resolved into its full path, and gets its attributes * via HgfsGetattrFromName. */ if (strcmp(dirEntry->d_name, ".") == 0 || strcmp(dirEntry->d_name, "..") == 0) { LOG(4, ("%s: assigning %s default attributes\n", __FUNCTION__, dirEntry->d_name)); HgfsPlatformGetDefaultDirAttrs(entryAttr); } else { HgfsNameStatus nameStatus; /* Check permission on the share and get the share path */ nameStatus = HgfsServerPolicy_GetSharePath(dirEntry->d_name, length, HGFS_OPEN_MODE_READ_ONLY, &sharePathLen, (char const **)&sharePath); if (nameStatus == HGFS_NAME_STATUS_COMPLETE) { /* * Server needs to produce list of shares that is consistent with * the list defined in UI. If a share can't be accessed because of * problems on the host, the server still enumerates it and * returns to the client. * XXX: We will open a new handle for this, but it should be safe * from oplock-induced deadlock because these are all directories, * and thus cannot have oplocks placed on them. */ status = HgfsPlatformGetattrFromName(sharePath, configOptions, dirEntry->d_name, entryAttr, NULL); if (HGFS_ERROR_SUCCESS != status) { /* * The dent no longer exists. Log the event. */ LOG(4, ("%s: stat FAILED\n", __FUNCTION__)); status = HGFS_ERROR_SUCCESS; } } else { LOG(4, ("%s: No such share or access denied\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } } } break; case DIRECTORY_SEARCH_TYPE_OTHER: default: NOT_IMPLEMENTED(); break; } /* * We need to unescape the name before sending it back to the client */ if (HGFS_ERROR_SUCCESS == status) { *entryName = Util_SafeStrdup(dirEntry->d_name); if (unescapeName) { *entryNameLength = HgfsEscape_Undo(*entryName, length + 1); } else { *entryNameLength = length; } LOG(4, ("%s: dent name is \"%s\" len = %u\n", __FUNCTION__, *entryName, *entryNameLength)); } else { *entryName = NULL; *entryNameLength = 0; LOG(4, ("%s: error %d getting dent\n", __FUNCTION__, status)); } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformScandir -- * * The cross-platform HGFS server code will call into this function * in order to populate a list of dents. In the Linux case, we want to avoid * using scandir(3) because it makes no provisions for not following * symlinks. Instead, we'll open(2) the directory with O_DIRECTORY and * O_NOFOLLOW, call getdents(2) directly, then close(2) the directory. * * On Mac OS getdirentries became deprecated starting from 10.6 and * there is no similar API available. Thus on Mac OS readdir is used that * returns one directory entry at a time. * * Results: * Zero on success. numDents contains the number of directory entries found. * Non-zero on error. * * Side effects: * Memory allocation. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformScandir(char const *baseDir, // IN: Directory to search in size_t baseDirLen, // IN: Ignored Bool followSymlinks, // IN: followSymlinks config option struct DirectoryEntry ***dents, // OUT: Array of DirectoryEntrys int *numDents) // OUT: Number of DirectoryEntrys { #if defined(__APPLE__) DIR *fd = NULL; #else int fd = -1; int openFlags = O_NONBLOCK | O_RDONLY | O_DIRECTORY | O_NOFOLLOW; #endif int result; DirectoryEntry **myDents = NULL; int myNumDents = 0; HgfsInternalStatus status = 0; /* * XXX: glibc uses 8192 (BUFSIZ) when it can't get st_blksize from a stat. * Should we follow its lead and use stat to get st_blksize? */ char buffer[8192]; #if defined(__APPLE__) /* * Since opendir does not support O_NOFOLLOW flag need to explicitly verify * that we are not dealing with symlink if follow symlinks is * not allowed. */ if (!followSymlinks) { struct stat st; if (lstat(baseDir, &st) == -1) { status = errno; LOG(4, ("%s: error in lstat: %d (%s)\n", __FUNCTION__, status, Err_Errno2String(status))); goto exit; } if (S_ISLNK(st.st_mode)) { status = EACCES; LOG(4, ("%s: do not follow symlink\n", __FUNCTION__)); goto exit; } } fd = Posix_OpenDir(baseDir); if (NULL == fd) { status = errno; LOG(4, ("%s: error in opendir: %d (%s)\n", __FUNCTION__, status, Err_Errno2String(status))); goto exit; } #else /* Follow symlinks if config option is set. */ if (followSymlinks) { openFlags &= ~O_NOFOLLOW; } /* We want a directory. No FIFOs. Symlinks only if config option is set. */ result = Posix_Open(baseDir, openFlags); if (result < 0) { status = errno; LOG(4, ("%s: error in open: %d (%s)\n", __FUNCTION__, status, Err_Errno2String(status))); goto exit; } fd = result; #endif /* * Rather than read a single dent at a time, batch up multiple dents * in each call by using a buffer substantially larger than one dent. */ while ((result = getdents(fd, (void *)buffer, sizeof buffer)) > 0) { size_t offset = 0; while (offset < result) { DirectoryEntry *newDent, **newDents; newDent = (DirectoryEntry *)(buffer + offset); /* This dent had better fit in the actual space we've got left. */ ASSERT(newDent->d_reclen <= result - offset); /* Add another dent pointer to the dents array. */ newDents = realloc(myDents, sizeof *myDents * (myNumDents + 1)); if (newDents == NULL) { status = ENOMEM; goto exit; } myDents = newDents; /* * Allocate the new dent and set it up. We do a straight memcpy of * the entire record to avoid dealing with platform-specific fields. */ myDents[myNumDents] = malloc(newDent->d_reclen); if (myDents[myNumDents] == NULL) { status = ENOMEM; goto exit; } if (HgfsConvertToUtf8FormC(newDent->d_name, newDent->d_reclen - offsetof(DirectoryEntry, d_name))) { memcpy(myDents[myNumDents], newDent, newDent->d_reclen); /* * Dent is done. Bump the offset to the batched buffer to process the * next dent within it. */ myNumDents++; } else { /* * XXX: * HGFS discards all file names that can't be converted to utf8. * It is not desirable since it causes many problems like * failure to delete directories which contain such files. * Need to change this to a more reasonable behavior, similar * to name escaping which is used to deal with illegal file names. */ free(myDents[myNumDents]); } offset += newDent->d_reclen; } } if (result == -1) { status = errno; LOG(4, ("%s: error in getdents: %d (%s)\n", __FUNCTION__, status, Err_Errno2String(status))); goto exit; } exit: #if defined(__APPLE__) if (NULL != fd && closedir(fd) < 0) { #else if (fd != -1 && close(fd) < 0) { #endif status = errno; LOG(4, ("%s: error in close: %d (%s)\n", __FUNCTION__, status, Err_Errno2String(status))); } /* * On error, free all allocated dents. On success, set the dents pointer * given to us by the client. */ if (status != 0) { size_t i; for (i = 0; i < myNumDents; i++) { free(myDents[i]); } free(myDents); } else { *dents = myDents; *numDents = myNumDents; } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformScanvdir -- * * Perform a scandir on our virtual directory. * * Get directory entry names from the given callback function, and * build an array of DirectoryEntrys of all the names. Somewhat similar to * scandir(3) on linux, but more general. * * Results: * On success, the number of directory entries found. * On failure, negative error. * * Side effects: * Memory allocation. * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformScanvdir(HgfsServerResEnumGetFunc enumNamesGet, // IN: Function to get name HgfsServerResEnumInitFunc enumNamesInit, // IN: Setup function HgfsServerResEnumExitFunc enumNamesExit, // IN: Cleanup function DirectorySearchType type, // IN: Kind of search - unused struct DirectoryEntry ***dents, // OUT: Array of DirectoryEntrys uint32 *numDents) // OUT: total number of directory entrys { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; uint32 totalDents = 0; // Number of allocated dents uint32 myNumDents = 0; // Current actual number of dents DirectoryEntry **myDents = NULL; // So realloc is happy w/ zero myNumDents void *enumNamesHandle; ASSERT(NULL != enumNamesInit); ASSERT(NULL != enumNamesGet); ASSERT(NULL != enumNamesExit); enumNamesHandle = enumNamesInit(); if (NULL == enumNamesHandle) { status = HGFS_ERROR_NOT_ENOUGH_MEMORY; LOG(4, ("%s: Error: init state ret %u\n", __FUNCTION__, status)); goto exit; } for (;;) { DirectoryEntry *currentEntry; char const *currentEntryName; size_t currentEntryNameLen; size_t currentEntryLen; size_t maxNameLen; Bool done = FALSE; /* Add '.' and ".." as the first dents. */ if (myNumDents == 0) { currentEntryName = "."; currentEntryNameLen = 1; } else if (myNumDents == 1) { currentEntryName = ".."; currentEntryNameLen = 2; } else { if (!enumNamesGet(enumNamesHandle, ¤tEntryName, ¤tEntryNameLen, &done)) { status = HGFS_ERROR_INVALID_PARAMETER; LOG(4, ("%s: Error: get next entry name ret %u\n", __FUNCTION__, status)); goto exit; } } if (done) { LOG(4, ("%s: No more names\n", __FUNCTION__)); break; } #if defined(sun) /* * Solaris lacks a single definition of NAME_MAX and using pathconf(), to * determine NAME_MAX for the current directory, is too cumbersome for * our purposes, so we use PATH_MAX as a reasonable upper bound on the * length of the name. */ maxNameLen = PATH_MAX; #else maxNameLen = sizeof currentEntry->d_name; #endif if (currentEntryNameLen >= maxNameLen) { Log("%s: Error: Name \"%s\" is too long.\n", __FUNCTION__, currentEntryName); continue; } /* See if we need to allocate more memory */ if (myNumDents == totalDents) { void *p; if (totalDents != 0) { totalDents *= 2; } else { totalDents = 100; } p = realloc(myDents, totalDents * sizeof *myDents); if (NULL == p) { status = HGFS_ERROR_NOT_ENOUGH_MEMORY; LOG(4, ("%s: Error: realloc growing array memory ret %u\n", __FUNCTION__, status)); goto exit; } myDents = p; } /* This file/directory can be added to the list. */ LOG(4, ("%s: Nextfilename = \"%s\"\n", __FUNCTION__, currentEntryName)); /* * Start with the size of the DirectoryEntry struct, subtract the static * length of the d_name buffer (256 in Linux, 1 in Solaris, etc) and add * back just enough space for the UTF-8 name and nul terminator. */ currentEntryLen = offsetof(DirectoryEntry, d_name) + currentEntryNameLen + 1; currentEntry = malloc(currentEntryLen); if (NULL == currentEntry) { status = HGFS_ERROR_NOT_ENOUGH_MEMORY; LOG(4, ("%s: Error: allocate dentry memory ret %u\n", __FUNCTION__, status)); goto exit; } currentEntry->d_reclen = (unsigned short)currentEntryLen; memcpy(currentEntry->d_name, currentEntryName, currentEntryNameLen); currentEntry->d_name[currentEntryNameLen] = 0; myDents[myNumDents] = currentEntry; myNumDents++; } /* Trim extra memory off of dents */ { void *p; p = realloc(myDents, myNumDents * sizeof *myDents); if (NULL != p) { myDents = p; } else { LOG(4, ("%s: Error: realloc trimming array memory\n", __FUNCTION__)); } } *dents = myDents; *numDents = myNumDents; exit: if (NULL != enumNamesHandle) { /* Call the exit callback to teardown any state. */ if (!enumNamesExit(enumNamesHandle)) { LOG(4, ("%s: Error cleanup failed\n", __FUNCTION__)); } } if (HGFS_ERROR_SUCCESS != status) { unsigned int i; /* Free whatever has been allocated so far */ for (i = 0; i < myNumDents; i++) { free(myDents[i]); } free(myDents); } return status; } /* *---------------------------------------------------------------------- * * Request Handler Functions * ------------------------- * * The functions that follow are all of the same type: they take a * request packet which came from the driver, process it, and fill out * a reply packet which is then sent back to the driver. They are * called by DispatchPacket, which dispatches an incoming packet to * the correct handler function based on the packet's opcode. * * These functions all take the following as input: * * - A pointer to a buffer containing the incoming request packet, * - A pointer to a buffer big enough to hold the outgoing reply packet, * - A pointer to the size of the incoming packet, packetSize. * * After processing the request, the handler functions write the reply * packet into the output buffer and set the packetSize to be the size * of the OUTGOING reply packet. The ServerLoop function uses the size * to send the reply back to the driver. * * Note that it is potentially okay for the caller to use the same * buffer for both input and output; handler functions should make * sure they are safe w.r.t. this possibility by storing any state * from the input buffer before they clobber it by potentially writing * output into the same buffer. * * Handler functions should return zero if they successfully processed * the request, or a negative error if an unrecoverable error * occurred. Normal errors (e.g. a poorly formed request packet) * should be handled by sending an error packet back to the driver, * NOT by returning an error code to the caller, because errors * returned by handler functions cause the server to terminate. * * [bac] * *---------------------------------------------------------------------- */ /* *----------------------------------------------------------------------------- * * HgfsPlatformReadFile -- * * Reads data from a file. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformReadFile(fileDesc file, // IN: file descriptor HgfsSessionInfo *session, // IN: session info uint64 offset, // IN: file offset to read from uint32 requiredSize, // IN: length of data to read void* payload, // OUT: buffer for the read data uint32 *actualSize) // OUT: actual length read { int error; HgfsInternalStatus status = 0; HgfsHandle handle; Bool sequentialOpen; ASSERT(session); LOG(4, ("%s: read fh %u, offset %"FMT64"u, count %u\n", __FUNCTION__, file, offset, requiredSize)); if (!HgfsFileDesc2Handle(file, session, &handle)) { LOG(4, ("%s: Could not get file handle\n", __FUNCTION__)); return EBADF; } if (!HgfsHandleIsSequentialOpen(handle, session, &sequentialOpen)) { LOG(4, ("%s: Could not get sequenial open status\n", __FUNCTION__)); return EBADF; } #if defined(__linux__) || defined(__APPLE__) /* Read from the file. */ if (sequentialOpen) { error = read(file, payload, requiredSize); } else { error = pread(file, payload, requiredSize, offset); } #else /* * Seek to the offset and read from the file. Grab the IO lock to make * this and the subsequent read atomic. */ MXUser_AcquireExclLock(session->fileIOLock); if (sequentialOpen) { error = 0; // No error from seek } else { # ifdef linux { uint64 res; # if !defined(VM_X86_64) error = _llseek(file, offset >> 32, offset & 0xFFFFFFFF, &res, 0); # else error = llseek(file, offset >> 32, offset & 0xFFFFFFFF, &res, 0); # endif } # else error = lseek(file, offset, 0); # endif } if (error >= 0) { error = read(file, payload, requiredSize); } else { LOG(4, ("%s: could not seek to %"FMT64"u: %s\n", __FUNCTION__, offset, Err_Errno2String(status))); } MXUser_ReleaseExclLock(session->fileIOLock); #endif if (error < 0) { status = errno; LOG(4, ("%s: error reading from file: %s\n", __FUNCTION__, Err_Errno2String(status))); } else { LOG(4, ("%s: read %d bytes\n", __FUNCTION__, error)); *actualSize = error; } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformWriteFile -- * * Performs actual writing data to a file. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformWriteFile(fileDesc writeFd, // IN: file descriptor HgfsSessionInfo *session, // IN: session info uint64 writeOffset, // IN: file offset to write to uint32 writeDataSize, // IN: length of data to write HgfsWriteFlags writeFlags, // IN: write flags Bool writeSequential, // IN: write is sequential Bool writeAppend, // IN: write is appended const void *writeData, // IN: data to be written uint32 *writtenSize) // OUT: actual length written { HgfsInternalStatus status = 0; int error = 0; LOG(4, ("%s: write fh %u offset %"FMT64"u, count %u\n", __FUNCTION__, writeFd, writeOffset, writeDataSize)); #if !defined(sun) if (!writeSequential) { status = HgfsWriteCheckIORange(writeOffset, writeDataSize); if (status != 0) { return status; } } #endif #if defined(__linux__) /* Write to the file. */ if (writeSequential) { error = write(writeFd, writeData, writeDataSize); } else { error = pwrite(writeFd, writeData, writeDataSize, writeOffset); } #elif defined(__APPLE__) { /* Write to the file. */ if (writeSequential || writeAppend) { error = write(writeFd, writeData, writeDataSize); } else { error = pwrite(writeFd, writeData, writeDataSize, writeOffset); } } #else /* * Seek to the offset and write from the file. Grab the IO lock to make * this and the subsequent write atomic. */ MXUser_AcquireExclLock(session->fileIOLock); if (!writeSequential) { # ifdef linux { uint64 res; # if !defined(VM_X86_64) error = _llseek(writeFd, writeOffset >> 32, writeOffset & 0xFFFFFFFF, &res, 0); # else error = llseek(writeFd, writeOffset >> 32, writeOffset & 0xFFFFFFFF, &res, 0); # endif } # else error = lseek(writeFd, writeOffset, 0); # endif } if (error < 0) { LOG(4, ("%s: could not seek to %"FMT64"u: %s\n", __FUNCTION__, writeOffset, Err_Errno2String(errno))); } else { error = write(writeFd, writeData, writeDataSize); } { int savedErr = errno; MXUser_ReleaseExclLock(session->fileIOLock); errno = savedErr; } #endif if (error < 0) { status = errno; LOG(4, ("%s: error writing to file: %s\n", __FUNCTION__, Err_Errno2String(status))); } else { *writtenSize = error; LOG(4, ("%s: wrote %d bytes\n", __FUNCTION__, *writtenSize)); } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformSearchDir -- * * Handle platform specific logic needed to perform search open request. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformSearchDir(HgfsNameStatus nameStatus, // IN: name status const char *dirName, // IN: relative directory name size_t dirNameLength, // IN: length of dirName uint32 caseFlags, // IN: case flags HgfsShareInfo *shareInfo, // IN: sharfed folder information char *baseDir, // IN: name of the shared directory uint32 baseDirLen, // IN: length of the baseDir HgfsSessionInfo *session, // IN: session info HgfsHandle *handle) // OUT: search handle { HgfsInternalStatus status = 0; switch (nameStatus) { case HGFS_NAME_STATUS_COMPLETE: { const char *inEnd; const char *next; int len; ASSERT(baseDir); LOG(4, ("%s: searching in \"%s\", %s.\n", __FUNCTION__, baseDir, dirName)); inEnd = dirName + dirNameLength; /* Get the first component. */ len = CPName_GetComponent(dirName, inEnd, &next); if (len >= 0) { if (*inEnd != '\0') { LOG(4, ("%s: dir name not nul-terminated!\n", __FUNCTION__)); /* * NT4 clients can send the name without a nul-terminator. * The space for the nul is included and tested for in the size * calculations above. Size of structure (includes a single * character of the name) and the full dirname length. */ *(char *)inEnd = '\0'; } LOG(4, ("%s: dirName: %s.\n", __FUNCTION__, dirName)); status = HgfsServerSearchRealDir(baseDir, baseDirLen, dirName, shareInfo->rootDir, session, handle); } else { LOG(4, ("%s: get first component failed\n", __FUNCTION__)); status = ENOENT; } /* * If the directory exists but shared folder is write only * then return access denied, otherwise preserve the original * error code. */ if (!shareInfo->readPermissions && HGFS_NAME_STATUS_COMPLETE == status) { status = HGFS_NAME_STATUS_ACCESS_DENIED; } if (status != 0) { LOG(4, ("%s: couldn't scandir\n", __FUNCTION__)); } break; } case HGFS_NAME_STATUS_INCOMPLETE_BASE: /* * This is the base of our namespace, so enumerate all * shares. [bac] */ LOG(4, ("%s: opened search on base\n", __FUNCTION__)); status = HgfsServerSearchVirtualDir(HgfsServerResEnumGet, HgfsServerResEnumInit, HgfsServerResEnumExit, DIRECTORY_SEARCH_TYPE_BASE, session, handle); if (status != 0) { LOG(4, ("%s: couldn't enumerate shares\n", __FUNCTION__)); } break; default: LOG(4, ("%s: access check failed\n", __FUNCTION__)); status = HgfsPlatformConvertFromNameStatus(nameStatus); } if (status == 0) { HGFS_SERVER_DIR_DUMP_DENTS(*handle, session); } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformRestartSearchDir -- * * Handle platform specific restarting of a directory search. * * Results: * HGFS_ERROR_SUCCESS or an appropriate error code. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformRestartSearchDir(HgfsHandle handle, // IN: search handle HgfsSessionInfo *session, // IN: session info DirectorySearchType searchType) // IN: Kind of search { HgfsInternalStatus status; switch (searchType) { case DIRECTORY_SEARCH_TYPE_BASE: /* Entries are shares */ status = HgfsServerRestartSearchVirtualDir(HgfsServerResEnumGet, HgfsServerResEnumInit, HgfsServerResEnumExit, session, handle); break; case DIRECTORY_SEARCH_TYPE_OTHER: /* Entries of this type are unknown and not supported for this platform. */ case DIRECTORY_SEARCH_TYPE_DIR: /* Entries are files and subdirectories: currently not implemented! */ default: status = EINVAL; break; } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformHandleIncompleteName -- * * Returns platform error that matches HgfsNameStatus. * * Results: * Non-zero error code. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformHandleIncompleteName(HgfsNameStatus nameStatus, // IN: name status HgfsFileAttrInfo *attr) // OUT: unused { return HgfsPlatformConvertFromNameStatus(nameStatus); } /* *----------------------------------------------------------------------------- * * HgfsPlatformDeleteFileByName -- * * POSIX specific implementation of a delete file request which accepts * utf8 file path as a parameter. * * Simply calls Posix_Unlink. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformDeleteFileByName(char const *utf8Name) // IN: full file path in uf8 encoding { HgfsInternalStatus status; LOG(4, ("%s: unlinking \"%s\"\n", __FUNCTION__, utf8Name)); status = Posix_Unlink(utf8Name); if (status) { status = errno; LOG(4, ("%s: error: %s\n", __FUNCTION__, Err_Errno2String(status))); } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformDeleteFileByHandle -- * * POSIX specific implementation of a delete file request which accepts * HgfsHandle as a parameter. * * File handle must have appropriate access mode to allow file deletion. * Shared folder restrictions are enforced here as well. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformDeleteFileByHandle(HgfsHandle file, // IN: File being deleted HgfsSessionInfo *session) // IN: session info { HgfsInternalStatus status; Bool readPermissions; Bool writePermissions; char *localName; size_t localNameSize; if (HgfsHandle2FileNameMode(file, session, &writePermissions, &readPermissions, &localName, &localNameSize)) { if (writePermissions && readPermissions) { status = HgfsPlatformDeleteFileByName(localName); } else { status = EPERM; } free(localName); } else { LOG(4, ("%s: could not map cached file handle %u\n", __FUNCTION__, file)); status = EBADF; } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformDeleteDirByName -- * * POSIX specific implementation of a delete directory request which accepts * utf8 file path as a parameter. * * Simply calls Posix_Rmdir. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformDeleteDirByName(char const *utf8Name) // IN: full file path in uf8 encoding { HgfsInternalStatus status; LOG(4, ("%s: removing \"%s\"\n", __FUNCTION__, utf8Name)); status = Posix_Rmdir(utf8Name); if (status) { status = errno; LOG(4, ("%s: error: %s\n", __FUNCTION__, Err_Errno2String(status))); } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformDeleteDirByHandle -- * * POSIX specific implementation of a Delete directory request which accepts * HgfsHandle as a parameter. * * File handle must have appropriate access mode to allow file deletion. * Shared folder restrictions are enforced here as well. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformDeleteDirByHandle(HgfsHandle file, // IN: File being deleted HgfsSessionInfo *session) // IN: session info { HgfsInternalStatus status; Bool readPermissions; Bool writePermissions; char *localName; size_t localNameSize; if (HgfsHandle2FileNameMode(file, session, &writePermissions, &readPermissions, &localName, &localNameSize)) { if (writePermissions && readPermissions) { status = HgfsPlatformDeleteDirByName(localName); } else { status = EPERM; } free(localName); } else { LOG(4, ("%s: could not map cached file handle %u\n", __FUNCTION__, file)); status = EBADF; } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformFileExists -- * * Platform specific function that that verifies if a file or directory exists. * * Results: * 0 if user has permissions to traverse the parent directory and * the file exists, POSIX error code otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformFileExists(char *localTargetName) // IN: Full file path utf8 encoding { int err; err = Posix_Access(localTargetName, F_OK); if (-1 == err) { err = errno; } return err; } /* *----------------------------------------------------------------------------- * * HgfsPlatformRename -- * * POSIX version of the function that renames a file or directory. * * Results: * 0 on success, POSIX error code otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformRename(char *localSrcName, // IN: local path to source file fileDesc srcFile, // IN: source file handle char *localTargetName, // IN: local path to target file fileDesc targetFile, // IN: target file handle HgfsRenameHint hints) // IN: rename hints { HgfsInternalStatus status = 0; if (hints & HGFS_RENAME_HINT_NO_REPLACE_EXISTING) { if (0 == HgfsPlatformFileExists(localTargetName)) { status = EEXIST; goto exit; } } LOG(4, ("%s: renaming \"%s\" to \"%s\"\n", __FUNCTION__, localSrcName, localTargetName)); status = Posix_Rename(localSrcName, localTargetName); if (status) { status = errno; LOG(4, ("%s: error: %s\n", __FUNCTION__, Err_Errno2String(status))); } exit: return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformCreateDir -- * * POSIX specific code that implements create directory request. * * It invokes POSIX to create the directory and then assigns * file attributes to the new directory if attributes are specified * by the guest. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformCreateDir(HgfsCreateDirInfo *info, // IN: direcotry properties char *utf8Name) // IN: full path for the new directory { mode_t permissions; HgfsInternalStatus status; /* * Create mode_t for use in mkdir(). If owner permissions are missing, use * read/write/execute for the owner permissions. If group or other * permissions are missing, use the owner permissions. * * This sort of makes sense. If the Windows driver wants to make a dir * read-only, it probably intended for the dir to be 666. Since creating * a directory requires a valid mode, it's highly unlikely that we'll ever * be creating a directory without owner permissions. */ permissions = 0; permissions |= info->mask & HGFS_CREATE_DIR_VALID_SPECIAL_PERMS ? info->specialPerms << 9 : 0; permissions |= info->mask & HGFS_CREATE_DIR_VALID_OWNER_PERMS ? info->ownerPerms << 6 : S_IRWXU; permissions |= info->mask & HGFS_CREATE_DIR_VALID_GROUP_PERMS ? info->groupPerms << 3 : (permissions & S_IRWXU) >> 3; permissions |= info->mask & HGFS_CREATE_DIR_VALID_OTHER_PERMS ? info->otherPerms : (permissions & S_IRWXU) >> 6; LOG(4, ("%s: making dir \"%s\", mode %"FMTMODE"\n", __FUNCTION__, utf8Name, permissions)); status = Posix_Mkdir(utf8Name, permissions); if ((info->mask & HGFS_CREATE_DIR_VALID_FILE_ATTR) && (info->fileAttr & HGFS_ATTR_HIDDEN) && 0 == status) { /* * Set hidden attribute when requested. * Do not fail directory creation if setting hidden attribute fails. */ HgfsSetHiddenXAttr(utf8Name, TRUE, permissions); } if (status) { status = errno; LOG(4, ("%s: error: %s\n", __FUNCTION__, Err_Errno2String(status))); } return status; } /* *----------------------------------------------------------------------------- * * HgfsPlatformSymlinkCreate -- * * Platform specific function that actually creates the symbolic link. * * Results: * Zero on success. * Non-zero on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsPlatformSymlinkCreate(char *localSymlinkName, // IN: symbolic link file name char *localTargetName) // IN: symlink target name { HgfsInternalStatus status = 0; int error; LOG(4, ("%s: %s -> %s\n", __FUNCTION__, localSymlinkName, localTargetName)); /* XXX: Should make use of targetNameP->flags? */ error = Posix_Symlink(localTargetName, localSymlinkName); if (error) { status = errno; LOG(4, ("%s: error: %s\n", __FUNCTION__, Err_Errno2String(errno))); } return status; } /* *---------------------------------------------------------------------- * * HgfsPlatformPathHasSymlink -- * * This function determines if any of the intermediate components of the * fileName makes references outside the actual shared path. We do not * check for the last component as none of the server operations follow * symlinks. Also some ops that call us expect to operate on a symlink * final component. * * We use following algorithm. It takes 2 parameters, sharePath and * fileName, and returns non-zero errno if fileName makes an invalid * reference. The idea is to resolve both the sharePath and parent * directory of the fileName. The sharePath is already resolved * beforehand in HgfsServerPolicyRead. During resolution, we eliminate * all the ".", "..", and symlinks handled by the realpath(3) libc call. * * We use parent because last component could be a symlink or a component * that doesn't exist. After resolving, we determine if sharePath is a * prefix of fileName. * * Note that realpath(3) behaves differently on GNU and BSD systems. * Following table lists the difference: * * GNU realpath BSD realpath * ----------------------- ----------------------- * * "/tmp/existingFile" "/tmp/existingFile" (0) "/tmp/existingFile" (0) * "/tmp/missingFile" NULL (ENOENT) "/tmp/missingFile" (0) * "/missingDir/foo" NULL (ENOENT) NULL (ENOENT) * In /tmp, "" NULL (ENOENT) "/tmp" (0) * In /tmp, "." "/tmp" (0) "/tmp" (0) * * Results: * HGFS_NAME_STATUS_COMPLETE if the given path has a symlink, an appropriate name status error otherwise. * * Side effects: * None. * *---------------------------------------------------------------------- */ HgfsNameStatus HgfsPlatformPathHasSymlink(const char *fileName, // IN size_t fileNameLength, // IN const char *sharePath, // IN size_t sharePathLength) // IN { char *resolvedFileDirPath = NULL; char *fileDirName = NULL; HgfsInternalStatus status; HgfsNameStatus nameStatus = HGFS_NAME_STATUS_COMPLETE; ASSERT(fileName); ASSERT(sharePath); ASSERT(sharePathLength <= fileNameLength); LOG(4, ("%s: fileName: %s, sharePath: %s#\n", __FUNCTION__, fileName, sharePath)); /* * Return success if: * - empty fileName or * - sharePath is empty (this is for special root share that allows * access to entire host) or * - fileName and sharePath are same. */ if (fileNameLength == 0 || sharePathLength == 0 || Str_Strcmp(sharePath, fileName) == 0) { goto exit; } /* Separate out parent directory of the fileName. */ File_GetPathName(fileName, &fileDirName, NULL); /* * File_GetPathName may return an empty string to signify the root of * the filesystem. To simplify subsequent processing, let's convert such * empty strings to "/" when found. See File_GetPathName header comment * for details. */ if (strlen(fileDirName) == 0) { char *p; p = realloc(fileDirName, sizeof (DIRSEPS)); if (p == NULL) { nameStatus = HGFS_NAME_STATUS_OUT_OF_MEMORY; LOG(4, ("%s: failed to realloc fileDirName.\n", __FUNCTION__)); goto exit; } else { fileDirName = p; Str_Strcpy(fileDirName, DIRSEPS, sizeof (DIRSEPS)); } } /* * Resolve parent directory of fileName. * Use realpath(2) to resolve the parent. */ resolvedFileDirPath = Posix_RealPath(fileDirName); if (resolvedFileDirPath == NULL) { /* Let's return some meaningful errors if possible. */ status = errno; switch (status) { case ENOENT: nameStatus = HGFS_NAME_STATUS_DOES_NOT_EXIST; break; case ENOTDIR: nameStatus = HGFS_NAME_STATUS_NOT_A_DIRECTORY; break; default: nameStatus = HGFS_NAME_STATUS_FAILURE; break; } LOG(4, ("%s: realpath failed: fileDirName: %s: %s\n", __FUNCTION__, fileDirName, Err_Errno2String(errno))); goto exit; } /* Resolved parent should match with the shareName. */ if (Str_Strncmp(sharePath, resolvedFileDirPath, sharePathLength) != 0) { nameStatus = HGFS_NAME_STATUS_ACCESS_DENIED; LOG(4, ("%s: resolved parent do not match, parent: %s, resolved: %s#\n", __FUNCTION__, fileDirName, resolvedFileDirPath)); goto exit; } exit: free(resolvedFileDirPath); free(fileDirName); return nameStatus; } /* *----------------------------------------------------------------------------- * * HgfsServerWriteWin32Stream -- * * Handle a write request in the WIN32_STREAM_ID format. * * Results: * EOPNOTSUPP, because this is unimplemented. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsServerWriteWin32Stream(char const *packetIn, // IN: incoming packet HgfsOp op, // IN: request type const void *payload, // IN: HGFS operational packet (without header) size_t payloadSize, // IN: size of HGFS operational packet HgfsSessionInfo *session) // IN: session info { return EOPNOTSUPP; } #if defined(__APPLE__) /* *----------------------------------------------------------------------------- * * HgfsGetHiddenXattr -- * * For Mac hosts returns true if file has invisible bit set in the FileFinder * extended attributes. * * Results: * 0 if succeeded getting attribute, error code otherwise otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsGetHiddenXAttr(char const *fileName, // IN: File name Bool *attribute) // OUT: Hidden atribute { struct attrlist attrList; struct FInfoAttrBuf attrBuf; HgfsInternalStatus err; ASSERT(fileName); ASSERT(attribute); memset(&attrList, 0, sizeof attrList); attrList.bitmapcount = ATTR_BIT_MAP_COUNT; attrList.commonattr = ATTR_CMN_OBJTYPE | ATTR_CMN_FNDRINFO; err = getattrlist(fileName, &attrList, &attrBuf, sizeof attrBuf, 0); if (err == 0) { switch (attrBuf.objType) { case VREG: { FileInfo *info = (FileInfo*) attrBuf.finderInfo; uint16 finderFlags = CFSwapInt16BigToHost(info->finderFlags); *attribute = (finderFlags & kIsInvisible) != 0; break; } case VDIR: { FolderInfo *info = (FolderInfo*) attrBuf.finderInfo; uint16 finderFlags = CFSwapInt16BigToHost(info->finderFlags); *attribute = (finderFlags & kIsInvisible) != 0; break; } default: LOG(4, ("%s: Unrecognized object type %d\n", __FUNCTION__, attrBuf.objType)); err = EINVAL; } } else { LOG(4, ("%s: Error %d when getting attributes\n", __FUNCTION__, err)); } return err; } /* *----------------------------------------------------------------------------- * * ChangeInvisibleFlag -- * * Changes value of the invisible bit in a flags variable to a value defined * by setHidden parameter. * * Results: * TRUE flag has been changed, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool ChangeInvisibleFlag(uint16 *flags, // IN/OUT: variable that contains flags Bool setHidden) // IN: new value for the invisible flag { Bool changed = FALSE; /* * Finder keeps, reports and expects to set flags in big endian format. * Needs to convert to host endian before using constants * and then convert back to big endian before saving */ uint16 finderFlags = CFSwapInt16BigToHost(*flags); Bool isHidden = (finderFlags & kIsInvisible) != 0; if (setHidden) { if (!isHidden) { finderFlags |= kIsInvisible; changed = TRUE; } } else if (isHidden) { finderFlags &= ~kIsInvisible; changed = TRUE; } if (changed) { *flags = CFSwapInt16HostToBig(finderFlags); } return changed; } /* *----------------------------------------------------------------------------- * * HgfsSetHiddenXAttr -- * * Sets new value for the invisible attribute of a file. * * Results: * 0 if succeeded, error code otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsSetHiddenXAttr(char const *fileName, // IN: path to the file Bool setHidden, // IN: new value to the invisible attribute mode_t permissions) // IN: permissions of the file { HgfsInternalStatus err; Bool changed = FALSE; struct attrlist attrList; struct FInfoAttrBuf attrBuf; ASSERT(fileName); memset(&attrList, 0, sizeof attrList); attrList.bitmapcount = ATTR_BIT_MAP_COUNT; attrList.commonattr = ATTR_CMN_OBJTYPE | ATTR_CMN_FNDRINFO; err = getattrlist(fileName, &attrList, &attrBuf, sizeof attrBuf, 0); if (err == 0) { switch (attrBuf.objType) { case VREG: { FileInfo *info = (FileInfo*) attrBuf.finderInfo; changed = ChangeInvisibleFlag(&info->finderFlags, setHidden); break; } case VDIR: { FolderInfo *info = (FolderInfo*) attrBuf.finderInfo; changed = ChangeInvisibleFlag(&info->finderFlags, setHidden); break; } default: LOG(4, ("%s: Unrecognized object type %d\n", __FUNCTION__, attrBuf.objType)); err = EINVAL; } } else { err = errno; } if (changed) { attrList.commonattr = ATTR_CMN_FNDRINFO; err = setattrlist(fileName, &attrList, attrBuf.finderInfo, sizeof attrBuf.finderInfo, 0); if (0 != err) { err = errno; } if (EACCES == err) { mode_t mode = permissions | S_IWOTH | S_IWGRP | S_IWUSR; if (chmod(fileName, mode) == 0) { err = setattrlist(fileName, &attrList, attrBuf.finderInfo, sizeof attrBuf.finderInfo, 0); if (0 != err) { err = errno; } chmod(fileName, permissions); } else { err = errno; } } } return err; } #else // __APPLE__ /* *----------------------------------------------------------------------------- * * HgfsGetHiddenXAttr -- * * Always returns 0 since there is no support for invisible files in Linux * HGFS server. * * Results: * 0 always. This is required to allow apps that use the hidden feature to * continue to work. attribute value is set to FALSE always. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsGetHiddenXAttr(char const *fileName, // IN: File name Bool *attribute) // OUT: Value of the hidden attribute { *attribute = FALSE; return 0; } /* *----------------------------------------------------------------------------- * * HgfsSetHiddenXAttr -- * * Sets new value for the invisible attribute of a file. * Currently Linux server does not support invisible or hiddden files. * So this is a nop. * * Results: * 0 always. This is required to allow apps that use the hidden feature to * continue to work. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsSetHiddenXAttr(char const *fileName, // IN: File name Bool value, // IN: Value of the attribute to set mode_t permissions) // IN: permissions of the file { return 0; } #endif // __APPLE__ #if !defined(sun) /* *----------------------------------------------------------------------------- * * HgfsWriteCheckIORange -- * * Verifies that the write arguments do not exceed the maxiuum file size. * * Results: * 0 on success, otherwise an appropriate error. * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsWriteCheckIORange(off_t offset, // IN: uint32 bytesToWrite) // IN: { HgfsInternalStatus status = 0; struct rlimit fileSize; if (getrlimit(RLIMIT_FSIZE, &fileSize) < 0) { status = errno; LOG(4, ("%s: Could not get file size limit\n", __FUNCTION__)); goto exit; } LOG(6, ("%s: File Size limits: 0x%"FMT64"x 0x%"FMT64"x\n", __FUNCTION__, fileSize.rlim_cur, fileSize.rlim_max)); /* * Check the offset is within the file size range. */ if (fileSize.rlim_cur < offset) { status = EFBIG; LOG(4, ("%s: Write offset exceeds max file size limit - 0x%"FMT64"x\n", __FUNCTION__, offset)); goto exit; } /* * Check the data to write does not exceed the max file size. */ if (fileSize.rlim_cur - offset < bytesToWrite) { status = EFBIG; LOG(4, ("%s: Write data 0x%x bytes @ 0x%"FMT64"x size exceeds max file size\n", __FUNCTION__, bytesToWrite, offset)); goto exit; } exit: LOG(6, ("%s: Write data 0x%x bytes @ 0x%"FMT64"x returns %d\n", __FUNCTION__, bytesToWrite, offset, status)); return status; } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerOplock.c000066400000000000000000000237551321503522500266300ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2012-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerOplock.c -- * * HGFS server opportunistic lock support that is common to all platforms. */ #if defined(__APPLE__) #define _DARWIN_USE_64_BIT_INODE #endif #include #include #include "vmware.h" #include "str.h" #include "cpName.h" #include "cpNameLite.h" #include "hgfsServerInt.h" #include "hgfsServerOplockInt.h" /* * Local data */ /* * Global data */ /* * Local functions */ /* *----------------------------------------------------------------------------- * * HgfsServerOplockInit -- * * Set up any state needed to start HGFS server. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsServerOplockInit(void) { Bool result = FALSE; #ifdef HGFS_OPLOCKS result = HgfsPlatformOplockInit(); #endif return result; } /* *----------------------------------------------------------------------------- * * HgfsServerOplockDestroy -- * * Tear down any oplock related state used for HGFS server. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsServerOplockDestroy(void) { #ifdef HGFS_OPLOCKS /* Tear down oplock state, so we no longer catch signals. */ HgfsPlatformOplockDestroy(); #endif } /* *----------------------------------------------------------------------------- * * HgfsHandle2ServerLock -- * * Retrieve the serverlock information for the file node that corresponds to * the specified hgfs handle. If the server is not compiled with oplock * support, we always return TRUE and HGFS_LOCK_NONE. * * Results: * TRUE if the hgfs handle is valid and the lock was retrieved successfully. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsHandle2ServerLock(HgfsHandle handle, // IN: Hgfs file handle HgfsSessionInfo *session, // IN: Session info HgfsLockType *lock) // OUT: Server lock { #ifdef HGFS_OPLOCKS Bool found = FALSE; HgfsFileNode *fileNode = NULL; ASSERT(lock); MXUser_AcquireExclLock(session->nodeArrayLock); fileNode = HgfsHandle2FileNode(handle, session); if (fileNode == NULL) { goto exit; } *lock = fileNode->serverLock; found = TRUE; exit: MXUser_ReleaseExclLock(session->nodeArrayLock); return found; #else *lock = HGFS_LOCK_NONE; return TRUE; #endif } /* *----------------------------------------------------------------------------- * * HgfsFileHasServerLock -- * * Check if the file with the given name is already opened with a server * lock on it. If the server is compiled without oplock support, we always * return FALSE. * * Results: * TRUE if the node was found and has an oplock. * FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsFileHasServerLock(const char *utf8Name, // IN: Name in UTF8 HgfsSessionInfo *session, // IN: Session info HgfsLockType *serverLock, // OUT: Existing oplock fileDesc *fileDesc) // OUT: Existing fd { #ifdef HGFS_OPLOCKS unsigned int i; Bool found = FALSE; ASSERT(utf8Name); ASSERT(session); ASSERT(session->nodeArray); MXUser_AcquireExclLock(session->nodeArrayLock); for (i = 0; i < session->numNodes; i++) { HgfsFileNode *existingFileNode = &session->nodeArray[i]; if ((existingFileNode->state == FILENODE_STATE_IN_USE_CACHED) && (existingFileNode->serverLock != HGFS_LOCK_NONE) && (!stricmp(existingFileNode->utf8Name, utf8Name))) { LOG(4, ("Found file with a lock: %s\n", utf8Name)); *serverLock = existingFileNode->serverLock; *fileDesc = existingFileNode->fileDesc; found = TRUE; break; } } MXUser_ReleaseExclLock(session->nodeArrayLock); return found; #else return FALSE; #endif } #ifdef HGFS_OPLOCKS /* *----------------------------------------------------------------------------- * * HgfsServerOplockBreakReply -- * * The client was sent an oplock break request, and responded with this * reply. It contains the oplock status that the client is now in. Since * the break could have actually been a degrade, it is well within the * client's rights to transition to a non-broken state. We need to make * sure that such a transition was legal, acknowledge the brea * appropriately, and update our own state. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsServerOplockBreakReply(const unsigned char *packetIn, // IN: Reply packet unsigned int packetSize, // IN: Size of packet void *clientData) // IN: From request { HgfsReplyServerLockChange *reply; ServerLockData *lockData = clientData; ASSERT(packetIn); ASSERT(clientData); if (packetSize < sizeof *reply) { return; } reply = (HgfsReplyServerLockChange *)packetIn; /* * XXX: It should be safe to ignore the status and id from the actual * HgfsReply. The only information we need to properly acknowledge the break * is the original fd and the new lease, which, in the case of a degrade, * is double checked in HgfsAckOplockBreak, so we'd be safe from a garbage * value. */ HgfsAckOplockBreak(lockData, reply->serverLock); } /* *----------------------------------------------------------------------------- * * HgfsServerOplockBreak -- * * When the host FS needs to break the oplock so that another client * can open the file, it signals the event in the overlapped structure * that we used to request an oplock. * This sets off the following chains of events: * 1. Send the oplock break request to the guest. * 2. Once the guest acknowledges the oplock break, the completion * routine GuestRpcServerRequestCallback will fire, causing * HgfsServerOplockBreakReply to also fire, which will break the oplock * on the host FS. * * Results: * None. * * Side effects: * If successful, allocates memory for the rpc request. * *----------------------------------------------------------------------------- */ void HgfsServerOplockBreak(ServerLockData *lockData) { HgfsHandle hgfsHandle; char *requestBuffer = NULL; HgfsRequestServerLockChange *request; HgfsLockType lock; LOG(4, ("%s: entered\n", __FUNCTION__)); /* * XXX: Just because the file in not in the cache on the server, * does not mean it was closed on the client. It is possible that * we closed the file on the server because we ran out of space * in cache. That's why for now as long as a file has a lock, * we don't remove it from the node cache. This should be fixed. * * In any case, none of these cache-related failures should cause us to ack * the oplock break locally. That is because if the file wasn't in the * cache, or it had no lock, chances are someone else (maybe the VCPU * thread) broke the oplock and/or closed the file. */ if (!HgfsFileDesc2Handle(lockData->fileDesc, &hgfsHandle)) { LOG(4, ("%s: file is not in the cache\n", __FUNCTION__)); goto free_and_exit; } if (!HgfsHandle2ServerLock(hgfsHandle, &lock)) { LOG(4, ("%s: could not retrieve node's lock info.\n", __FUNCTION__)); goto free_and_exit; } if (lock == HGFS_LOCK_NONE) { LOG(4, ("%s: the file does not have a server lock.\n", __FUNCTION__)); goto free_and_exit; } /* * We need to setup the entire request here. The command prefix will be * added later, so save some space for it. * * XXX: This should probably go into a common allocation function that * other out-of-band requests can use. */ requestBuffer = malloc(sizeof *request + HGFS_CLIENT_CMD_LEN); if (requestBuffer == NULL) { LOG(4, ("%s: could not allocate memory.\n", __FUNCTION__)); goto ack_and_exit; } /* Save space for the command prefix. */ request = (HgfsRequestServerLockChange *) (requestBuffer + HGFS_CLIENT_CMD_LEN); request->header.op = HGFS_OP_SERVER_LOCK_CHANGE; request->header.id = 0; /* XXX */ request->file = hgfsHandle; request->newServerLock = lockData->serverLock; /* * Just send the request size for our actual request; our callee will * write in the command prefix and modify the request size appropriately. * * If for some reason we fail, we'll acknowledge the oplock break * immediately. */ if (HgfsServerManager_SendRequest(requestBuffer, sizeof *request, HgfsServerOplockBreakReply, lockData)) { return; } free(requestBuffer); ack_and_exit: HgfsAckOplockBreak(lockData, HGFS_LOCK_NONE); return; free_and_exit: free(lockData); } #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerOplock.h000066400000000000000000000035561321503522500266320ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2013-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerOplock.h -- * * Header file for public common data types used in the HGFS * opportunistic lock routines. */ #ifndef _HGFS_SERVER_OPLOCK_H_ #define _HGFS_SERVER_OPLOCK_H_ #include "hgfsProto.h" // for protocol types #include "hgfsServerInt.h" // for common server types e.g. HgfsSessionInfo /* * Data structures */ /* * Global variables */ /* * Global functions */ Bool HgfsServerOplockInit(void); void HgfsServerOplockDestroy(void); Bool HgfsHandle2ServerLock(HgfsHandle handle, HgfsSessionInfo *session, HgfsLockType *lock); Bool HgfsFileHasServerLock(const char *utf8Name, HgfsSessionInfo *session, HgfsLockType *serverLock, fileDesc *fileDesc); Bool HgfsAcquireServerLock(fileDesc fileDesc, HgfsSessionInfo *session, HgfsLockType *serverLock); #endif // ifndef _HGFS_SERVER_OPLOCK_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerOplockInt.h000066400000000000000000000035461321503522500273040ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2013-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerOplock.h -- * * Header file for private common data types used in the HGFS * opportunistic lock routines. */ #ifndef _HGFS_SERVER_OPLOCKINT_H_ #define _HGFS_SERVER_OPLOCKINT_H_ #include "hgfsProto.h" // for protocol types #include "hgfsServerInt.h" // for common server types e.g. HgfsSessionInfo /* * Does this platform have oplock support? We define it here to avoid long * ifdefs all over the code. For now, Linux and Windows hosts only. * * XXX: Just kidding, no oplock support yet. */ #if 0 #define HGFS_OPLOCKS #endif /* * XXX describe the data structure */ /* Server lock related structure */ typedef struct { fileDesc fileDesc; int32 event; HgfsLockType serverLock; } ServerLockData; /* * Global variables */ /* * Global functions */ #ifdef HGFS_OPLOCKS void HgfsServerOplockBreak(ServerLockData *data); void HgfsAckOplockBreak(ServerLockData *lockData, HgfsLockType replyLock); #endif #endif // ifndef _HGFS_SERVER_OPLOCKINT_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerOplockLinux.c000066400000000000000000000250111321503522500276330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2012-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerOplockLinux.c -- * * HGFS server opportunistic lock support for the Linux platform. */ #include #include #include #include #include "vmware.h" #include "err.h" #include "hgfsServerInt.h" #include "hgfsServerOplockInt.h" #ifdef HGFS_OPLOCKS # include # include "sig.h" #endif /* * Local data */ /* * Global data */ /* * Local functions */ #ifdef HGFS_OPLOCKS static void HgfsServerSigOplockBreak(int sigNum, siginfo_t *info, ucontext_t *u, void *clientData); #endif /* *----------------------------------------------------------------------------- * * HgfsPlatformOplockInit -- * * Set up any state needed to start Linux HGFS server oplock support. * * Results: * TRUE always. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsPlatformOplockInit(void) { #ifdef HGFS_OPLOCKS /* Register a signal handler to catch oplock break signals. */ Sig_Callback(SIGIO, SIG_SAFE, HgfsServerSigOplockBreak, NULL); #endif return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPlatformOplockDestroy -- * * Tear down any state used for Linux HGFS server. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ void HgfsPlatformOplockDestroy(void) { #ifdef HGFS_OPLOCKS /* Tear down oplock state, so we no longer catch signals. */ Sig_Callback(SIGIO, SIG_NOHANDLER, NULL, NULL); #endif } /* *----------------------------------------------------------------------------- * * HgfsAcquireServerLock -- * * Acquire a lease for the open file. Typically we try and get the exact * lease desired, but if the client asked for HGFS_LOCK_OPPORTUNISTIC, we'll * take the "best" lease we can get. * * Results: * TRUE on success. serverLock contains the type of the lock acquired. * FALSE on failure. serverLock is HGFS_LOCK_NONE. * * XXX: This function has the potential to return per-platform error codes, * but since it is opportunistic by nature, it isn't necessary to do so. * * Side effects: * None. * *----------------------------------------------------------------------------- */ Bool HgfsAcquireServerLock(fileDesc fileDesc, // IN: OS handle HgfsSessionInfo *session, // IN: session info HgfsLockType *serverLock) // IN/OUT: Oplock asked for/granted { #ifdef HGFS_OPLOCKS HgfsLockType desiredLock; int leaseType, error; ASSERT(serverLock); ASSERT(session); desiredLock = *serverLock; if (desiredLock == HGFS_LOCK_NONE) { return TRUE; } if (!HgfsIsServerLockAllowed(session)) { return FALSE; } /* * First tell the kernel which signal to send us. SIGIO is already the * default, but if we skip this step, we won't get the siginfo_t when * a lease break occurs. * * XXX: Do I need to do fcntl(fileDesc, F_SETOWN, getpid())? */ if (fcntl(fileDesc, F_SETSIG, SIGIO)) { error = errno; Log("%s: Could not set SIGIO as the desired lease break signal for " "fd %d: %s\n", __FUNCTION__, fileDesc, Err_Errno2String(error)); return FALSE; } /* * If the client just wanted the best lock possible, start off with a write * lease and move down to a read lease if that was unavailable. */ if ((desiredLock == HGFS_LOCK_OPPORTUNISTIC) || (desiredLock == HGFS_LOCK_EXCLUSIVE)) { leaseType = F_WRLCK; } else if (desiredLock == HGFS_LOCK_SHARED) { leaseType = F_RDLCK; } else { LOG(4, ("%s: Unknown server lock\n", __FUNCTION__)); return FALSE; } if (fcntl(fileDesc, F_SETLEASE, leaseType)) { /* * If our client was opportunistic and we failed to get his lease because * someone else is already writing or reading to the file, try again with * a read lease. */ if (desiredLock == HGFS_LOCK_OPPORTUNISTIC && (errno == EAGAIN || errno == EACCES)) { leaseType = F_RDLCK; if (fcntl(fileDesc, F_SETLEASE, leaseType)) { error = errno; LOG(4, ("%s: Could not get any opportunistic lease for fd %d: %s\n", __FUNCTION__, fileDesc, Err_Errno2String(error))); return FALSE; } } else { error = errno; LOG(4, ("%s: Could not get %s lease for fd %d: %s\n", __FUNCTION__, leaseType == F_WRLCK ? "write" : "read", fileDesc, Err_Errno2String(errno))); return FALSE; } } /* Got a lease of some kind. */ LOG(4, ("%s: Got %s lease for fd %d\n", __FUNCTION__, leaseType == F_WRLCK ? "write" : "read", fileDesc)); *serverLock = leaseType == F_WRLCK ? HGFS_LOCK_EXCLUSIVE : HGFS_LOCK_SHARED; return TRUE; #else return FALSE; #endif } #ifdef HGFS_OPLOCKS /* *----------------------------------------------------------------------------- * * HgfsAckOplockBreak -- * * Platform-dependent implementation of oplock break acknowledgement. * This function gets called when the oplock break rpc command is completed. * The rpc oplock break command (HgfsServerOplockBreak) is in hgfsServer.c * * On Linux, we use fcntl() to downgrade the lease. Then we update the node * cache, free the clientData, and call it a day. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsAckOplockBreak(ServerLockData *lockData, // IN: server lock info HgfsLockType replyLock) // IN: client has this lock { int fileDesc, newLock; HgfsLockType actualLock; ASSERT(lockData); fileDesc = lockData->fileDesc; LOG(4, ("%s: Acknowledging break on fd %d\n", __FUNCTION__, fileDesc)); /* * The Linux server supports lock downgrading. We only downgrade to a shared * lock if our previous call to fcntl() said we could, and if the client * wants to downgrade to a shared lock. Otherwise, we break altogether. */ if (lockData->serverLock == HGFS_LOCK_SHARED && replyLock == HGFS_LOCK_SHARED) { newLock = F_RDLCK; actualLock = replyLock; } else { newLock = F_UNLCK; actualLock = HGFS_LOCK_NONE; } /* Downgrade or acknowledge the break altogether. */ if (fcntl(fileDesc, F_SETLEASE, newLock) == -1) { int error = errno; Log("%s: Could not break lease on fd %d: %s\n", __FUNCTION__, fileDesc, Err_Errno2String(error)); } /* Cleanup. */ HgfsUpdateNodeServerLock(fileDesc, actualLock); free(lockData); } /* *----------------------------------------------------------------------------- * * HgfsServerSigOplockBreak -- * * Handle a pending oplock break. Called from the VMX poll loop context. * All we really do is set up the state for an oplock break and call * HgfsServerOplockBreak which will do the rest of the work. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsServerSigOplockBreak(int sigNum, // IN: Signal number siginfo_t *info, // IN: Additional info about signal ucontext_t *u, // IN: Interrupted context (regs etc) void *clientData) // IN: Ignored { ServerLockData *lockData; int newLease, fd; HgfsLockType newServerLock; ASSERT(sigNum == SIGIO); ASSERT(info); ASSERT(clientData == NULL); fd = info->si_fd; LOG(4, ("%s: Received SIGIO for fd %d\n", __FUNCTION__, fd)); /* * We've got all we need from the signal handler, let it continue handling * signals of this type. */ Sig_Continue(sigNum); /* * According to locks.c in kernel source, doing F_GETLEASE when a lease * break is pending will return the new lease we should use. It'll be * F_RDLCK if we can downgrade, or F_UNLCK if we should break altogether. */ newLease = fcntl(fd, F_GETLEASE); if (newLease == F_RDLCK) { newServerLock = HGFS_LOCK_SHARED; } else if (newLease == F_UNLCK) { newServerLock = HGFS_LOCK_NONE; } else if (newLease == -1) { int error = errno; Log("%s: Could not get old lease for fd %d: %s\n", __FUNCTION__, fd, Err_Errno2String(error)); goto error; } else { Log("%s: Unexpected reply to get lease for fd %d: %d\n", __FUNCTION__, fd, newLease); goto error; } /* * Setup a ServerLockData struct so that we can make use of * HgfsServerOplockBreak which does the heavy lifting of discovering which * HGFS handle we're interested in breaking, sending the break, receiving * the acknowledgement, and firing the platform-specific acknowledgement * function (where we'll downgrade the lease). */ lockData = malloc(sizeof *lockData); if (lockData) { lockData->fileDesc = fd; lockData->serverLock = newServerLock; lockData->event = 0; // not needed /* * Relinquish control of this data. It'll get freed later, when the RPC * command completes. */ HgfsServerOplockBreak(lockData); return; } else { Log("%s: Could not allocate memory for lease break on behalf of fd %d\n", __FUNCTION__, fd); } error: /* Clean up as best we can. */ fcntl(fd, F_SETLEASE, F_UNLCK); HgfsUpdateNodeServerLock(fd, HGFS_LOCK_NONE); } #endif /* HGFS_OPLOCKS */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerPacketUtil.c000066400000000000000000000633601321503522500274420ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerPacketUtil.c -- * * Utility functions for manipulating packet used by hgfs server code */ #include #include #include #include "vmware.h" #include "hgfsServer.h" #include "hgfsServerInt.h" #include "util.h" static void *HSPUGetBuf(HgfsServerChannelCallbacks *chanCb, MappingType mappingType, HgfsVmxIov *iov, uint32 iovCount, uint32 startIndex, size_t dataSize, size_t bufSize, void **buf, Bool *isAllocated, uint32 *iovMappedCount); static void HSPUPutBuf(HgfsServerChannelCallbacks *chanCb, MappingType mappingType, HgfsVmxIov *iov, uint32 iovCount, uint32 startIndex, size_t bufSize, void **buf, Bool *isAllocated, uint32 *iovMappedCount); static void HSPUCopyBufToIovec(HgfsVmxIov *iov, uint32 iovMapped, uint32 startIndex, void *buf, size_t bufSize); static void HSPUCopyIovecToBuf(HgfsVmxIov *iov, uint32 iovMapped, uint32 startIndex, void *buf, size_t bufSize); static Bool HSPUMapBuf(HgfsChannelMapVirtAddrFunc mapVa, HgfsChannelUnmapVirtAddrFunc putVa, size_t mapSize, uint32 startIndex, uint32 iovCount, HgfsVmxIov *iov, uint32 *mappedCount); static void HSPUUnmapBuf(HgfsChannelUnmapVirtAddrFunc unmapVa, uint32 startIndex, HgfsVmxIov *iov, uint32 *mappedCount); /* *----------------------------------------------------------------------------- * * HSPU_ValidateRequestPacketSize -- * * Validate an HGFS packet size with the HGFS header in use, the HGFS opcode request * (its arguments) and optionally any opcode request data that is contained in the * size for the packet. * * Results: * TRUE if the packet size is large enough for the required request data. * FALSE if not. * * Side effects: * None. *----------------------------------------------------------------------------- */ Bool HSPU_ValidateRequestPacketSize(HgfsPacket *packet, // IN: Hgfs Packet size_t requestHeaderSize, // IN: request header size size_t requestOpSize, // IN: request op size size_t requestOpDataSize) // IN: request op data size { size_t bytesRemaining = packet->metaPacketDataSize; Bool requestSizeIsOkay = FALSE; /* * Validate the request buffer size ensuring that the the contained components * (request header, the operation arguments and lastly any data) fall within it. */ if (bytesRemaining >= requestHeaderSize) { bytesRemaining -= requestHeaderSize; } else { goto exit; } if (bytesRemaining >= requestOpSize) { bytesRemaining -= requestOpSize; } else { goto exit; } if (bytesRemaining >= requestOpDataSize) { requestSizeIsOkay = TRUE; } exit: return requestSizeIsOkay; } /* *----------------------------------------------------------------------------- * * HSPU_ValidateReplyPacketSize -- * * Validate a reply buffer size in an hgfs packet with the reply data * size for the request. * * Results: * TRUE if the reply buffer size is large enough for the request reply * results. FALSE if not. * * Side effects: * None. *----------------------------------------------------------------------------- */ Bool HSPU_ValidateReplyPacketSize(HgfsPacket *packet, // IN: Hgfs Packet size_t replyHeaderSize, // IN: reply header size size_t replyResultSize, // IN: reply result size size_t replyResultDataSize, // IN: reply result data size Bool useMappedMetaPacket) // IN: using meta buffer { size_t bytesRemaining; Bool replySizeIsOkay = FALSE; if (packet->replyPacket != NULL) { /* Pre-allocated reply buffer (as used by the backdoor). */ bytesRemaining = packet->replyPacketSize; } else if (useMappedMetaPacket) { /* No reply buffer (as used by the VMCI) reuse the metapacket buffer. */ bytesRemaining = packet->metaPacketSize; } else { /* No reply buffer but we will allocate the size required. */ replySizeIsOkay = TRUE; goto exit; } if (bytesRemaining >= replyHeaderSize) { bytesRemaining -= replyHeaderSize; } else { goto exit; } if (bytesRemaining >= replyResultSize) { bytesRemaining -= replyResultSize; } else { goto exit; } if (bytesRemaining >= replyResultDataSize) { replySizeIsOkay = TRUE; } exit: return replySizeIsOkay; } /* *----------------------------------------------------------------------------- * * HSPU_GetReplyPacket -- * * Get a reply packet given an hgfs packet. * Guest mappings may be established. * * Results: * Pointer to reply packet. * * Side effects: * Buffer may be allocated. *----------------------------------------------------------------------------- */ void * HSPU_GetReplyPacket(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsServerChannelCallbacks *chanCb, // IN: Channel callbacks size_t replyDataSize, // IN: Size of reply data size_t *replyPacketSize) // OUT: Size of reply Packet { if (packet->replyPacket != NULL) { /* * When we are transferring packets over backdoor, reply packet * is a static buffer. Backdoor should always return from here. */ packet->replyPacketDataSize = replyDataSize; LOG(4, ("Existing reply packet %s %"FMTSZ"u %"FMTSZ"u\n", __FUNCTION__, replyDataSize, packet->replyPacketSize)); ASSERT(replyDataSize <= packet->replyPacketSize); } else if (chanCb != NULL && chanCb->getWriteVa != NULL) { /* Can we write directly into guest memory? */ if (packet->metaPacket != NULL) { /* * Use the mapped metapacket buffer for the reply. * This currently makes assumptions about the mapping - * - It is mapped read -write * - It is always large enough for any reply * This will change as it is grossly inefficient as the maximum size * is always mapped and copied no matter how much data it really contains. */ LOG(10, ("%s Using meta packet for reply packet\n", __FUNCTION__)); ASSERT(BUF_READWRITEABLE == packet->metaMappingType); ASSERT(replyDataSize <= packet->metaPacketSize); packet->replyPacket = packet->metaPacket; packet->replyPacketDataSize = replyDataSize; packet->replyPacketSize = packet->metaPacketSize; packet->replyPacketIsAllocated = FALSE; /* * The reply is using the meta buffer so update the valid data size. * * Note, currently We know the reply size is going to be less than the * incoming request valid data size. This will updated when that part is * fixed. See the above comment about the assumptions and asserts. */ packet->metaPacketDataSize = packet->replyPacketDataSize; } else { NOT_IMPLEMENTED(); } } else { /* For sockets channel we always need to allocate buffer */ LOG(10, ("%s Allocating reply packet\n", __FUNCTION__)); packet->replyPacket = Util_SafeMalloc(replyDataSize); packet->replyPacketIsAllocated = TRUE; packet->replyPacketDataSize = replyDataSize; packet->replyPacketSize = replyDataSize; } *replyPacketSize = packet->replyPacketSize; return packet->replyPacket; } /* *----------------------------------------------------------------------------- * * HSPU_PutReplyPacket -- * * Free buffer if reply packet was allocated. * * Results: * None. * * Side effects: * None. *----------------------------------------------------------------------------- */ void HSPU_PutReplyPacket(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsServerChannelCallbacks *chanCb) // IN: Channel callbacks { /* * If there wasn't an allocated buffer for the reply, there is nothing to * do as the reply is in the metapacket buffer which will be handled by the * put on the metapacket. */ if (packet->replyPacketIsAllocated) { LOG(10, ("%s Freeing reply packet", __FUNCTION__)); free(packet->replyPacket); packet->replyPacketIsAllocated = FALSE; packet->replyPacket = NULL; packet->replyPacketSize = 0; } } /* *----------------------------------------------------------------------------- * * HSPU_GetMetaPacket -- * * Get a meta packet given an hgfs packet. * Guest mappings will be established. * * Results: * Pointer to meta packet. * * Side effects: * Buffer may be allocated. *----------------------------------------------------------------------------- */ void * HSPU_GetMetaPacket(HgfsPacket *packet, // IN/OUT: Hgfs Packet size_t *metaPacketSize, // OUT: Size of metaPacket HgfsServerChannelCallbacks *chanCb) // IN: Channel callbacks { *metaPacketSize = packet->metaPacketDataSize; if (packet->metaPacket != NULL) { return packet->metaPacket; } if (packet->metaPacketSize == 0) { return NULL; } packet->metaMappingType = BUF_READWRITEABLE; return HSPUGetBuf(chanCb, packet->metaMappingType, packet->iov, packet->iovCount, 0, packet->metaPacketDataSize, packet->metaPacketSize, &packet->metaPacket, &packet->metaPacketIsAllocated, &packet->metaPacketMappedIov); } /* *----------------------------------------------------------------------------- * * HSPU_ValidateDataPacketSize -- * * Validate a data packet buffer size in an hgfs packet with the required data * size for the request. * * Results: * TRUE if the data buffer size is valid for the request. * FALSE if not. * * Side effects: * None. *----------------------------------------------------------------------------- */ Bool HSPU_ValidateDataPacketSize(HgfsPacket *packet, // IN: Hgfs Packet size_t dataSize) // IN: data size { return (dataSize <= packet->dataPacketSize); } /* *----------------------------------------------------------------------------- * * HSPU_GetDataPacketBuf -- * * Get a data packet given an hgfs packet. * Guest mappings will be established. * * Results: * Pointer to data packet. * * Side effects: * Buffer may be allocated. *----------------------------------------------------------------------------- */ void * HSPU_GetDataPacketBuf(HgfsPacket *packet, // IN/OUT: Hgfs Packet MappingType mappingType, // IN: Writeable/Readable HgfsServerChannelCallbacks *chanCb) // IN: Channel callbacks { if (packet->dataPacket != NULL) { return packet->dataPacket; } if (packet->dataPacketSize == 0) { return NULL; } packet->dataMappingType = mappingType; return HSPUGetBuf(chanCb, packet->dataMappingType, packet->iov, packet->iovCount, packet->dataPacketIovIndex, packet->dataPacketDataSize, packet->dataPacketSize, &packet->dataPacket, &packet->dataPacketIsAllocated, &packet->dataPacketMappedIov); } /* *----------------------------------------------------------------------------- * * HSPUGetBuf -- * * Get a {meta, data} packet given an hgfs packet. * Guest mappings will be established. * * Results: * Pointer to buffer. * * Side effects: * Buffer may be allocated. *----------------------------------------------------------------------------- */ static void * HSPUGetBuf(HgfsServerChannelCallbacks *chanCb, // IN: Channel callbacks MappingType mappingType, // IN: Access type Readable/Writeable HgfsVmxIov *iov, // IN: iov array uint32 iovCount, // IN: iov array size uint32 startIndex, // IN: Start index of iov size_t dataSize, // IN: Size of data in tghe buffer size_t bufSize, // IN: Size of buffer void **buf, // OUT: Contigous buffer Bool *isAllocated, // OUT: Buffer allocated uint32 *iovMappedCount) // OUT: iov mapped count { uint32 iovMapped = 0; HgfsChannelMapVirtAddrFunc mapVa; Bool releaseMappings = FALSE; ASSERT(buf != NULL); *buf = NULL; *isAllocated = FALSE; if (chanCb == NULL) { goto exit; } if (mappingType == BUF_WRITEABLE || mappingType == BUF_READWRITEABLE) { mapVa = chanCb->getWriteVa; } else { ASSERT(mappingType == BUF_READABLE); mapVa = chanCb->getReadVa; } /* Looks like we are in the middle of poweroff. */ if (mapVa == NULL) { goto exit; } /* Establish guest memory mappings */ if (!HSPUMapBuf(mapVa, chanCb->putVa, bufSize, startIndex, iovCount, iov, &iovMapped)) { /* Guest probably passed us bad physical address */ goto exit; } if (iovMapped == 1) { /* A single page buffer is contiguous so hold on to guest mappings. */ *buf = iov[startIndex].va; goto exit; } /* More than one page was mapped. */ ASSERT(iov[startIndex].len < bufSize); LOG(10, ("%s: Hgfs Allocating buffer \n", __FUNCTION__)); *buf = Util_SafeMalloc(bufSize); *isAllocated = TRUE; if ((mappingType == BUF_READABLE || mappingType == BUF_READWRITEABLE) && (0 != dataSize)) { HSPUCopyIovecToBuf(iov, iovMapped, startIndex, *buf, dataSize); } releaseMappings = TRUE; exit: if (releaseMappings) { HSPUUnmapBuf(chanCb->putVa, startIndex, iov, &iovMapped); } *iovMappedCount = iovMapped; return *buf; } /* *----------------------------------------------------------------------------- * * HSPU_PutMetaPacket -- * * Free meta packet buffer if allocated. * Guest mappings will be released. * * Results: * void. * * Side effects: * *----------------------------------------------------------------------------- */ void HSPU_PutMetaPacket(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsServerChannelCallbacks *chanCb) // IN: Channel callbacks { if (packet->metaPacket == NULL) { return; } LOG(4, ("%s Hgfs Putting Meta packet\n", __FUNCTION__)); HSPUPutBuf(chanCb, packet->metaMappingType, packet->iov, packet->iovCount, 0, packet->metaPacketDataSize, &packet->metaPacket, &packet->metaPacketIsAllocated, &packet->metaPacketMappedIov); } /* *----------------------------------------------------------------------------- * * HSPU_SetDataPacketSize -- * * Set the size of the valid data in the data packet buffer. * * Results: * void. * * Side effects: * None. *----------------------------------------------------------------------------- */ void HSPU_SetDataPacketSize(HgfsPacket *packet, // IN/OUT: Hgfs Packet size_t dataSize) // IN: data size { ASSERT(NULL != packet); ASSERT(dataSize <= packet->dataPacketSize); packet->dataPacketDataSize = dataSize; } /* *----------------------------------------------------------------------------- * * HSPU_PutDataPacketBuf -- * * Free data packet buffer if allocated. * Guest mappings will be released. * * Results: * void. * * Side effects: * None. *----------------------------------------------------------------------------- */ void HSPU_PutDataPacketBuf(HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsServerChannelCallbacks *chanCb) // IN: Channel callbacks { if (packet->dataPacket == NULL) { return; } LOG(4, ("%s Hgfs Putting Data packet\n", __FUNCTION__)); HSPUPutBuf(chanCb, packet->dataMappingType, packet->iov, packet->iovCount, packet->dataPacketIovIndex, packet->dataPacketDataSize, &packet->dataPacket, &packet->dataPacketIsAllocated, &packet->dataPacketMappedIov); } /* *----------------------------------------------------------------------------- * * HSPUPutBuf -- * * Free buffer if allocated and release guest mappings. * * Results: * None. * * Side effects: * None. *----------------------------------------------------------------------------- */ void HSPUPutBuf(HgfsServerChannelCallbacks *chanCb, // IN: Channel callbacks MappingType mappingType, // IN: Access type Readable/Writeable HgfsVmxIov *iov, // IN: iov array uint32 iovCount, // IN: iov array size uint32 startIndex, // IN: Start index of iov size_t bufSize, // IN: Size of buffer void **buf, // OUT: Contigous buffer Bool *isAllocated, // OUT: Buffer allocated uint32 *iovMappedCount) // OUT: iov mapped count { ASSERT(buf != NULL); if (chanCb == NULL || chanCb->putVa == NULL) { goto exit; } if (*isAllocated && (mappingType == BUF_WRITEABLE || mappingType == BUF_READWRITEABLE)) { /* * 1. Map the iov's if required for the size into host addresses. * 2. Write the buffer data into the iov host addresses. * 3. Unmap the iov's host virtual addresses. */ if (0 == *iovMappedCount) { if (!HSPUMapBuf(chanCb->getWriteVa, chanCb->putVa, bufSize, startIndex, iovCount, iov, iovMappedCount)) { goto exit; } } HSPUCopyBufToIovec(iov, *iovMappedCount, startIndex, *buf, bufSize); } if (0 < *iovMappedCount) { HSPUUnmapBuf(chanCb->putVa, startIndex, iov, iovMappedCount); } exit: if (*isAllocated) { LOG(10, ("%s: Hgfs Freeing buffer \n", __FUNCTION__)); free(*buf); *isAllocated = FALSE; } *buf = NULL; } /* *----------------------------------------------------------------------------- * * HSPUCopyBufToIovec -- * * Write out buffer to data Iovec. * * Results: * void * * Side effects: * @iov is populated with contents of @buf *----------------------------------------------------------------------------- */ static void HSPUCopyBufToIovec(HgfsVmxIov *iov, // IN: iovs (array of mappings) uint32 iovCount, // IN: iov count of mappings uint32 startIndex, // IN: start index into iov void *buf, // IN: Contigous Buffer size_t bufSize) // IN: Size of buffer { size_t iovIndex; size_t endIndex; size_t remainingSize; size_t copiedAmount = 0; ASSERT(buf != NULL); for (iovIndex = startIndex, endIndex = startIndex + iovCount, remainingSize = bufSize; iovIndex < endIndex && remainingSize > 0; iovIndex++) { size_t copyAmount = remainingSize < iov[iovIndex].len ? remainingSize: iov[iovIndex].len; ASSERT(iov[iovIndex].va != NULL); memcpy(iov[iovIndex].va, (char *)buf + copiedAmount, copyAmount); remainingSize -= copyAmount; copiedAmount += copyAmount; } ASSERT(remainingSize == 0); } /* *----------------------------------------------------------------------------- * * HSPUCopyIovecToBuf -- * * Read Iovec into the buffer. * * Results: * void * * Side effects: * @iov is populated with contents of @buf *----------------------------------------------------------------------------- */ static void HSPUCopyIovecToBuf(HgfsVmxIov *iov, // IN: iovs (array of mappings) uint32 iovCount, // IN: iov count of mappings uint32 startIndex, // IN: start index into iov void *buf, // IN: contigous Buffer size_t bufSize) // IN: size of buffer { size_t iovIndex; size_t endIndex; size_t remainingSize; size_t copiedAmount = 0; for (iovIndex = startIndex, endIndex = startIndex + iovCount, remainingSize = bufSize; iovIndex < endIndex && remainingSize > 0; iovIndex++) { size_t copyAmount = remainingSize < iov[iovIndex].len ? remainingSize : iov[iovIndex].len; memcpy((char *)buf + copiedAmount, iov[iovIndex].va, copyAmount); copiedAmount += copyAmount; remainingSize -= copyAmount; } ASSERT(copiedAmount == bufSize && remainingSize == 0); } /* *----------------------------------------------------------------------------- * * HSPUMapBuf -- * * Map the buffer for the required size. * * Results: * TRUE if we mapped the requested size and the number of mappings performed. * Otherwise FALSE if something failed, and 0 mappings performed. * * Side effects: * None. *----------------------------------------------------------------------------- */ static Bool HSPUMapBuf(HgfsChannelMapVirtAddrFunc mapVa, // IN: map virtual address function HgfsChannelUnmapVirtAddrFunc putVa, // IN: unmap virtual address function size_t mapSize, // IN: size to map uint32 startIndex, // IN: Start index of iovs to map uint32 iovCount, // IN: iov count HgfsVmxIov *iov, // IN/OUT: iovs (array) to map uint32 *mappedCount) // OUT: mapped iov count { uint32 iovIndex; uint32 mappedIovCount; size_t remainingSize; Bool mapped = TRUE; for (iovIndex = startIndex, mappedIovCount = 0, remainingSize = mapSize; iovIndex < iovCount && remainingSize > 0; iovIndex++, mappedIovCount++) { iov[iovIndex].context = NULL; /* Check: Iov in VMCI should never cross page boundary */ ASSERT(iov[iovIndex].len <= (PAGE_SIZE - PAGE_OFFSET(iov[iovIndex].pa))); iov[iovIndex].va = mapVa(iov[iovIndex].pa, iov[iovIndex].len, &iov[iovIndex].context); if (NULL == iov[iovIndex].va) { /* Failed to map the physical address. */ break; } remainingSize = remainingSize < iov[iovIndex].len ? 0: remainingSize - iov[iovIndex].len; } if (0 != remainingSize) { /* Something failed in the mappings Undo any mappings we created. */ HSPUUnmapBuf(putVa, startIndex, iov, &mappedIovCount); mapped = FALSE; } *mappedCount = mappedIovCount; return mapped; } /* *----------------------------------------------------------------------------- * * HSPUUnmapBuf -- * * Unmap the buffer and release guest mappings. * * Results: * None. * * Side effects: * None. *----------------------------------------------------------------------------- */ static void HSPUUnmapBuf(HgfsChannelUnmapVirtAddrFunc unmapVa, // IN/OUT: Hgfs Packet uint32 startIndex, // IN: Start index of iovs to map HgfsVmxIov *iov, // IN/OUT: iovs (array) to map uint32 *mappedCount) // IN/OUT: iov count to unmap { uint32 iovIndex; uint32 endIndex; for (iovIndex = startIndex, endIndex = startIndex + *mappedCount; iovIndex < endIndex; iovIndex++) { ASSERT(iov[iovIndex].context); unmapVa(&iov[iovIndex].context); iov[iovIndex].context = NULL; iov[iovIndex].va = NULL; } *mappedCount = 0; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerParameters.c000066400000000000000000005732301321503522500275020ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #include #include #include "vmware.h" #include "str.h" #include "cpName.h" #include "cpNameLite.h" #include "hgfsServerInt.h" #include "hgfsServerPolicy.h" #include "codeset.h" #include "config.h" #include "file.h" #include "util.h" #include "wiper.h" #include "vm_basic_asm.h" #include "hgfsServerParameters.h" #ifdef _WIN32 #define HGFS_REQUEST_WIN32_SUPPORTED HGFS_REQUEST_SUPPORTED #define HGFS_REQUEST_POSIX_SUPPORTED HGFS_REQUEST_NOT_SUPPORTED #else #define HGFS_REQUEST_WIN32_SUPPORTED HGFS_REQUEST_NOT_SUPPORTED #define HGFS_REQUEST_POSIX_SUPPORTED HGFS_REQUEST_SUPPORTED #endif #define HGFS_ASSERT_PACK_PARAMS \ do { \ ASSERT(packet); \ ASSERT(packetHeader); \ ASSERT(session); \ ASSERT(payloadSize); \ } while(0) /* * This is the default/minimal set of capabilities which is supported by every transport. * Every transport and session may have additional capabilities in addition to these. */ static HgfsCapability hgfsDefaultCapabilityTable[] = { {HGFS_OP_OPEN, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_READ, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_WRITE, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_CLOSE, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SEARCH_OPEN, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SEARCH_READ, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SEARCH_CLOSE, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_GETATTR, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SETATTR, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_CREATE_DIR, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_DELETE_FILE, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_DELETE_DIR, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_RENAME, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_QUERY_VOLUME_INFO, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_OPEN_V2, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_GETATTR_V2, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SETATTR_V2, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SEARCH_READ_V2, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_CREATE_SYMLINK, HGFS_REQUEST_POSIX_SUPPORTED}, {HGFS_OP_SERVER_LOCK_CHANGE, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_CREATE_DIR_V2, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_DELETE_FILE_V2, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_DELETE_DIR_V2, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_RENAME_V2, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_OPEN_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_READ_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_WRITE_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_CLOSE_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SEARCH_OPEN_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SEARCH_READ_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SEARCH_CLOSE_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_GETATTR_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_SETATTR_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_CREATE_DIR_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_DELETE_FILE_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_DELETE_DIR_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_RENAME_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_QUERY_VOLUME_INFO_V3, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_CREATE_SYMLINK_V3, HGFS_REQUEST_POSIX_SUPPORTED}, {HGFS_OP_SERVER_LOCK_CHANGE_V3, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_WRITE_WIN32_STREAM_V3, HGFS_REQUEST_WIN32_SUPPORTED}, {HGFS_OP_CREATE_SESSION_V4, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_DESTROY_SESSION_V4, HGFS_REQUEST_SUPPORTED}, {HGFS_OP_READ_FAST_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_WRITE_FAST_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_SET_WATCH_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_REMOVE_WATCH_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_NOTIFY_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_SEARCH_READ_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_OPEN_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_ENUMERATE_STREAMS_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_GETATTR_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_SETATTR_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_DELETE_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_LINKMOVE_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_FSCTL_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_ACCESS_CHECK_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_FSYNC_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_QUERY_VOLUME_INFO_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_OPLOCK_ACQUIRE_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_OPLOCK_BREAK_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_LOCK_BYTE_RANGE_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_UNLOCK_BYTE_RANGE_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_QUERY_EAS_V4, HGFS_REQUEST_NOT_SUPPORTED}, {HGFS_OP_SET_EAS_V4, HGFS_REQUEST_NOT_SUPPORTED}, }; /* *----------------------------------------------------------------------------- * * HgfsValidateReplySize -- * * Verify if the size of a reply does not exceed maximum supported size. * * Results: * TRUE if the packet size is acceptable, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsValidateReplySize(char const *packetIn, HgfsOp op, size_t packetSize) { Bool result; HgfsRequest *request = (HgfsRequest *)packetIn; if (HGFS_OP_NEW_HEADER != request->op) { if (HGFS_OP_READ_V3 == op) { result = packetSize <= HGFS_LARGE_PACKET_MAX; } else { result = packetSize <= HGFS_PACKET_MAX; } } else { result = TRUE; } if (!result) { LOG(4, ("%s: Reply exceeded maximum support size!\n", __FUNCTION__)); } return result; } /* *----------------------------------------------------------------------------- * * HgfsGetPayloadSize -- * * Returns size of the payload based on incoming packet and total * packet size. * * Results: * Size of the payload in bytes. * * Side effects: * None * *----------------------------------------------------------------------------- */ size_t HgfsGetPayloadSize(char const *packetIn, // IN: request packet size_t packetSize) // IN: request packet size { HgfsRequest *request = (HgfsRequest *)packetIn; size_t result; ASSERT(packetSize >= sizeof *request); if (request->op < HGFS_OP_CREATE_SESSION_V4) { result = packetSize - sizeof *request; } else { HgfsHeader *header = (HgfsHeader *)packetIn; ASSERT(packetSize >= header->packetSize); ASSERT(header->packetSize >= header->headerSize); result = header->packetSize - header->headerSize; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackHeaderV1V2 -- * * Unpack the client request that contains a basic valid HgfsHeader for protocol * versions 1 and 2. * Extract the useful details for the caller. * * Results: * HGFS_ERROR_SUCCESS always. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsUnpackHeaderV1V2(const HgfsRequest *request, // IN: request header size_t requestSize, // IN: request data size uint32 *requestId, // OUT: unique request id HgfsOp *opcode, // OUT: request opcode size_t *payloadSize, // OUT: size of the payload const void **payload) // OUT: pointer to the payload { /* V1 or V2 requests do not have a separate header. */ *requestId = request->id; *opcode = request->op; *payloadSize = requestSize; *payload = request; return HGFS_ERROR_SUCCESS; } /* *----------------------------------------------------------------------------- * * HgfsUnpackHeaderV3 -- * * Unpack the client request that contains a basic valid HgfsHeader for protocol * version 3. * Extract the useful details for the caller. * * Results: * HGFS_ERROR_SUCCESS always. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsUnpackHeaderV3(const HgfsRequest *request, // IN: request header size_t requestSize, // IN: request data size uint32 *requestId, // OUT: unique request id HgfsOp *opcode, // OUT: request opcode size_t *payloadSize, // OUT: size of the payload const void **payload) // OUT: pointer to the payload { /* Old header with V3 request. */ *requestId = request->id; *opcode = request->op; if (requestSize > sizeof *request) { *payload = HGFS_REQ_GET_PAYLOAD_V3(request); *payloadSize = requestSize - ((char *)*payload - (char *)request); } else { *payload = NULL; *payloadSize = 0; } return HGFS_ERROR_SUCCESS; } /* *----------------------------------------------------------------------------- * * HgfsUnpackHeaderV4 -- * * Unpack the client request that contains a basic valid HgfsHeader for protocol * version 4 and newer. * Extract the useful details for the caller. * * Results: * HGFS_ERROR_SUCCESS if successful or * HGFS_ERROR_PROTOCOL for a malformed request, and we cannot trust the data. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static HgfsInternalStatus HgfsUnpackHeaderV4(const HgfsHeader *requestHeader, // IN: request header size_t requestSize, // IN: request data size uint64 *sessionId, // OUT: session Id uint32 *requestId, // OUT: unique request id uint32 *hdrFlags, // OUT: header flags uint32 *information, // OUT: generic information HgfsOp *opcode, // OUT: request opcode size_t *payloadSize, // OUT: size of the payload const void **payload) // OUT: pointer to the payload { HgfsInternalStatus status = HGFS_ERROR_SUCCESS; if (requestSize < sizeof *requestHeader) { LOG(4, ("%s: Malformed HGFS packet received - header is too small!\n", __FUNCTION__)); status = HGFS_ERROR_PROTOCOL; goto exit; } if (requestSize < requestHeader->packetSize || requestHeader->packetSize < requestHeader->headerSize) { LOG(4, ("%s: Malformed HGFS packet received - inconsistent header" " and packet sizes!\n", __FUNCTION__)); status = HGFS_ERROR_PROTOCOL; goto exit; } if (HGFS_HEADER_VERSION_1 > requestHeader->version) { LOG(4, ("%s: Malformed HGFS packet received - invalid header version!\n", __FUNCTION__)); status = HGFS_ERROR_PROTOCOL; goto exit; } ASSERT(HGFS_OP_NEW_HEADER == requestHeader->dummy); /* The basics of the header are validated, get the remaining parameters. */ *sessionId = requestHeader->sessionId; *requestId = requestHeader->requestId; *opcode = requestHeader->op; /* * For version 1 of the header the file copy client did not ensure * the following fields (and reserved fields) were set and thus can * contain garbage. * For this reason, we just zero out these fields for this header version. */ if (HGFS_HEADER_VERSION_1 == requestHeader->version) { *hdrFlags = 0; *information = 0; } else { *hdrFlags = requestHeader->flags; *information = requestHeader->information; } *payloadSize = requestHeader->packetSize - requestHeader->headerSize; if (0 < *payloadSize) { *payload = (char *)requestHeader + requestHeader->headerSize; } else { *payload = NULL; Log("%s: HGFS packet with header and no payload!\n", __FUNCTION__); } exit: return status; } /* *----------------------------------------------------------------------------- * * HgfsUnpackPacketParams -- * * Takes the Hgfs packet and extracts the operation parameters. * This validates the incoming packet as part of the processing. * * Results: * HGFS_ERROR_SUCCESS if all the request parameters are successfully extracted. * HGFS_ERROR_INTERNAL if an error occurs without sufficient request data to be * able to send a reply to the client. * Any other appropriate error if the incoming packet has errors and there is * sufficient information to send a response. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsInternalStatus HgfsUnpackPacketParams(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size Bool *sessionEnabled, // OUT: session enabled request uint64 *sessionId, // OUT: session Id uint32 *requestId, // OUT: unique request id HgfsOp *opcode, // OUT: request opcode size_t *payloadSize, // OUT: size of the opcode request const void **payload) // OUT: pointer to the opcode request { const HgfsRequest *request; HgfsInternalStatus unpackStatus = HGFS_ERROR_SUCCESS; ASSERT(NULL != packet); request = packet; LOG(4, ("%s: Received a request with opcode %d.\n", __FUNCTION__, request->op)); /* * Error out if less than HgfsRequest size. * We cannot continue any further with this packet. */ if (packetSize < sizeof *request) { LOG(4, ("%s: Received a request with opcode %"FMTSZ"u.\n", __FUNCTION__, packetSize)); unpackStatus = HGFS_ERROR_INTERNAL; goto exit; } *sessionEnabled = FALSE; if (request->op < HGFS_OP_OPEN_V3) { unpackStatus = HgfsUnpackHeaderV1V2(request, packetSize, requestId, opcode, payloadSize, payload); } else if (request->op < HGFS_OP_CREATE_SESSION_V4) { unpackStatus = HgfsUnpackHeaderV3(request, packetSize, requestId, opcode, payloadSize, payload); } else if (HGFS_OP_NEW_HEADER == request->op) { /* The legacy op means a new header but we can have V3 and newer opcodes. */ const HgfsHeader *requestHdr = packet; uint32 hdrFlags = 0; uint32 information; *sessionEnabled = TRUE; unpackStatus = HgfsUnpackHeaderV4(requestHdr, packetSize, sessionId, requestId, &hdrFlags, &information, opcode, payloadSize, payload); /* * Test if the client sent invalid flags (and information in future cases). * Note, a basic sanitation was done in the unpack header itself, only V2 * or newer allowed to pass meaningful values through. */ if (0 != hdrFlags && 0 == (hdrFlags & (HGFS_PACKET_FLAG_REQUEST | HGFS_PACKET_FLAG_REPLY))) { unpackStatus = HGFS_ERROR_PROTOCOL; } } else { LOG(4, ("%s: HGFS packet - unknown opcode == newer client or malformed!\n", __FUNCTION__)); unpackStatus = HGFS_ERROR_INTERNAL; } exit: LOG(4, ("%s: unpacked request(op %d, id %u) -> %u.\n", __FUNCTION__, request->op, *requestId, unpackStatus)); return unpackStatus; } /* *----------------------------------------------------------------------------- * * HgfsUnpackOpenPayloadV1 -- * * Unpack and validate payload for hgfs open request V1 to the HgfsFileOpenInfo * structure that is used to pass around open request information. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackOpenPayloadV1(const HgfsRequestOpen *requestV1, // IN: request payload size_t payloadSize, // IN: request payload size HgfsFileOpenInfo *openInfo) // IN/OUT: open info struct { size_t extra; /* Enforced by the dispatch function. */ if (payloadSize < sizeof *requestV1) { LOG(4, ("%s: Malformed HGFS packet received - payload too small\n", __FUNCTION__)); return FALSE; } extra = payloadSize - sizeof *requestV1; /* * The request file name length is user-provided, so this test must be * carefully written to prevent wraparounds. */ if (requestV1->fileName.length > extra) { /* The input packet is smaller than the request. */ LOG(4, ("%s: Malformed HGFS packet received - payload too small to hold file name\n", __FUNCTION__)); return FALSE; } /* For OpenV1 requests, we know exactly what fields we expect. */ openInfo->mask = HGFS_OPEN_VALID_MODE | HGFS_OPEN_VALID_FLAGS | HGFS_OPEN_VALID_OWNER_PERMS | HGFS_OPEN_VALID_FILE_NAME; openInfo->mode = requestV1->mode; openInfo->cpName = requestV1->fileName.name; openInfo->cpNameSize = requestV1->fileName.length; openInfo->flags = requestV1->flags; openInfo->ownerPerms = requestV1->permissions; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackOpenPayloadV2 -- * * Unpack and validate payload for hgfs open request V2 to the HgfsFileOpenInfo * structure that is used to pass around open request information. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackOpenPayloadV2(const HgfsRequestOpenV2 *requestV2, // IN: request payload size_t payloadSize, // IN: request payload size HgfsFileOpenInfo *openInfo) // IN/OUT: open info struct { size_t extra; /* Enforced by the dispatch function. */ if (payloadSize < sizeof *requestV2) { LOG(4, ("%s: Malformed HGFS packet received - payload too small\n", __FUNCTION__)); return FALSE; } extra = payloadSize - sizeof *requestV2; if (!(requestV2->mask & HGFS_OPEN_VALID_FILE_NAME)) { /* We do not support open requests without a valid file name. */ LOG(4, ("%s: Malformed HGFS packet received - invalid mask\n", __FUNCTION__)); return FALSE; } /* * The request file name length is user-provided, so this test must be * carefully written to prevent wraparounds. */ if (requestV2->fileName.length > extra) { /* The input packet is smaller than the request. */ LOG(4, ("%s: Malformed HGFS packet received - payload too small to hold file name\n", __FUNCTION__)); return FALSE; } /* * Copy all the fields into our carrier struct. Some will probably be * garbage, but it's simpler to copy everything now and check the * valid bits before reading later. */ openInfo->mask = requestV2->mask; openInfo->mode = requestV2->mode; openInfo->cpName = requestV2->fileName.name; openInfo->cpNameSize = requestV2->fileName.length; openInfo->flags = requestV2->flags; openInfo->specialPerms = requestV2->specialPerms; openInfo->ownerPerms = requestV2->ownerPerms; openInfo->groupPerms = requestV2->groupPerms; openInfo->otherPerms = requestV2->otherPerms; openInfo->attr = requestV2->attr; openInfo->allocationSize = requestV2->allocationSize; openInfo->desiredAccess = requestV2->desiredAccess; openInfo->shareAccess = requestV2->shareAccess; openInfo->desiredLock = requestV2->desiredLock; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackOpenPayloadV3 -- * * Unpack and validate payload for hgfs open request V3 to the HgfsFileOpenInfo * structure that is used to pass around open request information. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackOpenPayloadV3(const HgfsRequestOpenV3 *requestV3, // IN: request payload size_t payloadSize, // IN: request payload size HgfsFileOpenInfo *openInfo) // IN/OUT: open info struct { size_t extra; /* Enforced by the dispatch function. */ if (payloadSize < sizeof *requestV3) { LOG(4, ("%s: Malformed HGFS packet received - payload too small\n", __FUNCTION__)); return FALSE; } extra = payloadSize - sizeof *requestV3; if (!(requestV3->mask & HGFS_OPEN_VALID_FILE_NAME)) { /* We do not support open requests without a valid file name. */ LOG(4, ("%s: Malformed HGFS packet received - incorrect mask\n", __FUNCTION__)); return FALSE; } /* * The request file name length is user-provided, so this test must be * carefully written to prevent wraparounds. */ if (requestV3->fileName.length > extra) { /* The input packet is smaller than the request. */ LOG(4, ("%s: Malformed HGFS packet received - payload too small to hold file name\n", __FUNCTION__)); return FALSE; } /* * Copy all the fields into our carrier struct. Some will probably be * garbage, but it's simpler to copy everything now and check the * valid bits before reading later. */ openInfo->mask = requestV3->mask; openInfo->mode = requestV3->mode; openInfo->cpName = requestV3->fileName.name; openInfo->cpNameSize = requestV3->fileName.length; openInfo->caseFlags = requestV3->fileName.caseType; openInfo->flags = requestV3->flags; openInfo->specialPerms = requestV3->specialPerms; openInfo->ownerPerms = requestV3->ownerPerms; openInfo->groupPerms = requestV3->groupPerms; openInfo->otherPerms = requestV3->otherPerms; openInfo->attr = requestV3->attr; openInfo->allocationSize = requestV3->allocationSize; openInfo->desiredAccess = requestV3->desiredAccess; openInfo->shareAccess = requestV3->shareAccess; openInfo->desiredLock = requestV3->desiredLock; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackOpenRequest -- * * Unpack hgfs open request to the HgfsFileOpenInfo structure that is used * to pass around open request information. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackOpenRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: packet size HgfsOp op, // IN: requested operation HgfsFileOpenInfo *openInfo) // IN/OUT: open info structure { Bool result; ASSERT(packet); ASSERT(openInfo); openInfo->requestType = op; openInfo->caseFlags = HGFS_FILE_NAME_DEFAULT_CASE; switch (op) { case HGFS_OP_OPEN_V3: { const HgfsRequestOpenV3 *requestV3 = packet; LOG(4, ("%s: HGFS_OP_OPEN_V3\n", __FUNCTION__)); result = HgfsUnpackOpenPayloadV3(requestV3, packetSize, openInfo); break; } case HGFS_OP_OPEN_V2: { const HgfsRequestOpenV2 *requestV2 = packet; LOG(4, ("%s: HGFS_OP_OPEN_V2\n", __FUNCTION__)); result = HgfsUnpackOpenPayloadV2(requestV2, packetSize, openInfo); break; } case HGFS_OP_OPEN: { const HgfsRequestOpen *requestV1 = packet; LOG(4, ("%s: HGFS_OP_OPEN\n", __FUNCTION__)); result = HgfsUnpackOpenPayloadV1(requestV1, packetSize, openInfo); break; } default: NOT_REACHED(); result = FALSE; } if (!result) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); } return result; } /* *----------------------------------------------------------------------------- * * HgfsPackReplyHeaderV4 -- * * Pack hgfs header that corresponds to an HGFS protocol packet. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsPackReplyHeaderV4(HgfsStatus status, // IN: reply status uint32 payloadSize, // IN: size of the reply payload HgfsOp opcode, // IN: request type uint64 sessionId, // IN: session id uint32 requestId, // IN: request id uint32 hdrFlags, // IN: header flags size_t hdrPacketSize, // IN: header packet size HgfsHeader *hdrPacket) // OUT: outgoing packet header { Bool result = FALSE; if (hdrPacketSize >= sizeof *hdrPacket) { memset(hdrPacket, 0, sizeof *hdrPacket); hdrPacket->version = HGFS_HEADER_VERSION; hdrPacket->dummy = HGFS_OP_NEW_HEADER; hdrPacket->packetSize = payloadSize + sizeof *hdrPacket; hdrPacket->headerSize = sizeof *hdrPacket; hdrPacket->requestId = requestId; hdrPacket->op = opcode; hdrPacket->status = status; hdrPacket->flags = hdrFlags; hdrPacket->information = status; hdrPacket->sessionId = sessionId; result = TRUE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsPackLegacyReplyHeader -- * * Pack pre-V4 reply header. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsPackLegacyReplyHeader(HgfsStatus status, // IN: reply status HgfsHandle id, // IN: original packet id size_t hdrPacketSize, // IN: header packet size HgfsReply *hdrPacket) // OUT: outgoing packet header { Bool result = FALSE; if (hdrPacketSize >= sizeof *hdrPacket) { memset(hdrPacket, 0, sizeof *hdrPacket); hdrPacket->status = status; hdrPacket->id = id; result = TRUE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsPackReplyHeader -- * * Pack hgfs header that corresponds to an HGFS protocol packet. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackReplyHeader(HgfsInternalStatus status, // IN: reply status uint32 payloadSize, // IN: size of the reply payload Bool sessionEnabledHeader, // IN: session enabled header uint64 sessionId, // IN: session id uint32 requestId, // IN: request id HgfsOp opcode, // IN: request operation uint32 hdrFlags, // IN: header flags size_t hdrPacketSize, // IN: header packet size void *hdrPacket) // OUT: outgoing packet header { HgfsStatus replyStatus; Bool result; if (NULL == hdrPacket) { result = FALSE; goto exit; } replyStatus = HgfsConvertFromInternalStatus(status); if (sessionEnabledHeader) { result = HgfsPackReplyHeaderV4(replyStatus, payloadSize, opcode, sessionId, requestId, HGFS_PACKET_FLAG_REPLY, hdrPacketSize, hdrPacket); } else { result = HgfsPackLegacyReplyHeader(replyStatus, requestId, hdrPacketSize, hdrPacket); } exit: return result; } /* *----------------------------------------------------------------------------- * * HgfsPackOpenReplyV3 -- * * Pack hgfs open V3 reply payload to the HgfsReplyOpenV3 structure. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackOpenReplyV3(HgfsFileOpenInfo *openInfo, // IN: open info struct HgfsReplyOpenV3 *reply) // OUT: size of packet { reply->file = openInfo->file; reply->reserved = 0; reply->flags = 0; if (openInfo->mask & HGFS_OPEN_VALID_SERVER_LOCK) { reply->acquiredLock = openInfo->acquiredLock; } else { reply->acquiredLock = HGFS_LOCK_NONE; } } /* *----------------------------------------------------------------------------- * * HgfsPackOpenV2Reply -- * * Pack hgfs open V2 reply payload to the HgfsReplyOpenV3 structure. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackOpenV2Reply(HgfsFileOpenInfo *openInfo, // IN: open info struct HgfsReplyOpenV2 *reply) // OUT: reply payload { reply->file = openInfo->file; if (openInfo->mask & HGFS_OPEN_VALID_SERVER_LOCK) { reply->acquiredLock = openInfo->acquiredLock; } else { reply->acquiredLock = HGFS_LOCK_NONE; } } /* *----------------------------------------------------------------------------- * * HgfsPackOpenV1Reply -- * * Pack hgfs open V1 reply payload to the HgfsReplyOpenV3 structure. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackOpenV1Reply(HgfsFileOpenInfo *openInfo, // IN: open info struct HgfsReplyOpen *reply) // OUT: reply payload { reply->file = openInfo->file; } /* *----------------------------------------------------------------------------- * * HgfsPackOpenReply -- * * Pack hgfs open reply to the HgfsReplyOpen{V2} structure. * * Results: * Always TRUE, FALSE if bad opcode. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackOpenReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsFileOpenInfo *openInfo, // IN: open info struct size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; ASSERT(openInfo); HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; switch (openInfo->requestType) { case HGFS_OP_OPEN_V3: { HgfsReplyOpenV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); HgfsPackOpenReplyV3(openInfo, reply); *payloadSize = sizeof *reply; break; } case HGFS_OP_OPEN_V2: { HgfsReplyOpenV2 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); HgfsPackOpenV2Reply(openInfo, reply); *payloadSize = sizeof *reply; break; } case HGFS_OP_OPEN: { HgfsReplyOpen *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); HgfsPackOpenV1Reply(openInfo, reply); *payloadSize = sizeof *reply; break; } default: NOT_REACHED(); result = FALSE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackClosePayload -- * * Unpack hgfs close payload to get the handle which need to be closed. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackClosePayload(const HgfsRequestClose *request, // IN: payload size_t payloadSize, // IN: payload size HgfsHandle* file) // OUT: HGFS handle to close { LOG(4, ("%s: HGFS_OP_CLOSE\n", __FUNCTION__)); if (payloadSize >= sizeof *request) { *file = request->file; return TRUE; } return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackClosePayloadV3 -- * * Unpack hgfs close payload V3 to get the handle which need to be closed. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackClosePayloadV3(const HgfsRequestCloseV3 *requestV3, // IN: payload size_t payloadSize, // IN: payload size HgfsHandle* file) // OUT: HGFS handle to close { LOG(4, ("%s: HGFS_OP_CLOSE_V3\n", __FUNCTION__)); if (payloadSize >= sizeof *requestV3) { *file = requestV3->file; return TRUE; } LOG(4, ("%s: Too small HGFS packet\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackCloseRequest -- * * Unpack hgfs close request to get the handle to close. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackCloseRequest(const void *packet, // IN: request packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type HgfsHandle *file) // OUT: Handle to close { ASSERT(packet); switch (op) { case HGFS_OP_CLOSE_V3: { const HgfsRequestCloseV3 *requestV3 = packet; if (!HgfsUnpackClosePayloadV3(requestV3, packetSize, file)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_CLOSE: { const HgfsRequestClose *requestV1 = packet; if (!HgfsUnpackClosePayload(requestV1, packetSize, file)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } default: NOT_REACHED(); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackCloseReply -- * * Pack hgfs close reply to the HgfsReplyClose(V3) structure. * * Results: * Always TRUE, FALSE if bad opcode. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackCloseReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of packet excluding header HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; switch (op) { case HGFS_OP_CLOSE_V3: { HgfsReplyCloseV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); /* Reply consists of a reserved field only. */ reply->reserved = 0; *payloadSize = sizeof *reply; break; } case HGFS_OP_CLOSE: { HgfsReplyClose *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } default: NOT_REACHED(); result = FALSE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSearchClosePayload -- * * Unpack hgfs search close payload to get the search handle which need to be closed. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSearchClosePayload(const HgfsRequestSearchClose *request, // IN: payload size_t payloadSize, // IN: payload size HgfsHandle* search) // OUT: search to close { LOG(4, ("%s: HGFS_OP_SEARCH_CLOSE\n", __FUNCTION__)); if (payloadSize >= sizeof *request) { *search = request->search; return TRUE; } LOG(4, ("%s: Too small HGFS packet\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSearchClosePayloadV3 -- * * Unpack hgfs search close payload V3 to get the search handle which need to * be closed. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSearchClosePayloadV3(const HgfsRequestSearchCloseV3 *requestV3, // IN: payload size_t payloadSize, // IN: payload size HgfsHandle* search) // OUT: search { LOG(4, ("%s: HGFS_OP_SEARCH_CLOSE_V3\n", __FUNCTION__)); if (payloadSize >= sizeof *requestV3) { *search = requestV3->search; return TRUE; } LOG(4, ("%s: Too small HGFS packet\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSearchCloseRequest -- * * Unpack hgfs search close request to get the search handle. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackSearchCloseRequest(const void *packet, // IN: request packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type HgfsHandle *search) // OUT: search to close { ASSERT(packet); switch (op) { case HGFS_OP_SEARCH_CLOSE_V3: { const HgfsRequestSearchCloseV3 *requestV3 = packet; if (!HgfsUnpackSearchClosePayloadV3(requestV3, packetSize, search)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_SEARCH_CLOSE: { const HgfsRequestSearchClose *requestV1 = packet; if (!HgfsUnpackSearchClosePayload(requestV1, packetSize, search)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } default: NOT_REACHED(); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackSearchCloseReply -- * * Pack hgfs SearchClose reply into a HgfsReplySearchClose(V3) structure. * * Results: * Always TRUE, except when it is called with a * wrong op or insufficient output buffer (which is a programming error). * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackSearchCloseReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; switch (op) { case HGFS_OP_SEARCH_CLOSE_V3: { HgfsReplyCloseV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); /* Reply consists of only a reserved field. */ reply->reserved = 0; *payloadSize = sizeof *reply; break; } case HGFS_OP_SEARCH_CLOSE: { HgfsReplyClose *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } default: NOT_REACHED(); result = FALSE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackFileName -- * * Unpack HgfsFileName into a pointer to a CPName and size of the name. * Verifies that input buffer has enough space to hold the name. * * Results: * TRUE on success, FALSE on failure (buffer too small). * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackFileName(const HgfsFileName *name, // IN: file name size_t maxNameSize, // IN: space allocated for the name const char **cpName, // OUT: CP name size_t *cpNameSize) // OUT: CP name size { /* * The request file name length is user-provided, so this test must be * carefully written to prevent wraparounds. */ if (name->length > maxNameSize) { /* The input packet is smaller than the request. */ return FALSE; } *cpName = name->name; *cpNameSize = name->length; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackFileNameV3 -- * * Unpack HgfsFileNameV3 into a pointer to a CPName and size of the name * or into file handle. * Verifies that input buffer has enough space to hold the name. * * Results: * TRUE on success, FALSE on failure (buffer too small). * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackFileNameV3(const HgfsFileNameV3 *name, // IN: file name size_t maxNameSize, // IN: space allocated for the name Bool *useHandle, // OUT: file name or handle returned? const char **cpName, // OUT: CP name size_t *cpNameSize, // OUT: CP name size HgfsHandle *file, // OUT: HGFS file handle uint32 *caseFlags) // OUT: case-sensitivity flags { *useHandle = FALSE; *file = HGFS_INVALID_HANDLE; *cpName = NULL; *cpNameSize = 0; /* * If we've been asked to reuse a handle, we don't need to look at, let * alone test the filename or its length. */ if (name->flags & HGFS_FILE_NAME_USE_FILE_DESC) { *file = name->fid; *caseFlags = HGFS_FILE_NAME_DEFAULT_CASE; *useHandle = TRUE; } else { /* * The request file name length is user-provided, so this test must be * carefully written to prevent wraparounds. */ if (name->length > maxNameSize) { /* The input packet is smaller than the request */ LOG(4, ("%s: Error unpacking file name - buffer too small\n", __FUNCTION__)); return FALSE; } *cpName = name->name; *cpNameSize = name->length; *caseFlags = name->caseType; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackDeletePayloadV3 -- * * Unpack hgfs delete request V3 payload and initialize a corresponding * HgfsHandle or file name to tell us which to delete. Hints * holds flags to specify a handle or name for the file or * directory to delete. * * Since the structure of the get delete request packet is the same * for Delete File or Directory of the protocol, code is identical for * both operations. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackDeletePayloadV3(const HgfsRequestDeleteV3 *requestV3, // IN: request payload size_t payloadSize, // IN: payload size const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsDeleteHint *hints, // OUT: delete hints HgfsHandle *file, // OUT: file handle uint32 *caseFlags) // OUT: case-sensitivity flags { Bool result = TRUE; Bool useHandle; if (payloadSize < sizeof *requestV3) { result = FALSE; goto exit; } *hints = requestV3->hints; if (!HgfsUnpackFileNameV3(&requestV3->fileName, payloadSize - sizeof *requestV3, &useHandle, cpName, cpNameSize, file, caseFlags)) { result = FALSE; goto exit; } if (useHandle) { *hints |= HGFS_DELETE_HINT_USE_FILE_DESC; } exit: LOG(8, ("%s: unpacking HGFS_OP_DELETE_DIR/FILE_V3 -> %d\n", __FUNCTION__, result)); return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackDeletePayloadV2 -- * * Unpack hgfs delete request V2 payload and initialize a corresponding * HgfsHandle or file name to tell us which to delete. Hints * holds flags to specify a handle or name for the file or * directory to delete. * * Since the structure of the get delete request packet is the same * for Delete File or Directory of the protocol, code is identical for * both operations. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackDeletePayloadV2(const HgfsRequestDeleteV2 *requestV2, // IN: request payload size_t payloadSize, // IN: payload size const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsDeleteHint *hints, // OUT: delete hints HgfsHandle *file) // OUT: file handle { Bool result = TRUE; /* Enforced by the dispatch function. */ ASSERT(payloadSize >= sizeof *requestV2); *file = HGFS_INVALID_HANDLE; *hints = requestV2->hints; /* * If we've been asked to reuse a handle, we don't need to look at, let * alone test the filename or its length. */ if (requestV2->hints & HGFS_DELETE_HINT_USE_FILE_DESC) { *file = requestV2->file; *cpName = NULL; *cpNameSize = 0; } else { result = HgfsUnpackFileName(&requestV2->fileName, payloadSize - sizeof *requestV2, cpName, cpNameSize); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackDeletePayloadV1 -- * * Unpack hgfs delete request V1 payload and initialize a corresponding * file name to tell us which to delete. * * Since the structure of the get delete request packet is the same * for Delete File or Directory of the protocol, code is identical for * both operations. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackDeletePayloadV1(const HgfsRequestDelete *requestV1, // IN: request payload size_t payloadSize, // IN: payload size const char **cpName, // OUT: cpName size_t *cpNameSize) // OUT: cpName size { return HgfsUnpackFileName(&requestV1->fileName, payloadSize - sizeof *requestV1, cpName, cpNameSize); } /* *----------------------------------------------------------------------------- * * HgfsUnpackDeleteRequest -- * * Unpack hgfs delete request and initialize a corresponding * HgfsHandle or file name to tell us which to delete. Hints * holds flags to specify a handle or name for the file or * directory to delete. * * Since the structure of the get delete request packet is the same * for Delete File or Directory of the protocol, code is identical for * both operations. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackDeleteRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: requested operation const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsDeleteHint *hints, // OUT: delete hints HgfsHandle *file, // OUT: file handle uint32 *caseFlags) // OUT: case-sensitivity flags { ASSERT(packet); ASSERT(cpName); ASSERT(cpNameSize); ASSERT(file); ASSERT(hints); ASSERT(caseFlags); *caseFlags = HGFS_FILE_NAME_DEFAULT_CASE; *hints = 0; *file = HGFS_INVALID_HANDLE; switch (op) { case HGFS_OP_DELETE_FILE_V3: case HGFS_OP_DELETE_DIR_V3: { const HgfsRequestDeleteV3 *requestV3 = packet; if (!HgfsUnpackDeletePayloadV3(requestV3, packetSize, cpName, cpNameSize, hints, file, caseFlags)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_DELETE_FILE_V2: case HGFS_OP_DELETE_DIR_V2: { const HgfsRequestDeleteV2 *requestV2 = packet; if (!HgfsUnpackDeletePayloadV2(requestV2, packetSize, cpName, cpNameSize, hints, file)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_DELETE_FILE: case HGFS_OP_DELETE_DIR: { const HgfsRequestDelete *requestV1 = packet; if (!HgfsUnpackDeletePayloadV1(requestV1, packetSize, cpName, cpNameSize)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } default: NOT_REACHED(); LOG(4, ("%s: Invalid opcode\n", __FUNCTION__)); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackDeleteReply -- * * Pack hgfs delete reply. * Since the structure of the delete reply packet hasn't changed in * version 2 of the protocol, HgfsReplyDeleteV2 is identical to * HgfsReplyDelete. So use HgfsReplyDelete type to access packetIn to * keep the code simple. * * Results: * TRUE if valid op version reply filled, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackDeleteReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: requested operation size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; /* No reply payload, just header. */ switch (op) { case HGFS_OP_DELETE_FILE_V3: case HGFS_OP_DELETE_DIR_V3: { HgfsReplyDeleteV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } case HGFS_OP_DELETE_FILE_V2: case HGFS_OP_DELETE_FILE: case HGFS_OP_DELETE_DIR_V2: case HGFS_OP_DELETE_DIR: { HgfsReplyDelete *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } default: LOG(4, ("%s: invalid op code %d\n", __FUNCTION__, op)); result = FALSE; NOT_REACHED(); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackRenamePayloadV3 -- * * Unpack hgfs rename request V3 payload and initialize a corresponding * HgfsHandles or file names to tell us old and new names/handles. Hints * holds flags to specify a handle or name for the file or * directory to rename. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackRenamePayloadV3(const HgfsRequestRenameV3 *requestV3, // IN: request payload size_t payloadSize, // IN: payload size const char **cpOldName, // OUT: rename src size_t *cpOldNameLen, // OUT: rename src size const char **cpNewName, // OUT: rename dst size_t *cpNewNameLen, // OUT: rename dst size HgfsRenameHint *hints, // OUT: rename hints HgfsHandle *srcFile, // OUT: src file handle HgfsHandle *targetFile, // OUT: target file handle uint32 *oldCaseFlags, // OUT: source case flags uint32 *newCaseFlags) // OUT: dest. case flags { size_t extra; const HgfsFileNameV3 *newName; Bool useHandle; LOG(4, ("%s: HGFS_OP_RENAME_V3\n", __FUNCTION__)); if (payloadSize < sizeof *requestV3) { return FALSE; } extra = payloadSize - sizeof *requestV3; *hints = requestV3->hints; /* * Get the old and new filenames from the request. * * Getting the new filename is somewhat inconvenient, because we * don't know where request->newName actually starts, thanks to the * fact that request->oldName is of variable length. We get around * this by using an HgfsFileName*, assigning it to the correct address * just after request->oldName ends, and using that to access the * new name. */ /* * If we've been asked to reuse a handle, we don't need to look at, let * alone test the filename or its length. This applies to the source * and the target. */ if (!HgfsUnpackFileNameV3(&requestV3->oldName, extra, &useHandle, cpOldName, cpOldNameLen, srcFile, oldCaseFlags)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } if (useHandle) { *hints |= HGFS_RENAME_HINT_USE_SRCFILE_DESC; newName = &requestV3->newName; } else { newName = (const HgfsFileNameV3 *)(requestV3->oldName.name + 1 + *cpOldNameLen); extra -= *cpOldNameLen; } if (!HgfsUnpackFileNameV3(newName, extra, &useHandle, cpNewName, cpNewNameLen, targetFile, newCaseFlags)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } if (useHandle) { *hints |= HGFS_RENAME_HINT_USE_TARGETFILE_DESC; } LOG(8, ("%s: unpacking HGFS_OP_RENAME_V3 -> success\n", __FUNCTION__)); return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackRenamePayloadV2 -- * * Unpack hgfs rename request V2 payload and initialize a corresponding * HgfsHandle or file name to tell us which to delete. Hints * holds flags to specify a handle or name for the file or * directory to rename. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackRenamePayloadV2(const HgfsRequestRenameV2 *requestV2, // IN: request payload size_t payloadSize, // IN: payload size const char **cpOldName, // OUT: rename src size_t *cpOldNameLen, // OUT: rename src size const char **cpNewName, // OUT: rename dst size_t *cpNewNameLen, // OUT: rename dst size HgfsRenameHint *hints, // OUT: rename hints HgfsHandle *srcFile, // OUT: src file handle HgfsHandle *targetFile) // OUT: target file handle { const HgfsFileName *newName; size_t extra; /* Enforced by the dispatch function. */ if (payloadSize < sizeof *requestV2) { LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } extra = payloadSize - sizeof *requestV2; *hints = requestV2->hints; /* * If we've been asked to reuse a handle, we don't need to look at, let * alone test the filename or its length. This applies to the source * and the target. */ if (*hints & HGFS_RENAME_HINT_USE_SRCFILE_DESC) { *srcFile = requestV2->srcFile; *cpOldName = NULL; *cpOldNameLen = 0; } else { if (!HgfsUnpackFileName(&requestV2->oldName, extra, cpOldName, cpOldNameLen)) { LOG(4, ("%s: Error decoding HGFS packet - not enough room for file name\n", __FUNCTION__)); return FALSE; } extra -= *cpOldNameLen; } if (*hints & HGFS_RENAME_HINT_USE_TARGETFILE_DESC) { *targetFile = requestV2->targetFile; *cpNewName = NULL; *cpNewNameLen = 0; } else { newName = (const HgfsFileName *)((char *)(&requestV2->oldName + 1) + *cpOldNameLen); if (!HgfsUnpackFileName(newName, extra, cpNewName, cpNewNameLen)) { LOG(4, ("%s: Error decoding HGFS packet - not enough room for file name\n", __FUNCTION__)); return FALSE; } } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackRenamePayloadV1 -- * * Unpack hgfs rename request V1 payload and initialize a corresponding * old and new file names. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackRenamePayloadV1(const HgfsRequestRename *requestV1, // IN: request payload size_t payloadSize, // IN: payload size const char **cpOldName, // OUT: rename src size_t *cpOldNameLen, // OUT: rename src size const char **cpNewName, // OUT: rename dst size_t *cpNewNameLen) // OUT: rename dst size { const HgfsFileName *newName; uint32 extra; if (payloadSize < sizeof *requestV1) { return FALSE; } extra = payloadSize - sizeof *requestV1; if (!HgfsUnpackFileName(&requestV1->oldName, extra, cpOldName, cpOldNameLen)) { LOG(4, ("%s: Error decoding HGFS packet - not enough room for file name\n", __FUNCTION__)); return FALSE; } extra -= requestV1->oldName.length; newName = (const HgfsFileName *)((char *)(&requestV1->oldName + 1) + requestV1->oldName.length); return HgfsUnpackFileName(newName, extra, cpNewName, cpNewNameLen); } /* *----------------------------------------------------------------------------- * * HgfsUnpackRenameRequest -- * * Unpack hgfs rename request and initialize a corresponding * HgfsHandle or file name to tell us which to rename. Hints * holds flags to specify a handle or name for the file or * directory to rename. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackRenameRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: requested operation const char **cpOldName, // OUT: rename src size_t *cpOldNameLen, // OUT: rename src size const char **cpNewName, // OUT: rename dst size_t *cpNewNameLen, // OUT: rename dst size HgfsRenameHint *hints, // OUT: rename hints HgfsHandle *srcFile, // OUT: src file handle HgfsHandle *targetFile, // OUT: target file handle uint32 *oldCaseFlags, // OUT: source case-sensitivity flags uint32 *newCaseFlags) // OUT: dest. case-sensitivity flags { ASSERT(packet); ASSERT(cpOldName); ASSERT(cpOldNameLen); ASSERT(cpNewName); ASSERT(cpNewNameLen); ASSERT(srcFile); ASSERT(targetFile); ASSERT(hints); ASSERT(oldCaseFlags); ASSERT(newCaseFlags); /* Default values for legacy requests. */ *oldCaseFlags = HGFS_FILE_NAME_DEFAULT_CASE; *newCaseFlags = HGFS_FILE_NAME_DEFAULT_CASE; *hints = 0; switch (op) { case HGFS_OP_RENAME_V3: { const HgfsRequestRenameV3 *requestV3 = packet; if (!HgfsUnpackRenamePayloadV3(requestV3, packetSize, cpOldName, cpOldNameLen, cpNewName, cpNewNameLen, hints, srcFile, targetFile, oldCaseFlags, newCaseFlags)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_RENAME_V2: { const HgfsRequestRenameV2 *requestV2 = packet; if (!HgfsUnpackRenamePayloadV2(requestV2, packetSize, cpOldName, cpOldNameLen, cpNewName, cpNewNameLen, hints, srcFile, targetFile)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_RENAME: { const HgfsRequestRename *requestV1 = packet; if (!HgfsUnpackRenamePayloadV1(requestV1, packetSize, cpOldName, cpOldNameLen, cpNewName, cpNewNameLen)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } default: LOG(4, ("%s: Invalid opcode %d\n", __FUNCTION__, op)); NOT_REACHED(); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackRenameReply -- * * Pack hgfs rename reply. * Since the structure of the rename reply packet hasn't changed in * version 2 of the protocol, HgfsReplyRenameV2 is identical to * HgfsReplyRename. So use HgfsReplyRename type to access packetIn to * keep the code simple. * * Results: * TRUE if valid op and reply set, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackRenameReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: requested operation size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; switch (op) { case HGFS_OP_RENAME_V3: { HgfsReplyRenameV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); /* Reply consists of only a reserved field. */ reply->reserved = 0; *payloadSize = sizeof *reply; break; } case HGFS_OP_RENAME_V2: case HGFS_OP_RENAME: { HgfsReplyRename *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } default: LOG(4, ("%s: invalid op code %d\n", __FUNCTION__, op)); result = FALSE; NOT_REACHED(); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackGetattrPayloadV3 -- * * Unpack hgfs get attr request V3 payload and initialize a corresponding * HgfsHandle or file name to tell us which file to get attributes. Hints * holds flags to specify a handle or name for the file or * directory to get attributes. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackGetattrPayloadV3(const HgfsRequestGetattrV3 *requestV3,// IN: request payload size_t payloadSize, // IN: payload size const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsAttrHint *hints, // OUT: getattr hints HgfsHandle *file, // OUT: file handle uint32 *caseFlags) // OUT: case-sensitivity flags { Bool result = TRUE; Bool useHandle; if (payloadSize < sizeof *requestV3) { result = FALSE; goto exit; } *hints = requestV3->hints; if (!HgfsUnpackFileNameV3(&requestV3->fileName, payloadSize - sizeof *requestV3, &useHandle, cpName, cpNameSize, file, caseFlags)) { result = FALSE; goto exit; } if (useHandle) { *hints |= HGFS_ATTR_HINT_USE_FILE_DESC; } exit: LOG(8, ("%s: unpacking HGFS_OP_GETATTR_V3 -> %d\n", __FUNCTION__, result)); return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackGetattrPayloadV2 -- * * Unpack hgfs Getattr request V2 payload and initialize a corresponding * HgfsHandle or file name to tell us which to get attributes. Hints * holds flags to specify a handle or name for the file or * directory to get attributes. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackGetattrPayloadV2(const HgfsRequestGetattrV2 *requestV2,// IN: request payload size_t payloadSize, // IN: payload size const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsAttrHint *hints, // OUT: delete hints HgfsHandle *file) // OUT: file handle { Bool result = TRUE; if (payloadSize < sizeof *requestV2) { return FALSE; } *file = HGFS_INVALID_HANDLE; *hints = requestV2->hints; /* * If we've been asked to reuse a handle, we don't need to look at, let * alone test the filename or its length. */ if (requestV2->hints & HGFS_ATTR_HINT_USE_FILE_DESC) { *file = requestV2->file; *cpName = NULL; *cpNameSize = 0; } else { result = HgfsUnpackFileName(&requestV2->fileName, payloadSize - sizeof *requestV2, cpName, cpNameSize); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackGetattrPayloadV1 -- * * Unpack hgfs getattr request V1 payload and initialize a corresponding * file name to tell us which to get attributes. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackGetattrPayloadV1(const HgfsRequestGetattr *requestV1, // IN: request payload size_t payloadSize, // IN: payload size const char **cpName, // OUT: cpName size_t *cpNameSize) // OUT: cpName size { return HgfsUnpackFileName(&requestV1->fileName, payloadSize - sizeof *requestV1, cpName, cpNameSize); } /* *----------------------------------------------------------------------------- * * HgfsPackAttrV2 -- * * Packs attr version 2 reply structure. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackAttrV2(HgfsFileAttrInfo *attr, // IN: attr stucture HgfsAttrV2 *attr2) // OUT: attr in payload { attr2->mask = attr->mask; attr2->type = attr->type; attr2->size = attr->size; attr2->creationTime = attr->creationTime; attr2->accessTime = attr->accessTime; attr2->writeTime = attr->writeTime; attr2->attrChangeTime = attr->attrChangeTime; attr2->specialPerms = attr->specialPerms; attr2->ownerPerms = attr->ownerPerms; attr2->groupPerms = attr->groupPerms; attr2->otherPerms = attr->otherPerms; attr2->flags = attr->flags; attr2->allocationSize = attr->allocationSize; attr2->userId = attr->userId; attr2->groupId = attr->groupId; attr2->hostFileId = attr->hostFileId; attr2->volumeId = attr->volumeId; attr2->effectivePerms = attr->effectivePerms; } /* *----------------------------------------------------------------------------- * * HgfsUnpackAttrV2 -- * * Unpacks attr version 2 reply structure. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsUnpackAttrV2(const HgfsAttrV2 *attr2, // IN: attr in payload HgfsFileAttrInfo *attr) // OUT: attr stucture { attr->mask = attr2->mask; attr->type = attr2->type; attr->size = attr2->size; attr->creationTime = attr2->creationTime; attr->accessTime = attr2->accessTime; attr->writeTime = attr2->writeTime; attr->attrChangeTime = attr2->attrChangeTime; attr->specialPerms = attr2->specialPerms; attr->ownerPerms = attr2->ownerPerms; attr->groupPerms = attr2->groupPerms; attr->otherPerms = attr2->otherPerms; attr->flags = attr2->flags; attr->allocationSize = attr2->allocationSize; attr->userId = attr2->userId; attr->groupId = attr2->groupId; attr->hostFileId = attr2->hostFileId; attr->volumeId = attr2->volumeId; attr->effectivePerms = attr2->effectivePerms; } /* *----------------------------------------------------------------------------- * * HgfsInitFileAttr -- * * Initializes HgfsFileAttrInfo structure. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsInitFileAttr(HgfsOp op, // IN: request type HgfsFileAttrInfo *attr) // OUT: attr stucture { /* Initialize all fields with 0. */ memset(attr, 0, sizeof *attr); /* Explicitly initialize fields which need it. */ attr->requestType = op; attr->mask = HGFS_ATTR_VALID_NONE; } /* *----------------------------------------------------------------------------- * * HgfsPackGetattrReplyPayloadV3 -- * * Packs Getattr V3 reply payload. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackGetattrReplyPayloadV3(HgfsFileAttrInfo *attr, // IN: attr stucture const char *utf8TargetName, // IN: optional target name uint32 utf8TargetNameLen, // IN: file name length HgfsReplyGetattrV3 *reply) // OUT: payload { LOG(4, ("%s: attr type: %u\n", __FUNCTION__, attr->type)); HgfsPackAttrV2(attr, &reply->attr); reply->reserved = 0; if (utf8TargetName) { memcpy(reply->symlinkTarget.name, utf8TargetName, utf8TargetNameLen); CPNameLite_ConvertTo(reply->symlinkTarget.name, utf8TargetNameLen, DIRSEPC); } else { ASSERT(utf8TargetNameLen == 0); } reply->symlinkTarget.length = utf8TargetNameLen; reply->symlinkTarget.name[utf8TargetNameLen] = '\0'; reply->symlinkTarget.flags = 0; reply->symlinkTarget.fid = 0; reply->symlinkTarget.caseType = HGFS_FILE_NAME_DEFAULT_CASE; } /* *----------------------------------------------------------------------------- * * HgfsPackGetattrReplyPayloadV2 -- * * Packs rename reply payload V2 requests. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackGetattrReplyPayloadV2(HgfsFileAttrInfo *attr, // IN: attr stucture const char *utf8TargetName, // IN: optional target name uint32 utf8TargetNameLen, // IN: file name length HgfsReplyGetattrV2 *reply) // OUT: payload { HgfsPackAttrV2(attr, &reply->attr); if (utf8TargetName) { memcpy(reply->symlinkTarget.name, utf8TargetName, utf8TargetNameLen); CPNameLite_ConvertTo(reply->symlinkTarget.name, utf8TargetNameLen, DIRSEPC); } else { ASSERT(utf8TargetNameLen == 0); } reply->symlinkTarget.length = utf8TargetNameLen; reply->symlinkTarget.name[utf8TargetNameLen] = '\0'; } /* *----------------------------------------------------------------------------- * * HgfsPackGetattrReplyPayloadV1 -- * * Packs rename reply payload for V1 requests. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackGetattrReplyPayloadV1(HgfsFileAttrInfo *attr, // IN: attr stucture HgfsReplyGetattr *reply) // OUT: reply info { /* In GetattrV1, symlinks are treated as regular files. */ if (attr->type == HGFS_FILE_TYPE_SYMLINK) { reply->attr.type = HGFS_FILE_TYPE_REGULAR; } else { reply->attr.type = attr->type; } reply->attr.size = attr->size; reply->attr.creationTime = attr->creationTime; reply->attr.accessTime = attr->accessTime; reply->attr.writeTime = attr->writeTime; reply->attr.attrChangeTime = attr->attrChangeTime; reply->attr.permissions = attr->ownerPerms; } /* *----------------------------------------------------------------------------- * * HgfsUnpackGetattrRequest -- * * Unpack hgfs getattr request and initialize a corresponding * HgfsFileAttrInfo structure that is used to pass around getattr request * information. * * Since the structure of the get attributes request packet hasn't changed * in version 2 of the protocol, HgfsRequestGetattrV2 is identical to * HgfsRequestGetattr. So use HgfsRequestGetattr type to access packetIn to * keep the code simple. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackGetattrRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN request type HgfsFileAttrInfo *attrInfo, // IN/OUT: getattr info HgfsAttrHint *hints, // OUT: getattr hints const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsHandle *file, // OUT: file handle uint32 *caseType) // OUT: case-sensitivity flags { ASSERT(packet); ASSERT(attrInfo); ASSERT(cpName); ASSERT(cpNameSize); ASSERT(file); ASSERT(caseType); HgfsInitFileAttr(op, attrInfo); /* Default values for legacy requests. */ *caseType = HGFS_FILE_NAME_DEFAULT_CASE; *hints = 0; *file = HGFS_INVALID_HANDLE; switch (op) { case HGFS_OP_GETATTR_V3: { const HgfsRequestGetattrV3 *requestV3 = packet; if (!HgfsUnpackGetattrPayloadV3(requestV3, packetSize, cpName, cpNameSize, hints, file, caseType)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } LOG(4, ("%s: HGFS_OP_GETATTR_V3: %u\n", __FUNCTION__, *caseType)); break; } case HGFS_OP_GETATTR_V2: { const HgfsRequestGetattrV2 *requestV2 = packet; if (!HgfsUnpackGetattrPayloadV2(requestV2, packetSize, cpName, cpNameSize, hints, file)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_GETATTR: { const HgfsRequestGetattr *requestV1 = packet; if (!HgfsUnpackGetattrPayloadV1(requestV1, packetSize, cpName, cpNameSize)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } default: return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackGetattrReply -- * * Pack hgfs getattr reply to the HgfsReplyGetattr structure. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackGetattrReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsFileAttrInfo *attr, // IN: attr stucture const char *utf8TargetName, // IN: optional target name uint32 utf8TargetNameLen, // IN: file name length size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; switch (attr->requestType) { case HGFS_OP_GETATTR_V3: { HgfsReplyGetattrV3 *reply; *payloadSize = sizeof *reply + utf8TargetNameLen; reply = HgfsAllocInitReply(packet, packetHeader, *payloadSize, session); HgfsPackGetattrReplyPayloadV3(attr, utf8TargetName, utf8TargetNameLen, reply); break; } case HGFS_OP_GETATTR_V2: { HgfsReplyGetattrV2 *reply; *payloadSize = sizeof *reply + utf8TargetNameLen; reply = HgfsAllocInitReply(packet, packetHeader, *payloadSize, session); HgfsPackGetattrReplyPayloadV2(attr, utf8TargetName, utf8TargetNameLen, reply); break; } case HGFS_OP_GETATTR: { HgfsReplyGetattr *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); HgfsPackGetattrReplyPayloadV1(attr, reply); *payloadSize = sizeof *reply; break; } default: LOG(4, ("%s: Invalid GetAttr op.\n", __FUNCTION__)); NOT_REACHED(); result = FALSE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyHeaderV4 -- * * Packs SearchRead V4 reply header part for all entry records returned. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSearchReadReplyHeaderV4(HgfsSearchReadInfo *info, // IN: reply info HgfsReplySearchReadV4 *reply, // OUT: payload size_t *headerSize) // OUT: size written { reply->numberEntriesReturned = info->numberRecordsWritten; reply->offsetToContinue = info->currentIndex; reply->flags = info->replyFlags; reply->reserved = 0; *headerSize = offsetof(HgfsReplySearchReadV4, entries); } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyRecordV4 -- * * Packs SearchRead V4 reply record. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSearchReadReplyRecordV4(HgfsSearchReadEntry *entry, // IN: entry info HgfsDirEntryV4 *replylastEntry, // IN/OUT: payload HgfsDirEntryV4 *replyCurrentEntry) // OUT: reply buffer for dirent { HgfsFileAttrInfo *attr = &entry->attr; memset(replyCurrentEntry, 0, sizeof *replyCurrentEntry); if (NULL != replylastEntry) { replylastEntry->nextEntryOffset = ((char*)replyCurrentEntry - (char*)replylastEntry); } /* Set the valid data mask for the entry. */ replyCurrentEntry->mask = entry->mask; if (0 != (entry->mask & HGFS_SEARCH_READ_NAME)) { replyCurrentEntry->nextEntryOffset = 0; replyCurrentEntry->fileIndex = entry->fileIndex; if (0 != (replyCurrentEntry->mask & HGFS_SEARCH_READ_FILE_NODE_TYPE)) { replyCurrentEntry->fileType = attr->type; } if (0 != (entry->mask & HGFS_SEARCH_READ_FILE_SIZE)) { replyCurrentEntry->fileSize = attr->size; } if (0 != (entry->mask & HGFS_SEARCH_READ_ALLOCATION_SIZE)) { replyCurrentEntry->allocationSize = attr->allocationSize; } if (0 != (entry->mask & HGFS_SEARCH_READ_TIME_STAMP)) { replyCurrentEntry->creationTime = attr->creationTime; replyCurrentEntry->accessTime = attr->accessTime; replyCurrentEntry->writeTime = attr->writeTime; replyCurrentEntry->attrChangeTime = attr->attrChangeTime; } if (0 != (entry->mask & HGFS_SEARCH_READ_FILE_ATTRIBUTES)) { replyCurrentEntry->attrFlags = attr->flags; } if (0 != (entry->mask & HGFS_SEARCH_READ_FILE_ID)) { replyCurrentEntry->hostFileId = attr->hostFileId; } if (0 != (entry->mask & HGFS_SEARCH_READ_EA_SIZE)) { replyCurrentEntry->eaSize = attr->eaSize; } if (0 != (entry->mask & HGFS_SEARCH_READ_REPARSE_TAG)) { replyCurrentEntry->reparseTag = attr->reparseTag; } if (0 != (entry->mask & HGFS_SEARCH_READ_SHORT_NAME)) { ASSERT(attr->shortName.length > 0); memcpy(replyCurrentEntry->shortName.name, attr->shortName.name, attr->shortName.length); replyCurrentEntry->shortName.length = attr->shortName.length; } memcpy(replyCurrentEntry->fileName.name, entry->name, entry->nameLength); replyCurrentEntry->fileName.name[entry->nameLength] = 0; replyCurrentEntry->fileName.length = entry->nameLength; replyCurrentEntry->reserved = 0; } } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyHeaderV3 -- * * Packs SearchRead V3 reply record. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSearchReadReplyHeaderV3(HgfsSearchReadInfo *info, // IN: reply info HgfsReplySearchReadV3 *reply, // OUT: payload size_t *headerSize) // OUT: size written { ASSERT(info->numberRecordsWritten <= 1 && 0 != (info->flags & HGFS_SEARCH_READ_SINGLE_ENTRY)); reply->count = info->numberRecordsWritten; reply->reserved = 0; /* * Previous shipping tools expect to account for a whole reply, * which is not strictly correct, but we are stuck with it. */ *headerSize = sizeof *reply; } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyRecordV3 -- * * Packs SearchRead V3 reply record. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSearchReadReplyRecordV3(HgfsFileAttrInfo *attr, // IN: attr stucture const char *utf8Name, // IN: file name uint32 utf8NameLen, // IN: file name length HgfsDirEntry *replyDirent) // OUT: reply buffer for dirent { replyDirent->fileName.length = (uint32)utf8NameLen; replyDirent->fileName.flags = 0; replyDirent->fileName.fid = 0; replyDirent->fileName.caseType = HGFS_FILE_NAME_DEFAULT_CASE; replyDirent->nextEntry = 0; if (utf8NameLen != 0) { memcpy(replyDirent->fileName.name, utf8Name, utf8NameLen); replyDirent->fileName.name[utf8NameLen] = 0; HgfsPackAttrV2(attr, &replyDirent->attr); } } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyHeaderV2 -- * * Packs SearchRead V2 reply header (common) part for all records. * V2 replies only contain a single record, so there is nothing to do here. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSearchReadReplyHeaderV2(HgfsSearchReadInfo *info, // IN: unused HgfsReplySearchReadV2 *reply, // OUT: unused size_t *headerSize) // OUT: size written { /* The header has already been accounted for. */ *headerSize = sizeof *reply; } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyRecordV2 -- * * Packs SearchRead V2 reply record. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSearchReadReplyRecordV2(HgfsFileAttrInfo *attr, // IN: attr stucture const char *utf8Name, // IN: file name uint32 utf8NameLen, // IN: file name length HgfsReplySearchReadV2 *reply) // OUT: reply buffer { reply->fileName.length = (uint32)utf8NameLen; if (utf8NameLen != 0) { memcpy(reply->fileName.name, utf8Name, utf8NameLen); reply->fileName.name[utf8NameLen] = 0; HgfsPackAttrV2(attr, &reply->attr); } } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyHeaderV1 -- * * Packs SearchRead V1 reply header (common) part for all records. * V1 replies only contain a single record, so there is nothing to do here. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSearchReadReplyHeaderV1(HgfsSearchReadInfo *info, // IN: unused HgfsReplySearchRead *reply, // OUT: unused size_t *headerSize) // OUT: size written { /* The header has already been accounted for. */ *headerSize = sizeof *reply; } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyRecordV1 -- * * Packs SearchRead V1 reply record. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSearchReadReplyRecordV1(HgfsFileAttrInfo *attr, // IN: attr stucture const char *utf8Name, // IN: file name uint32 utf8NameLen, // IN: file name length HgfsReplySearchRead *reply) // OUT: reply buffer { reply->fileName.length = (uint32)utf8NameLen; if (utf8NameLen != 0) { memcpy(reply->fileName.name, utf8Name, utf8NameLen); reply->fileName.name[utf8NameLen] = 0; /* In SearchReadV1, symlinks are treated as regular files. */ if (attr->type == HGFS_FILE_TYPE_SYMLINK) { reply->attr.type = HGFS_FILE_TYPE_REGULAR; } else { reply->attr.type = attr->type; } reply->attr.size = attr->size; reply->attr.creationTime = attr->creationTime; reply->attr.accessTime = attr->accessTime; reply->attr.writeTime = attr->writeTime; reply->attr.attrChangeTime = attr->attrChangeTime; reply->attr.permissions = attr->ownerPerms; } } /* *----------------------------------------------------------------------------- * * HgfsUnpackSearchReadRequest -- * * Unpack hgfs search read request and initialize a corresponding * HgfsFileAttrInfo structure that is used to pass around attribute * information. * * Since the structure of the search read request packet hasn't changed in * version 2 of the protocol, HgfsRequestSearchReadV2 is identical to * HgfsRequestSearchRead. So use HgfsRequestSearchRead type to access * packetIn to keep the code simple. * * Results: * Always TRUE. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackSearchReadRequest(const void *packet, // IN: request packet size_t packetSize, // IN: packet size HgfsOp op, // IN: reqest type HgfsSearchReadInfo *info, // OUT: search info size_t *baseReplySize, // OUT: op base reply size size_t *inlineReplyDataSize, // OUT: size of inline reply data HgfsHandle *hgfsSearchHandle) // OUT: hgfs search handle { Bool result = TRUE; uint32 *startIndex; HgfsSearchReadMask *mask; HgfsSearchReadFlags *flags; size_t *replyPayloadSize; ASSERT(packet); ASSERT(info); ASSERT(baseReplySize); ASSERT(inlineReplyDataSize); ASSERT(hgfsSearchHandle); info->requestType = op; info->searchPattern = NULL; startIndex = &info->startIndex; replyPayloadSize = &info->payloadSize; mask = &info->requestedMask; flags = &info->flags; *mask = 0; *flags = 0; switch (op) { case HGFS_OP_SEARCH_READ_V4: { const HgfsRequestSearchReadV4 *request = packet; /* Enforced by the dispatch function. */ ASSERT(packetSize >= sizeof *request); if (0 != (request->flags & HGFS_SEARCH_READ_FID_OPEN_V4)) { /* * XXX - When this is implemented, the handle will get us a node, * (of directory type) and then with the node, we can look up a * search handle, if the data is cached in the search array. */ NOT_IMPLEMENTED(); } *hgfsSearchHandle = request->fid; *startIndex = request->restartIndex; *mask = request->mask; *flags = request->flags; *baseReplySize = offsetof(HgfsReplySearchReadV4, entries); *replyPayloadSize = request->replyDirEntryMaxSize; *inlineReplyDataSize = 0; ASSERT(*replyPayloadSize > 0); LOG(4, ("%s: HGFS_OP_SEARCH_READ_V4\n", __FUNCTION__)); break; } case HGFS_OP_SEARCH_READ_V3: { const HgfsRequestSearchReadV3 *request = packet; /* Enforced by the dispatch function. */ ASSERT(packetSize >= sizeof *request); *hgfsSearchHandle = request->search; *startIndex = request->offset; *flags = HGFS_SEARCH_READ_SINGLE_ENTRY; *mask = (HGFS_SEARCH_READ_FILE_NODE_TYPE | HGFS_SEARCH_READ_NAME | HGFS_SEARCH_READ_FILE_SIZE | HGFS_SEARCH_READ_TIME_STAMP | HGFS_SEARCH_READ_FILE_ATTRIBUTES | HGFS_SEARCH_READ_FILE_ID); *baseReplySize = offsetof(HgfsReplySearchReadV3, payload); *replyPayloadSize = HGFS_PACKET_MAX - *baseReplySize; *inlineReplyDataSize = *replyPayloadSize; LOG(4, ("%s: HGFS_OP_SEARCH_READ_V3\n", __FUNCTION__)); break; } case HGFS_OP_SEARCH_READ_V2: /* * Currently, the HgfsRequestSearchReadV2 is the same as * HgfsRequestSearchRead, so drop through. */ case HGFS_OP_SEARCH_READ: { const HgfsRequestSearchRead *request = packet; /* Enforced by the dispatch function. */ ASSERT(packetSize >= sizeof *request); *hgfsSearchHandle = request->search; *startIndex = request->offset; *flags = HGFS_SEARCH_READ_SINGLE_ENTRY; *mask = (HGFS_SEARCH_READ_FILE_NODE_TYPE | HGFS_SEARCH_READ_NAME | HGFS_SEARCH_READ_FILE_SIZE | HGFS_SEARCH_READ_TIME_STAMP | HGFS_SEARCH_READ_FILE_ATTRIBUTES); *baseReplySize = 0; *replyPayloadSize = HGFS_PACKET_MAX; *inlineReplyDataSize = *replyPayloadSize; break; } default: /* Should never occur. */ NOT_REACHED(); result = FALSE; Log("%s: ERROR Invalid OP %u\n", __FUNCTION__, op); break; } ASSERT(result); return result; } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyRecord -- * * Pack hgfs search read reply record to the current entry record. * If the last record is not NULL then update its offset to the current * entry field. * * Results: * TRUE on success and number of bytes written in replyRecordSize. * FALSE on failure, nothing written. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackSearchReadReplyRecord(HgfsOp requestType, // IN: search read request HgfsSearchReadEntry *entry, // IN: entry info size_t bytesRemaining, // IN: space in bytes for record void *lastSearchReadRecord, // IN/OUT: last packed entry void *currentSearchReadRecord,// OUT: currrent entry to pack size_t *replyRecordSize) // OUT: size of packet { Bool result = TRUE; size_t recordSize = 0; switch (requestType) { case HGFS_OP_SEARCH_READ_V4: { HgfsDirEntryV4 *replyCurrentEntry = currentSearchReadRecord; HgfsDirEntryV4 *replyLastEntry = lastSearchReadRecord; /* Skip the final empty record, it is not needed for V4.*/ if (0 == entry->nameLength) { break; } recordSize = offsetof(HgfsDirEntryV4, fileName.name) + entry->nameLength + 1; if (recordSize > bytesRemaining) { result = FALSE; break; } HgfsPackSearchReadReplyRecordV4(entry, replyLastEntry, replyCurrentEntry); break; } case HGFS_OP_SEARCH_READ_V3: { HgfsDirEntry *replyCurrentEntry = currentSearchReadRecord; /* * Previous shipping tools expect to account for a whole reply, * which is not strictly correct, it should be using * offsetof(HgfsDirEntry, fileName.name) + entry->nameLength + 1 * but we are stuck with it. */ recordSize = sizeof *replyCurrentEntry + entry->nameLength; if (recordSize > bytesRemaining) { result = FALSE; break; } HgfsPackSearchReadReplyRecordV3(&entry->attr, entry->name, entry->nameLength, replyCurrentEntry); break; } case HGFS_OP_SEARCH_READ_V2: { HgfsReplySearchReadV2 *replyV2 = currentSearchReadRecord; /* We have already accounted for the fixed part of the record. */ recordSize = entry->nameLength; if (recordSize > bytesRemaining) { result = FALSE; break; } HgfsPackSearchReadReplyRecordV2(&entry->attr, entry->name, entry->nameLength, replyV2); break; } case HGFS_OP_SEARCH_READ: { HgfsReplySearchRead *replyV1 = currentSearchReadRecord; /* We have already accounted for the fixed part of the record. */ recordSize = entry->nameLength; if (recordSize > bytesRemaining) { result = FALSE; break; } HgfsPackSearchReadReplyRecordV1(&entry->attr, entry->name, entry->nameLength, replyV1); break; } default: { Log("%s: Invalid SearchRead Op.", __FUNCTION__); NOT_REACHED(); result = FALSE; } } if (result) { *replyRecordSize = recordSize; } return result; } /* *----------------------------------------------------------------------------- * * HgfsPackSearchReadReplyHeader -- * * Pack hgfs search read reply header (common) part to all the * entries returned in the search read reply. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackSearchReadReplyHeader(HgfsSearchReadInfo *info, // IN: request info size_t *payloadSize) // OUT: size of packet { Bool result = TRUE; *payloadSize = 0; switch (info->requestType) { case HGFS_OP_SEARCH_READ_V4: { HgfsReplySearchReadV4 *reply = info->reply; HgfsPackSearchReadReplyHeaderV4(info, reply, payloadSize); break; } case HGFS_OP_SEARCH_READ_V3: { HgfsReplySearchReadV3 *reply = info->reply; HgfsPackSearchReadReplyHeaderV3(info, reply, payloadSize); break; } case HGFS_OP_SEARCH_READ_V2: { HgfsReplySearchReadV2 *reply = info->reply; HgfsPackSearchReadReplyHeaderV2(info, reply, payloadSize); break; } case HGFS_OP_SEARCH_READ: { HgfsReplySearchRead *reply = info->reply; HgfsPackSearchReadReplyHeaderV1(info, reply, payloadSize); break; } default: { LOG(4, ("%s: Invalid SearchRead Op.", __FUNCTION__)); NOT_REACHED(); result = FALSE; } } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSetattrPayloadV3 -- * * Unpack hgfs set attr request V3 payload and initialize a corresponding * HgfsHandle or file name to tell us which file to set attributes. Hints * holds flags to specify a handle or name for the file or * directory to set attributes. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSetattrPayloadV3(const HgfsRequestSetattrV3 *requestV3,// IN: request payload size_t payloadSize, // IN: payload size HgfsFileAttrInfo *attr, // OUT: setattr info const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsAttrHint *hints, // OUT: getattr hints HgfsHandle *file, // OUT: file handle uint32 *caseFlags) // OUT: case-sensitivity flags { Bool result = TRUE; Bool useHandle; if (payloadSize < sizeof *requestV3) { result = FALSE; goto exit; } *hints = requestV3->hints; HgfsUnpackAttrV2(&requestV3->attr, attr); if (!HgfsUnpackFileNameV3(&requestV3->fileName, payloadSize - sizeof *requestV3, &useHandle, cpName, cpNameSize, file, caseFlags)) { result = FALSE; goto exit; } if (useHandle) { *hints |= HGFS_ATTR_HINT_USE_FILE_DESC; } exit: LOG(8, ("%s: unpacking HGFS_OP_SETATTR_V3 -> %d\n", __FUNCTION__, result)); return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSetattrPayloadV2 -- * * Unpack hgfs Setattr request V2 payload and initialize a corresponding * HgfsHandle or file name to tell us which to set attributes. Hints * holds flags to specify a handle or name for the file or * directory to set attributes. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSetattrPayloadV2(const HgfsRequestSetattrV2 *requestV2,// IN: request payload size_t payloadSize, // IN: payload size HgfsFileAttrInfo *attr, // OUT: setattr info const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsAttrHint *hints, // OUT: delete hints HgfsHandle *file) // OUT: file handle { Bool result = TRUE; /* Enforced by the dispatch function. */ if (payloadSize < sizeof *requestV2) { return FALSE; } LOG(4, ("%s: unpacking HGFS_OP_SETATTR_V2\n", __FUNCTION__)); *file = HGFS_INVALID_HANDLE; *hints = requestV2->hints; HgfsUnpackAttrV2(&requestV2->attr, attr); if (requestV2->hints & HGFS_ATTR_HINT_USE_FILE_DESC) { *file = requestV2->file; *cpName = NULL; *cpNameSize = 0; } else { result = HgfsUnpackFileName(&requestV2->fileName, payloadSize - sizeof *requestV2, cpName, cpNameSize); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSetattrPayloadV1 -- * * Unpack hgfs setattr request V1 payload and initialize a corresponding * file name to tell us which to set attributes. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSetattrPayloadV1(const HgfsRequestSetattr *requestV1, // IN: request payload size_t payloadSize, // IN: payload size HgfsFileAttrInfo *attr, // OUT: setattr info const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsAttrHint *hints) // OUT: setattr hints { LOG(4, ("%s: unpacking HGFS_OP_SETATTR\n", __FUNCTION__)); attr->mask = 0; attr->mask |= requestV1->update & HGFS_ATTR_SIZE ? HGFS_ATTR_VALID_SIZE : 0; attr->mask |= requestV1->update & HGFS_ATTR_CREATE_TIME ? HGFS_ATTR_VALID_CREATE_TIME : 0; attr->mask |= requestV1->update & HGFS_ATTR_ACCESS_TIME ? HGFS_ATTR_VALID_ACCESS_TIME : 0; attr->mask |= requestV1->update & HGFS_ATTR_WRITE_TIME ? HGFS_ATTR_VALID_WRITE_TIME : 0; attr->mask |= requestV1->update & HGFS_ATTR_CHANGE_TIME ? HGFS_ATTR_VALID_CHANGE_TIME : 0; attr->mask |= requestV1->update & HGFS_ATTR_PERMISSIONS ? HGFS_ATTR_VALID_OWNER_PERMS : 0; *hints |= requestV1->update & HGFS_ATTR_ACCESS_TIME_SET ? HGFS_ATTR_HINT_SET_ACCESS_TIME : 0; *hints |= requestV1->update & HGFS_ATTR_WRITE_TIME_SET ? HGFS_ATTR_HINT_SET_WRITE_TIME : 0; attr->type = requestV1->attr.type; attr->size = requestV1->attr.size; attr->creationTime = requestV1->attr.creationTime; attr->accessTime = requestV1->attr.accessTime; attr->writeTime = requestV1->attr.writeTime; attr->attrChangeTime = requestV1->attr.attrChangeTime; attr->ownerPerms = requestV1->attr.permissions; return HgfsUnpackFileName(&requestV1->fileName, payloadSize - sizeof *requestV1, cpName, cpNameSize); } /* *----------------------------------------------------------------------------- * * HgfsUnpackSetattrRequest -- * * Unpack hgfs setattr request and initialize a corresponding * HgfsFileAttrInfo structure that is used to pass around setattr request * information. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackSetattrRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type HgfsFileAttrInfo *attr, // OUT: setattr info HgfsAttrHint *hints, // OUT: setattr hints const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsHandle *file, // OUT: server file ID uint32 *caseType) // OUT: case-sensitivity flags { ASSERT(packet); ASSERT(attr); ASSERT(cpName); ASSERT(cpNameSize); ASSERT(file); ASSERT(caseType); attr->requestType = op; /* Default values for legacy requests. */ *caseType = HGFS_FILE_NAME_DEFAULT_CASE; *hints = 0; *file = HGFS_INVALID_HANDLE; switch (op) { case HGFS_OP_SETATTR_V3: { const HgfsRequestSetattrV3 *requestV3 = packet; if (!HgfsUnpackSetattrPayloadV3(requestV3, packetSize, attr, cpName, cpNameSize, hints, file, caseType)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_SETATTR_V2: { const HgfsRequestSetattrV2 *requestV2 = packet; if (!HgfsUnpackSetattrPayloadV2(requestV2, packetSize, attr, cpName, cpNameSize, hints, file)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_SETATTR: { const HgfsRequestSetattr *requestV1 = packet; if (!HgfsUnpackSetattrPayloadV1(requestV1, packetSize, attr, cpName, cpNameSize, hints)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } default: LOG(4, ("%s: Incorrect opcode %d\n", __FUNCTION__, op)); NOT_REACHED(); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackSetattrReply -- * * Pack hgfs setattr reply. * Since the structure of the set attributes reply packet hasn't changed in * version 2 of the protocol, HgfsReplySetattrV2 is identical to * HgfsReplySetattr. So use HgfsReplySetattr type to access packetIn to * keep the code simple. * * Results: * TRUE if valid op and reply set, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackSetattrReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; *payloadSize = 0; switch (op) { case HGFS_OP_SETATTR_V3: { HgfsReplySetattrV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); /* Reply consists of only a reserved field. */ reply->reserved = 0; *payloadSize = sizeof *reply; break; } case HGFS_OP_SETATTR_V2: case HGFS_OP_SETATTR: { HgfsReplySetattr *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } default: result = FALSE; LOG(4, ("%s: invalid op code %d\n", __FUNCTION__, op)); NOT_REACHED(); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackCreateDirPayloadV3 -- * * Unpack hgfs create directory request V3 payload and initialize a corresponding * file name to tell us which directory to create. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackCreateDirPayloadV3(const HgfsRequestCreateDirV3 *requestV3, // IN: request payload size_t payloadSize, // IN: payload size HgfsCreateDirInfo *info) // IN/OUT: info struct { /* * The request file name length is user-provided, so this test must be * carefully written to prevent wraparounds. */ LOG(4, ("%s: HGFS_OP_CREATE_DIR_V3\n", __FUNCTION__)); ASSERT(payloadSize >= sizeof *requestV3); if (requestV3->fileName.length > payloadSize - sizeof *requestV3) { /* The input packet is smaller than the request. */ return FALSE; } if (!(requestV3->mask & HGFS_CREATE_DIR_VALID_FILE_NAME)) { /* We do not support requests without a valid file name. */ LOG(4, ("%s: Incorrect mask %x\n", __FUNCTION__, (uint32)requestV3->mask)); return FALSE; } /* * Copy all the fields into our carrier struct. Some will probably be * garbage, but it's simpler to copy everything now and check the * valid bits before reading later. */ info->mask = requestV3->mask; info->cpName = requestV3->fileName.name; info->cpNameSize = requestV3->fileName.length; info->caseFlags = requestV3->fileName.caseType; info->specialPerms = requestV3->specialPerms; info->fileAttr = requestV3->fileAttr; info->ownerPerms = requestV3->ownerPerms; info->groupPerms = requestV3->groupPerms; info->otherPerms = requestV3->otherPerms; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackCreateDirPayloadV2 -- * * Unpack hgfs create directory request V2 payload and initialize a corresponding * file name to tell us which directory to create. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackCreateDirPayloadV2(const HgfsRequestCreateDirV2 *requestV2, // IN: request payload size_t payloadSize, // IN: payload size HgfsCreateDirInfo *info) // IN/OUT: info struct { /* * The request file name length is user-provided, so this test must be * carefully written to prevent wraparounds. */ LOG(4, ("%s: HGFS_OP_CREATE_DIR_V2\n", __FUNCTION__)); ASSERT(payloadSize >= sizeof *requestV2); if (requestV2->fileName.length > payloadSize - sizeof *requestV2) { /* The input packet is smaller than the request. */ return FALSE; } if (!(requestV2->mask & HGFS_CREATE_DIR_VALID_FILE_NAME)) { /* We do not support requests without a valid file name. */ LOG(4, ("%s: Incorrect mask %x\n", __FUNCTION__, (uint32)requestV2->mask)); return FALSE; } /* * Copy all the fields into our carrier struct. Some will probably be * garbage, but it's simpler to copy everything now and check the * valid bits before reading later. */ info->mask = requestV2->mask; info->cpName = requestV2->fileName.name; info->cpNameSize = requestV2->fileName.length; info->specialPerms = requestV2->specialPerms; info->ownerPerms = requestV2->ownerPerms; info->groupPerms = requestV2->groupPerms; info->otherPerms = requestV2->otherPerms; info->fileAttr = 0; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackCreateDirPayloadV1 -- * * Unpack hgfs create directory request V1 payload and initialize a corresponding * file name to tell us which directory to create. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackCreateDirPayloadV1(const HgfsRequestCreateDir *requestV1, // IN: request payload size_t payloadSize, // IN: payload size HgfsCreateDirInfo *info) // IN/OUT: info struct { /* * The request file name length is user-provided, so this test must be * carefully written to prevent wraparounds. */ LOG(4, ("%s: HGFS_OP_CREATE_DIR_V1\n", __FUNCTION__)); ASSERT(payloadSize >= sizeof *requestV1); if (requestV1->fileName.length > payloadSize - sizeof *requestV1) { /* The input packet is smaller than the request. */ LOG(4, ("%s: HGFS packet too small for the file name\n", __FUNCTION__)); return FALSE; } /* For CreateDirV1 requests, we know exactly what fields we expect. */ info->mask = HGFS_CREATE_DIR_VALID_OWNER_PERMS | HGFS_CREATE_DIR_VALID_FILE_NAME; info->cpName = requestV1->fileName.name; info->cpNameSize = requestV1->fileName.length; info->ownerPerms = requestV1->permissions; info->fileAttr = 0; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackCreateDirRequest -- * * Unpack hgfs CreateDir request and initialize a corresponding * HgfsCreateDirInfo structure that is used to pass around CreateDir request * information. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackCreateDirRequest(const void *packet, // IN: incoming packet size_t packetSize, // IN: size of packet HgfsOp op, // IN: request type HgfsCreateDirInfo *info) // IN/OUT: info struct { ASSERT(packet); ASSERT(info); info->requestType = op; /* Default value for legacy requests. */ info->caseFlags = HGFS_FILE_NAME_DEFAULT_CASE; switch (op) { case HGFS_OP_CREATE_DIR_V3: { const HgfsRequestCreateDirV3 *requestV3 = packet; if (!HgfsUnpackCreateDirPayloadV3(requestV3, packetSize, info)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_CREATE_DIR_V2: { const HgfsRequestCreateDirV2 *requestV2 = packet; if (!HgfsUnpackCreateDirPayloadV2(requestV2, packetSize, info)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_CREATE_DIR: { const HgfsRequestCreateDir *requestV1 = packet; if (!HgfsUnpackCreateDirPayloadV1(requestV1, packetSize, info)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } default: LOG(4, ("%s: Incorrect opcode %d\n", __FUNCTION__, op)); NOT_REACHED(); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackCreateDirReply -- * * Pack hgfs CreateDir reply. * * Results: * TRUE if valid op and reply set, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackCreateDirReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; *payloadSize = 0; switch (op) { case HGFS_OP_CREATE_DIR_V3: { HgfsReplyCreateDirV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); /* Reply consists of only a reserved field. */ reply->reserved = 0; *payloadSize = sizeof *reply; break; } case HGFS_OP_CREATE_DIR_V2: { HgfsReplyCreateDirV2 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } case HGFS_OP_CREATE_DIR: { HgfsReplyCreateDir *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } default: result = FALSE; LOG(4, ("%s: invalid op code %d\n", __FUNCTION__, op)); NOT_REACHED(); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackWriteWin32StreamPayloadV3 -- * * Unpack hgfs write stream request V3 payload and initialize a corresponding * file name to tell us which directory to create. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackWriteWin32StreamPayloadV3(const HgfsRequestWriteWin32StreamV3 *requestV3, // IN: size_t payloadSize, // IN: HgfsHandle *file, // OUT: const char **data, // OUT: size_t *dataSize, // OUT: Bool *doSecurity) // OUT: { LOG(4, ("%s: HGFS_OP_WRITE_WIN32_STREAM_V3\n", __FUNCTION__)); if (payloadSize < sizeof *requestV3) { LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } if (payloadSize >= requestV3->requiredSize + sizeof *requestV3) { *file = requestV3->file; *data = requestV3->payload; *dataSize = requestV3->requiredSize; *doSecurity = (requestV3->flags & HGFS_WIN32_STREAM_IGNORE_SECURITY) == 0; return TRUE; } LOG(4, ("%s: HGFS packet too small - user data do not fit\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackWriteWin32StreamRequest -- * * Unpack hgfs SendFileUsingReader request. Returns file to write to, data * and whether to restore the security stream. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackWriteWin32StreamRequest(const void *packet, // IN: incoming packet size_t packetSize, // IN: size of packet HgfsOp op, // IN: request type HgfsHandle *file, // OUT: file to write to const char **data, // OUT: data to write size_t *dataSize, // OUT: size of data Bool *doSecurity) // OUT: restore sec.str. { ASSERT(packet); ASSERT(file); ASSERT(data); ASSERT(dataSize); ASSERT(doSecurity); if (op != HGFS_OP_WRITE_WIN32_STREAM_V3) { /* The only supported version for the moment is V3. */ LOG(4, ("%s: Incorrect opcode %d\n", __FUNCTION__, op)); NOT_REACHED(); return FALSE; } return HgfsUnpackWriteWin32StreamPayloadV3(packet, packetSize, file, data, dataSize, doSecurity); } /* *----------------------------------------------------------------------------- * * HgfsPackWriteWin32StreamReply -- * * Pack hgfs SendFileUsingReader reply. * Returns the actual amount of data written in the reply. * * Results: * TRUE if valid op and reply set, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackWriteWin32StreamReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type uint32 actualSize, // IN: amount written size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { HgfsReplyWriteWin32StreamV3 *reply; Bool result = TRUE; *payloadSize = 0; if (HGFS_OP_WRITE_WIN32_STREAM_V3 == op) { reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); reply->reserved = 0; reply->actualSize = actualSize; *payloadSize = sizeof *reply; } else { LOG(4, ("%s: Incorrect opcode %d\n", __FUNCTION__, op)); NOT_REACHED(); result = FALSE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackReadPayload -- * * Unpack hgfs read payload to get the file handle and file offset to read from and * the length of data to read. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackReadPayload(const HgfsRequestRead *request, // IN: payload size_t payloadSize, // IN: payload size HgfsHandle* file, // OUT: HGFS handle to close uint64 *offset, // OUT: offset to read from uint32 *length) // OUT: length of data to read { LOG(4, ("%s: HGFS_OP_READ\n", __FUNCTION__)); if (payloadSize >= sizeof *request) { *file = request->file; *offset = request->offset; *length = request->requiredSize; return TRUE; } LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackReadPayloadV3 -- * * Unpack hgfs read payload V3 to get parameters needed to perform read. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackReadPayloadV3(const HgfsRequestReadV3 *requestV3, // IN: payload size_t payloadSize, // IN: payload size HgfsHandle* file, // OUT: HGFS handle to close uint64 *offset, // OUT: offset to read from uint32 *length) // OUT: length of data to read { LOG(4, ("%s: HGFS_OP_READ_V3\n", __FUNCTION__)); if (payloadSize >= sizeof *requestV3) { *file = requestV3->file; *offset = requestV3->offset; *length = requestV3->requiredSize; return TRUE; } LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackReadRequest -- * * Unpack hgfs read request. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackReadRequest(const void *packet, // IN: HGFS request size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type HgfsHandle *file, // OUT: Handle to close uint64 *offset, // OUT: offset to read from uint32 *length) // OUT: length of data to read { Bool result; ASSERT(packet); switch (op) { case HGFS_OP_READ_FAST_V4: case HGFS_OP_READ_V3: { const HgfsRequestReadV3 *requestV3 = packet; result = HgfsUnpackReadPayloadV3(requestV3, packetSize, file, offset, length); break; } case HGFS_OP_READ: { const HgfsRequestRead *requestV1 = packet; result = HgfsUnpackReadPayload(requestV1, packetSize, file, offset, length); break; } default: NOT_REACHED(); result = FALSE; } if (!result) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackWritePayload -- * * Unpack hgfs write payload to get the file handle, file offset, of data to write, * write flags and pointer to the data to write. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackWritePayload(const HgfsRequestWrite *request, // IN: request payload size_t payloadSize, // IN: request payload size HgfsHandle* file, // OUT: HGFS handle to write to uint64 *offset, // OUT: offset to read from uint32 *length, // OUT: length of data to write HgfsWriteFlags *flags, // OUT: write flags const void **data) // OUT: data to be written { LOG(4, ("%s: HGFS_OP_WRITE\n", __FUNCTION__)); if (payloadSize >= sizeof *request) { if (sizeof *request + request->requiredSize - 1 <= payloadSize) { *file = request->file; *flags = request->flags; *offset = request->offset; *data = request->payload; *length = request->requiredSize; return TRUE; } } LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackWritePayloadV3 -- * * Unpack hgfs write payload V3. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackWritePayloadV3(const HgfsRequestWriteV3 *requestV3, // IN: payload size_t payloadSize, // IN: request payload size HgfsHandle* file, // OUT: HGFS handle write to uint64 *offset, // OUT: offset to read from uint32 *length, // OUT: length of data to write HgfsWriteFlags *flags, // OUT: write flags const void **data) // OUT: data to be written { LOG(4, ("%s: HGFS_OP_WRITE_V3\n", __FUNCTION__)); if (payloadSize >= sizeof *requestV3) { if (sizeof *requestV3 + requestV3->requiredSize - 1 <= payloadSize) { *file = requestV3->file; *flags = requestV3->flags; *offset = requestV3->offset; *data = requestV3->payload; *length = requestV3->requiredSize; return TRUE; } } LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackWriteFastPayloadV4 -- * * Unpack hgfs write fast payload V4. * The only difference from V3 payload is that data to write are * provided in the payload but located in a separate buffer. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackWriteFastPayloadV4(const HgfsRequestWriteV3 *requestV3, // IN: payload size_t payloadSize, // IN: request payload size HgfsHandle* file, // OUT: HGFS handle write to uint64 *offset, // OUT: offset to write to uint32 *length, // OUT: size of data to write HgfsWriteFlags *flags) // OUT: write flags { LOG(4, ("%s: HGFS_OP_WRITE_V3\n", __FUNCTION__)); if (payloadSize >= sizeof *requestV3) { *file = requestV3->file; *flags = requestV3->flags; *offset = requestV3->offset; *length = requestV3->requiredSize; return TRUE; } LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackWriteRequest -- * * Unpack hgfs write request to get parameters and data to write. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackWriteRequest(const void *writeRequest,// IN: write request params size_t writeRequestSize, // IN: write request params size HgfsOp writeOp, // IN: request version HgfsHandle *file, // OUT: Handle to write to uint64 *offset, // OUT: offset to write to uint32 *length, // OUT: length of data to write HgfsWriteFlags *flags, // OUT: write flags const void **data) // OUT: data to be written { Bool result; switch (writeOp) { case HGFS_OP_WRITE_FAST_V4: { const HgfsRequestWriteV3 *requestV3 = writeRequest; *data = NULL; /* Write data is retrieved from shared memory. */ result = HgfsUnpackWriteFastPayloadV4(requestV3, writeRequestSize, file, offset, length, flags); break; } case HGFS_OP_WRITE_V3: { const HgfsRequestWriteV3 *requestV3 = writeRequest; result = HgfsUnpackWritePayloadV3(requestV3, writeRequestSize, file, offset, length, flags, data); break; } case HGFS_OP_WRITE: { const HgfsRequestWrite *requestV1 = writeRequest; result = HgfsUnpackWritePayload(requestV1, writeRequestSize, file, offset, length, flags, data); break; } default: LOG(4, ("%s: Incorrect opcode %d\n", __FUNCTION__, writeOp)); NOT_REACHED(); result = FALSE; } if (!result) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); } return result; } /* *----------------------------------------------------------------------------- * * HgfsPackWriteReply -- * * Pack hgfs write reply to the HgfsReplyWrite structure. * * Results: * Always TRUE, FALSE if bad opcode. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackWriteReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type uint32 actualSize, // IN: number of bytes that were written size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; *payloadSize = 0; switch (op) { case HGFS_OP_WRITE_FAST_V4: case HGFS_OP_WRITE_V3: { HgfsReplyWriteV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); reply->reserved = 0; reply->actualSize = actualSize; *payloadSize = sizeof *reply; break; } case HGFS_OP_WRITE: { HgfsReplyWrite *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); reply->actualSize = actualSize; *payloadSize = sizeof *reply; break; } default: NOT_REACHED(); result = FALSE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackQueryVolumePayload -- * * Unpack hgfs query volume payload to get the file name which must be used to query * volume information. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackQueryVolumePayload(const HgfsRequestQueryVolume *request, // IN: request payload size_t payloadSize, // IN: request payload size const char **fileName, // OUT: volume name size_t *nameLength) // OUT: volume name length { LOG(4, ("%s: HGFS_OP_QUERY_VOLUME_INFO\n", __FUNCTION__)); if (payloadSize >= sizeof *request) { return HgfsUnpackFileName(&request->fileName, payloadSize - sizeof *request + 1, fileName, nameLength); } LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackQueryVolumePayloadV3 -- * * Unpack hgfs query volume payload V3. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackQueryVolumePayloadV3(const HgfsRequestQueryVolumeV3 *requestV3, // IN: payload size_t payloadSize, // IN: payload size Bool *useHandle, // OUT: use handle HgfsHandle* file, // OUT: HGFS handle const char **fileName, // OUT: volume name size_t *nameLength, // OUT: name length uint32 * caseFlags) // OUT: case flags { LOG(4, ("%s: HGFS_OP_QUERY_VOLUME_INFO_V3\n", __FUNCTION__)); if (payloadSize >= sizeof *requestV3) { return HgfsUnpackFileNameV3(&requestV3->fileName, payloadSize - sizeof *requestV3 + 1, useHandle, fileName, nameLength, file, caseFlags); } LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackQueryVolumeRequest -- * * Unpack hgfs query volume information request to get parameters related to * query volume operation. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackQueryVolumeRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type Bool *useHandle, // OUT: use handle const char **fileName, // OUT: file name size_t *fileNameLength, // OUT: file name length uint32 *caseFlags, // OUT: case sensitivity HgfsHandle *file) // OUT: Handle to the volume { ASSERT(packet); switch (op) { case HGFS_OP_QUERY_VOLUME_INFO_V3: { const HgfsRequestQueryVolumeV3 *requestV3 = packet; if (!HgfsUnpackQueryVolumePayloadV3(requestV3, packetSize, useHandle, file, fileName, fileNameLength, caseFlags)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_QUERY_VOLUME_INFO: { const HgfsRequestQueryVolume *requestV1 = packet; if (!HgfsUnpackQueryVolumePayload(requestV1, packetSize, fileName, fileNameLength)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } *file = HGFS_INVALID_HANDLE; *caseFlags = HGFS_FILE_NAME_DEFAULT_CASE; *useHandle = FALSE; break; } default: LOG(4, ("%s: Incorrect opcode %d\n", __FUNCTION__, op)); NOT_REACHED(); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackQueryVolumeReply -- * * Pack hgfs query volume reply. * * Results: * TRUE if valid op and reply set, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackQueryVolumeReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type uint64 freeBytes, // IN: volume free space uint64 totalBytes, // IN: volume capacity size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; *payloadSize = 0; switch (op) { case HGFS_OP_QUERY_VOLUME_INFO_V3: { HgfsReplyQueryVolumeV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); reply->reserved = 0; reply->freeBytes = freeBytes; reply->totalBytes = totalBytes; *payloadSize = sizeof *reply; break; } case HGFS_OP_QUERY_VOLUME_INFO: { HgfsReplyQueryVolume *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); reply->freeBytes = freeBytes; reply->totalBytes = totalBytes; *payloadSize = sizeof *reply; break; } default: result = FALSE; LOG(4, ("%s: invalid op code %d\n", __FUNCTION__, op)); NOT_REACHED(); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSymlinkCreatePayload -- * * Unpack hgfs symbolic link payload to get symbolic link file name * and symbolic link target. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSymlinkCreatePayload(const HgfsRequestSymlinkCreate *request, // IN: request payload size_t payloadSize, // IN: payload size const char **srcFileName, // OUT: link file name size_t *srcNameLength, // OUT: file name length const char **tgFileName, // OUT: target file name size_t *tgNameLength) // OUT: target name length { uint32 prefixSize; LOG(4, ("%s: HGFS_OP_CREATE_SYMLINK_V3\n", __FUNCTION__)); prefixSize = offsetof(HgfsRequestSymlinkCreate, symlinkName.name); if (payloadSize >= prefixSize) { if (HgfsUnpackFileName(&request->symlinkName, payloadSize - prefixSize, srcFileName, srcNameLength)) { const HgfsFileName *targetName = (const HgfsFileName *)(*srcFileName + 1 + *srcNameLength); prefixSize = ((char *)targetName - (char *)request) + offsetof(HgfsFileName, name); return HgfsUnpackFileName(targetName, payloadSize - prefixSize, tgFileName, tgNameLength); } } return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSymlinkCreatePayloadV3 -- * * Unpack hgfs create symbolic link payload V3. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSymlinkCreatePayloadV3(const HgfsRequestSymlinkCreateV3 *requestV3, // IN: size_t payloadSize, // IN: Bool *srcUseHandle, // OUT: HgfsHandle* srcFile, // OUT: const char **srcFileName, // OUT: size_t *srcNameLength, // OUT: uint32 *srcCaseFlags, // OUT: Bool *tgUseHandle, // OUT: HgfsHandle* tgFile, // OUT: const char **tgFileName, // OUT: size_t *tgNameLength, // OUT: uint32 * tgCaseFlags) // OUT: { uint32 prefixSize; LOG(4, ("%s: HGFS_OP_CREATE_SYMLINK_V3\n", __FUNCTION__)); prefixSize = offsetof(HgfsRequestSymlinkCreateV3, symlinkName.name); if (payloadSize >= prefixSize) { if (HgfsUnpackFileNameV3(&requestV3->symlinkName, payloadSize - prefixSize, srcUseHandle, srcFileName, srcNameLength, srcFile, srcCaseFlags)) { const HgfsFileNameV3 *targetName; if (*srcUseHandle) { targetName = &requestV3->targetName; } else { targetName = (const HgfsFileNameV3 *)(*srcFileName + 1 + *srcNameLength); } prefixSize = ((char *)targetName - (char *)requestV3) + offsetof(HgfsFileNameV3, name); return HgfsUnpackFileNameV3(targetName, payloadSize - prefixSize, tgUseHandle, tgFileName, tgNameLength, tgFile, tgCaseFlags); } } return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSymlinkCreateRequest -- * * Unpack hgfs symbolic link creation request to get parameters related to * creating the symbolic link. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackSymlinkCreateRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type Bool *srcUseHandle, // OUT: use source handle const char **srcFileName, // OUT: source file name size_t *srcFileNameLength, // OUT: source file name length uint32 *srcCaseFlags, // OUT: source case sensitivity HgfsHandle *srcFile, // OUT: source file handle Bool *tgUseHandle, // OUT: use target handle const char **tgFileName, // OUT: target file name size_t *tgFileNameLength, // OUT: target file name length uint32 *tgCaseFlags, // OUT: target case sensitivity HgfsHandle *tgFile) // OUT: target file handle { ASSERT(packet); switch (op) { case HGFS_OP_CREATE_SYMLINK_V3: { const HgfsRequestSymlinkCreateV3 *requestV3 = packet; if (!HgfsUnpackSymlinkCreatePayloadV3(requestV3, packetSize, srcUseHandle, srcFile, srcFileName, srcFileNameLength, srcCaseFlags, tgUseHandle, tgFile, tgFileName, tgFileNameLength, tgCaseFlags)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_CREATE_SYMLINK: { const HgfsRequestSymlinkCreate *requestV1 = packet; if (!HgfsUnpackSymlinkCreatePayload(requestV1, packetSize, srcFileName, srcFileNameLength, tgFileName, tgFileNameLength)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } *srcFile = HGFS_INVALID_HANDLE; *srcCaseFlags = HGFS_FILE_NAME_DEFAULT_CASE; *srcUseHandle = FALSE; *tgFile = HGFS_INVALID_HANDLE; *tgCaseFlags = HGFS_FILE_NAME_DEFAULT_CASE; *tgUseHandle = FALSE; break; } default: LOG(4, ("%s: Incorrect opcode %d\n", __FUNCTION__, op)); NOT_REACHED(); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackSymlinkCreateReply -- * * Pack hgfs symbolic link creation reply. * * Results: * TRUE if valid op and reply set, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackSymlinkCreateReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; switch (op) { case HGFS_OP_CREATE_SYMLINK_V3: { HgfsReplySymlinkCreateV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); /* Reply only consists of a reserved field. */ reply->reserved = 0; *payloadSize = sizeof *reply; break; } case HGFS_OP_CREATE_SYMLINK: { HgfsReplySymlinkCreate *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); *payloadSize = sizeof *reply; break; } default: result = FALSE; LOG(4, ("%s: invalid op code %d\n", __FUNCTION__, op)); NOT_REACHED(); } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSearchOpenPayload -- * * Unpack hgfs search open payload to get name of directory to open. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSearchOpenPayload(const HgfsRequestSearchOpen *request, // IN: payload size_t payloadSize, // IN: payload size const char **dirName, // OUT: directory name size_t *dirNameLength) // OUT: name length { LOG(4, ("%s: HGFS_OP_SEARCH_OPEN\n", __FUNCTION__)); if (payloadSize >= sizeof *request) { if (sizeof *request + request->dirName.length - 1 <= payloadSize) { *dirName = request->dirName.name; *dirNameLength = request->dirName.length; return TRUE; } } LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSearchOpenPayloadV3 -- * * Unpack hgfs search open payload V3 to get name of directory to open and * case flags. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSearchOpenPayloadV3(const HgfsRequestSearchOpenV3 *requestV3, // IN: payload size_t payloadSize, // IN: payload size const char **dirName, // OUT: directory name size_t *dirNameLength, // OUT: name length uint32 *caseFlags) // OUT: case flags { Bool result = FALSE; LOG(4, ("%s: HGFS_OP_SEARCH_OPEN_V3\n", __FUNCTION__)); if (payloadSize >= sizeof *requestV3) { uint32 prefixSize = offsetof(HgfsRequestSearchOpenV3, dirName.name); Bool useDirHandle; HgfsHandle dirHandle; result = HgfsUnpackFileNameV3(&requestV3->dirName, payloadSize - prefixSize, &useDirHandle, dirName, dirNameLength, &dirHandle, caseFlags); if (useDirHandle) { LOG(4, ("%s: client is trying to a handle %u\n", __FUNCTION__, dirHandle)); result = FALSE; } } LOG(4, ("%s: returns %d\n", __FUNCTION__, result)); return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSearchOpenRequest -- * * Unpack hgfs search open request to get directory name and case flags. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackSearchOpenRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type const char **dirName, // OUT: directory name size_t *dirNameLength, // OUT: name length uint32 *caseFlags) // OUT: case flags { ASSERT(packet); switch (op) { case HGFS_OP_SEARCH_OPEN_V3: { const HgfsRequestSearchOpenV3 *requestV3 = packet; if (!HgfsUnpackSearchOpenPayloadV3(requestV3, packetSize, dirName, dirNameLength, caseFlags)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } break; } case HGFS_OP_SEARCH_OPEN: { const HgfsRequestSearchOpen *requestV1 = packet; if (!HgfsUnpackSearchOpenPayload(requestV1, packetSize, dirName, dirNameLength)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } *caseFlags = HGFS_FILE_NAME_DEFAULT_CASE; break; } default: LOG(4, ("%s: Incorrect opcode %d\n", __FUNCTION__, op)); NOT_REACHED(); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackSearchOpenReply -- * * Pack hgfs search open reply. * * Results: * TRUE unless it is invoked for a wrong op (which indicates a bug in the code). * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackSearchOpenReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type HgfsHandle search, // IN: search handle size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; switch (op) { case HGFS_OP_SEARCH_OPEN_V3: { HgfsReplySearchOpenV3 *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); reply->reserved = 0; reply->search = search; *payloadSize = sizeof *reply; break; } case HGFS_OP_SEARCH_OPEN: { HgfsReplySearchOpen *reply; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); reply->search = search; *payloadSize = sizeof *reply; break; } default: NOT_REACHED(); result = FALSE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackCreateSessionPayloadV4 -- * * Unpack hgfs create session request V4 payload. * * Results: * TRUE on success, FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackCreateSessionPayloadV4(const HgfsRequestCreateSessionV4 *requestV4, // IN: payload size_t payloadSize, // IN: HgfsCreateSessionInfo *info) // IN/OUT: info { LOG(4, ("%s: HGFS_OP_CREATE_SESSION_V4\n", __FUNCTION__)); if (payloadSize < offsetof(HgfsRequestCreateSessionV4, reserved)) { /* The input packet is smaller than the request. */ return FALSE; } if (requestV4->numCapabilities) { if (payloadSize < offsetof(HgfsRequestCreateSessionV4, capabilities) + requestV4->numCapabilities * sizeof(HgfsCapability)) { LOG(4, ("%s: HGFS packet too small\n", __FUNCTION__)); return FALSE; } } info->maxPacketSize = requestV4->maxPacketSize; info->flags = requestV4->flags; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackCreateSessionRequest -- * * Unpack hgfs CreateSession request and initialize a corresponding * HgfsCreateDirInfo structure that is used to pass around CreateDir request * information. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackCreateSessionRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: size of packet HgfsOp op, // IN: request type HgfsCreateSessionInfo *info) // IN/OUT: info struct { const HgfsRequestCreateSessionV4 *requestV4; ASSERT(packet); ASSERT(info); ASSERT(op == HGFS_OP_CREATE_SESSION_V4); requestV4 = packet; if (!HgfsUnpackCreateSessionPayloadV4(requestV4, packetSize, info)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackCreateSessionReply -- * * Pack hgfs CreateSession reply. * * Results: * Always TRUE. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackCreateSessionReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { HgfsReplyCreateSessionV4 *reply; uint32 numCapabilities = session->numberOfCapabilities; uint32 capabilitiesLen = numCapabilities * sizeof *session->hgfsSessionCapabilities; HGFS_ASSERT_PACK_PARAMS; *payloadSize = offsetof(HgfsReplyCreateSessionV4, capabilities) + capabilitiesLen; reply = HgfsAllocInitReply(packet, packetHeader, *payloadSize, session); reply->sessionId = session->sessionId; reply->numCapabilities = numCapabilities; reply->maxPacketSize = session->maxPacketSize; reply->identityOffset = 0; reply->flags = session->flags; reply->reserved = 0; memcpy(reply->capabilities, session->hgfsSessionCapabilities, capabilitiesLen); return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackDestroySessionReply -- * * Pack hgfs CreateSession reply. * * Results: * Always TRUE. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackDestroySessionReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { HgfsReplyDestroySessionV4 *reply; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); /* Reply only consists of a reserved field. */ *payloadSize = sizeof *reply; reply->reserved = 0; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsServerGetDefaultCapabilities -- * * Returns list capabilities that are supported by all sessions. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ void HgfsServerGetDefaultCapabilities(HgfsCapability *capabilities, // OUT: capabilities uint32 *numberOfCapabilities) // OUT: number of items { *numberOfCapabilities = ARRAYSIZE(hgfsDefaultCapabilityTable); ASSERT(*numberOfCapabilities <= HGFS_OP_MAX); memcpy(capabilities, hgfsDefaultCapabilityTable, sizeof hgfsDefaultCapabilityTable); } /* *----------------------------------------------------------------------------- * * HgfsPackSetWatchReplyV4 -- * * Pack hgfs set watch V4 reply payload to the HgfsReplySetWatchV4 structure. * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsPackSetWatchReplyV4(HgfsSubscriberHandle watchId, // IN: host id of thee new watch HgfsReplySetWatchV4 *reply) // OUT: reply buffer to fill { reply->watchId = watchId; reply->reserved = 0; } /* *----------------------------------------------------------------------------- * * HgfsPackSetWatchReply -- * * Pack hgfs set watch reply to the HgfsReplySetWatchV4 structure. * * Results: * TRUE if successfully allocated reply request, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackSetWatchReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: operation code HgfsSubscriberHandle watchId, // IN: id of the new watch size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HgfsReplySetWatchV4 *reply; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; if (HGFS_OP_SET_WATCH_V4 == op) { reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); HgfsPackSetWatchReplyV4(watchId, reply); *payloadSize = sizeof *reply; } else { NOT_REACHED(); result = FALSE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackSetWatchPayloadV4 -- * * Unpack HGFS set directory notication watch payload version 4 and initializes * a corresponding HgfsHandle or file name to tell us which directory to watch. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackSetWatchPayloadV4(const HgfsRequestSetWatchV4 *requestV4, // IN: request payload size_t payloadSize, // IN: payload size Bool *useHandle, // OUT: handle or cpName uint32 *flags, // OUT: watch flags uint32 *events, // OUT: event filter const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsHandle *dir, // OUT: directory handle uint32 *caseFlags) // OUT: case-sensitivity { if (payloadSize < sizeof *requestV4) { return FALSE; } *flags = requestV4->flags; *events = requestV4->events; return HgfsUnpackFileNameV3(&requestV4->fileName, payloadSize - sizeof *requestV4, useHandle, cpName, cpNameSize, dir, caseFlags); } /* *----------------------------------------------------------------------------- * * HgfsUnpackSetWatchRequest -- * * Unpack hgfs set directory notication watch request and initialize a corresponding * HgfsHandle or directory name to tell us which directory to monitor. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackSetWatchRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: requested operation Bool *useHandle, // OUT: handle or cpName const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size uint32 *flags, // OUT: flags for the new watch uint32 *events, // OUT: event filter HgfsHandle *dir, // OUT: direrctory handle uint32 *caseFlags) // OUT: case-sensitivity flags { const HgfsRequestSetWatchV4 *requestV4 = packet; Bool result; ASSERT(packet); ASSERT(cpName); ASSERT(cpNameSize); ASSERT(dir); ASSERT(flags); ASSERT(events); ASSERT(caseFlags); ASSERT(useHandle); if (HGFS_OP_SET_WATCH_V4 != op) { NOT_REACHED(); result = FALSE; } else { LOG(4, ("%s: HGFS_OP_SET_WATCH_V4\n", __FUNCTION__)); result = HgfsUnpackSetWatchPayloadV4(requestV4, packetSize, useHandle, flags, events, cpName, cpNameSize, dir, caseFlags); } if (!result) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); } return result; } /* *----------------------------------------------------------------------------- * * HgfsPackRemoveWatchReply -- * * Pack hgfs remove watch reply to the HgfsReplyRemoveWatchV4 structure. * * Results: * TRUE if successfully allocated reply request, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackRemoveWatchReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: operation code size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session) // IN: Session info { Bool result = TRUE; HgfsReplyRemoveWatchV4 *reply; HGFS_ASSERT_PACK_PARAMS; *payloadSize = 0; if (HGFS_OP_REMOVE_WATCH_V4 != op) { NOT_REACHED(); result = FALSE; } else { reply = HgfsAllocInitReply(packet, packetHeader, sizeof *reply, session); reply->reserved = 0; *payloadSize = sizeof *reply; } return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackRemoveWatchPayload -- * * Unpack HGFS remove directory notication watch payload version 4. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackRemoveWatchPayloadV4(const HgfsRequestRemoveWatchV4 *requestV4, // IN: request payload size_t payloadSize, // IN: payload size HgfsSubscriberHandle *watchId) // OUT: watch id { if (payloadSize < sizeof *requestV4) { return FALSE; } *watchId = requestV4->watchId; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackRemoveWatchRequest -- * * Unpack hgfs remove directory notication watch request. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackRemoveWatchRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: requested operation HgfsSubscriberHandle *watchId) // OUT: watch Id to remove { const HgfsRequestRemoveWatchV4 *requestV4 = packet; ASSERT(packet); ASSERT(watchId); ASSERT(HGFS_OP_REMOVE_WATCH_V4 == op); if (HGFS_OP_REMOVE_WATCH_V4 != op) { return FALSE; } else if (!HgfsUnpackRemoveWatchPayloadV4(requestV4, packetSize, watchId)) { LOG(4, ("%s: Error decoding HGFS packet\n", __FUNCTION__)); return FALSE; } return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackCalculateNotificationSize -- * * Calculates size needed for change notification packet. * * Results: * TRUE if successfully allocated reply request, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ size_t HgfsPackCalculateNotificationSize(char const *shareName, // IN: shared folder name char *fileName) // IN: relative file path { size_t result = sizeof (HgfsRequestNotifyV4); if (NULL != fileName) { size_t shareNameLen = strlen(shareName); result += strlen(fileName) + 1 + shareNameLen; } result += sizeof (HgfsHeader); return result; } /* *----------------------------------------------------------------------------- * * HgfsPackGetOplockBreakSize -- * * Gets the size needed for the oplock break request. * * Results: * Size of the oplock break request. * * Side effects: * None. * *----------------------------------------------------------------------------- */ size_t HgfsPackGetOplockBreakSize(void) { return sizeof (HgfsRequestOplockBreakV4) + sizeof (HgfsHeader); } /* *----------------------------------------------------------------------------- * * HgfsPackOplockBreakRequestV4( -- * * Pack hgfs oplock break V4 request to be sent to the guest. * * Results: * Length of the packed structure or 0 if the structure does not fit in the * the buffer. * * Side effects: * None * *----------------------------------------------------------------------------- */ static size_t HgfsPackOplockBreakRequestV4(HgfsHandle fileId, // IN: file ID HgfsLockType serverLock, // IN: lock type size_t bufferSize, // IN: available space HgfsRequestOplockBreakV4 *reply) // OUT: notification buffer { size_t size = 0; if (bufferSize < sizeof *reply) { goto exit; } reply->reserved = 0; reply->fid = fileId; reply->serverLock = serverLock; size = sizeof *reply; exit: return size; } /* *----------------------------------------------------------------------------- * * HgfsPackOplockBreakRequest -- * * Pack the HGFS protocol Oplock break request. * * Results: * TRUE if successfully packed the request, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackOplockBreakRequest(void *packet, // IN/OUT: Hgfs Packet HgfsHandle fileId, // IN: file ID HgfsLockType serverLock, // IN: lock type uint64 sessionId, // IN: session ID size_t *bufferSize) // IN/OUT: size of packet { size_t opBreakRequestSize; HgfsRequestOplockBreakV4 *opBreakRequest; HgfsHeader *header = packet; Bool result = TRUE; ASSERT(packet); ASSERT(bufferSize); if (*bufferSize < sizeof *header) { result = FALSE; goto exit; } /* * Initialize notification header. * Set status and requestId to 0 since these fields are not relevant for * oplock break requests. * Initialize payload size to 0 - it is not known yet and will be filled later. */ opBreakRequest = (HgfsRequestOplockBreakV4 *)((char *)header + sizeof *header); opBreakRequestSize = HgfsPackOplockBreakRequestV4(fileId, serverLock, *bufferSize - sizeof *header, opBreakRequest); if (0 == opBreakRequestSize) { result = FALSE; goto exit; } result = HgfsPackReplyHeaderV4(HGFS_ERROR_SUCCESS, opBreakRequestSize, HGFS_OP_OPLOCK_BREAK_V4, sessionId, 0, HGFS_PACKET_FLAG_REQUEST, *bufferSize, header); exit: return result; } /* *----------------------------------------------------------------------------- * * HgfsUnpackOplockBreakAckPayloadV4 -- * * Unpack HGFS oplock break acknowledge payload version 4. * * Results: * TRUE on success. * FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsUnpackOplockBreakAckPayloadV4(const HgfsReplyOplockBreakV4 *opBrkAck, // IN: request payload size_t payloadSize, // IN: payload size HgfsHandle *fileId, // OUT: file Id to remove HgfsLockType *serverLock) // OUT: lock type { if (payloadSize < sizeof *opBrkAck) { return FALSE; } *fileId = opBrkAck->fid; *serverLock = opBrkAck->serverLock; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsUnpackOplockBreakAckReply -- * * Unpack hgfs oplock break acknowledge reply. * * Results: * TRUE on success, FALSE on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsUnpackOplockBreakAckReply(const void *packet, // IN: HGFS packet size_t packetSize, // IN: reply packet size HgfsOp op, // IN: operation version HgfsHandle *fileId, // OUT: file Id to remove HgfsLockType *serverLock) // OUT: lock type { const HgfsReplyOplockBreakV4 *replyV4 = packet; Bool result = FALSE; ASSERT(fileId); ASSERT(serverLock); ASSERT(HGFS_OP_OPLOCK_BREAK_V4 == op); if (HGFS_OP_OPLOCK_BREAK_V4 == op) { result = HgfsUnpackOplockBreakAckPayloadV4(replyV4, packetSize, fileId, serverLock); } if (!result) { LOG(4, ("%s: Error unpacking HGFS_OP_OPLOCK_BREAK_V4 packet\n", __FUNCTION__)); } return result; } /* *----------------------------------------------------------------------------- * * HgfsBuildCPName -- * * Build crossplatform name out of share name and relative to the shared folder * file path. * * Results: * Length of the output crossplatform name. * * Side effects: * None * *----------------------------------------------------------------------------- */ static int HgfsBuildCPName(char const *shareName, // IN: utf8 share name char *fileName, // IN: utf8 file path char **cpName) // OUT: full name in cp format { size_t shareNameLen = strlen(shareName) + 1; size_t fileNameLen = strlen(fileName) + 1; char *fullName = Util_SafeMalloc(shareNameLen + fileNameLen); int cpNameResult; *cpName = Util_SafeMalloc(shareNameLen + fileNameLen); Str_Strcpy(fullName, shareName, shareNameLen); fullName[shareNameLen - 1] = DIRSEPC; Str_Strcpy(fullName + shareNameLen, fileName, fileNameLen); // Unescaped name can't be longer then escaped thus it must fit. cpNameResult = CPName_ConvertTo(fullName, shareNameLen + fileNameLen, *cpName); free(fullName); if (cpNameResult < 0) { free(*cpName); *cpName = NULL; } return cpNameResult; } /* *----------------------------------------------------------------------------- * * HgfsPackHgfsName -- * * Pack cpName into HgfsFileName structure. * * Results: * TRUE if there is enough space in the buffer, * FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsPackHgfsName(char *cpName, // IN: cpName to pack size_t cpNameLen, // IN: length of the cpName size_t availableSpace, // IN: space available for HgfsFileName size_t *nameSize, // OUT: space consumed by HgfsFileName HgfsFileName *fileName) // OUT: structure to pack cpName into { if (availableSpace < offsetof(HgfsFileName, name) + cpNameLen) { return FALSE; } fileName->length = cpNameLen; memcpy(fileName->name, cpName, cpNameLen); *nameSize = offsetof(HgfsFileName, name) + cpNameLen; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsPackChangeNotifyEventV4 -- * * Pack single change directory notification event information. * * Results: * Length of the packed structure or 0 if the structure does not fit in the * the buffer. * * Side effects: * None * *----------------------------------------------------------------------------- */ static size_t HgfsPackChangeNotifyEventV4(uint32 mask, // IN: event mask char const *shareName, // IN: share name char *fileName, // IN: file name size_t bufferSize, // IN: available space HgfsNotifyEventV4 *reply) // OUT: notificaiton buffer { size_t totalLength = 0; if (sizeof *reply > bufferSize) { /* Not enough space for the event, drop the event. */ goto exit; } reply->nextOffset = 0; reply->mask = mask; if (NULL != fileName) { char *cpFullName; size_t remainingSize; size_t hgfsNameSize; int cpFullNameSize; cpFullNameSize = HgfsBuildCPName(shareName, fileName, &cpFullName); if (cpFullNameSize < 0) { /* Could not build the crossplatform name, drop the event. */ goto exit; } remainingSize = bufferSize - offsetof(HgfsNotifyEventV4, fileName); if (!HgfsPackHgfsName(cpFullName, cpFullNameSize, remainingSize, &hgfsNameSize, &reply->fileName)) { /* Name would not fit, drop the event. */ free(cpFullName); goto exit; } remainingSize -= hgfsNameSize; totalLength = bufferSize - remainingSize; free(cpFullName); } else { reply->fileName.length = 0; totalLength = sizeof *reply; } exit: return totalLength; } /* *----------------------------------------------------------------------------- * * HgfsPackChangeNotifyRequestV4 -- * * Pack hgfs directory change notification request to be sent to the guest. * * Results: * Length of the packed structure or 0 if the structure does not fit in the * the buffer. * * Side effects: * None * *----------------------------------------------------------------------------- */ static size_t HgfsPackChangeNotifyRequestV4(HgfsSubscriberHandle watchId, // IN: watch uint32 flags, // IN: notify flags uint32 mask, // IN: event mask char const *shareName, // IN: share name char *fileName, // IN: relative file path size_t bufferSize, // IN: available space HgfsRequestNotifyV4 *reply) // OUT: notification buffer { size_t size = 0; size_t notificationOffset; if (bufferSize < sizeof *reply) { LOG(4, ("%s: Error HGFS_OP_NOTIFY_V4 buf size %"FMTSZ"u reply size %"FMTSZ"u\n", __FUNCTION__, bufferSize, sizeof *reply)); goto exit; } reply->watchId = watchId; reply->flags = flags; if ((flags & HGFS_NOTIFY_FLAG_OVERFLOW) == HGFS_NOTIFY_FLAG_OVERFLOW) { size = sizeof *reply; reply->count = 0; reply->flags = HGFS_NOTIFY_FLAG_OVERFLOW; } else { /* * For the moment server sends only one notification at a time and it relies * on transport to coalesce requests. * Later on we may consider supporting multiple notifications. */ reply->count = 1; notificationOffset = offsetof(HgfsRequestNotifyV4, events); size = HgfsPackChangeNotifyEventV4(mask, shareName, fileName, bufferSize - notificationOffset, reply->events); if (size != 0) { size += notificationOffset; } else { /* * Set event flag to tell guest that some events were dropped * when filling out notification details failed. */ size = sizeof *reply; reply->count = 0; reply->flags = HGFS_NOTIFY_FLAG_OVERFLOW; } } exit: return size; } /* *----------------------------------------------------------------------------- * * HgfsPackChangeNotificationRequest -- * * Pack hgfs directory change notification request to the * HgfsRequestNotifyV4 structure. * * Results: * TRUE if successfully allocated reply request, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsPackChangeNotificationRequest(void *packet, // IN/OUT: Hgfs Packet HgfsSubscriberHandle subscriber, // IN: watch char const *shareName, // IN: share name char *fileName, // IN: relative name uint32 mask, // IN: event mask uint32 notifyFlags, // IN: notify flags HgfsSessionInfo *session, // IN: session size_t *bufferSize) // INOUT: size of packet { size_t notifyRequestSize; HgfsRequestNotifyV4 *notifyRequest; HgfsHeader *header = packet; Bool result = FALSE; ASSERT(packet); ASSERT(shareName); ASSERT(NULL != fileName || (notifyFlags & HGFS_NOTIFY_FLAG_OVERFLOW) == HGFS_NOTIFY_FLAG_OVERFLOW); ASSERT(session); ASSERT(bufferSize); LOG(4, ("%s: HGFS_OP_NOTIFY_V4\n", __FUNCTION__)); if (*bufferSize < sizeof *header) { LOG(4, ("%s: Error HGFS_OP_NOTIFY_V4 buf size %"FMTSZ"u min %"FMTSZ"u\n", __FUNCTION__, *bufferSize, sizeof *header)); goto exit; } /* * Initialize notification header. * Set status and requestId to 0 since these fields are not relevant for * notifications. * Initialize payload size to 0 - it is not known yet and will be filled later. */ notifyRequest = (HgfsRequestNotifyV4 *)((char *)header + sizeof *header); notifyRequestSize = HgfsPackChangeNotifyRequestV4(subscriber, notifyFlags, mask, shareName, fileName, *bufferSize - sizeof *header, notifyRequest); if (0 != notifyRequestSize) { result = HgfsPackReplyHeaderV4(HGFS_ERROR_SUCCESS, notifyRequestSize, HGFS_OP_NOTIFY_V4, session->sessionId, 0, HGFS_PACKET_FLAG_REQUEST, *bufferSize, header); } exit: return result; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServer/hgfsServerParameters.h000066400000000000000000000512351321503522500275030ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2013-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerParameters.h -- * * This defines the HGFS protocol message packet functions * for creating requests and extracting data from replies. */ #ifndef _HGFS_SERVER_PARAMETERS_H_ #define _HGFS_SERVER_PARAMETERS_H_ #include "hgfsServer.h" // for HgfsPacket type #include "hgfsProto.h" // for the HGFS protocol request, reply and types #include "hgfsUtil.h" // for HgfsInternalStatus #include "hgfsServerInt.h" // for HgfsSessionInfo /* * Global functions */ HgfsInternalStatus HgfsUnpackPacketParams(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size Bool *sessionEnabled, // OUT: session enabled request uint64 *sessionId, // OUT: session Id uint32 *requestId, // OUT: unique request id HgfsOp *opcode, // OUT: request opcode size_t *payloadSize, // OUT: size of the opcode request const void **payload); // OUT: pointer to the opcode request Bool HgfsPackReplyHeader(HgfsInternalStatus status, // IN: reply status uint32 payloadSize, // IN: size of the reply payload Bool sessionEnabledHeader, // IN: session enabled header uint64 sessionId, // IN: session id uint32 requestId, // IN: request id HgfsOp op, // IN: request type uint32 hdrFlags, // IN: header flags size_t hdrPacketSize, // IN: header packet size void *hdrPacket); // OUT: outgoing packet header Bool HgfsUnpackOpenRequest(const void *packet, // IN: incoming packet size_t packetSize, // IN: size of packet HgfsOp op, // IN: request type HgfsFileOpenInfo *openInfo); // IN/OUT: open info struct Bool HgfsPackOpenReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsFileOpenInfo *openInfo, // IN: open info struct size_t *payloadSize, // OUT: outgoing packet size HgfsSessionInfo *session); // IN: Session Info Bool HgfsUnpackGetattrRequest(const void *packetHeader, // IN: packet header size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type HgfsFileAttrInfo *attrInfo, // IN/OUT: unpacked attr struct HgfsAttrHint *hints, // OUT: getattr hints const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsHandle *file, // OUT: file handle uint32 *caseFlags); // OUT: case-sensitivity flags Bool HgfsUnpackDeleteRequest(const void *packet, // IN: request packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: requested operation const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsDeleteHint *hints, // OUT: delete hints HgfsHandle *file, // OUT: file handle uint32 *caseFlags); // OUT: case-sensitivity flags Bool HgfsPackDeleteReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: requested operation size_t *payloadSize, // OUT: size of HGFS packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsUnpackRenameRequest(const void *packet, // IN: request packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: requested operation const char **cpOldName, // OUT: rename src size_t *cpOldNameLen, // OUT: rename src size const char **cpNewName, // OUT: rename dst size_t *cpNewNameLen, // OUT: rename dst size HgfsRenameHint *hints, // OUT: rename hints HgfsHandle *srcFile, // OUT: src file handle HgfsHandle *targetFile, // OUT: target file handle uint32 *oldCaseFlags, // OUT: old case-sensitivity flags uint32 *newCaseFlags); // OUT: new case-sensitivity flags Bool HgfsPackRenameReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: requested operation size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsPackGetattrReply(HgfsPacket *packet, // IN/OUT: Hgfs packet const void *packetHeader, // IN: packet header HgfsFileAttrInfo *attr, // IN: attr stucture const char *utf8TargetName, // IN: optional target name uint32 utf8TargetNameLen, // IN: file name length size_t *payloadSize, // OUT: size of HGFS packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsPackSymlinkCreateReply(HgfsPacket *packet, // IN/OUT: Hgfs packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of HGFS packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsUnpackSearchReadRequest(const void *packet, // IN: request packet size_t packetSize, // IN: packet size HgfsOp op, // IN: requested operation HgfsSearchReadInfo *info, // OUT: search info size_t *baseReplySize, // OUT: op base reply size size_t *inlineReplyDataSize, // OUT: size of inline reply data HgfsHandle *hgfsSearchHandle);// OUT: hgfs search handle Bool HgfsPackSearchReadReplyRecord(HgfsOp requestType, // IN: search read request HgfsSearchReadEntry *entry, // IN: entry info size_t maxRecordSize, // IN: max size in bytes for record void *lastSearchReadRecord, // IN/OUT: last packed entry void *currentSearchReadRecord,// OUT: currrent entry to pack size_t *replyRecordSize); // OUT: size of packet Bool HgfsPackSearchReadReplyHeader(HgfsSearchReadInfo *info, // IN: request info size_t *payloadSize); // OUT: size of packet Bool HgfsUnpackSetattrRequest(const void *packet, // IN: request packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: requested operation HgfsFileAttrInfo *attr, // IN/OUT: getattr info HgfsAttrHint *hints, // OUT: setattr hints const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size HgfsHandle *file, // OUT: server file ID uint32 *caseFlags); // OUT: case-sensitivity flags Bool HgfsPackSetattrReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsUnpackCreateDirRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: size of packet HgfsOp op, // IN: requested operation HgfsCreateDirInfo *info); // IN/OUT: info struct Bool HgfsPackCreateDirReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsPackQueryVolumeReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type uint64 freeBytes, // IN: volume free space uint64 totalBytes, // IN: volume capacity size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsUnpackQueryVolumeRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type Bool *useHandle, // OUT: use handle const char **fileName, // OUT: file name size_t *fileNameLength, // OUT: file name length uint32 *caseFlags, // OUT: case sensitivity HgfsHandle *file); // OUT: Handle to the volume Bool HgfsUnpackSymlinkCreateRequest(const void *packet, // IN: request packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type Bool *srcUseHandle, // OUT: use source handle const char **srcFileName, // OUT: source file name size_t *srcFileNameLength, // OUT: source file name length uint32 *srcCaseFlags, // OUT: source case sensitivity HgfsHandle *srcFile, // OUT: source file handle Bool *tgUseHandle, // OUT: use target handle const char **tgFileName, // OUT: target file name size_t *tgFileNameLength, // OUT: target file name length uint32 *tgCaseFlags, // OUT: target case sensitivity HgfsHandle *tgFile); // OUT: target file handle Bool HgfsUnpackWriteWin32StreamRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: size of packet HgfsOp op, // IN: request type HgfsHandle *file, // OUT: file to write to const char **payload, // OUT: data to write size_t *requiredSize, // OUT: size of data Bool *doSecurity); // OUT: restore sec.str. Bool HgfsUnpackCreateSessionRequest(const void *packetHeader, // IN: request packet size_t packetSize, // IN: size of packet HgfsOp op, // IN: request type HgfsCreateSessionInfo *info); // IN/OUT: info struct Bool HgfsPackWriteWin32StreamReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet headert HgfsOp op, // IN: request type uint32 actualSize, // IN: amount written size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN:Session Info Bool HgfsUnpackCloseRequest(const void *packet, // IN: request packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type HgfsHandle *file); // OUT: Handle to close Bool HgfsUnpackSearchOpenRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type const char **dirName, // OUT: directory name size_t *dirNameLength, // OUT: name length uint32 *caseFlags); // OUT: case flags Bool HgfsPackCloseReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsUnpackSearchCloseRequest(const void *packet, // IN: request packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type HgfsHandle *file); // OUT: Handle to close Bool HgfsPackSearchOpenReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type HgfsHandle search, // IN: search handle size_t *packetSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsPackSearchCloseReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type size_t *packetSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsPackWriteReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: request type uint32 actualSize, // IN: number of bytes that were written size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session info Bool HgfsUnpackReadRequest(const void *packet, // IN: HGFS request size_t packetSize, // IN: request packet size HgfsOp op, // IN: request type HgfsHandle *file, // OUT: Handle to close uint64 *offset, // OUT: offset to read from uint32 *length); // OUT: length of data to read Bool HgfsUnpackWriteRequest(const void *writeRequest,// IN: HGFS write request params size_t writeRequestSize, // IN: write request params size HgfsOp writeOp, // IN: request version HgfsHandle *file, // OUT: Handle to write to uint64 *offset, // OUT: offset to write to uint32 *length, // OUT: length of data to write HgfsWriteFlags *flags, // OUT: write flags const void **data); // OUT: data to be written Bool HgfsPackCreateSessionReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info Bool HgfsPackDestroySessionReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session Info void HgfsServerGetDefaultCapabilities(HgfsCapability *capabilities, // OUT: uint32 *numberOfCapabilities); // OUT: Bool HgfsUnpackSetWatchRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: request packet size HgfsOp op, // IN: requested operation Bool *useHandle, // OUT: handle or cpName const char **cpName, // OUT: cpName size_t *cpNameSize, // OUT: cpName size uint32 *flags, // OUT: flags for the new watch uint32 *events, // OUT: event filter HgfsHandle *dir, // OUT: direrctory handle uint32 *caseFlags); // OUT: case-sensitivity flags Bool HgfsPackSetWatchReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: operation code HgfsSubscriberHandle watchId, // IN: new watch id size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session info Bool HgfsUnpackRemoveWatchRequest(const void *packet, // IN: HGFS packet size_t packetSize, // IN: packet size HgfsOp op, // IN: operation code HgfsSubscriberHandle *watchId); // OUT: watch Id Bool HgfsPackRemoveWatchReply(HgfsPacket *packet, // IN/OUT: Hgfs Packet const void *packetHeader, // IN: packet header HgfsOp op, // IN: operation code size_t *payloadSize, // OUT: size of packet HgfsSessionInfo *session); // IN: Session info size_t HgfsPackCalculateNotificationSize(char const *shareName, // IN: shared folder name char *fileName); // IN: file name Bool HgfsPackChangeNotificationRequest(void *packet, // IN/OUT: Hgfs Packet HgfsSubscriberHandle subscriber, // IN: watch char const *shareName, // IN: share name char *fileName, // IN: file name uint32 mask, // IN: event mask uint32 notifyFlags, // IN: notify flags HgfsSessionInfo *session, // IN: session size_t *bufferSize); // IN/OUT: packet size #endif // ifndef _HGFS_SERVER_PARAMETERS_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerManagerGuest/000077500000000000000000000000001321503522500254655ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerManagerGuest/Makefile.am000066400000000000000000000022211321503522500275160ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libHgfsServerManagerGuest.la libHgfsServerManagerGuest_la_SOURCES = libHgfsServerManagerGuest_la_SOURCES += hgfsServerManagerGuest.c libHgfsServerManagerGuest_la_SOURCES += hgfsChannelGuest.c libHgfsServerManagerGuest_la_SOURCES += hgfsChannelGuestBd.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerManagerGuest/hgfsChannelGuest.c000066400000000000000000000515271321503522500310730ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsChannelGuest.c -- * * Channel abstraction for the HGFS server. * */ #include #include "vm_basic_defs.h" #include "vm_assert.h" #include "vm_atomic.h" #include "util.h" #include "hgfsChannelGuestInt.h" #include "hgfsServer.h" #include "hgfsServerManager.h" /* * HGFS server connection channel and state object usage. * * Currently, all plugins can share this same HGFS server channel and state. * This allows us to use a common channel so it is only initialized * once, by the first loaded plugin which requires an HGFS channel, and torn * down when the final plugin that uses the HGFS server is unloaded. * * Currently, the plugins are loaded (and unloaded) in any particular order, * and those operations are serialized. (For example the HGFS server plugin * maybe the first plugin loaded that uses this channel, but is not the final * plugin to be unloaded that uses the channel. This also may change in the * future, so no dependencies can be made on order of loading and unloading * of plugins.) * Furthermore, multiple plugins use the HGFS channel and server and some plugins * have multiple connections. Some plugins also create and teardown connections * during general mutlithreaded operation of the tools processes. * * In order to support the above, we must track how many users of the shared * connection there are. This allows us to tear down the shared connection * when the final plugin that is using it is unloaded, and when no * channels are in use the HGFS server state can be torn down. */ /* * The HGFS server state. * * This object is initiliazed once only and is shared across all * connections, shared or private. * Each new channel connection will reference the server and so the HGFS * server is initialized when the first new channel is being created. Each * new channel just increments the reference of server state object. * When the final channel is torn down the final HGFS server reference is * also removed and the HGFS server exit is called and this object is torn down. */ typedef struct HgfsChannelServerData { const HgfsServerCallbacks *serverCBTable; /* HGFS server entry points. */ Atomic_uint32 refCount; /* Server data reference count. */ } HgfsChannelServerData; /* * Transport channels context. * * Multiple callers share this same channel currently as only one * transport channel is required. Therefore, the channel is referenced * for each client that it is returned to (a usage count). */ typedef struct HgfsChannelData { const char *name; /* Channel name. */ const HgfsGuestChannelCBTable *ops; /* Channel operations. */ uint32 state; /* Channel state (see flags below). */ struct HgfsGuestConn *connection; /* Opaque server connection */ HgfsChannelServerData *serverInfo; /* HGFS server entry points. */ Atomic_uint32 refCount; /* Channel reference count. */ } HgfsChannelData; #define HGFS_CHANNEL_STATE_INIT (1 << 0) #define HGFS_CHANNEL_STATE_CBINIT (1 << 1) /* Static channel registration - assumes only one for now. */ static HgfsChannelData gHgfsChannels[] = { { "guest", &gGuestBackdoorOps, 0, NULL, NULL, {0} }, }; static HgfsServerConfig gHgfsGuestCfgSettings = { (HGFS_CONFIG_SHARE_ALL_HOST_DRIVES_ENABLED | HGFS_CONFIG_VOL_INFO_MIN), HGFS_MAX_CACHED_FILENODES }; /* HGFS server info state. Referenced by each separate channel that uses it. */ static HgfsChannelServerData gHgfsChannelServerInfo = { NULL, {0} }; static void HgfsChannelTeardownChannel(HgfsChannelData *channel); static void HgfsChannelTeardownServer(HgfsChannelServerData *serverInfo); static void HgfsChannelExitChannel(HgfsChannelData *channel); /* *---------------------------------------------------------------------------- * * HGFS SERVER DATA FUNCTIONS * *---------------------------------------------------------------------------- */ /* *---------------------------------------------------------------------------- * * HgfsChannelGetServer -- * * Increment the server data reference count. * * Results: * The value of the reference count before the increment. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static uint32 HgfsChannelGetServer(HgfsChannelServerData *serverInfo) // IN/OUT: ref count { ASSERT(NULL != serverInfo); return Atomic_ReadInc32(&serverInfo->refCount); } /* *---------------------------------------------------------------------------- * * HgfsChannelPutServer -- * * Decrement server data reference count. * * Teardown the server data object if removed the final reference. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsChannelPutServer(HgfsChannelServerData *serverInfo) // IN/OUT: ref count { ASSERT(NULL != serverInfo); if (Atomic_ReadDec32(&serverInfo->refCount) == 1) { HgfsChannelTeardownServer(serverInfo); } } /* *---------------------------------------------------------------------------- * * HgfsChannelInitServer -- * * Initialize HGFS server and save the state. * * Results: * TRUE if success, FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static Bool HgfsChannelInitServer(HgfsServerMgrCallbacks *mgrCb, // IN: server manager callbacks HgfsChannelServerData *serverInfo) // IN/OUT: ref count { Bool result; ASSERT(NULL == serverInfo->serverCBTable); Debug("%s: Initialize Hgfs server.\n", __FUNCTION__); /* If we have a new connection initialize the server session with default settings. */ result = HgfsServer_InitState(&serverInfo->serverCBTable, &gHgfsGuestCfgSettings, mgrCb); if (!result) { Debug("%s: Could not init Hgfs server.\n", __FUNCTION__); } return result; } /* *---------------------------------------------------------------------------- * * HgfsChannelExitServer -- * * Reset the HGFS server and destroy the state. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsChannelExitServer(HgfsChannelServerData *serverInfo) // IN/OUT: ref count { if (NULL != serverInfo->serverCBTable) { Debug("%s: Teardown Hgfs server.\n", __FUNCTION__); HgfsServer_ExitState(); serverInfo->serverCBTable = NULL; } } /* *---------------------------------------------------------------------------- * * HgfsChannelTeardownServer -- * * Teardown the HGFS server state for all connections. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsChannelTeardownServer(HgfsChannelServerData *serverInfo) // IN/OUT: connection manager object { HgfsChannelExitServer(serverInfo); } /* *---------------------------------------------------------------------------- * * CHANNEL DATA FUNCTIONS * *---------------------------------------------------------------------------- */ /* *---------------------------------------------------------------------------- * * HgfsChannelGetChannel -- * * Increment channel data reference count. * * Results: * The value of the reference count before the increment. * * Side effects: * None. * *---------------------------------------------------------------------------- */ uint32 HgfsChannelGetChannel(HgfsChannelData *channel) // IN/OUT: ref count { ASSERT(NULL != channel); return Atomic_ReadInc32(&channel->refCount); } /* *---------------------------------------------------------------------------- * * HgfsChannelPutChannel -- * * Decrement channel reference count. * * Teardown channel object if removed the final reference. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsChannelPutChannel(HgfsChannelData *channel) // IN/OUT: ref count { ASSERT(NULL != channel); if (Atomic_ReadDec32(&channel->refCount) == 1) { HgfsChannelTeardownChannel(channel); } } /* *----------------------------------------------------------------------------- * * HgfsChannelInitChannel -- * * Initializes a channel by initializing the HGFS server state. * * Results: * TRUE if the channel initialized, FALSE otherwise. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsChannelInitChannel(HgfsChannelData *channel, // IN/OUT: channel object HgfsServerMgrCallbacks *mgrCb, // IN: server manager callbacks HgfsChannelServerData *serverInfo) // IN/OUT: server info { Bool result = TRUE; uint32 serverInfoCount; channel->state = 0; /* * Reference the HGFS server as it will be used by the new channel. * The HGFS server should only be initialized once, i.e. on the first * caller instance, otherwise only reference the server info for * the new channel. */ serverInfoCount = HgfsChannelGetServer(serverInfo); /* Referenced the server, save it for dereferencing. */ channel->serverInfo = serverInfo; if (0 == serverInfoCount) { /* The HGFS server has not been initialized, do it now. */ result = HgfsChannelInitServer(mgrCb, channel->serverInfo); if (!result) { Debug("%s: Could not init Hgfs server.\n", __FUNCTION__); goto exit; } } channel->state |= HGFS_CHANNEL_STATE_INIT; exit: if (!result) { HgfsChannelExitChannel(channel); } Debug("%s: Init channel return %d.\n", __FUNCTION__, result); return result; } /* *----------------------------------------------------------------------------- * * HgfsChannelExitChannel -- * * Teardown the channel and teardown the HGFS server. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsChannelExitChannel(HgfsChannelData *channel) // IN/OUT: channel object { if (NULL != channel->serverInfo) { /* Remove the reference for the HGFS server info. */ HgfsChannelPutServer(channel->serverInfo); channel->serverInfo = NULL; } channel->state = 0; Debug("%s: Exit channel returns.\n", __FUNCTION__); } /* *----------------------------------------------------------------------------- * * HgfsChannelActivateChannel -- * * Activate a channel by calling the channels init callback. * * Results: * TRUE if a channel is active. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsChannelActivateChannel(HgfsChannelData *channel, // IN/OUT: channel object void *rpc, // IN: Rpc channel void *rpcCallback) // IN: Rpc callback { Bool success = FALSE; struct HgfsGuestConn *connData = NULL; if (channel->ops->init(&channel->serverInfo->serverCBTable->session, rpc, rpcCallback, &connData)) { channel->state |= HGFS_CHANNEL_STATE_CBINIT; channel->connection = connData; success = TRUE; } return success; } /* *----------------------------------------------------------------------------- * * HgfsChannelDeactivateChannel -- * * Deactivate a channel by calling the channels exit callback. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsChannelDeactivateChannel(HgfsChannelData *channel) // IN/OUT: channel object { channel->ops->exit(channel->connection); channel->state &= ~HGFS_CHANNEL_STATE_CBINIT; channel->connection = NULL; } /* *----------------------------------------------------------------------------- * * HgfsChannelIsChannelActive -- * * Is the channel active (initialized) for processing requests. * * Results: * TRUE if a channel is active. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsChannelIsChannelActive(HgfsChannelData *channel) // IN/OUT: channel object { return (0 != (channel->state & HGFS_CHANNEL_STATE_INIT) && 0 != (channel->state & HGFS_CHANNEL_STATE_CBINIT)); } /* *----------------------------------------------------------------------------- * * HgfsChannelReceive -- * * Received a request on a channel pass on to the channel callback. * * Results: * TRUE if a channel ws deactivated. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsChannelReceive(HgfsChannelData *channel, // IN/OUT: channel object char const *packetIn, // IN: incoming packet size_t packetInSize, // IN: incoming packet size char *packetOut, // OUT: outgoing packet size_t *packetOutSize) // IN/OUT: outgoing packet size { return channel->ops->receive(channel->connection, packetIn, packetInSize, packetOut, packetOutSize); } /* *---------------------------------------------------------------------------- * * HgfsChannelTeardownChannel -- * * Teardown the channel for HGFS. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsChannelTeardownChannel(HgfsChannelData *channel) // IN/OUT: connection manager object { if (HgfsChannelIsChannelActive(channel)) { HgfsChannelDeactivateChannel(channel); } HgfsChannelExitChannel(channel); } /* *---------------------------------------------------------------------------- * * CHANNEL PUBLIC FUNCTIONS * *---------------------------------------------------------------------------- */ /* *---------------------------------------------------------------------------- * * HgfsChannelGuest_Init -- * * Sets up the channel for HGFS. * * Initialize all the defined channels. * At least one channel should succeed it's initialization * completely, else we fail. * * Results: * TRUE on success, FALSE on failure. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool HgfsChannelGuest_Init(HgfsServerMgrData *mgrData, // IN/OUT: server manager data HgfsServerMgrCallbacks *mgrCb) // IN: server manager callbacks { Bool success = FALSE; HgfsChannelData *channel = &gHgfsChannels[0]; // Shared channel (internal RPC) uint32 channelRefCount; ASSERT(NULL != mgrData); ASSERT(NULL == mgrData->connection); /* Currently, the RPC override is not implemented. */ ASSERT(NULL == mgrData->rpc); ASSERT(NULL == mgrData->rpcCallback); ASSERT(NULL != mgrData->appName); Debug("%s: app %s rpc = %p rpc cb = %p.\n", __FUNCTION__, mgrData->appName, mgrData->rpc, mgrData->rpcCallback); if (NULL != mgrData->rpc || NULL != mgrData->rpcCallback) { /* * XXX - Would malloc a new channel here and activate * with the required RPC. */ Debug("%s: Guest channel RPC override not supported.\n", __FUNCTION__); goto exit; } /* * Reference the channel. Initialize only for the first * caller instance, otherwise only reference the channel for * return to the caller. */ channelRefCount = HgfsChannelGetChannel(channel); /* We have referenced the channel, save it for later dereference. */ mgrData->connection = channel; if (0 == channelRefCount) { /* Initialize channels objects. */ if (!HgfsChannelInitChannel(channel, mgrCb, &gHgfsChannelServerInfo)) { Debug("%s: Could not init channel.\n", __FUNCTION__); goto exit; } /* Call the channels initializers. */ if (!HgfsChannelActivateChannel(channel, mgrData->rpc, mgrData->rpcCallback)) { Debug("%s: Could not activate channel.\n", __FUNCTION__); goto exit; } } success = TRUE; exit: if (!success) { HgfsChannelGuest_Exit(mgrData); } return success; } /* *---------------------------------------------------------------------------- * * HgfsChannelGuest_Exit -- * * Dereference the channel which for the final reference will * close the channel for HGFS. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ void HgfsChannelGuest_Exit(HgfsServerMgrData *mgrData) // IN/OUT: connection manager object { HgfsChannelData *channel; ASSERT(NULL != mgrData); ASSERT(NULL != mgrData->appName); channel = mgrData->connection; Debug("%s: app %s rpc = %p rpc cb = %p chn = %p.\n", __FUNCTION__, mgrData->appName, mgrData->rpc, mgrData->rpcCallback, channel); if (NULL != channel) { HgfsChannelPutChannel(channel); mgrData->connection = NULL; } } /* *---------------------------------------------------------------------------- * * HgfsChannelGuest_Receive -- * * Process packet not associated with an HGFS only registered callback. * * * Results: * TRUE if successfully processed FALSE otherwise. * * Side effects: * None * *---------------------------------------------------------------------------- */ Bool HgfsChannelGuest_Receive(HgfsServerMgrData *mgrData, // IN/OUT : conn manager char const *packetIn, // IN: incoming packet size_t packetInSize, // IN: incoming packet size char *packetOut, // OUT: outgoing packet size_t *packetOutSize) // IN/OUT: outgoing packet size { HgfsChannelData *channel = NULL; Bool result = FALSE; ASSERT(NULL != mgrData); ASSERT(NULL != mgrData->connection); ASSERT(NULL != mgrData->appName); channel = mgrData->connection; Debug("%s: %s Channel receive request.\n", __FUNCTION__, mgrData->appName); if (HgfsChannelIsChannelActive(channel)) { result = HgfsChannelReceive(channel, packetIn, packetInSize, packetOut, packetOutSize); } Debug("%s: Channel receive returns %#x.\n", __FUNCTION__, result); return result; } /* *---------------------------------------------------------------------------- * * HgfsChannelGuest_InvalidateInactiveSessions - * * Sends a request to invalidate all the inactive HGFS server sessions. * * Results: * Number of active sessions remaining inside the HGFS server. * * Side effects: * None * *---------------------------------------------------------------------------- */ uint32 HgfsChannelGuest_InvalidateInactiveSessions(HgfsServerMgrData *mgrData) // IN: conn manager { HgfsChannelData *channel = NULL; uint32 result = 0; ASSERT(NULL != mgrData); ASSERT(NULL != mgrData->connection); ASSERT(NULL != mgrData->appName); channel = mgrData->connection; Debug("%s: %s Channel. Invalidating inactive sessions.\n", __FUNCTION__, mgrData->appName); if (HgfsChannelIsChannelActive(channel)) { result = channel->ops->invalidateInactiveSessions(channel->connection); } return result; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerManagerGuest/hgfsChannelGuestBd.c000066400000000000000000000506271321503522500313410ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsChannel.c -- * * Channel abstraction for the HGFS server. * */ #include #include "vm_basic_defs.h" #include "vm_assert.h" #include "vm_atomic.h" #include "util.h" #include "hgfsChannelGuestInt.h" #include "hgfsServer.h" #include "hgfsServerManager.h" typedef enum { HGFS_GST_CONN_UNINITIALIZED, HGFS_GST_CONN_NOTCONNECTED, HGFS_GST_CONN_CONNECTED, } HgfsGuestConnState; /* Since there is only one connection we use globals. */ typedef struct HgfsGuestConn { Atomic_uint32 refCount; /* Reference count. */ HgfsGuestConnState state; const HgfsServerSessionCallbacks *serverCbTable; /* Server session callbacks. */ HgfsServerChannelCallbacks channelCbTable; void *serverSession; size_t packetOutLen; unsigned char *clientPacketOut; /* Client supplied buffer. */ unsigned char packetOut[HGFS_LARGE_PACKET_MAX]; /* For RPC msg callbacks. */ } HgfsGuestConn; /* Callback functions. */ static Bool HgfsChannelGuestBdInit(const HgfsServerSessionCallbacks *serverCBTable, void *rpc, void *rpcCallback, HgfsGuestConn **connection); static void HgfsChannelGuestBdExit(HgfsGuestConn *data); static Bool HgfsChannelGuestBdSend(void *data, HgfsPacket *packet, HgfsSendFlags flags); static Bool HgfsChannelGuestBdReceive(HgfsGuestConn *data, char const *packetIn, size_t packetInSize, char *packetOut, size_t *packetOutSize); static uint32 HgfsChannelGuestBdInvalidateInactiveSessions(HgfsGuestConn *data); const HgfsGuestChannelCBTable gGuestBackdoorOps = { HgfsChannelGuestBdInit, HgfsChannelGuestBdExit, HgfsChannelGuestBdReceive, HgfsChannelGuestBdInvalidateInactiveSessions, }; /* Private functions. */ static Bool HgfsChannelGuestConnConnect(HgfsGuestConn *connData); static void HgfsChannelGuestConnDestroy(HgfsGuestConn *connData); static Bool HgfsChannelGuestReceiveInternal(HgfsGuestConn *connData, char const *packetIn, size_t packetInSize, char *packetOut, size_t *packetOutSize); /* *---------------------------------------------------------------------------- * * CONNECTION DATA FUNCTIONS * *---------------------------------------------------------------------------- */ /* *---------------------------------------------------------------------------- * * HgfsChannelGuestConnGet -- * * Increment connection reference count. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsChannelGuestConnGet(HgfsGuestConn *connData) // IN: connection { ASSERT(connData); Atomic_Inc(&connData->refCount); } /* *---------------------------------------------------------------------------- * * HgfsChannelGuestConnPut -- * * Decrement connection reference count. * * Free connection data if this is the last reference. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static void HgfsChannelGuestConnPut(HgfsGuestConn *connData) // IN: connection { ASSERT(connData); if (Atomic_ReadDec32(&connData->refCount) == 1) { HgfsChannelGuestConnDestroy(connData); } } /* *----------------------------------------------------------------------------- * * HgfsChannelGuestConnInit -- * * Initializes the connection. * * Results: * TRUE always and the channel initialized. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsChannelGuestConnInit(HgfsGuestConn **connData, // IN/OUT: channel object const HgfsServerSessionCallbacks *serverCBTable) // IN: server callbacks { HgfsGuestConn *conn = NULL; conn = Util_SafeCalloc(1, sizeof *conn); /* Give ourselves a reference of one. */ HgfsChannelGuestConnGet(conn); conn->serverCbTable = serverCBTable; conn->state = HGFS_GST_CONN_NOTCONNECTED; *connData = conn; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsChannelGuestConnExit -- * * Teardown the connection. * * Removes the reference and if it is the last will cause the connection * to be destroyed. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsChannelGuestConnExit(HgfsGuestConn *connData) // IN/OUT: channel object { connData->state = HGFS_GST_CONN_UNINITIALIZED; HgfsChannelGuestConnPut(connData); } /* *----------------------------------------------------------------------------- * * HgfsChannelGuestConnDestroy -- * * Destroy the connection. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsChannelGuestConnDestroy(HgfsGuestConn *connData) // IN/OUT: channel object { /* Make sure the server closes it's own session data. */ if (NULL != connData->serverSession) { connData->serverCbTable->close(connData->serverSession); connData->serverSession = NULL; } free(connData); } /* *----------------------------------------------------------------------------- * * HgfsChannelGuestConnCreate -- * * Create's the RPC connection for the HGFS guest if asked. * * Create the pseudo connection for the guest - state transition. * (See the comment in the function where the RPC initialization * is expected to be added. * This entails is registering our callback to receive messages for the * connection object passed. We will have the ability to receive * requests until we unregister our callback.) * * NOTE: There is only handler and connction that can be used for * all HGFS guest requests. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsChannelGuestConnCreate(HgfsGuestConn *connData, // IN: connection void *rpc, // IN: Rpc channel unused void *rpcCallback) // IN: Rpc callback unused { ASSERT(connData->state == HGFS_GST_CONN_NOTCONNECTED); /* * Rpc may be NULL for some cases. For example, if we * just need to provide an HGFS server connection * not associated with an HGFS only RPC connection. */ if (connData->state == HGFS_GST_CONN_NOTCONNECTED) { /* XXX - Here is where we would register an RPC callback if required. */ connData->state = HGFS_GST_CONN_CONNECTED; HgfsChannelGuestConnGet(connData); } } /* *----------------------------------------------------------------------------- * * HgfsChannelGuestConnClose -- * * Closes the connection for the HGFS guest. * * If required unregisters the callback will prevent us from * receiving any more requests closing the connection. * * Results: * TRUE if closed, FALSE if was not connected. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static Bool HgfsChannelGuestConnClose(HgfsGuestConn *connData, // IN: Connection void *rpc, // IN: Rpc channel unused void *rpcCallback) // IN: Rpc callback unused { Bool result = FALSE; if (connData->state == HGFS_GST_CONN_CONNECTED) { /* XXX - Here is where we would unregister an RPC callback. */ /* Clear the connection object since we are unregistered. */ connData->state = HGFS_GST_CONN_NOTCONNECTED; HgfsChannelGuestConnPut(connData); result = TRUE; } return result; } /* *----------------------------------------------------------------------------- * * HgfsChannelGuestConnConnect -- * * Send connection to the server. * * Results: * TRUE if server returns a data object, FALSE if not. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsChannelGuestConnConnect(HgfsGuestConn *connData) // IN: our connection data { Bool result; static HgfsServerChannelData HgfsBdCapData = { 0, HGFS_LARGE_PACKET_MAX }; connData->channelCbTable.registerThread = NULL; connData->channelCbTable.unregisterThread = NULL; connData->channelCbTable.getWriteVa = NULL; connData->channelCbTable.getReadVa = NULL; connData->channelCbTable.putVa = NULL; connData->channelCbTable.send = HgfsChannelGuestBdSend; result = connData->serverCbTable->connect(connData, &connData->channelCbTable, &HgfsBdCapData, &connData->serverSession); if (result) { HgfsChannelGuestConnGet(connData); } return result; } /* *----------------------------------------------------------------------------- * * HgfsChannelGuestConnDisconnect -- * * Send disconnect to the server. * * NOTE: The server data will be maintained until * the connection is totally closed (last reference is gone). * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static void HgfsChannelGuestConnDisconnect(HgfsGuestConn *connData) // IN: connection { if (connData->serverSession != NULL) { /* Tell the server to to disconnect the session. */ connData->serverCbTable->disconnect(connData->serverSession); HgfsChannelGuestConnPut(connData); } } /* *---------------------------------------------------------------------------- * * HgfsChannelGuestConnCloseInternal -- * * Close the client and send a disconnect to the server for the session. * * Results: * None. * * Side effects: * Closes the client connection and empties the queues. * *---------------------------------------------------------------------------- */ static void HgfsChannelGuestConnCloseInternal(HgfsGuestConn *connData, // IN: Connection data void *rpc, // IN: Rpc channel unused void *rpcCallback) // IN: Rpc callback unused { /* Close (unregister the backdoor RPC) connection. */ if (HgfsChannelGuestConnClose(connData, rpc, rpcCallback)) { /* Disconnect the connection from the server. */ HgfsChannelGuestConnDisconnect(connData); } } /* *---------------------------------------------------------------------------- * * HgfsChannelGuestReceiveInternal -- * * Process packet not associated with any session. * * This function is used in the HGFS server inside Tools. * * Create an internal session if not already created, and process the packet. * * Results: * TRUE if received packet ok and processed, FALSE otherwise. * * Side effects: * None * *---------------------------------------------------------------------------- */ static Bool HgfsChannelGuestReceiveInternal(HgfsGuestConn *connData, // IN: connection char const *packetIn, // IN: incoming packet size_t packetInSize, // IN: incoming packet size char *packetOut, // OUT: outgoing packet size_t *packetOutSize) // IN/OUT: outgoing packet size { HgfsPacket packet; ASSERT(packetIn); ASSERT(packetOut); ASSERT(packetOutSize); if (connData->state == HGFS_GST_CONN_UNINITIALIZED) { /* The connection was closed as we are exiting, so bail. */ *packetOutSize = 0; return FALSE; } /* This is just a ping, return nothing. */ if (*packetOutSize == 0) { return TRUE; } /* * Create the session if not already created. * This session is destroyed in HgfsServer_ExitState. */ if (connData->serverSession == NULL) { /* Do our guest connect now which will inform the server. */ if (!HgfsChannelGuestConnConnect(connData)) { *packetOutSize = 0; return FALSE; } } memset(&packet, 0, sizeof packet); /* For backdoor there is only one iov */ packet.iov[0].va = (void *)packetIn; packet.iov[0].len = packetInSize; packet.iovCount = 1; packet.metaPacket = (void *)packetIn; packet.metaPacketDataSize = packetInSize; packet.metaPacketSize = packetInSize; packet.replyPacket = packetOut; packet.replyPacketSize = *packetOutSize; packet.state |= HGFS_STATE_CLIENT_REQUEST; /* The server will perform a synchronous processing of requests. */ connData->serverCbTable->receive(&packet, connData->serverSession); *packetOutSize = connData->packetOutLen; return TRUE; } /* *---------------------------------------------------------------------------- * * REGISTERED CALLBACK FUNCTIONS * * XXX - Where we would have any internally registered callback routines. * This routine would call HgfsChannelGuestReceiveInternal to process the * request. * *---------------------------------------------------------------------------- */ /* *---------------------------------------------------------------------------- * * GUEST CHANNEL CALLBACKS * *---------------------------------------------------------------------------- */ /* *---------------------------------------------------------------------------- * * HgfsChannelGuestBdReceive -- * * Process packet not associated with our registered callback. * * * Results: * TRUE if received packet ok and processed, FALSE otherwise. * * Side effects: * None * *---------------------------------------------------------------------------- */ Bool HgfsChannelGuestBdReceive(HgfsGuestConn *connData, // IN: connection char const *packetIn, // IN: incoming packet size_t packetInSize, // IN: incoming packet size char *packetOut, // OUT: outgoing packet size_t *packetOutSize) // IN/OUT: outgoing packet size { Bool result = TRUE; ASSERT(NULL != packetIn); ASSERT(NULL != packetOut); ASSERT(NULL != packetOutSize); ASSERT(NULL != connData); if (NULL == connData) { result = FALSE; goto exit; } connData->packetOutLen = *packetOutSize; connData->clientPacketOut = packetOut; result = HgfsChannelGuestReceiveInternal(connData, packetIn, packetInSize, connData->clientPacketOut, packetOutSize); connData->clientPacketOut = NULL; connData->packetOutLen = sizeof connData->packetOut; exit: return result; } /* *---------------------------------------------------------------------------- * * HgfsChannelGuestBdInvalidateInactiveSessions -- * * Sends a request to invalidate all the inactive HGFS server sessions. * * Results: * Number of active sessions remaining inside the HGFS server. * * Side effects: * None * *---------------------------------------------------------------------------- */ uint32 HgfsChannelGuestBdInvalidateInactiveSessions(HgfsGuestConn *connData) // IN: connection { ASSERT(NULL != connData); if (NULL == connData) { return 0; } if (connData->state == HGFS_GST_CONN_UNINITIALIZED) { /* The connection was closed as we are exiting, so bail. */ return 0; } /* The server will perform a synchronous processing of requests. */ if (connData->serverSession) { return connData->serverCbTable->invalidateInactiveSessions(connData->serverSession); } return 0; } /* *----------------------------------------------------------------------------- * * HgfsChannelGuestBdSend -- * * Send reply to the request * * Results: * Always TRUE. * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsChannelGuestBdSend(void *conn, // IN: our connection data HgfsPacket *packet, // IN/OUT: Hgfs Packet HgfsSendFlags flags) // IN: Flags to say how to process { HgfsGuestConn *connData = conn; ASSERT(NULL != connData); ASSERT(NULL != packet); ASSERT(NULL != packet->replyPacket); ASSERT(packet->replyPacketDataSize <= connData->packetOutLen); ASSERT(packet->replyPacketSize == connData->packetOutLen); if (packet->replyPacketDataSize > connData->packetOutLen) { packet->replyPacketDataSize = connData->packetOutLen; } connData->packetOutLen = (uint32)packet->replyPacketDataSize; if (!(flags & HGFS_SEND_NO_COMPLETE)) { connData->serverCbTable->sendComplete(packet, connData->serverSession); } return TRUE; } /* *---------------------------------------------------------------------------- * * HgfsChannelGuestBdInit -- * * Called from channel manager. * * Initializes our channel connections. * * Results: * Always TRUE. * * Side effects: * Registers RPC call. * *---------------------------------------------------------------------------- */ static Bool HgfsChannelGuestBdInit(const HgfsServerSessionCallbacks *serverCBTable, // IN: server callbacks void *rpc, // IN: Rpc channel unused void *rpcCallback, // IN: Rpc callback unused HgfsGuestConn **connection) // OUT: connection object { HgfsGuestConn *connData = NULL; Bool result; ASSERT(NULL != connection); /* Create our connection object. */ result = HgfsChannelGuestConnInit(&connData, serverCBTable); if (!result) { Debug("%s: Error: guest connection initialized.\n", __FUNCTION__); goto exit; } /* * Create our connection now with any rpc handle and callback. */ HgfsChannelGuestConnCreate(connData, rpc, rpcCallback); exit: if (!result) { if (NULL != connData) { HgfsChannelGuestBdExit(connData); connData = NULL; } } *connection = connData; Debug("%s: guest initialized.\n", __FUNCTION__); return result; } /* *---------------------------------------------------------------------------- * * HgfsChannelGuestBdExit -- * * Tearsdown our channel connections. * * Results: * None. * * Side effects: * Unregisters RPC call. * *---------------------------------------------------------------------------- */ static void HgfsChannelGuestBdExit(HgfsGuestConn *connData) { ASSERT(NULL != connData); if (NULL != connData) { /* Currently no rpc to unregister. */ HgfsChannelGuestConnCloseInternal(connData, NULL, NULL); HgfsChannelGuestConnExit(connData); } } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerManagerGuest/hgfsChannelGuestInt.h000066400000000000000000000051151321503522500315430ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _HGFSCHANNELGUESTINT_H_ #define _HGFSCHANNELGUESTINT_H_ #if defined(VMTOOLS_USE_GLIB) #define G_LOG_DOMAIN "hgfsd" #define Debug g_debug #define Warning g_warning #else #include "debug.h" #endif #include "hgfsServer.h" #include "hgfsServerManager.h" /** * @file hgfsChannelGuestInt.h * * Prototypes of Hgfs channel packet process handler found in * hgfsChannelGuest.c */ /* * Opaque structure owned by the guest channel to hold the connection * data to the HGFS server. Only held by the channel manager to pass * back to the guest channel for requests and teardown. * (Or it would be used with any registered internal callback.) */ struct HgfsGuestConn; /* * Guest channel table of callbacks. */ typedef struct HgfsGuestChannelCBTable { Bool (*init)(const HgfsServerSessionCallbacks *, void *, void *, struct HgfsGuestConn **); void (*exit)(struct HgfsGuestConn *); Bool (*receive)(struct HgfsGuestConn *, char const *, size_t, char *, size_t *); uint32 (*invalidateInactiveSessions)(struct HgfsGuestConn *); } HgfsGuestChannelCBTable; /* The guest channels callback tables. */ extern const HgfsGuestChannelCBTable gGuestBackdoorOps; /* For use by HgfsServerManager. */ Bool HgfsChannelGuest_Init(HgfsServerMgrData *data, HgfsServerMgrCallbacks *cb); void HgfsChannelGuest_Exit(HgfsServerMgrData *data); Bool HgfsChannelGuest_Receive(HgfsServerMgrData *data, char const *packetIn, size_t packetInSize, char *packetOut, size_t *packetOutSize); uint32 HgfsChannelGuest_InvalidateInactiveSessions(HgfsServerMgrData *data); #endif /* _HGFSCHANNELGUESTINT_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerManagerGuest/hgfsServerManagerGuest.c000066400000000000000000000121171321503522500322540ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006,2014-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerManagerGuest.c -- * * Functionality to utilize the hgfs server in bora/lib from within * a guest application. * */ #include #include "hgfsServerPolicy.h" #include "hgfsChannelGuestInt.h" #include "hgfsServerManager.h" #include "vm_basic_defs.h" #include "vm_assert.h" #include "hgfs.h" /* * Local for now and will be used in conjuncutntion with the manager data passed * on registration. */ static HgfsServerMgrCallbacks gHgfsServerManagerGuestData = { { NULL, // Filled by the policy manager } }; /* *---------------------------------------------------------------------------- * * HgfsServerManager_ProcessPacket -- * * Handles hgfs requests from a client not by our * registered RPC callback. * * Results: * TRUE on success, FALSE on error. * * Side effects: * None. * *---------------------------------------------------------------------------- */ Bool HgfsServerManager_ProcessPacket(HgfsServerMgrData *mgrData, // IN: hgfs mgr char const *packetIn, // IN: rqst size_t packetInSize, // IN: rqst size char *packetOut, // OUT: rep size_t *packetOutSize) // IN/OUT: rep buf/data size { Debug("%s: Processing Packet for %s.\n", __FUNCTION__, mgrData->appName); /* Pass to the channel to handle processing and the server. */ return HgfsChannelGuest_Receive(mgrData, packetIn, packetInSize, packetOut, packetOutSize); } /* *---------------------------------------------------------------------------- * * HgfsServerManager_Register -- * * Registers the hgfs server to be used in classic synchronous fashion. * * Results: * TRUE on success, FALSE on failure. * * Side effects: * Hgfs packets sent to this channel will be handled. * *---------------------------------------------------------------------------- */ Bool HgfsServerManager_Register(HgfsServerMgrData *data) // IN: RpcIn channel { ASSERT(data); ASSERT(data->appName); Debug("%s: Register %s.\n", __FUNCTION__, data->appName); /* * Passing NULL here is safe because the shares maintained by the guest * policy server never change, invalidating the need for an invalidate * function. * XXX - retrieve the enum of shares routines and will need to pass this * down through the channel guest into the HGFS server directly. */ if (!HgfsServerPolicy_Init(NULL, &gHgfsServerManagerGuestData.enumResources)) { return FALSE; } if (!HgfsChannelGuest_Init(data, &gHgfsServerManagerGuestData)) { HgfsServerPolicy_Cleanup(); return FALSE; } return TRUE; } /* *---------------------------------------------------------------------------- * * HgfsServerManager_InvalidateInactiveSessions -- * * Sends a request to invalidate all the inactive HGFS server sessions. * * Results: * Number of active sessions remaining inside the HGFS server. * * Side effects: * None. * *---------------------------------------------------------------------------- */ uint32 HgfsServerManager_InvalidateInactiveSessions(HgfsServerMgrData *mgrData) // IN: RpcIn channel { ASSERT(mgrData); Debug("%s: Invalidate Inactive Sessions for %s.\n", __FUNCTION__, mgrData->appName); return HgfsChannelGuest_InvalidateInactiveSessions(mgrData); } /* *---------------------------------------------------------------------------- * * HgfsServerManager_Unregister -- * * Cleans up the hgfs server. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ void HgfsServerManager_Unregister(HgfsServerMgrData *data) // IN: RpcIn channel { ASSERT(data); ASSERT(data->appName != NULL); Debug("%s: Unregister %s.\n", __FUNCTION__, data->appName); HgfsChannelGuest_Exit(data); HgfsServerPolicy_Cleanup(); memset(&gHgfsServerManagerGuestData, 0, sizeof gHgfsServerManagerGuestData); } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerPolicyGuest/000077500000000000000000000000001321503522500253525ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerPolicyGuest/Makefile.am000066400000000000000000000020251321503522500274050ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libHgfsServerPolicyGuest.la libHgfsServerPolicyGuest_la_SOURCES = libHgfsServerPolicyGuest_la_SOURCES += hgfsServerPolicyGuest.c open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsServerPolicyGuest/hgfsServerPolicyGuest.c000066400000000000000000000446271321503522500320410ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsServerPolicyGuest.c -- * * Implementation of access policy for hgfs server running in a * VM. All access is allowed. */ #ifdef sun # include # include #elif defined(__FreeBSD__) # include #endif #undef LOG #define LGLEVEL (10) #define LGPFX_FMT "%s:%s:" #define LGPFX "hgfsd" #if defined VMTOOLS_USE_GLIB #define G_LOG_DOMAIN LGPFX #define Debug g_debug #define Warning g_warning #else #include "debug.h" #endif #define DOLOG(_min) ((_min) <= LGLEVEL) #define LOG(_level, args) \ do { \ if (DOLOG(_level)) { \ Debug(LGPFX_FMT, LGPFX, __FUNCTION__); \ Debug args; \ } \ } while (0) #include "vmware.h" #include "hgfsServerPolicy.h" typedef struct HgfsServerPolicyState { /* * An empty list means that the policy server enforces the "deny all access * requests" policy --hpreg */ DblLnkLst_Links shares; } HgfsServerPolicyState; static HgfsServerPolicyState myState; static void * HgfsServerPolicyEnumSharesInit(void); static Bool HgfsServerPolicyEnumSharesGet(void *data, char const **name, size_t *len, Bool *done); static Bool HgfsServerPolicyEnumSharesExit(void *data); /* *----------------------------------------------------------------------------- * * HgfsServerPolicyDestroyShare -- * * Destroy the internal representation of a share --hpreg * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerPolicyDestroyShare(HgfsSharedFolder *share) // IN { ASSERT(share); free(share); } /* *----------------------------------------------------------------------------- * * HgfsServerPolicyDestroyShares -- * * Destroy the internal representation of all shares. The function is * idempotent --hpreg * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static void HgfsServerPolicyDestroyShares(DblLnkLst_Links *head) // IN { ASSERT(head); while (head->next != head) { HgfsSharedFolder *share; share = DblLnkLst_Container(head->next, HgfsSharedFolder, links); ASSERT(share); DblLnkLst_Unlink1(&share->links); HgfsServerPolicyDestroyShare(share); } } /* *----------------------------------------------------------------------------- * * HgfsServerPolicy_Init -- * * Initialize the HGFS security server state. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsServerPolicy_Init(HgfsInvalidateObjectsFunc invalidateObjects, // Unused HgfsServerResEnumCallbacks *enumResources) // OUT enum callbacks { HgfsSharedFolder *rootShare; /* * Currently these callbacks are not used, so make sure our caller doesn't pass * it in. */ ASSERT(invalidateObjects == NULL); DblLnkLst_Init(&myState.shares); /* For the guest, we hard code a "root" share */ rootShare = (HgfsSharedFolder *)malloc(sizeof *rootShare); if (!rootShare) { LOG(4, ("HgfsServerPolicy_Init: memory allocation failed\n")); return FALSE; } DblLnkLst_Init(&rootShare->links); /* * A path = "" has special meaning; it indicates that access is * granted to the root of the server filesystem, and in Win32 * causes everything after the share name in the request to be * interpreted as either a drive letter or UNC name. [bac] */ rootShare->path = ""; rootShare->name = HGFS_SERVER_POLICY_ROOT_SHARE_NAME; rootShare->readAccess = TRUE; rootShare->writeAccess = TRUE; /* These are strictly optimizations to save work later */ rootShare->pathLen = strlen(rootShare->path); rootShare->nameLen = strlen(rootShare->name); rootShare->handle = HGFS_INVALID_FOLDER_HANDLE; /* Add the root node to the end of the list */ DblLnkLst_LinkLast(&myState.shares, &rootShare->links); /* * Fill the share enumeration callback table. */ enumResources->init = HgfsServerPolicyEnumSharesInit; enumResources->get = HgfsServerPolicyEnumSharesGet; enumResources->exit = HgfsServerPolicyEnumSharesExit; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicy_Cleanup -- * * Cleanup the HGFS security server state. * * Results: * TRUE on success * FALSE on failure * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsServerPolicy_Cleanup(void) { HgfsServerPolicyDestroyShares(&myState.shares); return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicyGetShare -- * * Get the share whose name matches the given name (if any). * * Results: * The share, if a match is found. * NULL otherwise * * Side effects: * None * *----------------------------------------------------------------------------- */ static HgfsSharedFolder * HgfsServerPolicyGetShare(HgfsServerPolicyState *state, // IN char const *nameIn, // IN: Name to check size_t nameInLen) // IN: Length of nameIn { DblLnkLst_Links *l; ASSERT(state); ASSERT(nameIn); /* * First try to find a share that matches the given name exactly. * This is to handle the case where 2 share names differ in case only. */ for (l = state->shares.next; l != &state->shares; l = l->next) { HgfsSharedFolder *share; share = DblLnkLst_Container(l, HgfsSharedFolder, links); ASSERT(share); if (nameInLen == share->nameLen && !memcmp(nameIn, share->name, nameInLen)) { return share; } } /* * There was no match. As a fall back try a case insensitive match. * This is because some Windows applications uppercase or lowercase the * entire path before sending the request. */ for (l = state->shares.next; l != &state->shares; l = l->next) { HgfsSharedFolder *share; char *tempName; /* * Null terminate the input name before a case insensitive comparison. * This is just to protect against bad implementations of strnicmp. */ if (!(tempName = (char *)malloc(nameInLen + 1))) { LOG(4, ("HgfsServerPolicyGetShare: couldn't allocate tempName\n")); return NULL; } memcpy(tempName, nameIn, nameInLen); tempName[nameInLen] = 0; share = DblLnkLst_Container(l, HgfsSharedFolder, links); ASSERT(share); if (nameInLen == share->nameLen && #ifdef _WIN32 !strnicmp(tempName, share->name, nameInLen)) { #else !strncasecmp(tempName, share->name, nameInLen)) { #endif free(tempName); return share; } free(tempName); } return NULL; } /* State used by HgfsServerPolicyEnumSharesGet and friends */ typedef struct State { DblLnkLst_Links *next; } GetSharesState; /* *----------------------------------------------------------------------------- * * HgfsServerPolicyEnumSharesInit -- * * Setup state for HgfsServerPolicyEnumSharesGet * * Results: * Pointer to state on success. * NULL on failure. * * Side effects: * None * *----------------------------------------------------------------------------- */ static void * HgfsServerPolicyEnumSharesInit(void) { GetSharesState *that; that = malloc(sizeof *that); if (!that) { LOG(4, ("HgfsServerPolicyEnumSharesInit: couldn't allocate state\n")); return NULL; } that->next = myState.shares.next; return that; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicyEnumSharesGet -- * * Enumerate share names one at a time. * * When finished, sets "done" to TRUE. * * Should be called with the results obtained by calling * HgfsServerPolicyEnumSharesInit. * * Results: * TRUE on success. * FALSE on failure (never happens). * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsServerPolicyEnumSharesGet(void *data, // IN: Callback data char const **name, // OUT: Share name size_t *len, // OUT: Name length Bool *done) // OUT: Completion status { GetSharesState *that; HgfsSharedFolder *share; that = (GetSharesState *)data; ASSERT(that); ASSERT(name); ASSERT(len); ASSERT(done); if (that->next == &myState.shares) { /* No more shares */ *done = TRUE; return TRUE; } share = DblLnkLst_Container(that->next, HgfsSharedFolder, links); ASSERT(share); that->next = share->links.next; *name = share->name; *len = share->nameLen; LOG(4, ("HgfsServerPolicyEnumSharesGet: Share name is \"%s\"\n", *name)); *done = FALSE; return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicyEnumSharesExit -- * * Cleanup state from HgfsServerPolicyEnumSharesGet * * Results: * TRUE on success. * FALSE on failure (never happens). * * Side effects: * None * *----------------------------------------------------------------------------- */ static Bool HgfsServerPolicyEnumSharesExit(void *data) // IN: Callback data { GetSharesState *that; that = (GetSharesState *)data; ASSERT(that); free(that); return TRUE; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicy_GetSharePath -- * * Get the local path for a share name by looking at the requested * name, finding the matching share (if any), checking access * permissions, and returning the share's local path. * * Results: * An HgfsNameStatus value indicating the result is returned. * * The local path for the shareName is also returned if a match is found and * access is permitted. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsNameStatus HgfsServerPolicy_GetSharePath(char const *nameIn, // IN: Name to check size_t nameInLen, // IN: Length of nameIn HgfsOpenMode mode, // IN: Requested access mode size_t *sharePathLen, // OUT: Length of share path char const **sharePath) // OUT: Share path { HgfsSharedFolder *myShare; ASSERT(nameIn); ASSERT(sharePathLen); ASSERT(sharePath); myShare = HgfsServerPolicyGetShare(&myState, nameIn, nameInLen); if (!myShare) { LOG(4, ("HgfsServerPolicy_GetSharePath: No matching share name\n")); return HGFS_NAME_STATUS_DOES_NOT_EXIST; } /* * See if access is allowed in the requested mode. * * XXX Yeah, this is retarded. We should be using bits instead of * an enum for HgfsOpenMode. Add it to the todo list. [bac] */ switch (HGFS_OPEN_MODE_ACCMODE(mode)) { case HGFS_OPEN_MODE_READ_ONLY: if (!myShare->readAccess) { LOG(4, ("HgfsServerPolicy_GetSharePath: Read access denied\n")); return HGFS_NAME_STATUS_ACCESS_DENIED; } break; case HGFS_OPEN_MODE_WRITE_ONLY: if (!myShare->writeAccess) { LOG(4, ("HgfsServerPolicy_GetSharePath: Write access denied\n")); return HGFS_NAME_STATUS_ACCESS_DENIED; } break; case HGFS_OPEN_MODE_READ_WRITE: if (!myShare->readAccess || !myShare->writeAccess) { LOG(4, ("HgfsServerPolicy_GetSharePath: Read/write access denied\n")); return HGFS_NAME_STATUS_ACCESS_DENIED; } break; default: LOG(0, ("HgfsServerPolicy_GetSharePath: Invalid mode\n")); return HGFS_NAME_STATUS_FAILURE; break; } *sharePathLen = myShare->pathLen; *sharePath = myShare->path; return HGFS_NAME_STATUS_COMPLETE; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicy_ProcessCPName -- * * Get the local path for a share name by looking at the requested * name, finding the matching share (if any) and returning the share's * local path local path and permissions. * * Results: * An HgfsNameStatus value indicating the result is returned. * * The local path for the shareName is also returned if a match is found. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsNameStatus HgfsServerPolicy_ProcessCPName(char const *nameIn, // IN: name in CPName form size_t nameInLen, // IN: length of the name Bool *readAccess, // OUT: Read permissions Bool *writeAccess, // OUT: Write permissions HgfsSharedFolderHandle *handle,// OUT: folder handle char const **shareBaseDir) // OUT: Shared directory { HgfsSharedFolder *myShare; ASSERT(nameIn); ASSERT(shareBaseDir); myShare = HgfsServerPolicyGetShare(&myState, nameIn, nameInLen); if (!myShare) { LOG(4, ("%s: No matching share name\n", __FUNCTION__)); return HGFS_NAME_STATUS_DOES_NOT_EXIST; } *readAccess = myShare->readAccess; *writeAccess = myShare->writeAccess; *shareBaseDir = myShare->path; *handle = myShare->handle; return HGFS_NAME_STATUS_COMPLETE; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicy_GetShareOptions -- * * Get the HGFS share config options by looking at the requested name, * finding the matching share (if any). * * Results: * HGFS_NAME_STATUS_COMPLETE on success, and HGFS_NAME_STATUS_DOES_NOT_EXIST * if no matching share. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsNameStatus HgfsServerPolicy_GetShareOptions(char const *nameIn, // IN: Share name size_t nameInLen, // IN: Share name length HgfsShareOptions *configOptions)// OUT: Config options { HgfsSharedFolder *share; char const *inEnd; char *next; int len; ASSERT(nameIn); ASSERT(configOptions); inEnd = nameIn + nameInLen; len = CPName_GetComponent(nameIn, inEnd, (char const **) &next); if (len < 0) { LOG(4, ("HgfsServerPolicy_GetShareOptions: get first component failed\n")); return HGFS_NAME_STATUS_FAILURE; } share = HgfsServerPolicyGetShare(&myState, nameIn, len); if (!share) { LOG(4, ("HgfsServerPolicy_GetShareOptions: No matching share name.\n")); return HGFS_NAME_STATUS_DOES_NOT_EXIST; } *configOptions = share->configOptions; return HGFS_NAME_STATUS_COMPLETE; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicy_IsShareOptionSet -- * * Check if the specified config option is set. * * Results: * TRUE if set. * FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ Bool HgfsServerPolicy_IsShareOptionSet(HgfsShareOptions configOptions, // IN: config options uint32 option) // IN: option to check { return (configOptions & option) == option; } /* *----------------------------------------------------------------------------- * * HgfsServerPolicy_GetShareMode -- * * Get the access mode for a share by looking at the requested * name, finding the matching share (if any), and returning * the share's access mode. * * Results: * An HgfsNameStatus value indicating the result is returned. * * The access mode for the shareName is also returned if a match is found. * * Side effects: * None * *----------------------------------------------------------------------------- */ HgfsNameStatus HgfsServerPolicy_GetShareMode(char const *nameIn, // IN: Share name to retrieve size_t nameInLen, // IN: Length of Share name HgfsOpenMode *mode) // OUT: Share's access mode { HgfsSharedFolder *share; ASSERT(nameIn); ASSERT(mode); share = HgfsServerPolicyGetShare(&myState, nameIn, nameInLen); if (!share) { LOG(4, ("HgfsServerPolicy_GetShareMode: No matching share name\n")); return HGFS_NAME_STATUS_DOES_NOT_EXIST; } /* * Get the access mode. */ if (share->readAccess && share->writeAccess) { *mode = HGFS_OPEN_MODE_READ_WRITE; } else if (share->readAccess) { *mode = HGFS_OPEN_MODE_READ_ONLY; } else if (share->writeAccess) { *mode = HGFS_OPEN_MODE_WRITE_ONLY; } else { /* Share should be at least read or write access. */ ASSERT(FALSE); LOG(4, ("HgfsServerPolicy_GetShareMode: Invalid access mode\n")); return HGFS_NAME_STATUS_FAILURE; } return HGFS_NAME_STATUS_COMPLETE; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsUri/000077500000000000000000000000001321503522500224535ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsUri/Makefile.am000066400000000000000000000020561321503522500245120ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2015-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libHgfsUri.la libHgfsUri_la_SOURCES = libHgfsUri_la_SOURCES += hgfsUriPosix.c AM_CFLAGS = AM_CFLAGS += -DVMTOOLS_USE_GLIB AM_CFLAGS += @GLIB2_CPPFLAGS@ open-vm-tools-stable-10.2.0/open-vm-tools/lib/hgfsUri/hgfsUriPosix.c000066400000000000000000000071651321503522500252620ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsPosix.c -- * * Provides a library for guest applications to convert local pathames to * x-vmware-share:// style URIs */ #if !defined __linux__ && !defined __APPLE__ && !defined __FreeBSD__ # error This file should not be compiled #endif #include "vmware.h" #include "debug.h" #include "str.h" #include #include "hgfsUri.h" #include "hgfsHelper.h" #include "util.h" #include "unicode.h" #include "hgfsEscape.h" #include "ghIntegrationCommon.h" // For GHI_HGFS_SHARE_URL_UTF8 /* *----------------------------------------------------------------------------- * * HgfsUri_ConvertFromPathToHgfsUri -- * * Test the UTF8 pathname to see if it's on an HGFS Share. If it is * construct a UTF8 URI in the form of x-vmware-share://share_name/item.txt. * If not, convert to a regular UTF8 URI string. * * Results: * Filename as UTF8 URI string if success, NULL if failed. * * Side effects: * Memory may be allocated for the returned string. * *----------------------------------------------------------------------------- */ char * HgfsUri_ConvertFromPathToHgfsUri(const char *pathName, // IN: path to convert Bool hgfsOnly) // IN { char *shareUri = NULL; Bool isHgfsName = FALSE; char *sharesDefaultRootPath = NULL; /* We can only operate on full paths. */ if (pathName[0] != DIRSEPC) { return shareUri; } /* Retrieve the servername & share name in use. */ if (!HgfsHlpr_QuerySharesDefaultRootPath(&sharesDefaultRootPath)) { Debug("%s: Unable to query shares default root path\n", __FUNCTION__); goto exit; } if (Unicode_StartsWith(pathName, sharesDefaultRootPath)) { char *relativeSharePath = NULL; char *escapedSharePath = NULL; UnicodeIndex relativePathStart = strlen(sharesDefaultRootPath); if ( strlen(pathName) > relativePathStart && pathName[relativePathStart] == DIRSEPC) { relativePathStart++; } relativeSharePath = Unicode_RemoveRange(pathName, 0, relativePathStart); HgfsEscape_Undo(relativeSharePath, strlen(relativeSharePath) + 1); escapedSharePath = g_uri_escape_string(relativeSharePath, "/", FALSE); shareUri = Unicode_Append(GHI_HGFS_SHARE_URL_UTF8, escapedSharePath); g_free(escapedSharePath); free(relativeSharePath); isHgfsName = TRUE; } exit: if (!isHgfsName && !hgfsOnly) { /* Only convert non-hgfs file name if hgfsOnly is not set. */ char *escapedPath = g_uri_escape_string(pathName, "/", FALSE); shareUri = Str_Asprintf(NULL, "file://%s", escapedPath); g_free(escapedPath); } HgfsHlpr_FreeSharesRootPath(sharesDefaultRootPath); return shareUri; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/impersonate/000077500000000000000000000000001321503522500233725ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/impersonate/Makefile.am000066400000000000000000000021051321503522500254240ustar00rootroot00000000000000################################################################################ ### Copyright (C) 2007-2016 VMware, Inc. All rights reserved. ### ### This program is free software; you can redistribute it and/or modify ### it under the terms of version 2 of the GNU General Public License as ### published by the Free Software Foundation. ### ### 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, write to the Free Software ### Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ################################################################################ noinst_LTLIBRARIES = libImpersonate.la libImpersonate_la_SOURCES = libImpersonate_la_SOURCES += impersonate.c libImpersonate_la_SOURCES += impersonatePosix.c AM_CFLAGS = @LIB_IMPERSONATE_CPPFLAGS@ open-vm-tools-stable-10.2.0/open-vm-tools/lib/impersonate/impersonate.c000066400000000000000000000235041321503522500260700ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * impersonate.c -- * * Description: * Code to impersonate as a user when running under a privileged account. * Nested impersonation is not supported. */ #include #include "vmware.h" #include "auth.h" #include "userlock.h" #include "mutexRankLib.h" #include "impersonateInt.h" static Atomic_Ptr impersonateLockStorage; Bool impersonationEnabled = FALSE; /* *---------------------------------------------------------------------- * * ImpersonateGetLock -- * * Get/create the impersonate lock. * * Results: * See above. * * Side effects: * See above. * *---------------------------------------------------------------------- */ static INLINE MXUserRecLock * ImpersonateGetLock(void) { MXUserRecLock *lock = MXUser_CreateSingletonRecLock(&impersonateLockStorage, "impersonateLock", RANK_impersonateLock); return lock; } /* *---------------------------------------------------------------------- * * ImpersonateLock -- * * Acquire or release the impersonate lock. Protects access to * the library's static and TLS states. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE void ImpersonateLock(Bool lock) // IN { MXUserRecLock *impersonateLock = ImpersonateGetLock(); if (lock) { MXUser_AcquireRecLock(impersonateLock); } else { MXUser_ReleaseRecLock(impersonateLock); } } /* *---------------------------------------------------------------------- * * Impersonate_Init -- * * Initialize the impersonation module. On windows also load * userenv.dll. * Without calling this, code calling into this module will * essentially be noops. * * Call when single-threaded. * * Side effects: * * Loads the library. We keep the library loaded thereafter. * *---------------------------------------------------------------------- */ void Impersonate_Init(void) { if (!impersonationEnabled) { ImpersonateInit(); impersonationEnabled = TRUE; } } /* *---------------------------------------------------------------------------- * * Impersonate_Runas -- * * Impersonate as the appropriate runas user. In linux this is always * the config file owner regardless the calling context. In windows, the * runas user is the caller passed into the method, except when the VM has * a preconfigured runas user, in which case we will impersonate using his * credentials instead. * * In windows, if caller is not set, fail if preconfigured runas user is * not found. * * Results: * TRUE if impersonation succeeds, FALSE otherwise. * * Side effects: * imp.impersonatedUser may be updated. * *---------------------------------------------------------------------------- */ Bool Impersonate_Runas(const char *cfg, // IN const char *caller, // IN AuthToken callerToken) // IN { Bool res; if (!impersonationEnabled) { return TRUE; } ImpersonateLock(TRUE); res = ImpersonateRunas(cfg, caller, callerToken); ImpersonateLock(FALSE); return res; } /* *---------------------------------------------------------------------------- * * Impersonate_Owner -- * * Impersonate as the owner of the specified file. * * Results: * TRUE if impersonation succeeds, FALSE otherwise. * * Side effects: * imp.impersonatedUser may be updated. * *---------------------------------------------------------------------------- */ Bool Impersonate_Owner(const char *file) // IN { Bool res; if (!impersonationEnabled) { return TRUE; } ImpersonateLock(TRUE); res = ImpersonateOwner(file); ImpersonateLock(FALSE); return res; } /* *---------------------------------------------------------------------------- * * Impersonate_Do -- * * Impersonate as user. Can be nested if impersonated as that same user * each time. Can switch back to root temporarily regardless of nesting * level via Impersonate_ForceRoot. Calling Impersonate_UnforceRoot will * return to original impersonation at the same nesting level. * * Results: * TRUE if impersonation succeeds, FALSE otherwise. * * Side effects: * imp.impersonatedUser may be updated. * imp.impersonatedToken(Win32 only) may be updated. * *---------------------------------------------------------------------------- */ Bool Impersonate_Do(const char *user, // IN AuthToken token) // IN { Bool res; if (!impersonationEnabled) { return TRUE; } ImpersonateLock(TRUE); res = ImpersonateDo(user, token); ImpersonateLock(FALSE); return res; } /* *---------------------------------------------------------------------------- * * Impersonate_Undo -- * * Undoes a previous impersonation. When we undo the last in the nesting * of impersonation ops, switch back to root. * * Results: * TRUE on success, FALSE otherwise * * Side effects: * On reverting back to root, * imp.impersonatedUser is freed. * imp.impersonatedToken (win32) is invalid. * *---------------------------------------------------------------------------- */ Bool Impersonate_Undo(void) { Bool res; ImpersonationState *imp = NULL; if (!impersonationEnabled) { return TRUE; } ImpersonateLock(TRUE); imp = ImpersonateGetTLS(); ASSERT(imp); WIN32_ONLY(ASSERT(!imp->forceRoot)); imp->refCount--; POSIX_ONLY(IMPWARN(("Impersonate_Undo (%x %x) drop refcount to %d\n", getpid(), imp, imp->refCount))); WIN32_ONLY(IMPWARN(("Impersonate_Undo (%x) drop refcount to %d\n", (int) imp, imp->refCount))); if (imp->refCount > 0) { ImpersonateLock(FALSE); return TRUE; } res = ImpersonateUndo(); ImpersonateLock(FALSE); return res; } /* *---------------------------------------------------------------------------- * * Impersonate_Who -- * * Returns currently impersonated user name. If not impersonated, * returns NULL. * * Results: * Currently impersonated user name. NULL if not impersonated. * * Side effects: * None. * *---------------------------------------------------------------------------- */ char * Impersonate_Who(void) { char *impUser; ImpersonationState *imp = NULL; if (!impersonationEnabled) { return strdup(""); } ImpersonateLock(TRUE); imp = ImpersonateGetTLS(); ASSERT(imp); impUser = strdup(imp->impersonatedUser); VERIFY(impUser); ImpersonateLock(FALSE); return impUser; } /* *---------------------------------------------------------------------------- * * Impersonate_ForceRoot -- * * Go back to base impersonate level (LocalSystem/root) for a brief period * of time. Doesnt do anything on linux. * Should only be used when already impersonated. This call is not nestable. * No other impersonation is permitted before calling Impersonate_UnforceRoot. * * Results: * TRUE on success, FALSE on failure. * * Side effects: * imp.forceRoot is set to TRUE on success. * *---------------------------------------------------------------------------- */ Bool Impersonate_ForceRoot(void) { Bool res; if (!impersonationEnabled) { return TRUE; } ImpersonateLock(TRUE); res = ImpersonateForceRoot(); ImpersonateLock(FALSE); return res; } /* *---------------------------------------------------------------------------- * * Impersonate_UnforceRoot -- * * Go back to impersonate the user that we switched to root from. * See Impersonate_ForceRoot. * * Results: * TRUE on success, FALSE on failure. * * Side effects: * imp.forceRoot is set to FALSE on success. * *---------------------------------------------------------------------------- */ Bool Impersonate_UnforceRoot(void) { Bool res; if (!impersonationEnabled) { return TRUE; } ImpersonateLock(TRUE); res = ImpersonateUnforceRoot(); ImpersonateLock(FALSE); return res; } #ifdef _WIN32 /* *---------------------------------------------------------------------------- * * Impersonate_CfgRunasOnly -- * * Impersonate as the preconfigured runas user for the VM. * Fails if runas user credentials are not found. * * Results: * TRUE if preconfigured runas user is found impersonation succeeds, * FALSE otherwise. * * Side effects: * imp.impersonatedUser may be updated. * *---------------------------------------------------------------------------- */ Bool Impersonate_CfgRunasOnly(const char *cfg) // IN { Bool res; ImpersonateLock(TRUE); res = Impersonate_Runas(cfg, NULL, NULL); ImpersonateLock(FALSE); return res; } #endif //_WIN32 open-vm-tools-stable-10.2.0/open-vm-tools/lib/impersonate/impersonateInt.h000066400000000000000000000037641321503522500265560ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * impersonateInt.h -- * * Header file shared by impersonate code */ #ifndef _IMPERSONATE_INT_H_ #define _IMPERSONATE_INT_H_ #include "vmware.h" #include "msg.h" #include "impersonate.h" #include "auth.h" //#define IMP_VERBOSE 1 #define INVALID_PTHREAD_KEY_VALUE (-1) #ifdef IMP_VERBOSE #define IMPWARN(x) Warning x #else #define IMPWARN(x) #endif typedef struct ImpersonationState { const char *impersonatedUser; // the user we are currently impersonating int refCount; // # of times we are impersonating as same user #ifdef _WIN32 HANDLE impersonatedToken; // the access token currently impersonated with Bool forceRoot; // are we temporarily switching back to root? #endif } ImpersonationState; void ImpersonateInit(void); ImpersonationState *ImpersonateGetTLS(void); Bool ImpersonateRunas(const char *cfg, const char *caller, AuthToken callerToken); Bool ImpersonateOwner(const char *file); Bool ImpersonateDo(const char *user, AuthToken token); Bool ImpersonateUndo(void); Bool ImpersonateForceRoot(void); Bool ImpersonateUnforceRoot(void); #endif // ImpersonateInt.h open-vm-tools-stable-10.2.0/open-vm-tools/lib/impersonate/impersonatePosix.c000066400000000000000000000271741321503522500271220ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * impersonatePosix.c -- * * Description: * Posix specific functions to impersonate as specific users. */ #include #include #include #include #include #include #include #include #if !defined(VMX86_TOOLS) #include #endif #include #include "impersonateInt.h" #include "su.h" #include "posix.h" #if !defined(VMX86_TOOLS) static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; static pthread_key_t threadLocalStorageKey = INVALID_PTHREAD_KEY_VALUE; static void ThreadLocalFree(void *ptr); #else static ImpersonationState *impLinux = NULL; #endif static Bool ImpersonateDoPosix(struct passwd *pwd); /* *---------------------------------------------------------------------------- * * ImpersonateInit -- * * Linux specific initialization (thread local storage for linux) * * Results: * None. * * Side effects: * Memory created. * *---------------------------------------------------------------------------- */ void ImpersonateInit(void) { #if !defined(VMX86_TOOLS) int status; status = pthread_key_create(&threadLocalStorageKey, ThreadLocalFree); if (status != 0) { Warning("Impersonate: key_create failed: %d\n", status); VERIFY(status == 0); return; } VERIFY(threadLocalStorageKey != INVALID_PTHREAD_KEY_VALUE); #endif } /* *---------------------------------------------------------------------- * * ThreadLocalFree -- * * A wrapper for "free()". This function is called when a thread * terminates so that the thread-local state can be deallocated. * *---------------------------------------------------------------------- */ #if !defined(VMX86_TOOLS) static void ThreadLocalFree(void *ptr) { ImpersonationState *imp = (ImpersonationState*) ptr; IMPWARN(("Impersonate: ThreadLocalFree(0x%08x)\n", imp)); ASSERT(imp); ASSERT(imp->impersonatedUser == NULL); ASSERT(imp->refCount == 0); free(imp); } #endif /* *---------------------------------------------------------------------------- * * ImpersonateGetTLS -- * * This function abstracts away the differences between Linux and * Windows for obtaining a pointer to thread-local state. * * Results: * Returns pointer to thread-local state. * * Side effects: * On Linux this function will allocate state on the first occasion * that a particular thread calls this function for the first time. * *---------------------------------------------------------------------------- */ ImpersonationState * ImpersonateGetTLS(void) { ImpersonationState *ptr = NULL; int status; /* If a prior call has already allocated state, then use it */ #if !defined(VMX86_TOOLS) /* If a prior call has already allocated state, then use it */ ptr = pthread_getspecific(threadLocalStorageKey); #else ptr = impLinux; #endif if (ptr != NULL) { return ptr; } /* No state allocated, so we need to allocate it */ ptr = calloc(1, sizeof *ptr); VERIFY(ptr); #if !defined(VMX86_TOOLS) status = pthread_setspecific(threadLocalStorageKey, ptr); #else impLinux = ptr; status = 0; #endif if (status != 0) { Warning("Impersonate: setspecific: %d\n", status); VERIFY(status == 0); } return ptr; } /* *---------------------------------------------------------------------------- * * ImpersonateRunas -- * * Impersonate as the appropriate runas user. In linux this is always * the config file owner regardless the calling context. * * Results: * TRUE if impersonation succeeds, FALSE otherwise. * * Side effects: * imp.impersonatedUser may be updated. * *---------------------------------------------------------------------------- */ Bool ImpersonateRunas(const char *cfg, // IN const char *caller, // IN AuthToken callerToken) // IN { /* * In linux, this call always impersonates as the owner of the config file. */ ASSERT(!caller && !callerToken); return ImpersonateOwner(cfg); } /* *---------------------------------------------------------------------------- * * ImpersonateOwner -- * * Impersonate the owner of the config file. Only makes sense on linux. * * Results: * TRUE if impersonation succeeds, false otherwise. * * Side effects: * imp.impersonatedUser may be updated. * *---------------------------------------------------------------------------- */ Bool ImpersonateOwner(const char *file) // IN { struct stat buf; char buffer[BUFSIZ]; struct passwd pw; struct passwd *ppw = &pw; int error; if (Posix_Stat(file, &buf) == -1) { Warning("Failed to lookup owner for: %s. Reason: %s\n", file, Err_Errno2String(errno)); return FALSE; } if ((error = Posix_Getpwuid_r(buf.st_uid, &pw, buffer, BUFSIZ, &ppw)) != 0 || !ppw) { if (error == 0) { error = ENOENT; } Warning("Failed to lookup user with uid: %" FMTUID ". Reason: %s\n", buf.st_uid, Err_Errno2String(error)); return FALSE; } return ImpersonateDoPosix(ppw); } /* *---------------------------------------------------------------------- * * ImpersonateUndo -- Linux specific * * Change back into the superuser * * Side effects: * * EUID is set back to the superuser, and environment variables are * updated back. * *---------------------------------------------------------------------- */ Bool ImpersonateUndo(void) { char buffer[BUFSIZ]; struct passwd pw; struct passwd *ppw = &pw; ImpersonationState *imp = NULL; int ret; int error; #if !defined(VMX86_TOOLS) pthread_mutex_lock(&mut); #endif imp = ImpersonateGetTLS(); ASSERT(imp); //ASSERT(imp->impersonatedUser); if ((error = Posix_Getpwuid_r(0, &pw, buffer, BUFSIZ, &ppw)) != 0 || !ppw) { if (error == 0) { error = ENOENT; } ret = error; Warning("Failed to get password entry for uid 0: %s\n", Err_Errno2String(error)); goto exit; } #if __APPLE__ NOT_IMPLEMENTED(); #else /* Return to root */ ret = Id_SetEUid(ppw->pw_uid); if (ret < 0) { goto exit; } #endif ret = Id_SetGid(ppw->pw_gid); if (ret < 0) { goto exit; } /* * The call to initgroups leaks memory in versions of glibc earlier than 2.1.93. * See bug 10042. -jhu */ ret = initgroups(ppw->pw_name, ppw->pw_gid); if (ret < 0) { goto exit; } /* Restore root's environment */ Posix_Setenv("USER", ppw->pw_name, 1); Posix_Setenv("HOME", ppw->pw_dir, 1); Posix_Setenv("SHELL", ppw->pw_shell, 1); free((char *)imp->impersonatedUser); imp->impersonatedUser = NULL; ret = 0; exit: VERIFY(ret == 0); #if !defined(VMX86_TOOLS) pthread_mutex_unlock(&mut); #endif return (ret ? FALSE : TRUE); } /* *---------------------------------------------------------------------------- * * ImpersonateDoPosix -- * * Impersonate as the user corresponding to the passwd entry * XXX: Mostly copied from vmsd_impersonate.c * * Results: * TRUE if impersonation succeeds, FALSE otherwise. * * Side effects: * imp.impersonatedUser is updated. * *---------------------------------------------------------------------------- */ Bool ImpersonateDoPosix(struct passwd *pwd) // IN { int ret = 0; ImpersonationState *imp = NULL; #if !defined(VMX86_TOOLS) pthread_mutex_lock(&mut); #endif imp = ImpersonateGetTLS(); ASSERT(imp); if (pwd->pw_uid == geteuid()) { imp->refCount++; IMPWARN(("ImpersonateDoPosix (%s : %x : %x) refcount = %d\n", imp->impersonatedUser, getpid(), imp, imp->refCount)); goto unlock; } ASSERT(getuid() == 0); VERIFY(geteuid() == 0); ret = Id_SetGid(pwd->pw_gid); if (ret < 0) { goto exit; } /* * The call to initgroups leaks memory in versions of glibc earlier than * 2.1.93.See bug 10042. -jhu */ ret = initgroups(pwd->pw_name, pwd->pw_gid); if (ret < 0) { goto exit; } #if __APPLE__ NOT_IMPLEMENTED(); #else ret = Id_SetEUid(pwd->pw_uid); if (ret < 0) { goto exit; } #endif /* Setup the user's environment */ Posix_Setenv("USER", pwd->pw_name, 1); Posix_Setenv("HOME", pwd->pw_dir, 1); Posix_Setenv("SHELL", pwd->pw_shell, 1); imp->impersonatedUser = strdup(pwd->pw_name); VERIFY(imp->impersonatedUser); exit: imp->refCount = 1; VERIFY(ret == 0); unlock: #if !defined(VMX86_TOOLS) pthread_mutex_unlock(&mut); #endif return (ret ? FALSE : TRUE); } /* *---------------------------------------------------------------------------- * * ImpersonateDo -- * * Impersonate as user. Can be nested if impersonated as that same user * each time. Can switch back to root temporarily regardless of nesting * level via Impersonate_ForceRoot. Calling Impersonate_UnforceRoot will * return to original impersonation at the same nesting level. * * Results: * TRUE if impersonation succeeds, FALSE otherwise. * * Side effects: * imp.impersonatedUser may be updated. * *---------------------------------------------------------------------------- */ Bool ImpersonateDo(const char *user, // IN AuthToken token) // IN { char buffer[BUFSIZ]; struct passwd pw; struct passwd *ppw = &pw; int error; if ((error = Posix_Getpwnam_r(user, &pw, buffer, BUFSIZ, &ppw)) != 0 || !ppw) { if (error == 0) { error = ENOENT; } Warning("Failed to get password entry for : %s. Reason: %s\n", user, Err_Errno2String(error)); return FALSE; } return ImpersonateDoPosix(ppw); } /* *---------------------------------------------------------------------------- * * ImpersonateForceRoot -- * * Go back to base impersonate level (LocalSystem/root) for a brief * period of time. * Should only be used when already impersonated. This call is not nestable. * No other impersonation is permitted before calling Impersonate_UnforceRoot. * * Results: * TRUE on success, FALSE on failure. * * Side effects: * imp.forceRoot is set to TRUE on success. * *---------------------------------------------------------------------------- */ Bool ImpersonateForceRoot(void) { return TRUE; } /* *---------------------------------------------------------------------------- * * ImpersonateUnforceRoot -- * * Unforce from root to original impersonation context * * Results: * TRUE on success, FALSE otherwise. * * Side effects: * imp.forceRoot is set to FALSE on success * *---------------------------------------------------------------------------- */ Bool ImpersonateUnforceRoot(void) { return TRUE; } open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/000077500000000000000000000000001321503522500224675ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/appUtil.h000066400000000000000000000126711321503522500242650ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * appUtil.h -- * * Utility functions for guest applications. */ #ifndef _APP_UTIL_H_ #define _APP_UTIL_H_ #ifdef _WIN32 #include #endif #include "vmware.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #include "vmware/guestrpc/capabilities.h" #ifdef __cplusplus }; #endif // __cplusplus /* * Platform-agnostic bitmask of types of handlers to include. * Used by the AppUtil file type functions. */ typedef enum { FILE_TYPE_INCLUDE_NONE = 0, FILE_TYPE_INCLUDE_URI = 1, // Include URI handlers FILE_TYPE_INCLUDE_PERCEIVED_HANDLERS = 1 << 1, // Include perceived type handlers // (see bug 1440812). FILE_TYPE_INCLUDE_ALL = FILE_TYPE_INCLUDE_URI | FILE_TYPE_INCLUDE_PERCEIVED_HANDLERS } FileTypeInclusions; #ifdef _WIN32 /* The maximum number of icons that can be retrieved in a single query. */ #define APPUTIL_MAX_NUM_ICONS 16 /* Predefined (N x N pixels) icon sizes */ #define APPUTIL_ICON_SMALL 16 #define APPUTIL_ICON_BIG 32 typedef struct AppUtilIconEntry { uint32 width; // width of icon in pixels uint32 height; // height of icon in pixels uint32 widthBytes; // width of one row in bytes, including padding uint32 dataLength; // length of bgra data, in bytes unsigned char *dataBGRA; // pointer to bgra data } AppUtilIconEntry; typedef struct AppUtilIconInfo { uint32 numEntries; AppUtilIconEntry *iconList; } AppUtilIconInfo; typedef enum { APPUTIL_UPPER_LEFT_DIB = -1, // the origin is the upper-left corner of the bitmap APPUTIL_LOWER_LEFT_DIB = 1, // the origin is the lower-left corner of the bitmap } AppUtilBitmapOrigin; #ifdef __cplusplus extern "C" { #endif // __cplusplus Bool AppUtil_GetIconDataByHandle(HICON hIcon, AppUtilBitmapOrigin origin, AppUtilIconEntry *icon); Bool AppUtil_GetDIBitsAlloc(HDC hdc, HBITMAP hbmp, UINT uStartScan, UINT cScanLines, LPBITMAPINFO lpbi, UINT uUsage, char **bits); HICON AppUtil_GetWindowIcon(HWND hwnd, uint32 iconSize); void AppUtil_BuildGlobalApplicationList(FileTypeInclusions inclusions); wchar_t* AppUtil_SanitizeCommandLine(const wchar_t *commandLineUtf16); char *AppUtil_ActionURIForCommandLine(const WCHAR *commandLineUtf16); Bool AppUtil_CommandLineForShellCommandURI(const char *shellCommandURI, char **executablePath, char **commandLine); Bool AppUtil_GetLinkIconData(const TCHAR *path, AppUtilIconInfo *iconInfo, AppUtilBitmapOrigin dibOrientation); Bool AppUtil_GetAppIconData(const TCHAR *path, AppUtilIconInfo *iconInfo, AppUtilBitmapOrigin dibOrientation); Bool AppUtil_LoadIcon(HMODULE module, LPCWSTR resID, AppUtilBitmapOrigin origin, AppUtilIconInfo *icon); Bool AppUtil_CopyIcon(const AppUtilIconInfo *srcIcon, AppUtilIconInfo *dstIcon); void AppUtil_DestroyIcon(AppUtilIconInfo *icon); Bool AppUtil_GetIconIndexAndLocationForShortcut(const TCHAR *shortcut, int maxLen, TCHAR *iconFile, int *iconIndex); PISECURITY_DESCRIPTOR AppUtil_AllocateLowIntegritySD(void); LPSTR AppUtil_ToLowerUtf8(LPCSTR s); LPWSTR AppUtil_ToLowerUtf16(LPCWSTR s); #ifdef __cplusplus }; #endif // __cplusplus #else // not _WIN32 #include #ifdef __cplusplus extern "C" { #endif // __cplusplus void AppUtil_Init(void); GPtrArray *AppUtil_CollectIconArray(const char *iconName, unsigned long windowID); void AppUtil_FreeIconArray(GPtrArray *pixbufs); Bool AppUtil_AppIsSkippable(const char *appName); char *AppUtil_CanonicalizeAppName(const char *appName, const char *cwd); #ifdef __cplusplus }; #endif // __cplusplus #endif /* * Platform-independent functions. */ #ifdef __cplusplus extern "C" { #endif // __cplusplus void AppUtil_SendGuestCaps(const GuestCapabilities *caps, size_t numCaps, Bool enabled); #ifdef __cplusplus }; #endif // __cplusplus #endif // _APP_UTIL_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/asyncsocket.h000066400000000000000000000710121321503522500251670ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #ifndef __ASYNC_SOCKET_H__ #define __ASYNC_SOCKET_H__ /* * asyncsocket.h -- * * The AsyncSocket object is a fairly simple wrapper around a basic TCP * socket. It's potentially asynchronous for both read and write * operations. Reads are "requested" by registering a receive function * that is called once the requested amount of data has been read from * the socket. Similarly, writes are queued along with a send function * that is called once the data has been written. Errors are reported via * a separate callback. */ #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_USERLEVEL #ifdef _WIN32 #include #include #else #include #endif #include "includeCheck.h" #if defined(__cplusplus) extern "C" { #endif /* * Error codes */ #define ASOCKERR_SUCCESS 0 #define ASOCKERR_GENERIC 1 #define ASOCKERR_TIMEOUT 2 #define ASOCKERR_NOTCONNECTED 3 #define ASOCKERR_REMOTE_DISCONNECT 4 #define ASOCKERR_INVAL 5 #define ASOCKERR_CONNECT 6 #define ASOCKERR_ACCEPT 7 #define ASOCKERR_POLL 8 #define ASOCKERR_CLOSED 9 #define ASOCKERR_BIND 10 #define ASOCKERR_BINDADDRINUSE 11 #define ASOCKERR_LISTEN 12 #define ASOCKERR_CONNECTSSL 13 #define ASOCKERR_NETUNREACH 14 #define ASOCKERR_ADDRUNRESV 15 #define ASOCKERR_BUSY 16 /* * Cross-platform codes for AsyncSocket_GetGenericError(): */ #ifdef _WIN32 #define ASOCK_ENOTCONN WSAENOTCONN #define ASOCK_ENOTSOCK WSAENOTSOCK #define ASOCK_EADDRINUSE WSAEADDRINUSE #define ASOCK_ECONNECTING WSAEWOULDBLOCK #define ASOCK_EWOULDBLOCK WSAEWOULDBLOCK #define ASOCK_ENETUNREACH WSAENETUNREACH #define ASOCK_ECONNRESET WSAECONNRESET #define ASOCK_ECONNABORTED WSAECONNABORTED #define ASOCK_EPIPE ERROR_NO_DATA #else #define ASOCK_ENOTCONN ENOTCONN #define ASOCK_ENOTSOCK ENOTSOCK #define ASOCK_EADDRINUSE EADDRINUSE #define ASOCK_ECONNECTING EINPROGRESS #define ASOCK_EWOULDBLOCK EWOULDBLOCK #define ASOCK_ENETUNREACH ENETUNREACH #define ASOCK_ECONNRESET ECONNRESET #define ASOCK_ECONNABORTED ECONNABORTED #define ASOCK_EPIPE EPIPE #endif /* * Websocket close status codes -- * * enum has numbers in names because RFC6455 refers to the numbers frequently. */ enum { WEB_SOCKET_CLOSE_STATUS_1000_NORMAL = 1000, WEB_SOCKET_CLOSE_STATUS_1001_GOING_AWAY = 1001, WEB_SOCKET_CLOSE_STATUS_1002_PROTOCOL_ERROR = 1002, WEB_SOCKET_CLOSE_STATUS_1003_INVALID_DATA = 1003, WEB_SOCKET_CLOSE_STATUS_1005_EMPTY = 1005, WEB_SOCKET_CLOSE_STATUS_1006_ABNORMAL = 1006, WEB_SOCKET_CLOSE_STATUS_1007_INCONSISTENT_DATA = 1007, WEB_SOCKET_CLOSE_STATUS_1008_POLICY_VIOLATION = 1008, WEB_SOCKET_CLOSE_STATUS_1009_MESSAGE_TOO_BIG = 1009, WEB_SOCKET_CLOSE_STATUS_1010_UNSUPPORTED_EXTENSIONS = 1010, WEB_SOCKET_CLOSE_STATUS_1015_TLS_HANDSHAKE_ERROR = 1015, }; /* * Flags passed into AsyncSocket_Connect*(). * Default value is '0'. * The first two flags allow explicitly selecting * an ESX network stack. They no longer make sense because the * COS is gone. The flags are left around just to ensure we don't have * any flag collisions from users of the library. * The 3rd is for code that uses inet_pton() to get an IP address. * inet_pton() returns address in network-byte-order, * instead of the expected host-byte-order. */ typedef enum { // ASOCKCONN_USE_ESX_SHADOW_STACK = 1<<0, // ASOCKCONN_USE_ESX_NATIVE_STACK = 1<<1, ASOCKCONN_ADDR_IN_NETWORK_BYTE_ORDER = 1<<2 } AsyncSocketConnectFlags; /* * SSL opaque type declarations (so we don't have to include ssl.h) */ struct SSLSockStruct; struct _SSLVerifyParam; /* * AsyncSocket type is opaque */ typedef struct AsyncSocket AsyncSocket; /* * AsyncSocket registers poll callbacks, so give client the opportunity * to control how this is done. * * All the AsyncSocket constructors (Listen, Connect, Attach) take an * optional AsyncSocketPollParam* argument; if NULL the default behavior is * used (callback is registered in POLL_CS_MAIN and locked by the BULL). * Or the client can specify its favorite poll class and locking behavior. * Use of IVmdbPoll is only supported for regular sockets and for Attach. */ #include "poll.h" struct IVmdbPoll; typedef struct AsyncSocketPollParams { int flags; /* Default 0, only POLL_FLAG_NO_BULL is valid */ MXUserRecLock *lock; /* Default: none but BULL */ PollClassSet pollClass; /* Default is POLL_CS_MAIN */ struct IVmdbPoll *iPoll; /* Default NULL: use Poll_Callback */ } AsyncSocketPollParams; /* * Initialize platform libraries */ int AsyncSocket_Init(void); /* * Check the current state of the socket */ typedef enum AsyncSocketState { AsyncSocketListening, AsyncSocketConnecting, AsyncSocketConnected, AsyncSocketCBCancelled, AsyncSocketClosed, } AsyncSocketState; typedef struct AsyncSocketNetworkStats { uint32 cwndBytes; /* maximum outstanding bytes */ uint32 rttSmoothedAvgMillis; /* rtt average in milliseconds */ uint32 rttSmoothedVarMillis; /* rtt variance in milliseconds */ uint32 queuedBytes; /* unsent bytes in send queue */ uint32 inflightBytes; /* current outstanding bytes */ double packetLossPercent; /* packet loss percentage */ } AsyncSocketNetworkStats; /* * The following covers all facilities involving dynamic socket options w.r.t. * various async sockets, excluding the async socket options API on the * sockets themselves, which can be found in asyncSocketVTable.h and those * files implementing that API. * * Potential related future work is covered in * asyncsocket/README-asyncSocketOptions-future-work.txt. * * Summary of dynamic socket options: * * Dynamic socket option = setting settable by the async socket API user * including during the lifetime of the socket. An interface spiritually * similar to setsockopt()'s seemed appropriate. * * The option-setting API looks as follows: * * int ...SetOption(AsyncSocket *asyncSocket, * AsyncSocketOpts_Layer layer, // enum type * AsyncSocketOpts_ID optID, // an integer type * const void *valuePtr, * size_t inBufLen) * * Both native (setsockopt()) and non-native (usually, struct member) * options are supported. layer and optID arguments are conceptually similar * to setsockopt() level and option_name arguments, respectively. * * FOR NATIVE (setsockopt()) OPTIONS: * layer = setsockopt() level value. * optID = setsockopt() option_name value. * * FOR NON-NATIVE (struct member inside socket impl.) OPTIONS: * layer = ..._BASE, ..._TCP, ..._FEC, etc. * (pertains to the various AsyncSocket types); * optID = value from enum type appropriate to the chosen layer. * * Examples (prefixes omitted for space): * * -- NATIVE OPTIONS -- * optID | layer | <= | ssopt() level | ssopt() option_name * ---------------+-------------+----+---------------+-------------------- * == option_name | == level | <= | SOL_SOCKET | SO_SNDBUF * == option_name | == level | <= | IPPROTO_TCP | TCP_NODELAY * * -- NON-NATIVE OPTIONS -- * optID | layer | <= | AsyncSocket type(s) * -------------------------------+-------+----+-------------------- * _SEND_LOW_LATENCY_MODE | _BASE | <= | any * (enum AsyncSocket_OptID) | | | * _ALLOW_DECREASING_BUFFER_SIZE | _TCP | <= | AsyncTCPSocket * (enum AsyncTCPSocket_OptID) | | | * _MAX_CWND | _FEC | <= | FECAsyncSocket * (enum FECAsyncSocket_OptID) | | | * * Socket option lists for each non-native layer are just enums. Each socket * type should declare its own socket option enum in its own .h file; e.g., see * AsyncTCPSocket_OptID in this file. Some option lists apply to all async * sockets; these are also here in asyncsocket.h. * * The only way in which different socket option layers coexist in the same * file is the layer enum, AsyncSocketOpts_Layer, in the present file, * which enumerates all possible layers. * * The lack of any other cross-pollution between different non-native option * lists' containing files is a deliberate design choice. */ /* * Integral type used for the optID argument to ->setOption() async socket API. * * For a non-native option, use an enum value for your socket type. * (Example: ASYNC_TCP_SOCKET_OPT_ALLOW_DECREASING_BUFFER_SIZE * of type AsyncTCPSocket_OptID, which would apply to TCP sockets only.) * * For a native (setsockopt()) option, use the setsockopt() integer directly. * (Example: TCP_NODELAY.) * * Let's use a typedef as a small bit of abstraction and to be able to easily * change it to size_t, if (for example) we start indexing arrays with this * thing. */ typedef int AsyncSocketOpts_ID; /* * Enum type used for the layer argument to ->setOption() async socket API. * As explained in the summary comment above, this * informs the particular ->setOption() implementation how to interpret * the accompanying optID integer value, as it may refer to one of several * option lists; and possible different socket instances (not as of this * writing). * * If editing, see summary comment above first for background. * * The values explicitly in this enum are for non-native options. * For native options, simply use the level value as for setsockopt(). * * Ordinal values for all these non-native layers must not clash * with the native levels; hence the `LEVEL + CONSTANT` trick * just below. */ typedef enum { /* * Used when optID applies to a non-native socket option applicable to ANY * async socket type. */ ASYNC_SOCKET_OPTS_LAYER_BASE = SOL_SOCKET + 1000, /* * Next enums must follow the above ordinally, so just: * ASYNC_SOCKET_OPTS_LAYER_, * ASYNC_SOCKET_OPTS_LAYER_, ... */ ASYNC_SOCKET_OPTS_LAYER_BLAST_PROXY, } AsyncSocketOpts_Layer; /* * Enum type used for the OptId argument to ->setOption() async socket API, * when optID refers to a non-native option of any AsyncSocket regardless * of type. */ typedef enum { /* * Bool indicating whether to put the socket into a mode where we attempt * to issue sends directly from within ->send(). Ordinarily * (FALSE), we would set up a Poll callback from within ->send(), * which introduces some non-zero latency to the send path. In * low-latency-send mode (TRUE), that delay is potentially avoided. This * does introduce a behavioral change; the send completion * callback may be triggered before the call to ->send() returns. As * not all clients may be expecting this, we don't enable this mode * unless requested by the client. * * Default: FALSE. */ ASYNC_SOCKET_OPT_SEND_LOW_LATENCY_MODE } AsyncSocket_OptID; /* * Note: If you need to add a non-native option that applies to AsyncTCPSockets * only, you'd probably introduce an enum here named AsyncTCPSocket_OptID; and * at least one layer named ASYNC_SOCKET_OPTS_LAYER_TCP in the enum * AsyncSocketOpts_Layer. */ /* API functions for all AsyncSockets. */ AsyncSocketState AsyncSocket_GetState(AsyncSocket *sock); const char * AsyncSocket_Err2String(int err); const char * AsyncSocket_MsgError(int asyncSockErr); int AsyncSocket_GetGenericErrno(AsyncSocket *s); /* * Return a "unique" ID */ int AsyncSocket_GetID(AsyncSocket *asock); /* * Return the fd corresponding to the socket. */ int AsyncSocket_GetFd(AsyncSocket *asock); /* * Return the remote IP address associated with this socket if applicable */ int AsyncSocket_GetRemoteIPStr(AsyncSocket *asock, const char **ipStr); int AsyncSocket_GetLocalVMCIAddress(AsyncSocket *asock, uint32 *cid, uint32 *port); int AsyncSocket_GetRemoteVMCIAddress(AsyncSocket *asock, uint32 *cid, uint32 *port); int AsyncSocket_GetINETIPStr(AsyncSocket *asock, int socketFamily, char **ipRetStr); unsigned int AsyncSocket_GetPort(AsyncSocket *asock); /* * Recv callback fires once previously requested data has been received */ typedef void (*AsyncSocketRecvFn) (void *buf, int len, AsyncSocket *asock, void *clientData); /* * Send callback fires once previously queued data has been sent */ typedef void (*AsyncSocketSendFn) (void *buf, int len, AsyncSocket *asock, void *clientData); /* * Error callback fires on I/O errors during read/write operations */ typedef void (*AsyncSocketErrorFn) (int error, AsyncSocket *asock, void *clientData); typedef void (*AsyncSocketConnectFn) (AsyncSocket *asock, void *clientData); typedef void (*AsyncSocketSslAcceptFn) (Bool status, AsyncSocket *asock, void *clientData); typedef void (*AsyncSocketSslConnectFn) (Bool status, AsyncSocket *asock, void *clientData); typedef void (*AsyncSocketCloseFn) (AsyncSocket *asock, void *clientData); /* * Callback to handle http upgrade request header */ typedef int (*AsyncWebSocketHandleUpgradeRequestFn) (AsyncSocket *asock, void *clientData, const char *httpRequest, char **httpResponse); /* * Listen on port and fire callback with new asock */ AsyncSocket *AsyncSocket_Listen(const char *addrStr, unsigned int port, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketPollParams *pollParams, int *outError); AsyncSocket *AsyncSocket_ListenLoopback(unsigned int port, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketPollParams *pollParams, int *outError); AsyncSocket *AsyncSocket_ListenVMCI(unsigned int cid, unsigned int port, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketPollParams *pollParams, int *outError); AsyncSocket *AsyncSocket_ListenWebSocket(const char *addrStr, unsigned int port, Bool useSSL, const char *protocols[], AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketPollParams *pollParams, void *sslCtx, int *outError); AsyncSocket *AsyncSocket_ListenWebSocketEx(const char *addrStr, unsigned int port, Bool useSSL, const char *protocols[], AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketPollParams *pollParams, void *sslCtx, AsyncWebSocketHandleUpgradeRequestFn handleUpgradeRequestFn, int *outError); #ifndef _WIN32 AsyncSocket *AsyncSocket_ListenWebSocketUDS(const char *pipeName, Bool useSSL, const char *protocols[], AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketPollParams *pollParams, int *outError); AsyncSocket *AsyncSocket_ListenSocketUDS(const char *pipeName, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketPollParams *pollParams, int *outError); #endif /* * Connect to address:port and fire callback with new asock */ AsyncSocket *AsyncSocket_Connect(const char *hostname, unsigned int port, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketConnectFlags flags, AsyncSocketPollParams *pollParams, int *error); AsyncSocket *AsyncSocket_ConnectVMCI(unsigned int cid, unsigned int port, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketConnectFlags flags, AsyncSocketPollParams *pollParams, int *error); #ifndef _WIN32 AsyncSocket *AsyncSocket_ConnectUnixDomain(const char *path, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketConnectFlags flags, AsyncSocketPollParams *pollParams, int *error); #else AsyncSocket * AsyncSocket_ConnectNamedPipe(const char *pipeName, AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketConnectFlags flags, AsyncSocketPollParams *pollParams, int *outError); AsyncSocket* AsyncSocket_CreateNamedPipe(const char *pipeName, AsyncSocketConnectFn connectFn, void *clientData, DWORD openMode, DWORD pipeMode, uint32 numInstances, AsyncSocketPollParams *pollParams, int *error); #endif AsyncSocket * AsyncSocket_ConnectWebSocket(const char *url, struct _SSLVerifyParam *sslVerifyParam, const char *httpProxy, const char *cookies, const char *protocols[], AsyncSocketConnectFn connectFn, void *clientData, AsyncSocketConnectFlags flags, AsyncSocketPollParams *pollParams, int *error); /* * Initiate SSL connection on existing asock, with optional cert verification */ Bool AsyncSocket_ConnectSSL(AsyncSocket *asock, struct _SSLVerifyParam *verifyParam, void *sslContext); int AsyncSocket_StartSslConnect(AsyncSocket *asock, struct _SSLVerifyParam *verifyParam, void *sslCtx, AsyncSocketSslConnectFn sslConnectFn, void *clientData); Bool AsyncSocket_AcceptSSL(AsyncSocket *asock, void *sslCtx); int AsyncSocket_StartSslAccept(AsyncSocket *asock, void *sslCtx, AsyncSocketSslAcceptFn sslAcceptFn, void *clientData); /* * Create a new AsyncSocket from an existing socket */ AsyncSocket *AsyncSocket_AttachToFd(int fd, AsyncSocketPollParams *pollParams, int *error); AsyncSocket *AsyncSocket_AttachToSSLSock(struct SSLSockStruct *sslSock, AsyncSocketPollParams *pollParams, int *error); int AsyncSocket_UseNodelay(AsyncSocket *asyncSocket, Bool nodelay); int AsyncSocket_SetTCPTimeouts(AsyncSocket *asyncSocket, int keepIdleSec, int keepIntvlSec, int keepCnt); Bool AsyncSocket_EstablishMinBufferSizes(AsyncSocket *asyncSocket, int sendSz, int recvSz); int AsyncSocket_SetSendLowLatencyMode(AsyncSocket *asyncSocket, Bool enable); int AsyncSocket_SetOption(AsyncSocket *asyncSocket, AsyncSocketOpts_Layer layer, AsyncSocketOpts_ID optID, const void *valuePtr, socklen_t inBufLen); int AsyncSocket_GetOption(AsyncSocket *asyncSocket, AsyncSocketOpts_Layer layer, AsyncSocketOpts_ID optID, void *valuePtr, socklen_t *outBufLen); /* * Waits until at least one packet is received or times out. */ int AsyncSocket_DoOneMsg(AsyncSocket *s, Bool read, int timeoutMS); /* * Waits until at least one connect() is accept()ed or times out. */ int AsyncSocket_WaitForConnection(AsyncSocket *s, int timeoutMS); /* * Waits until a socket is ready with readable data or times out. */ int AsyncSocket_WaitForReadMultiple(AsyncSocket **asock, int numSock, int timeoutMS, int *outIdx); /* * Send all pending packets onto the wire or give up after timeoutMS msecs. */ int AsyncSocket_Flush(AsyncSocket *asock, int timeoutMS); /* * Specify the exact amount of data to receive and the receive function to call. */ int AsyncSocket_Recv(AsyncSocket *asock, void *buf, int len, void *cb, void *cbData); /* * Specify the maximum amount of data to receive and the receive function to call. */ int AsyncSocket_RecvPartial(AsyncSocket *asock, void *buf, int len, void *cb, void *cbData); /* * Specify the amount of data to receive and the receive function to call. */ int AsyncSocket_RecvPassedFd(AsyncSocket *asock, void *buf, int len, void *cb, void *cbData); /* * Retrieve socket received via RecvPassedFd. */ int AsyncSocket_GetReceivedFd(AsyncSocket *asock); /* * Specify the amount of data to send/receive and how long to wait before giving * up. */ int AsyncSocket_RecvBlocking(AsyncSocket *asock, void *buf, int len, int *received, int timeoutMS); int AsyncSocket_RecvPartialBlocking(AsyncSocket *asock, void *buf, int len, int *received, int timeoutMS); int AsyncSocket_SendBlocking(AsyncSocket *asock, void *buf, int len, int *sent, int timeoutMS); /* * Specify the amount of data to send and the send function to call */ int AsyncSocket_Send(AsyncSocket *asock, void *buf, int len, AsyncSocketSendFn sendFn, void *clientData); int AsyncSocket_IsSendBufferFull(AsyncSocket *asock); int AsyncSocket_GetNetworkStats(AsyncSocket *asock, AsyncSocketNetworkStats *stats); int AsyncSocket_CancelRecv(AsyncSocket *asock, int *partialRecvd, void **recvBuf, void **recvFn); int AsyncSocket_CancelRecvEx(AsyncSocket *asock, int *partialRecvd, void **recvBuf, void **recvFn, Bool cancelOnSend); /* * Unregister asynchronous send and recv from poll */ int AsyncSocket_CancelCbForClose(AsyncSocket *asock); /* * Set the error handler to invoke on I/O errors (default is to close the * socket) */ int AsyncSocket_SetErrorFn(AsyncSocket *asock, AsyncSocketErrorFn errorFn, void *clientData); /* * Set optional AsyncSocket_Close() behaviors. */ int AsyncSocket_SetCloseOptions(AsyncSocket *asock, int flushEnabledMaxWaitMsec, AsyncSocketCloseFn closeCb); /* * Close the connection and destroy the asock. */ int AsyncSocket_Close(AsyncSocket *asock); /* * Retrieve the URI Supplied for a websocket connection */ char *AsyncSocket_GetWebSocketURI(AsyncSocket *asock); /* * Retrieve the Cookie Supplied for a websocket connection */ char *AsyncSocket_GetWebSocketCookie(AsyncSocket *asock); /* * Set the Cookie for a websocket connection */ int AsyncSocket_SetWebSocketCookie(AsyncSocket *asock, // IN void *clientData, // IN const char *path, // IN const char *sessionId); // IN /* * Retrieve the close status, if received, for a websocket connection */ uint16 AsyncSocket_GetWebSocketCloseStatus(AsyncSocket *asock); /* * Get negotiated websocket protocol */ const char *AsyncSocket_GetWebSocketProtocol(AsyncSocket *asock); /* * Get error code for websocket failure */ int AsyncSocket_GetWebSocketError(AsyncSocket *asock); const char * stristr(const char *s, const char *find); /* * Helper function to parse websocket URL */ Bool AsyncSocket_WebSocketParseURL(const char *url, char **hostname, unsigned int *port, Bool *useSSL, char **relativeURL); /* * Find and return the value for the given header key in the supplied buffer */ char *AsyncSocket_WebSocketGetHttpHeader(const char *request, const char *webKey); /* * Some logging macros for convenience */ #define ASOCKPREFIX "SOCKET " #define ASOCKWARN(_asock, _warnargs) \ do { \ Warning(ASOCKPREFIX "%d (%d) ", \ AsyncSocket_GetID(_asock), AsyncSocket_GetFd(_asock)); \ Warning _warnargs; \ } while (0) #define ASOCKLG0(_asock, _logargs) \ do { \ Log(ASOCKPREFIX "%d (%d) ", \ AsyncSocket_GetID(_asock), AsyncSocket_GetFd(_asock)); \ Log _logargs; \ } while (0) #define ASOCKLOG(_level, _asock, _logargs) \ do { \ if (((_level) == 0) || DOLOG_BYNAME(asyncsocket, (_level))) { \ Log(ASOCKPREFIX "%d (%d) ", \ AsyncSocket_GetID((_asock)), AsyncSocket_GetFd(_asock)); \ Log _logargs; \ } \ } while(0) #if defined(__cplusplus) } // extern "C" #endif #endif // __ASYNC_SOCKET_H__ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/auth.h000066400000000000000000000045651321503522500236130ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _AUTH_H_ #define _AUTH_H_ /* * auth.h -- * * Defines for the authorization library. */ #include "vm_basic_types.h" #include "unicodeTypes.h" #if _WIN32 # include /* * This is quite possibly wrong, but fixes compile errors * for now. Come back to this when authentication is * properly implemented. */ typedef HANDLE AuthToken; #else # include //for getpwent, etc. # include //for initgroups typedef const struct passwd * AuthToken; #endif #if defined(__cplusplus) extern "C" { #endif #if _WIN32 BOOL Auth_StoreAccountInformation(const char *username, const char *password); BOOL Auth_DeleteAccountInformation(); BOOL Auth_RetrieveAccountInformation(char **username, char **password); #define AUTH_ATTRIBUTE_RUNAS_LOCAL_SYSTEM 0x1 #define AUTH_LOCAL_SYSTEM_USER "SYSTEM" BOOL Auth_StoreAccountInformationForVM(const char *filename, uint32 attributes, const char *username, const char *password); BOOL Auth_DeleteAccountInformationForVM(const char *filename); BOOL Auth_AccountInformationIsStoredForVMs(); BOOL Auth_DeleteAccountInformationStoredForVMs(); uint32 Auth_RetrieveAccountInformationForVM(const char *filename, uint32 *attributes, char **username, char **password); #else AuthToken Auth_GetPwnam(const char *user); AuthToken Auth_AuthenticateSelf(void); #endif AuthToken Auth_AuthenticateUser(const char *user, const char *pass); void Auth_CloseToken(AuthToken token); #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/backdoor.h000066400000000000000000000037501321503522500244310ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1999-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * backdoor.h -- * * First layer of the internal communication channel between guest * applications and vmware */ #ifndef _BACKDOOR_H_ #define _BACKDOOR_H_ #include "vm_basic_types.h" #include "vm_assert.h" #include "backdoor_types.h" #if defined(__cplusplus) extern "C" { #endif void Backdoor(Backdoor_proto *bp); // IN/OUT void Backdoor_InOut(Backdoor_proto *bp); // IN/OUT void Backdoor_HbOut(Backdoor_proto_hb *bp); // IN/OUT void Backdoor_HbIn(Backdoor_proto_hb *bp); // IN/OUT #if defined(__cplusplus) } // extern "C" #endif #endif /* _BACKDOOR_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/backdoor_def.h000066400000000000000000000345021321503522500252460ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * backdoor_def.h -- * * This contains backdoor defines that can be included from * an assembly language file. */ #ifndef _BACKDOOR_DEF_H_ #define _BACKDOOR_DEF_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #if defined __cplusplus extern "C" { #endif /* * If you want to add a new low-level backdoor call for a guest userland * application, please consider using the GuestRpc mechanism instead. --hpreg */ #define BDOOR_MAGIC 0x564D5868 /* Low-bandwidth backdoor port. --hpreg */ #define BDOOR_PORT 0x5658 #define BDOOR_CMD_GETMHZ 1 /* * BDOOR_CMD_APMFUNCTION is used by: * * o The FrobOS code, which instead should either program the virtual chipset * (like the new BIOS code does, matthias offered to implement that), or not * use any VM-specific code (which requires that we correctly implement * "power off on CLI HLT" for SMP VMs, boris offered to implement that) * * o The old BIOS code, which will soon be jettisoned * * --hpreg */ #define BDOOR_CMD_APMFUNCTION 2 /* CPL0 only. */ #define BDOOR_CMD_GETDISKGEO 3 #define BDOOR_CMD_GETPTRLOCATION 4 #define BDOOR_CMD_SETPTRLOCATION 5 #define BDOOR_CMD_GETSELLENGTH 6 #define BDOOR_CMD_GETNEXTPIECE 7 #define BDOOR_CMD_SETSELLENGTH 8 #define BDOOR_CMD_SETNEXTPIECE 9 #define BDOOR_CMD_GETVERSION 10 #define BDOOR_CMD_GETDEVICELISTELEMENT 11 #define BDOOR_CMD_TOGGLEDEVICE 12 #define BDOOR_CMD_GETGUIOPTIONS 13 #define BDOOR_CMD_SETGUIOPTIONS 14 #define BDOOR_CMD_GETSCREENSIZE 15 #define BDOOR_CMD_MONITOR_CONTROL 16 /* Disabled by default. */ #define BDOOR_CMD_GETHWVERSION 17 #define BDOOR_CMD_OSNOTFOUND 18 /* CPL0 only. */ #define BDOOR_CMD_GETUUID 19 #define BDOOR_CMD_GETMEMSIZE 20 //#define BDOOR_CMD_HOSTCOPY 21 /* Not in use. Was devel only. */ //#define BDOOR_CMD_SERVICE_VM 22 /* Not in use. Never shipped. */ #define BDOOR_CMD_GETTIME 23 /* Deprecated -> GETTIMEFULL. */ #define BDOOR_CMD_STOPCATCHUP 24 #define BDOOR_CMD_PUTCHR 25 /* Disabled by default. */ #define BDOOR_CMD_ENABLE_MSG 26 /* Devel only. */ #define BDOOR_CMD_GOTO_TCL 27 /* Devel only. */ #define BDOOR_CMD_INITPCIOPROM 28 /* CPL 0 only. */ //#define BDOOR_CMD_INT13 29 /* Not in use. */ #define BDOOR_CMD_MESSAGE 30 #define BDOOR_CMD_SIDT 31 #define BDOOR_CMD_SGDT 32 #define BDOOR_CMD_SLDT_STR 33 #define BDOOR_CMD_ISACPIDISABLED 34 //#define BDOOR_CMD_TOE 35 /* Not in use. */ #define BDOOR_CMD_ISMOUSEABSOLUTE 36 #define BDOOR_CMD_PATCH_SMBIOS_STRUCTS 37 /* CPL 0 only. */ #define BDOOR_CMD_MAPMEM 38 /* Devel only */ #define BDOOR_CMD_ABSPOINTER_DATA 39 #define BDOOR_CMD_ABSPOINTER_STATUS 40 #define BDOOR_CMD_ABSPOINTER_COMMAND 41 //#define BDOOR_CMD_TIMER_SPONGE 42 /* Not in use. */ #define BDOOR_CMD_PATCH_ACPI_TABLES 43 /* CPL 0 only. */ //#define BDOOR_CMD_DEVEL_FAKEHARDWARE 44 /* Not in use. */ #define BDOOR_CMD_GETHZ 45 #define BDOOR_CMD_GETTIMEFULL 46 //#define BDOOR_CMD_STATELOGGER 47 /* Not in use. */ #define BDOOR_CMD_CHECKFORCEBIOSSETUP 48 /* CPL 0 only. */ #define BDOOR_CMD_LAZYTIMEREMULATION 49 /* CPL 0 only. */ #define BDOOR_CMD_BIOSBBS 50 /* CPL 0 only. */ //#define BDOOR_CMD_VASSERT 51 /* Not in use. */ #define BDOOR_CMD_ISGOSDARWIN 52 #define BDOOR_CMD_DEBUGEVENT 53 #define BDOOR_CMD_OSNOTMACOSXSERVER 54 /* CPL 0 only. */ #define BDOOR_CMD_GETTIMEFULL_WITH_LAG 55 #define BDOOR_CMD_ACPI_HOTPLUG_DEVICE 56 /* Devel only. */ #define BDOOR_CMD_ACPI_HOTPLUG_MEMORY 57 /* Devel only. */ #define BDOOR_CMD_ACPI_HOTPLUG_CBRET 58 /* Devel only. */ //#define BDOOR_CMD_GET_HOST_VIDEO_MODES 59 /* Not in use. */ #define BDOOR_CMD_ACPI_HOTPLUG_CPU 60 /* Devel only. */ //#define BDOOR_CMD_USB_HOTPLUG_MOUSE 61 /* Not in use. Never shipped. */ #define BDOOR_CMD_XPMODE 62 /* CPL 0 only. */ #define BDOOR_CMD_NESTING_CONTROL 63 #define BDOOR_CMD_FIRMWARE_INIT 64 /* CPL 0 only. */ #define BDOOR_CMD_FIRMWARE_ACPI_SERVICES 65 /* CPL 0 only. */ # define BDOOR_CMD_FAS_GET_TABLE_SIZE 0 # define BDOOR_CMD_FAS_GET_TABLE_DATA 1 # define BDOOR_CMD_FAS_GET_PLATFORM_NAME 2 # define BDOOR_CMD_FAS_GET_PCIE_OSC_MASK 3 # define BDOOR_CMD_FAS_GET_APIC_ROUTING 4 # define BDOOR_CMD_FAS_GET_TABLE_SKIP 5 # define BDOOR_CMD_FAS_GET_SLEEP_ENABLES 6 # define BDOOR_CMD_FAS_GET_HARD_RESET_ENABLE 7 # define BDOOR_CMD_FAS_GET_MOUSE_HID 8 # define BDOOR_CMD_FAS_GET_SMBIOS_VERSION 9 # define BDOOR_CMD_FAS_GET_64BIT_PCI_HOLE_SIZE 10 //#define BDOOR_CMD_FAS_GET_NVDIMM_FMT_CODE 11 /* Not in use. Never shipped. */ # define BDOOR_CMD_FAS_SRP_ENABLED 12 # define BDOOR_CMD_FAS_EXIT_BOOT_SERVICES 13 #define BDOOR_CMD_SENDPSHAREHINTS 66 /* Not in use. Deprecated. */ #define BDOOR_CMD_ENABLE_USB_MOUSE 67 #define BDOOR_CMD_GET_VCPU_INFO 68 # define BDOOR_CMD_VCPU_SLC64 0 # define BDOOR_CMD_VCPU_SYNC_VTSCS 1 # define BDOOR_CMD_VCPU_HV_REPLAY_OK 2 # define BDOOR_CMD_VCPU_LEGACY_X2APIC_OK 3 # define BDOOR_CMD_VCPU_MMIO_HONORS_PAT 4 # define BDOOR_CMD_VCPU_RESERVED 31 #define BDOOR_CMD_EFI_SERIALCON_CONFIG 69 /* CPL 0 only. */ #define BDOOR_CMD_BUG328986 70 /* CPL 0 only. */ #define BDOOR_CMD_FIRMWARE_ERROR 71 /* CPL 0 only. */ # define BDOOR_CMD_FE_INSUFFICIENT_MEM 0 # define BDOOR_CMD_FE_EXCEPTION 1 # define BDOOR_CMD_FE_SGX 2 # define BDOOR_CMD_FE_PCI_MMIO 3 #define BDOOR_CMD_VMK_INFO 72 #define BDOOR_CMD_EFI_BOOT_CONFIG 73 /* CPL 0 only. */ # define BDOOR_CMD_EBC_LEGACYBOOT_ENABLED 0 # define BDOOR_CMD_EBC_GET_ORDER 1 # define BDOOR_CMD_EBC_SHELL_ACTIVE 2 # define BDOOR_CMD_EBC_GET_NETWORK_BOOT_PROTOCOL 3 # define BDOOR_CMD_EBC_QUICKBOOT_ENABLED 4 # define BDOOR_CMD_EBC_GET_PXE_ARCH 5 #define BDOOR_CMD_GET_HW_MODEL 74 /* CPL 0 only. */ #define BDOOR_CMD_GET_SVGA_CAPABILITIES 75 /* CPL 0 only. */ #define BDOOR_CMD_GET_FORCE_X2APIC 76 /* CPL 0 only */ #define BDOOR_CMD_SET_PCI_HOLE 77 /* CPL 0 only */ #define BDOOR_CMD_GET_PCI_HOLE 78 /* CPL 0 only */ #define BDOOR_CMD_GET_PCI_BAR 79 /* CPL 0 only */ #define BDOOR_CMD_SHOULD_GENERATE_SYSTEMID 80 /* CPL 0 only */ #define BDOOR_CMD_READ_DEBUG_FILE 81 /* Devel only. */ #define BDOOR_CMD_SCREENSHOT 82 /* Devel only. */ #define BDOOR_CMD_INJECT_KEY 83 /* Devel only. */ #define BDOOR_CMD_INJECT_MOUSE 84 /* Devel only. */ #define BDOOR_CMD_MKS_GUEST_STATS 85 /* CPL 0 only. */ # define BDOOR_CMD_MKSGS_RESET 0 # define BDOOR_CMD_MKSGS_ADD_PPN 1 # define BDOOR_CMD_MKSGS_REMOVE_PPN 2 #define BDOOR_CMD_ABSPOINTER_RESTRICT 86 #define BDOOR_CMD_GUEST_INTEGRITY 87 # define BDOOR_CMD_GI_GET_CAPABILITIES 0 # define BDOOR_CMD_GI_SETUP_ENTRY_POINT 1 # define BDOOR_CMD_GI_SETUP_ALERTS 2 # define BDOOR_CMD_GI_SETUP_STORE 3 # define BDOOR_CMD_GI_SETUP_EVENT_RING 4 # define BDOOR_CMD_GI_SETUP_NON_FAULT_READ 5 # define BDOOR_CMD_GI_ENTER_INTEGRITY_MODE 6 # define BDOOR_CMD_GI_EXIT_INTEGRITY_MODE 7 # define BDOOR_CMD_GI_RESET_INTEGRITY_MODE 8 # define BDOOR_CMD_GI_GET_EVENT_RING_STATE 9 # define BDOOR_CMD_GI_CONSUME_RING_EVENTS 10 # define BDOOR_CMD_GI_WATCH_MAPPINGS_START 11 # define BDOOR_CMD_GI_WATCH_MAPPINGS_STOP 12 # define BDOOR_CMD_GI_CHECK_MAPPINGS_NOW 13 # define BDOOR_CMD_GI_WATCH_PPNS_START 14 # define BDOOR_CMD_GI_WATCH_PPNS_STOP 15 # define BDOOR_CMD_GI_SEND_MSG 16 # define BDOOR_CMD_GI_TEST_READ_MOB 128 # define BDOOR_CMD_GI_TEST_ADD_EVENT 129 # define BDOOR_CMD_GI_TEST_MAPPING 130 # define BDOOR_CMD_GI_TEST_PPN 131 # define BDOOR_CMD_GI_MAX 131 #define BDOOR_CMD_MKSSTATS_SNAPSHOT 88 /* Devel only. */ # define BDOOR_CMD_MKSSTATS_START 0 # define BDOOR_CMD_MKSSTATS_STOP 1 #define BDOOR_CMD_SECUREBOOT 89 #define BDOOR_CMD_COPY_PHYSMEM 90 /* Devel only. */ #define BDOOR_CMD_STEALCLOCK 91 /* CPL 0 only. */ # define BDOOR_STEALCLOCK_STATUS_DISABLED 0 # define BDOOR_STEALCLOCK_STATUS_ENABLED 1 #define BDOOR_CMD_GUEST_PAGE_HINTS 92 /* CPL 0 only */ #define BDOOR_CMD_FIRMWARE_UPDATE 93 /* CPL 0 only. */ # define BDOOR_CMD_FU_GET_HOST_VERSION 0 # define BDOOR_CMD_FU_UPDATE_FROM_HOST 1 # define BDOOR_CMD_FU_LOCK 2 #define BDOOR_CMD_MAX 94 /* * IMPORTANT NOTE: When modifying the behavior of an existing backdoor command, * you must adhere to the semantics expected by the oldest Tools who use that * command. Specifically, do not alter the way in which the command modifies * the registers. Otherwise backwards compatibility will suffer. */ /* Nesting control operations */ #define NESTING_CONTROL_RESTRICT_BACKDOOR 0 #define NESTING_CONTROL_OPEN_BACKDOOR 1 #define NESTING_CONTROL_QUERY 2 #define NESTING_CONTROL_MAX 2 /* EFI Boot Order options, nibble-sized. */ #define EFI_BOOT_ORDER_TYPE_EFI 0x0 #define EFI_BOOT_ORDER_TYPE_LEGACY 0x1 #define EFI_BOOT_ORDER_TYPE_NONE 0xf #define BDOOR_NETWORK_BOOT_PROTOCOL_NONE 0x0 #define BDOOR_NETWORK_BOOT_PROTOCOL_IPV4 0x1 #define BDOOR_NETWORK_BOOT_PROTOCOL_IPV6 0x2 #define BDOOR_SECUREBOOT_STATUS_DISABLED 0xFFFFFFFFUL #define BDOOR_SECUREBOOT_STATUS_APPROVED 1 #define BDOOR_SECUREBOOT_STATUS_DENIED 2 /* High-bandwidth backdoor port. --hpreg */ #define BDOORHB_PORT 0x5659 #define BDOORHB_CMD_MESSAGE 0 #define BDOORHB_CMD_VASSERT 1 #define BDOORHB_CMD_MAX 2 /* * There is another backdoor which allows access to certain TSC-related * values using otherwise illegal PMC indices when the pseudo_perfctr * control flag is set. */ #define BDOOR_PMC_HW_TSC 0x10000 #define BDOOR_PMC_REAL_NS 0x10001 #define BDOOR_PMC_APPARENT_NS 0x10002 #define BDOOR_PMC_PSEUDO_TSC 0x10003 #define IS_BDOOR_PMC(index) (((index) | 3) == 0x10003) #define BDOOR_CMD(ecx) ((ecx) & 0xffff) /* Sub commands for BDOOR_CMD_VMK_INFO */ #define BDOOR_CMD_VMK_INFO_ENTRY 1 /* * Current format for the guest page hints is: * * Arg0: BDOOR_MAGIC, Arg3: BDOOR_PORT * * Arg1: (rbx on x86) * * 0 64 * | PPN | * * Arg2: (rcx on x86) * * 0 16 32 64 * | Command | Type | Reserved | * * Arg4: (rsi on x86) * * 0 16 64 * | numPages | Reserved | * */ #define BDOOR_GUEST_PAGE_HINTS_NOT_SUPPORTED ((unsigned)-1) #define BDOOR_GUEST_PAGE_HINTS_MAX_PAGES (0xffff) #define BDOOR_GUEST_PAGE_HINTS_TYPE_PSHARE (0) #define BDOOR_GUEST_PAGE_HINTS_TYPE(reg) (((reg) >> 16) & 0xffff) #ifdef VMM /* *---------------------------------------------------------------------- * * Backdoor_CmdRequiresFullyValidVCPU -- * * A few backdoor commands require the full VCPU to be valid * (including GDTR, IDTR, TR and LDTR). The rest get read/write * access to GPRs and read access to Segment registers (selectors). * * Result: * True iff VECX contains a command that require the full VCPU to * be valid. * *---------------------------------------------------------------------- */ static INLINE Bool Backdoor_CmdRequiresFullyValidVCPU(unsigned cmd) { return cmd == BDOOR_CMD_SIDT || cmd == BDOOR_CMD_SGDT || cmd == BDOOR_CMD_SLDT_STR; } #endif #ifdef VM_ARM_64 #define BDOOR_ARM64_LB_PORT (BDOOR_PORT) #define BDOOR_ARM64_HB_PORT_IN (BDOORHB_PORT) #define BDOOR_ARM64_HB_PORT_OUT (BDOORHB_PORT +1) #define BDOOR_ARG0 REG_X0 #define BDOOR_ARG1 REG_X1 #define BDOOR_ARG2 REG_X2 #define BDOOR_ARG3 REG_X3 #define BDOOR_ARG4 REG_X4 #define BDOOR_ARG5 REG_X5 #define BDOOR_ARG6 REG_X6 #else #define BDOOR_ARG0 REG_RAX #define BDOOR_ARG1 REG_RBX #define BDOOR_ARG2 REG_RCX #define BDOOR_ARG3 REG_RDX #define BDOOR_ARG4 REG_RSI #define BDOOR_ARG5 REG_RDI #define BDOOR_ARG6 REG_RBP #endif #if defined __cplusplus } #endif #endif // _BACKDOOR_DEF_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/backdoor_types.h000066400000000000000000000101061321503522500256460ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1999-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * backdoor_types.h -- * * Type definitions for backdoor interaction code. */ #ifndef _BACKDOOR_TYPES_H_ #define _BACKDOOR_TYPES_H_ #ifndef VM_I386 #error The backdoor protocol is only supported on x86 architectures. #endif /* * These #defines are intended for defining register structs as part of * existing named unions. If the union should encapsulate the register * (and nothing else), use DECLARE_REG_NAMED_STRUCT defined below. */ #define DECLARE_REG32_STRUCT \ struct { \ uint16 low; \ uint16 high; \ } halfs; \ uint32 word #define DECLARE_REG64_STRUCT \ DECLARE_REG32_STRUCT; \ struct { \ uint32 low; \ uint32 high; \ } words; \ uint64 quad #if defined (VM_X86_64) || defined (VM_ARM_64) #define DECLARE_REG_STRUCT DECLARE_REG64_STRUCT #else #define DECLARE_REG_STRUCT DECLARE_REG32_STRUCT #endif #define DECLARE_REG_NAMED_STRUCT(_r) \ union { DECLARE_REG_STRUCT; } _r /* * Some of the registers are expressed by semantic name, because if they were * expressed as register structs declared above, we could only address them * by fixed size (half-word, word, quad, etc.) instead of by varying size * (size_t, uintptr_t). * * To be cleaner, these registers are expressed ONLY by semantic name, * rather than by a union of the semantic name and a register struct. */ typedef union { struct { DECLARE_REG_NAMED_STRUCT(ax); size_t size; /* Register bx. */ DECLARE_REG_NAMED_STRUCT(cx); DECLARE_REG_NAMED_STRUCT(dx); DECLARE_REG_NAMED_STRUCT(si); DECLARE_REG_NAMED_STRUCT(di); } in; struct { DECLARE_REG_NAMED_STRUCT(ax); DECLARE_REG_NAMED_STRUCT(bx); DECLARE_REG_NAMED_STRUCT(cx); DECLARE_REG_NAMED_STRUCT(dx); DECLARE_REG_NAMED_STRUCT(si); DECLARE_REG_NAMED_STRUCT(di); } out; } Backdoor_proto; typedef union { struct { DECLARE_REG_NAMED_STRUCT(ax); DECLARE_REG_NAMED_STRUCT(bx); size_t size; /* Register cx. */ DECLARE_REG_NAMED_STRUCT(dx); uintptr_t srcAddr; /* Register si. */ uintptr_t dstAddr; /* Register di. */ DECLARE_REG_NAMED_STRUCT(bp); } in; struct { DECLARE_REG_NAMED_STRUCT(ax); DECLARE_REG_NAMED_STRUCT(bx); DECLARE_REG_NAMED_STRUCT(cx); DECLARE_REG_NAMED_STRUCT(dx); DECLARE_REG_NAMED_STRUCT(si); DECLARE_REG_NAMED_STRUCT(di); DECLARE_REG_NAMED_STRUCT(bp); } out; } Backdoor_proto_hb; MY_ASSERTS(BACKDOOR_STRUCT_SIZES, ASSERT_ON_COMPILE(sizeof(Backdoor_proto) == 6 * sizeof(uintptr_t)); ASSERT_ON_COMPILE(sizeof(Backdoor_proto_hb) == 7 * sizeof(uintptr_t)); ) #undef DECLARE_REG_STRUCT #endif /* _BACKDOOR_TYPES_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/base64.h000066400000000000000000000037011321503522500237250ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * base64.h -- * * Functions to base64 encode/decode buffers. Implemented in * lib/misc/base64.c. */ #ifndef _BASE64_H #define _BASE64_H #if defined(__cplusplus) extern "C" { #endif Bool Base64_Encode(uint8 const *src, size_t srcLength, char *target, size_t targSize, size_t *dataLength); Bool Base64_Decode(char const *src, uint8 *target, size_t targSize, size_t *dataLength); Bool Base64_ChunkDecode(char const *src, size_t inSize, uint8 *target, size_t targSize, size_t *dataLength); Bool Base64_ValidEncoding(char const *src, size_t srcLength); size_t Base64_EncodedLength(uint8 const *src, size_t srcLength); size_t Base64_DecodedLength(char const *src, size_t srcLength); Bool Base64_EasyEncode(const uint8 *src, size_t srcLength, char **target); Bool Base64_EasyDecode(const char *src, uint8 **target, size_t *targSize); Bool Base64_DecodeFixed(const char *src, char *outBuf, size_t outBufSize); #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/buildNumber.h000066400000000000000000000004311321503522500251060ustar00rootroot00000000000000#define BUILD_NUMBER \ "build-7253323" #define BUILD_NUMBER_NUMERIC \ 7253323 #define BUILD_NUMBER_NUMERIC_STRING \ "7253323" #define PRODUCT_BUILD_NUMBER \ "product-build-1608" #define PRODUCT_BUILD_NUMBER_NUMERIC \ 1608 #define PRODUCT_BUILD_NUMBER_NUMERIC_STRING \ "1608" open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/capsProvider.h000066400000000000000000000026451321503522500253100ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * capsProvider.h -- * * Interface implemented by dnd manager objects to obtain their * capabilities. Mainly needed by Windows host and guest code. */ #ifndef __CAPS_PROVIDER_H__ #define __CAPS_PROVIDER_H__ #if defined VMX86_TOOLS || COMPILE_WITHOUT_CUI # ifdef LIB_EXPORT # undef LIB_EXPORT # endif #define LIB_EXPORT #else #include "libExport.hh" #endif #if defined(SWIG) class CapsProvider #else class LIB_EXPORT CapsProvider #endif { public: virtual ~CapsProvider() {}; virtual Bool CheckCapability(uint32 caps) = 0; }; #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/circList.h000066400000000000000000000253121321503522500244170ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * circList.h -- * * macros, prototypes and struct definitions for double-linked * circular lists. */ #ifndef _CIRCLIST_H_ #define _CIRCLIST_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMMON #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include "vmware.h" #if defined(__cplusplus) extern "C" { #endif typedef struct ListItem { struct ListItem *prev; struct ListItem *next; } ListItem; /* *---------------------------------------------------------------------- * * CircList_IsEmpty -- * * A NULL list is an empty list. * * Result: * TRUE if list is empty, FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE Bool CircList_IsEmpty(const ListItem *item) // IN { return item == NULL; } /* *---------------------------------------------------------------------- * * CircList_InitItem -- * * Initialize item as a single-element circular list. * * Result: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE void CircList_InitItem(ListItem *item) // OUT { item->prev = item->next = item; } /* *---------------------------------------------------------------------- * * CircList_First -- * * Return first item in the list. * * Result: * First item. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE ListItem * CircList_First(ListItem *item) // IN { return item; } /* *---------------------------------------------------------------------- * * CircList_Last -- * * Return last item in the list. * * Result: * Last item. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE ListItem * CircList_Last(ListItem *item) { return item->prev; } /* * CIRC_LIST_CONTAINER - get the struct for this entry (like list_entry) * @ptr: the &struct ListItem pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list struct within the struct. */ #define CIRC_LIST_CONTAINER(ptr, type, member) \ VMW_CONTAINER_OF(ptr, type, member) /* * Historical name, left here to reduce churn. * TODO: remove, all LIST_CONTAINER uses should be * VMW_CONTAINER_OF and stop depending on circList.h * to provide the definition. */ #define LIST_CONTAINER(ptr, type, member) VMW_CONTAINER_OF(ptr, type, member) /* * LIST_SCAN_FROM scans the list from "from" up until "until". * The loop variable p should not be destroyed in the process. * "from" is an element in the list where to start scanning. * "until" is the element where search should stop. * member is the field to use for the search - either "next" or "prev". */ #define CIRC_LIST_SCAN_FROM(p, from, until, member) \ for (p = (from); (p) != NULL; \ (p) = (((p)->member == (until)) ? NULL : (p)->member)) /* scan the entire list (non-destructively) */ #define CIRC_LIST_SCAN(p, l) \ CIRC_LIST_SCAN_FROM(p, CircList_First(l), CircList_First(l), next) /* scan the entire list where loop element may be destroyed */ #define CIRC_LIST_SCAN_SAFE(p, pn, l) \ if (!CircList_IsEmpty(l)) \ for (p = (l), (pn) = CircList_Next(p, l); (p) != NULL; \ (p) = (pn), (pn) = CircList_Next(p, l)) /* scan the entire list backwards where loop element may be destroyed */ #define CIRC_LIST_SCAN_BACK_SAFE(p, pn, l) \ if (!CircList_IsEmpty(l)) \ for (p = CircList_Last(l), (pn) = CircList_Prev(p, l); (p) != NULL; \ (p) = (pn), (pn) = CircList_Prev(p, l)) /* *---------------------------------------------------------------------- * * CircList_Next -- * * Returns the next member of a doubly linked list, or NULL if last. * Assumes: p is member of the list headed by head. * * Result: * If head or p is NULL, return NULL. Otherwise, * next list member (or null if last). * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE ListItem * CircList_Next(ListItem *p, // IN ListItem *head) // IN { if (head == NULL || p == NULL) { return NULL; } /* both p and head are non-null */ p = p->next; return p == head ? NULL : p; } /* *---------------------------------------------------------------------- * * CircList_Prev -- * * Returns the prev member of a doubly linked list, or NULL if first. * Assumes: p is member of the list headed by head. * * Result: * If head or prev is NULL, return NULL. Otherwise, * prev list member (or null if first). * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE ListItem * CircList_Prev(ListItem *p, // IN ListItem *head) // IN { if (head == NULL || p == NULL) { return NULL; } /* both p and head are non-null */ return p == head ? NULL : p->prev; } /* *---------------------------------------------------------------------- * * CircList_DeleteItem -- * * Deletes a member of a doubly linked list, possibly modifies the * list header itself. * Assumes neither p nor headp is null and p is a member of *headp. * * Result: * None * * Side effects: * Modifies *headp. * *---------------------------------------------------------------------- */ static INLINE void CircList_DeleteItem(ListItem *p, // IN ListItem **headp) // IN/OUT { ListItem *next; ASSERT(p != NULL); ASSERT(headp != NULL); next = p->next; if (p == next) { *headp = NULL; } else { next->prev = p->prev; p->prev->next = next; if (*headp == p) { *headp = next; } } } /* *---------------------------------------------------------------------- * * CircList_Queue -- * * Adds a new member to the back of a doubly linked list (queue) * Assumes neither p nor headp is null and p is not a member of *headp. * * Result: * None * * Side effects: * Modifies *headp. * *---------------------------------------------------------------------- */ static INLINE void CircList_Queue(ListItem *p, // IN ListItem **headp) // IN/OUT { ListItem *head; head = *headp; if (CircList_IsEmpty(head)) { CircList_InitItem(p); *headp = p; } else { p->prev = head->prev; p->next = head; p->prev->next = p; head->prev = p; } } /* *---------------------------------------------------------------------- * * CircList_Push -- * * Adds a new member to the front of a doubly linked list (stack) * Assumes neither p nor headp is null and p is not a member of *headp. * * Result: * None * * Side effects: * Modifies *headp. * *---------------------------------------------------------------------- */ static INLINE void CircList_Push(ListItem *p, // IN ListItem **headp) // IN/OUT { CircList_Queue(p, headp); *headp = p; } /* *---------------------------------------------------------------------- * * CircList_Splice -- * * Make a single list {l1 l2} from {l1} and {l2} and return it. * It is okay for one or both lists to be NULL. * No checking is done. It is assumed that l1 and l2 are two * distinct lists. * * Result: * A list { l1 l2 }. * * Side effects: * Modifies l1 and l2 list pointers. * *---------------------------------------------------------------------- */ static INLINE ListItem * CircList_Splice(ListItem *l1, // IN ListItem *l2) // IN { ListItem *l1Last, *l2Last; if (CircList_IsEmpty(l1)) { return l2; } if (CircList_IsEmpty(l2)) { return l1; } l1Last = l1->prev; /* last elem of l1 */ l2Last = l2->prev; /* last elem of l2 */ /* * l1 -> ... -> l1Last l2 -> ... l2Last */ l1Last->next = l2; l2->prev = l1Last; l1->prev = l2Last; l2Last->next = l1; return l1; } #if 0 /* Presently unused, enable if a use is found */ /* *---------------------------------------------------------------------- * * CircList_Split -- * * Make a list l = {l1 l2} into two separate lists {l1} and {l2}, where: * l = { ... x -> p -> ... } split into: * l1 = { ... -> x } * l2 = { p -> ... } * Assumes neither p nor l is null and p is a member of l. * If p is the first element of l, then l1 will be NULL. * * Result: * None. * * Side effects: * Sets *l1p and *l2p to the resulting two lists. * Modifies l's pointers. * *---------------------------------------------------------------------- */ static INLINE void CircList_Split(ListItem *p, // IN ListItem *l, // IN ListItem **l1p, // OUT ListItem **l2p) // OUT { ListItem *last; if (p == CircList_First(l)) { /* first element */ *l1p = NULL; *l2p = l; return; } last = l->prev; *l1p = l; p->prev->next = l; l->prev = p->prev; *l2p = p; p->prev = last; last->next = p; } #endif /* *---------------------------------------------------------------------- * * CircList_Size -- * * Return the number of items in the list. * * Result: * The number of items in the list. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE int CircList_Size(ListItem *head) // IN { ListItem *li; int ret = 0; CIRC_LIST_SCAN(li, head) { ret++; } return ret; } #if defined(__cplusplus) } // extern "C" #endif #endif /* _CIRCLIST_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/clamped.h000066400000000000000000000210011321503522500242370ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * clamped.h -- * * Clamped arithmetic. This header file provides inline * arithmetic operations that don't overflow. Instead, they * saturate at the data type's max or min value. */ #ifndef _CLAMPED_H_ #define _CLAMPED_H_ #include "vm_basic_types.h" #include "vm_assert.h" #if defined __cplusplus extern "C" { #endif /* *----------------------------------------------------------------------------- * * Clamped_U64To32 -- * * Convert unsigned 64-bit to 32-bit, clamping instead of truncating. * * Results: * On success, returns TRUE. If the result would have overflowed * and we clamped it to MAX_UINT32, returns FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool Clamped_U64To32(uint32 *out, // OUT uint64 a) // IN { uint32 clamped = (uint32)a; if (UNLIKELY(a != clamped)) { *out = MAX_UINT32; return FALSE; } *out = clamped; return TRUE; } /* *----------------------------------------------------------------------------- * * Clamped_S64To32 -- * * Convert signed 64-bit to 32-bit, clamping instead of truncating. * * Results: * On success, returns TRUE. If the result would have overflowed * and we clamped it to MAX_INT32 or MIN_INT32, returns FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool Clamped_S64To32(int32 *out, // OUT int64 a) // IN { int32 clamped = (int32)a; if (UNLIKELY(a != clamped)) { *out = a < 0 ? MIN_INT32 : MAX_INT32; return FALSE; } *out = clamped; return TRUE; } /* *----------------------------------------------------------------------------- * * Clamped_S32To16 -- * * Convert signed 32-bit to 16-bit, clamping instead of truncating. * * Results: * On success, returns TRUE. If the result would have overflowed * and we clamped it to MAX_INT16 or MIN_INT16, returns FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool Clamped_S32To16(int16 *out, // OUT int32 a) // IN { int16 clamped = (int16)a; if (UNLIKELY(a != clamped)) { *out = a < 0 ? MIN_INT16 : MAX_INT16; return FALSE; } *out = clamped; return TRUE; } /* *---------------------------------------------------------------------- * * Clamped_SAdd32 -- * * Signed 32-bit addition. * * Add two integers, clamping the result to MAX_INT32 or * MIN_INT32 if it would have overflowed. * * Results: * On success, returns TRUE. * If the result would have overflowed and we clamped it, returns FALSE. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE Bool Clamped_SAdd32(int32 *out, // OUT int32 a, // IN int32 b) // IN { return Clamped_S64To32(out, (int64)a + b); } /* *----------------------------------------------------------------------------- * * Clamped_UMul32 -- * * Unsigned 32-bit multiplication. * * We're abusing the fact that 32x32-bit multiplication always * returns a 64-bit result on x86 anyway, and that the compiler * should be smart enough to optimize the code here into a * 32x32-bit multiply. * * Results: * On success, returns TRUE. If the result would have overflowed * and we clamped it to MAX_UINT32, returns FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool Clamped_UMul32(uint32 *out, // OUT uint32 a, // IN uint32 b) // IN { return Clamped_U64To32(out, (uint64)a * b); } /* *----------------------------------------------------------------------------- * * Clamped_SMul32 -- * * Signed 32-bit multiplication. * * Results: * On success, returns TRUE. If the result would have overflowed * and we clamped it to MAX_INT32 or MIN_INT32, returns FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool Clamped_SMul32(int32 *out, // OUT int32 a, // IN int32 b) // IN { return Clamped_S64To32(out, (int64)a * b); } /* *----------------------------------------------------------------------------- * * Clamped_UAdd32 -- * * Unsigned 32-bit addition. * * This is a utility function for 32-bit unsigned addition, * in which the result is clamped to MAX_UINT32 on overflow. * * Results: * On success, returns TRUE. If the result would have overflowed * and we clamped it to MAX_UINT32, returns FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool Clamped_UAdd32(uint32 *out, // OUT uint32 a, // IN uint32 b) // IN { uint32 c = a + b; /* * Checking against one src operand is sufficient. */ if (UNLIKELY(c < a)) { *out = MAX_UINT32; return FALSE; } *out = c; return TRUE; } /* *----------------------------------------------------------------------------- * * Clamped_UAdd64 -- * * Unsigned 64-bit addition. * * This is a utility function for 64-bit unsigned addition, * in which the result is clamped to MAX_UINT64 on overflow. * * Results: * On success, returns TRUE. If the result would have overflowed * and we clamped it to MAX_UINT64, returns FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool Clamped_UAdd64(uint64 *out, // OUT uint64 a, // IN uint64 b) // IN { uint64 c = a + b; /* * Checking against one src operand is sufficient. */ if (UNLIKELY(c < a)) { *out = MAX_UINT64; return FALSE; } *out = c; return TRUE; } /* *----------------------------------------------------------------------------- * * Clamped_URoundUpBits32 -- * * Round up an unsigned 32-bit number by the specified number * of bits. Clamp to MAX_UINT32 on overflow. * * Results: * On success, returns TRUE. If the result would have overflowed * and we clamped it to MAX_UINT32, returns FALSE. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool Clamped_URoundUpBits32(uint32 *out, // OUT uint32 x, // IN uint32 bits) // IN { uint32 mask = (1 << bits) - 1; uint32 c = (x + mask) & ~mask; ASSERT(bits < sizeof(uint32) * 8); if (UNLIKELY(x + mask < x)) { *out = MAX_UINT32; return FALSE; } *out = c; return TRUE; } #if defined __cplusplus } // extern "C" #endif #endif // ifndef _CLAMPED_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/codeset.h000066400000000000000000000425301321503522500242720ustar00rootroot00000000000000/* ********************************************************** * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * **********************************************************/ /* * codeset.h -- * * UTF-16 handling macros. Based on utf16.h from ICU 1.8.1. * * ICU 1.8.1 license follows: * * ICU License - ICU 1.8.1 and later * * COPYRIGHT AND PERMISSION NOTICE * * Copyright (c) 1995-2006 International Business Machines Corporation * and others * * All rights reserved. * * Permission is hereby granted, free of charge, to any * person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all * copies of the Software and that both the above copyright * notice(s) and this permission notice appear in supporting * documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE * BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR * CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Except as contained in this notice, the name of a * copyright holder shall not be used in advertising or otherwise * to promote the sale, use or other dealings in this Software * without prior written authorization of the copyright holder. */ #ifndef __CODESET_H__ # define __CODESET_H__ #include "vm_basic_types.h" #include "vm_assert.h" #include "dynbuf.h" #if defined(__cplusplus) extern "C" { #endif /* * These platforms use UTF-8 (or pretend to): * FreeBSD: really UTF-8 * ESX: UTF-8 by policy decree * Mac: really UTF-8 */ #if defined(__FreeBSD__) || \ defined(VMX86_SERVER) || \ defined(__APPLE__) || \ defined __ANDROID__ #define CURRENT_IS_UTF8 #endif /* * Guard these defines, borrowed from ICU's utf16.h, so that source files * can include both. */ #ifndef __UTF16_H__ /** * Is this code point a surrogate (U+d800..U+dfff)? * @param c 32-bit code point * @return TRUE or FALSE * @stable ICU 2.4 */ #define U_IS_SURROGATE(c) (((c)&0xfffff800)==0xd800) /** * Does this code unit alone encode a code point (BMP, not a surrogate)? * @param c 16-bit code unit * @return TRUE or FALSE * @stable ICU 2.4 */ #define U16_IS_SINGLE(c) (!U_IS_SURROGATE(c)) /** * Is this code unit a lead surrogate (U+d800..U+dbff)? * @param c 16-bit code unit * @return TRUE or FALSE * @stable ICU 2.4 */ #define U16_IS_LEAD(c) (((c)&0xfffffc00)==0xd800) /** * Is this code unit a trail surrogate (U+dc00..U+dfff)? * @param c 16-bit code unit * @return TRUE or FALSE * @stable ICU 2.4 */ #define U16_IS_TRAIL(c) (((c)&0xfffffc00)==0xdc00) /** * Is this code unit a surrogate (U+d800..U+dfff)? * @param c 16-bit code unit * @return TRUE or FALSE * @stable ICU 2.4 */ #define U16_IS_SURROGATE(c) U_IS_SURROGATE(c) /** * Assuming c is a surrogate code point (U16_IS_SURROGATE(c)), * is it a lead surrogate? * @param c 16-bit code unit * @return TRUE or FALSE * @stable ICU 2.4 */ #define U16_IS_SURROGATE_LEAD(c) (((c)&0x400)==0) /** * Helper constant for U16_GET_SUPPLEMENTARY. * @internal */ #define U16_SURROGATE_OFFSET ((0xd800<<10UL)+0xdc00-0x10000) /** * Get a supplementary code point value (U+10000..U+10ffff) * from its lead and trail surrogates. * The result is undefined if the input values are not * lead and trail surrogates. * * @param lead lead surrogate (U+d800..U+dbff) * @param trail trail surrogate (U+dc00..U+dfff) * @return supplementary code point (U+10000..U+10ffff) * @stable ICU 2.4 */ #define U16_GET_SUPPLEMENTARY(lead, trail) \ (((uint32)(lead)<<10UL)+(uint32)(trail)-U16_SURROGATE_OFFSET) /** * Get the lead surrogate (0xd800..0xdbff) for a * supplementary code point (0x10000..0x10ffff). * @param supplementary 32-bit code point (U+10000..U+10ffff) * @return lead surrogate (U+d800..U+dbff) for supplementary * @stable ICU 2.4 */ #define U16_LEAD(supplementary) ((utf16_t)(((supplementary)>>10)+0xd7c0)) /** * Get the trail surrogate (0xdc00..0xdfff) for a * supplementary code point (0x10000..0x10ffff). * @param supplementary 32-bit code point (U+10000..U+10ffff) * @return trail surrogate (U+dc00..U+dfff) for supplementary * @stable ICU 2.4 */ #define U16_TRAIL(supplementary) ((utf16_t)(((supplementary)&0x3ff)|0xdc00)) /** * How many 16-bit code units are used to encode this Unicode code point? (1 or 2) * The result is not defined if c is not a Unicode code point (U+0000..U+10ffff). * @param c 32-bit code point * @return 1 or 2 * @stable ICU 2.4 */ #define U16_LENGTH(c) ((uint32)(c)<=0xffff ? 1 : 2) /** * The maximum number of 16-bit code units per Unicode code point (U+0000..U+10ffff). * @return 2 * @stable ICU 2.4 */ #define U16_MAX_LENGTH 2 /** * Get a code point from a string at a code point boundary offset, * and advance the offset to the next code point boundary. * (Post-incrementing forward iteration.) * "Safe" macro, handles unpaired surrogates and checks for string boundaries. * * The offset may point to the lead surrogate unit * for a supplementary code point, in which case the macro will read * the following trail surrogate as well. * If the offset points to a trail surrogate or * to a single, unpaired lead surrogate, then that itself * will be returned as the code point. * * @param s const utf16_t * string * @param i string offset, must be i(start) && U16_IS_LEAD(__c2=(s)[(i)-1])) { \ --(i); \ (c)=U16_GET_SUPPLEMENTARY(__c2, (c)); \ } \ } \ } #endif // __UTF16_H__ /* * Use this instead of "UTF-16" to specify UTF-16 in native byte order. */ #define CODESET_NATIVE_UTF16 "UTF-16LE" /* * Flags for conversion functions */ #define CSGTG_NORMAL 0x0000 /* Without any information loss. */ #define CSGTG_TRANSLIT 0x0001 /* Transliterate unknown characters. */ #define CSGTG_IGNORE 0x0002 /* Skip over untranslatable characters. */ /* * XXX -- this function is a temporary fix. It should be removed once we fix * the 3rd party library pathname issue. */ char * CodeSet_GetAltPathName(const utf16_t *pathW); // IN Bool CodeSet_Init(const char *icuDataDir); // IN: ICU datafile directory in current page, // can be NULL. void CodeSet_DontUseIcu(void); Bool CodeSet_GenericToGenericDb(const char *codeIn, // IN const char *bufIn, // IN size_t sizeIn, // IN const char *codeOut, // IN unsigned int flags, // IN DynBuf *db); // IN/OUT Bool CodeSet_GenericToGeneric(const char *codeIn, // IN const char *bufIn, // IN size_t sizeIn, // IN const char *codeOut, // IN unsigned int flags, // IN char **bufOut, // IN/OUT size_t *sizeOut); // IN/OUT Bool CodeSet_Utf8ToCurrent(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT Bool CodeSet_CurrentToUtf8(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT Bool CodeSet_Utf16leToUtf8Db(const char *bufIn, // IN size_t sizeIn, // IN DynBuf *db); // IN Bool CodeSet_Utf16leToUtf8(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT/OPT Bool CodeSet_Utf8ToUtf16le(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT/OPT Bool CodeSet_CurrentToUtf16le(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT/OPT Bool CodeSet_Utf16leToCurrent(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT/OPT Bool CodeSet_Utf16beToCurrent(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT/OPT Bool CodeSetOld_Utf8Normalize(const char *bufIn, // IN size_t sizeIn, // IN Bool precomposed, // IN DynBuf *db); // OUT Bool CodeSet_Utf8FormDToUtf8FormC(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT/OPT Bool CodeSet_Utf8FormCToUtf8FormD(const char *bufIn, // IN size_t sizeIn, // IN char **bufOut, // OUT size_t *sizeOut); // OUT/OPT const char * CodeSet_GetCurrentCodeSet(void); Bool CodeSet_IsEncodingSupported(const char *name); // IN: Bool CodeSet_Validate(const char *buf, // IN: the string size_t size, // IN: length of string const char *code); // IN: encoding Bool CodeSet_UTF8ToUTF32(const char *utf8, // IN: char **utf32); // OUT: Bool CodeSet_UTF32ToUTF8(const char *utf32, // IN: char **utf8); // OUT: int CodeSet_LengthInCodePoints(const char *utf8); // IN: int CodeSet_CodePointOffsetToByteOffset(const char *utf8, // IN: int codePointOffset); // IN: int CodeSet_GetUtf8(const char *string, // IN: const char *end, // IN: uint32 *uchar); // OUT/OPT: Bool CodeSet_IsValidUTF8(const char *bufIn, // IN: size_t sizeIn); // IN: Bool CodeSet_IsStringValidUTF8(const char *string); // IN: /* *----------------------------------------------------------------------------- * * CodeSet_Utf8ToUtf16 -- * * A convenience wrapper that accepts a NUL-terminated UTF-8 string * and returns an allocated UTF-16 (LE) string. ASSERTs on failure. * * Results: * The allocted UTF-16 (LE) string, free with free(). * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE utf16_t * CodeSet_Utf8ToUtf16(const char *str) // IN: { utf16_t *strW; if (!CodeSet_Utf8ToUtf16le(str, strlen(str), (char **) &strW, NULL)) { NOT_IMPLEMENTED(); } return strW; } /* *----------------------------------------------------------------------------- * * CodeSet_Utf16ToUtf8 -- * * A convenience wrapper that accepts a NUL-terminated UTF-16 (LE) * string and returns an allocated UTF-8 string. ASSERTs on failure. * * Results: * The allocted UTF-8 string, free with free(). * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * CodeSet_Utf16ToUtf8(const utf16_t *strW) // IN: { char *str; size_t len; for (len = 0; strW[len]; len++) ; if (!CodeSet_Utf16leToUtf8((const char *) strW, len * sizeof strW[0], (char **) &str, NULL)) { NOT_IMPLEMENTED(); } return str; } /* *----------------------------------------------------------------------------- * * CodeSet_Utf8FindCodePointBoundary * * Determine if buf[offset] is a valid UTF-8 code point boundary * and find the previous boundary if it is not. The contents of * buf[offset] need not be defined, only data prior to this * location is examined. Useful for finding a suitable place to * put a NUL terminator. * * Results: * * Returns the offset of the byte immediately following the last * complete UTF-8 code point in buf that is entirely within the * range [0, offset-1]. Note that if the final UTF-8 code point * is complete, the input offset will be returned unchanged. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE size_t CodeSet_Utf8FindCodePointBoundary(const char *buf, // IN size_t offset) // IN { size_t origOffset = offset; signed char c; if (offset > 0) { /* * Back up 1 byte and then find the start of the UTF-8 code * point occupying that location. */ offset--; while (offset > 0 && (buf[offset] & 0xc0) == 0x80) { offset--; } /* * Maximum UTF-8 code point length is 4 */ ASSERT(origOffset - offset <= 4); c = buf[offset]; /* * The first byte of a UTF-8 code point needs to be one of * 0b0XXXXXXX, 0b110XXXXX, 0b1110XXXX, 0b11110XXX */ ASSERT(c >= 0 || (c >> 5) == -2 || (c >> 4) == -2 || (c >> 3) == -2); /* * offset now points to the start of a UTF-8 code point. If it * is a single byte or if the length, as encoded in the first * byte, matches the number of bytes we have backed up, then the * entire code point is present, so the original offset is a * valid code point starting offset. * * Length is encoded as * 2 bytes: 0b110XXXXX * 3 bytes: 0b1110XXXX * 4 bytes: 0b11110XXX * Thus the first byte is -2 when shifted right (signed) by * (7 - length). */ if (c >= 0 || (c >> (7 - origOffset + offset)) == -2) { return origOffset; } /* * Else we truncated a code point. Return its starting point. */ } return offset; } /* *----------------------------------------------------------------------------- * * CodeSet_Utf16FindCodePointBoundary * * Determine if buf[offset] is a valid UTF-16 code point boundary * and find the previous boundary if it is not. The contents of * buf[offset] need not be defined, only data prior to this * location is examined. Useful for finding a suitable place to * put a NUL terminator. * * Results: * * Returns the offset of the byte immediately following the last * complete UTF-16 code point in buf that is entirely within the * range [0, offset-1]. Note that if the final UTF-16 code point * is complete, the input offset will be returned unchanged. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE size_t CodeSet_Utf16FindCodePointBoundary(const char *buf, // IN size_t offset) // IN { size_t origOffset; const utf16_t *utf16Buf = (const utf16_t *)buf; origOffset = offset / 2; offset = origOffset - 1; if (origOffset > 0 && U16_IS_LEAD(utf16Buf[offset])) { return offset * 2; } return origOffset * 2; } #if defined(__cplusplus) } // extern "C" #endif #endif /* __CODESET_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/community_source.h000066400000000000000000000050251321503522500262460ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * community_source.h -- * * Macros for excluding source code from community. */ #ifndef _COMMUNITY_SOURCE_H_ #define _COMMUNITY_SOURCE_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_VMMON #define INCLUDE_ALLOW_VMKERNEL #define INCLUDE_ALLOW_VMKDRIVERS #define INCLUDE_ALLOW_VMK_MODULE #define INCLUDE_ALLOW_DISTRIBUTE #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" /* * Convenience macro for COMMUNITY_SOURCE */ #undef EXCLUDE_COMMUNITY_SOURCE #ifdef COMMUNITY_SOURCE #define EXCLUDE_COMMUNITY_SOURCE(x) #else #define EXCLUDE_COMMUNITY_SOURCE(x) x #endif #undef COMMUNITY_SOURCE_AMD_SECRET #if !defined(COMMUNITY_SOURCE) || defined(AMD_SOURCE) /* * It's ok to include AMD_SECRET source code for non-Community Source, * or for drops directed at AMD. */ #define COMMUNITY_SOURCE_AMD_SECRET #endif #undef COMMUNITY_SOURCE_INTEL_SECRET #if !defined(COMMUNITY_SOURCE) || defined(INTEL_SOURCE) /* * It's ok to include INTEL_SECRET source code for non-Community Source, * or for drops directed at Intel. */ #define COMMUNITY_SOURCE_INTEL_SECRET #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/compat/000077500000000000000000000000001321503522500237525ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/compat/compat_stdarg.h000066400000000000000000000045221321503522500267550ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * compat_stdarg.h -- * * Compatibility defines for systems that need the stdarg features. If your program * needs va_init, va_copy, va_end, etc. then include this file instead of including * stdarg.h directly. */ #ifndef _COMPAT_STDARG_H #define _COMPAT_STDARG_H 1 #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_VMMON #define INCLUDE_ALLOW_VMKERNEL #define INCLUDE_ALLOW_VMKDRIVERS #define INCLUDE_ALLOW_VMK_MODULE #define INCLUDE_ALLOW_DISTRIBUTE #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #if !defined(va_copy) # if defined(__va_copy) # define va_copy __va_copy # elif defined(_WIN32) # define va_copy(ap1, ap2) (*(ap1) = *(ap2)) # elif defined(VA_LIST_IS_ARRAY) # define va_copy(ap1, ap2) memcpy(ap1, ap2, sizeof(va_list)) # else # define va_copy(ap1, ap2) ((ap1) = (ap2)) # endif #endif #endif /* _COMPAT_STDARG_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/conf.h000066400000000000000000000134571321503522500235770ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2002-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * conf.h -- * * Manage the tools configuration file. * */ #ifndef __CONF_H__ #define __CONF_H__ #include "guestApp.h" #define CONF_FILE "tools.conf" #if ! defined(_WIN32) # define CONFVAL_POWERONSCRIPT_DEFAULT "poweron-vm-default" # define CONFVAL_POWEROFFSCRIPT_DEFAULT "poweroff-vm-default" # define CONFVAL_RESUMESCRIPT_DEFAULT "resume-vm-default" # define CONFVAL_SUSPENDSCRIPT_DEFAULT "suspend-vm-default" #else # define CONFVAL_POWERONSCRIPT_DEFAULT "poweron-vm-default.bat" # define CONFVAL_POWEROFFSCRIPT_DEFAULT "poweroff-vm-default.bat" # define CONFVAL_RESUMESCRIPT_DEFAULT "resume-vm-default.bat" # define CONFVAL_SUSPENDSCRIPT_DEFAULT "suspend-vm-default.bat" #endif #define CONFNAME_POWERONSCRIPT "poweron-script" #define CONFNAME_POWEROFFSCRIPT "poweroff-script" #define CONFNAME_RESUMESCRIPT "resume-script" #define CONFNAME_SUSPENDSCRIPT "suspend-script" #define CONFNAME_LOG "log" #define CONFNAME_LOGFILE "log.file" #define CONFNAME_LOGLEVEL "log.level" #define CONFNAME_DISABLETOOLSVERSION "disable-tools-version" #define CONFNAME_HIDETOOLSVERSION "hide-tools-version" #define CONFNAME_DISABLEPMTIMERWARNING "disable-pmtimerwarning" /* ****************************************************************************** * BEGIN GuestInfo goodies. */ /** * Defines the string used for the GuestInfo config file group. */ #define CONFGROUPNAME_GUESTINFO "guestinfo" /** * Lets user disable just the perf monitor. */ #define CONFNAME_GUESTINFO_DISABLEPERFMON "disable-perf-mon" /** * Lets user disable just DiskInfo. * * If thinking of deprecating this, please read bug 535343 first. */ #define CONFNAME_GUESTINFO_DISABLEQUERYDISKINFO "disable-query-diskinfo" /** * Define a custom GuestInfo poll interval (in seconds). * * @note Illegal values result in a @c g_warning and fallback to the default * poll interval. * * @param int User-defined poll interval. Set to 0 to disable polling. */ #define CONFNAME_GUESTINFO_POLLINTERVAL "poll-interval" /** * Define a custom GuestStats poll interval (in seconds). * * @note Illegal values result in a @c g_warning and fallback to the default * stats interval. * * @param int User-defined poll interval for stats. Set to 0 to disable polling. */ #define CONFNAME_GUESTINFO_STATSINTERVAL "stats-interval" /** * Indicates whether stat results should be written to the log. */ #define CONFNAME_GUESTINFO_ENABLESTATLOGGING "enable-stat-logging" /** * Set a comma separated list of network interface names that can be the * primary one * * @note interface names can use wildcards like '*' and '?' * * @param string comma separated list of interface name patterns. */ #define CONFNAME_GUESTINFO_PRIMARYNICS "primary-nics" /** * Set a comma separated list of network interface names that have * low priority (so they will be sorted to the end). * * @note interface names can use wildcards like '*' and '?' * * @param string comma separated list of interface name patterns. */ #define CONFNAME_GUESTINFO_LOWPRIORITYNICS "low-priority-nics" /** * Set a comma separated list of network interface names that shall be ignored. * * @note interface names can use wildcards like '*' and '?' * * @param string comma separated list of interface name patterns. */ #define CONFNAME_GUESTINFO_EXCLUDENICS "exclude-nics" /** * Lets user include reserved space in diskInfo space metrics on Linux. * * @param boolean Set to true to include reserved space. */ #define CONFNAME_DISKINFO_INCLUDERESERVED "diskinfo-include-reserved" /* * END GuestInfo goodies. ****************************************************************************** */ /* ****************************************************************************** * BEGIN Unity goodies. */ /** * Defines the string used for the Unity config file group. */ #define CONFGROUPNAME_UNITY "unity" /** * Lets users override system decisions about whether unity should be available. */ #define CONFNAME_UNITY_FORCEENABLE "forceEnable" /** * Lets users override the desktop background color when in Unity mode. */ #define CONFNAME_UNITY_BACKGROUNDCOLOR "desktop.backgroundColor" /** * Lets users enable (or disable) the Protocol Buffer enabled service */ #define CONFNAME_UNITY_ENABLEPBRPC "pbrpc.enable" /** * Lets users configure the socket type for the PBRPC Services */ #define CONFNAME_UNITY_PBRPCSOCKETTYPE "pbrpc.socketType" #define CONFNAME_UNITY_PBRPCSOCKETTYPE_IPSOCKET "ipsocket" #define CONFNAME_UNITY_PBRPCSOCKETTYPE_VSOCKET "vsocket" /* * END Unity goodies. ****************************************************************************** */ /** Where to find Tools data in the Win32 registry. */ #define CONF_VMWARE_TOOLS_REGKEY "Software\\VMware, Inc.\\VMware Tools" /* Wait 5 seconds between polls to see if the conf file has changed */ #define CONF_POLL_TIME 5 #endif /* __CONF_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/config.h000066400000000000000000000123771321503522500241170ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _CONFIG_H_ #define _CONFIG_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #include "preference.h" #if defined(__cplusplus) extern "C" { #endif /* * Well-known configuration variable names */ #define CONFIG_VMWAREDIR "libdir" struct CryptoKey; struct KeySafeUserRing; void Config_SetAny(const char *value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetString(const char *value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetStringPlain(const char *value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetStringSecure(const char *value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetBool(Bool value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetBoolPlain(Bool value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetBoolSecure(Bool value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetLong(int32 value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetInt64(int64 value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetLongPlain(int32 value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetLongSecure(int32 value, const char *fmt, ...) PRINTF_DECL(2, 3); void Config_SetDouble(double value, const char *fmt, ...) PRINTF_DECL(2, 3); char *Config_GetString(const char *defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); char *Config_GetStringPlain(const char *defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); char *Config_GetStringSecure(const char *defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); char *Config_GetAsString(const char *fmt, ...) PRINTF_DECL(1, 2); char *Config_GetStringEnum(const char *defaultValue, const char **choices, const char *fmt, ...) PRINTF_DECL(3, 4); int Config_CompareVersion(int version); int Config_CompareVersions(int version1, int version2); char *Config_GetPathName(const char *defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); Bool Config_GetBool(Bool defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); Bool Config_GetBoolPlain(Bool defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); Bool Config_GetBoolSecure(Bool defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); int32 Config_GetLong(int32 defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); int64 Config_GetInt64(int64 defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); int32 Config_GetLongPlain(int32 defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); int32 Config_GetLongSecure(int32 defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); int32 Config_GetTriState(int32 defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); double Config_GetDouble(double defaultValue, const char *fmt, ...) PRINTF_DECL(2, 3); Bool Config_NotSet(const char *fmt, ...) PRINTF_DECL(1, 2); void Config_Unset(const char *fmt, ...) PRINTF_DECL(1, 2); void Config_UnsetWithPrefix(const char *fmt, ...) PRINTF_DECL(1, 2); void Config_Set(void *value, int type, const char *fmt, ...) PRINTF_DECL(3, 4); /* * This is tricky to call because it returns allocated storage. Use * the typed wrappers instead (Config_Get*). */ void *Config_Get(const void *pDefaultValue, int type, const char *fmt, ...) PRINTF_DECL(3, 4); Bool Config_Load(const char *filename); Bool Config_Write(void); Bool Config_WriteNoMsg(void); Bool Config_FileIsWritable(void); uint32 Config_GetMask(uint32 defaultMask, const char *optionName); uint64 Config_GetMask64(uint64 defaultMask, const char *optionName); Bool Config_GetDataFileKey(struct CryptoKey **key, struct KeySafeUserRing **userRing); Bool Config_GetDataFileKeys(struct KeySafeUserRing **parentKeys, struct KeySafeUserRing **allKeys); Bool Config_TriToBool(Bool boolDefaultValue, int32 triValue); #if defined(__cplusplus) } // extern "C" #endif #endif // _CONFIG_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/cpName.h000066400000000000000000000107071321503522500240500ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpName.h -- * * Cross-platform name format used by hgfs. * */ #ifndef __CP_NAME_H__ #define __CP_NAME_H__ #ifdef __KERNEL__ # include "driver-config.h" # include #elif defined __FreeBSD__ # if defined _KERNEL # include # define strchr(s,c) index(s,c) # else # include # endif #elif defined __APPLE__ && defined KERNEL # include #elif !defined sun # include # include #endif #include "vm_basic_types.h" /* Status codes for processing share names */ typedef enum { HGFS_NAME_STATUS_COMPLETE, /* Name is complete */ HGFS_NAME_STATUS_FAILURE, /* Name processing failed */ HGFS_NAME_STATUS_INCOMPLETE_BASE, /* Name is base of namespace */ HGFS_NAME_STATUS_INCOMPLETE_ROOT, /* Name is "root" only */ HGFS_NAME_STATUS_INCOMPLETE_DRIVE, /* Name is "root drive" only */ HGFS_NAME_STATUS_INCOMPLETE_UNC, /* Name is "root unc" only */ HGFS_NAME_STATUS_INCOMPLETE_UNC_MACH, /* Name is "root unc " only */ HGFS_NAME_STATUS_DOES_NOT_EXIST, /* Name does not exist */ HGFS_NAME_STATUS_ACCESS_DENIED, /* Desired access to share denied */ HGFS_NAME_STATUS_SYMBOLIC_LINK, /* Name contains a symbolic link */ HGFS_NAME_STATUS_OUT_OF_MEMORY, /* Out of memory while processing */ HGFS_NAME_STATUS_TOO_LONG, /* Name has overly long component */ HGFS_NAME_STATUS_NOT_A_DIRECTORY, /* Name has path component not a dir */ } HgfsNameStatus; int CPName_ConvertTo(char const *nameIn, // IN: The buf to convert size_t bufOutSize, // IN: The size of the output buffer char *bufOut); // OUT: The output buffer int CPName_LinuxConvertTo(char const *nameIn, // IN: buf to convert size_t bufOutSize, // IN: size of the output buffer char *bufOut); // OUT: output buffer int CPName_WindowsConvertTo(char const *nameIn, // IN: buf to convert size_t bufOutSize, // IN: size of the output buffer char *bufOut); // OUT: output buffer int CPName_ConvertFrom(char const **bufIn, // IN/OUT: Input to convert size_t *inSize, // IN/OUT: Size of input buffer size_t *outSize, // IN/OUT: Size of output buffer char **bufOut); // IN/OUT: Output buffer HgfsNameStatus CPName_ConvertFromRoot(char const **bufIn, // IN/OUT: Input to convert size_t *inSize, // IN/OUT: Size of input size_t *outSize, // IN/OUT: Size of output buf char **bufOut); // IN/OUT: Output buffer int CPName_GetComponent(char const *begin, // IN: Beginning of buffer char const *end, // IN: End of buffer char const **next); // OUT: Next component char const * CPName_Print(char const *in, // IN: Name to print size_t size); // IN: Size of name #endif /* __CP_NAME_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/cpNameLite.h000066400000000000000000000043721321503522500246670ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpLiteName.h -- * * Cross-platform "lite" name format used by hgfs. * */ #ifndef __CP_NAME_LITE_H__ #define __CP_NAME_LITE_H__ #if defined __KERNEL__ && defined __linux__ # include "driver-config.h" # include #elif defined _KERNEL && defined __FreeBSD__ # include # define strchr(s,c) index(s,c) #else # include #endif #include "vm_basic_types.h" void CPNameLite_ConvertTo(char *bufIn, // IN/OUT: Input to convert size_t inSize, // IN: Size of input buffer char pathSep); // IN: Path separator void CPNameLite_ConvertFrom(char *bufIn, // IN/OUT: Input to convert size_t inSize, // IN: Size of input buffer char pathSep); // IN: Path separator #endif /* __CP_NAME_LITE_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/cpNameUtil.h000066400000000000000000000064351321503522500247110ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * cpNameUtil.h * * Utility functions for cross-platform name format. * */ #ifndef __CP_NAME_UTIL_H__ #define __CP_NAME_UTIL_H__ #include "vm_basic_types.h" #include "cpName.h" char *CPNameUtil_Strrchr(char const *cpNameIn, size_t cpNameInSize, char searchChar); int CPNameUtil_ConvertToRoot(char const *nameIn, size_t bufOutSize, char *bufOut); int CPNameUtil_LinuxConvertToRoot(char const *nameIn, size_t bufOutSize, char *bufOut); int CPNameUtil_WindowsConvertToRoot(char const *nameIn, size_t bufOutSize, char *bufOut); /* * Convert a set of files or directories CP names from current to form C. * In/out name lengths include a final nul-terminator to ensure * all the final name component is converted. */ Bool CPNameUtil_Utf8FormHostToUtf8FormC(const char *cpNameToConvert, size_t cpNameToConvertLen, char **cpUtf8FormCName, size_t *cpUtf8FormCNameLen); /* * Convert a set of files or directories CP names from current from form C. * In/out name lengths include a final nul-terminator to ensure * all the final name component is converted. */ Bool CPNameUtil_Utf8FormCToUtf8FormHost(const char *cpUtf8FormCName, size_t cpUtf8FormCNameLen, char **cpConvertedName, size_t *cpConvertedNameLen); void CPNameUtil_CharReplace(char *buf, size_t bufSize, char oldChar, char newChar); #endif /* __CP_NAME_UTIL_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/cpuid_info.h000066400000000000000000000047511321503522500247660ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _CPUID_INFO_H #define _CPUID_INFO_H #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMMON #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include "vm_basic_asm.h" #include "x86cpuid_asm.h" #if defined __cplusplus extern "C" { #endif typedef struct CPUID0 { int numEntries; char name[16]; // 4 extra bytes to null terminate } CPUID0; typedef struct CPUID1 { uint32 version; uint32 ebx; uint32 ecxFeatures; uint32 edxFeatures; } CPUID1; typedef struct CPUID80 { uint32 numEntries; uint32 ebx; uint32 ecx; uint32 edx; } CPUID80; typedef struct CPUID81 { uint32 eax; uint32 ebx; uint32 ecxFeatures; uint32 edxFeatures; } CPUID81; typedef struct CPUIDSummary { CPUID0 id0; CPUID1 id1; CPUIDRegs ida; CPUID80 id80; CPUID81 id81; CPUIDRegs id88, id8a; } CPUIDSummary; /* *---------------------------------------------------------------------- * * CPUIDSummary_RegsFromCpuid0 -- * * Fills in the given CPUIDRegs struct with the values from the CPUID0 struct. * * Results: * Returns the CPUIDRegs pointer passed in. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE CPUIDRegs* CPUIDSummary_RegsFromCpuid0(CPUID0* id0In, CPUIDRegs* id0Out) { id0Out->eax = id0In->numEntries; id0Out->ebx = *(uint32 *) (id0In->name + 0); id0Out->edx = *(uint32 *) (id0In->name + 4); id0Out->ecx = *(uint32 *) (id0In->name + 8); return id0Out; } #if defined __cplusplus } // extern "C" #endif #endif // _CPUID_INFO_H open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/cryptoError.h000066400000000000000000000060701321503522500251750ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * cryptoError.h -- * * Error code for cryptographic infrastructure library. */ #ifndef VMWARE_CRYPTOERROR_H #define VMWARE_CRYPTOERROR_H 1 #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vmware.h" typedef int CryptoError; #if defined(__cplusplus) extern "C" { #endif /* * This set of errors should not be expanded beyond a maximum value of 15 * without also updating the code for AIOMgr errors, which allots only 4 bits * for sub-error codes. * * Adding a lot of error codes to describe particular errors is a bad idea * anyhow, because it can be a security hole in itself; see, for example, the * SSL vulnerability described at . * It is best to distinguish only those types of errors that the caller can * legitimately use to figure out how to fix the problem and try again. */ #define CRYPTO_ERROR_SUCCESS ((CryptoError) 0) #define CRYPTO_ERROR_OPERATION_FAILED ((CryptoError) 1) #define CRYPTO_ERROR_UNKNOWN_ALGORITHM ((CryptoError) 2) #define CRYPTO_ERROR_BAD_BUFFER_SIZE ((CryptoError) 3) #define CRYPTO_ERROR_INVALID_OPERATION ((CryptoError) 4) #define CRYPTO_ERROR_NOMEM ((CryptoError) 5) #define CRYPTO_ERROR_NEED_PASSWORD ((CryptoError) 6) #define CRYPTO_ERROR_BAD_PASSWORD ((CryptoError) 7) #define CRYPTO_ERROR_IO_ERROR ((CryptoError) 8) #define CRYPTO_ERROR_UNKNOWN_ERROR ((CryptoError) 9) #define CRYPTO_ERROR_NAME_NOT_FOUND ((CryptoError) 10) #define CRYPTO_ERROR_NO_CRYPTO ((CryptoError) 11) #define CRYPTO_ERROR_LOCK_FAILURE ((CryptoError) 12) const char * CryptoError_ToString(CryptoError error); const char * CryptoError_ToMsgString(CryptoError error); static INLINE int CryptoError_ToInteger(CryptoError error) { return (int) error; } static INLINE CryptoError CryptoError_FromInteger(int index) { return (CryptoError) index; } static INLINE Bool CryptoError_IsSuccess(CryptoError error) { return (CRYPTO_ERROR_SUCCESS == error); } static INLINE Bool CryptoError_IsFailure(CryptoError error) { return (CRYPTO_ERROR_SUCCESS != error); } #if defined(__cplusplus) } // extern "C" #endif #endif /* cryptoError.h */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/dataMap.h000066400000000000000000000134311321503522500242110ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2013-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #ifndef _DATA_MAP_H_ #define _DATA_MAP_H_ #include "hashMap.h" #ifdef __cplusplus extern "C" { #endif typedef int32 DMKeyType; /* * Error codes for DataMap APIs */ typedef enum { DMERR_SUCCESS, /* success code */ DMERR_NOT_FOUND, /* data does not exist */ DMERR_ALREADY_EXIST, /* field ID already exist */ DMERR_DUPLICATED_FIELD_IDS, /* duplicated IDs in deserilization */ DMERR_INSUFFICIENT_MEM, /* insufficient memory */ DMERR_TYPE_MISMATCH, /* type does not match */ DMERR_INVALID_ARGS, /* invalid arguments */ DMERR_UNKNOWN_TYPE, /* type unknow in decoding */ DMERR_TRUNCATED_DATA, /* more data expected during decoding */ DMERR_BUFFER_TOO_SMALL, /* a user buffer is too small */ DMERR_INTEGER_OVERFLOW, /* an integer overflow happened */ DMERR_BAD_DATA /* bad data during decoding */ } ErrorCode; /* * Data field types */ typedef enum { DMFIELDTYPE_EMPTY, DMFIELDTYPE_INT64, DMFIELDTYPE_STRING, DMFIELDTYPE_INT64LIST, DMFIELDTYPE_STRINGLIST, DMFIELDTYPE_MAX } DMFieldType; typedef struct { HashMap *map; uint64 cookie; /* so we know the datamap is not some garbage data */ } DataMap; typedef struct { DMKeyType fieldId; const char *fieldName; } FieldIdNameEntry; /* * Initializer */ ErrorCode DataMap_Create(DataMap *that); // IN/OUT ErrorCode DataMap_Destroy(DataMap *that); // IN/OUT ErrorCode DataMap_Copy(const DataMap *src, // IN DataMap *dst); // OUT ErrorCode DataMap_Serialize(const DataMap *that, //IN char **buf, // OUT uint32 *bufLen); // OUT ErrorCode DataMap_Deserialize(const char *bufIn, // IN const int32 bufLen, // IN DataMap *that); // OUT ErrorCode DataMap_DeserializeContent(const char *bufIn, // IN const int32 bufLen, // IN DataMap *that); // OUT /* * Setters */ ErrorCode DataMap_SetInt64(DataMap *that, // IN/OUT DMKeyType fieldId, // IN int64 value, // IN Bool replace); // IN ErrorCode DataMap_SetString(DataMap *that, // IN/OUT DMKeyType fieldId, // IN char *str, // IN int32 strLen, // IN Bool replace); // IN ErrorCode DataMap_SetInt64List(DataMap *that, // IN/OUT DMKeyType fieldId, // IN int64 *numList, // IN int32 listLen, // IN Bool replace); // IN ErrorCode DataMap_SetStringList(DataMap *that, // IN/OUT DMKeyType fieldId, // IN char **strList, // IN int32 *strLens, // IN Bool replace); // IN /* * Getters */ DMFieldType DataMap_GetType(const DataMap *that, // IN DMKeyType fieldId); // IN ErrorCode DataMap_GetInt64(const DataMap *that, // IN DMKeyType fieldId, // IN int64 *value); // OUT ErrorCode DataMap_GetString(const DataMap *that, // IN DMKeyType fieldId, // IN char **str, // OUT int32 *strLen); // OUT ErrorCode DataMap_GetInt64List(const DataMap *that, // IN DMKeyType fieldId, // IN int64 **numList, // OUT int32 *listLen); // OUT ErrorCode DataMap_GetStringList(const DataMap *that, // IN DMKeyType fieldId, // IN char ***strList, // OUT int32 **strLens); // OUT ErrorCode DataMap_ToString(const DataMap *that, // IN FieldIdNameEntry *fieldIdList, // IN int32 fieldIdListLen, // IN int32 maxNumElements, // IN int32 maxStrLen, // IN char **buf); // OUT #ifdef __cplusplus } /* end of extern "C" */ #endif #endif // #ifdef _DATA_MAP_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/dbllnklst.h000066400000000000000000000210741321503522500246350ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * dbllnklst.h -- * * Double linked lists */ #ifndef _DBLLNKLST_H_ #define _DBLLNKLST_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif #define DblLnkLst_OffsetOf(type, field) ((intptr_t)&((type *)0)->field) #define DblLnkLst_Container(addr, type, field) \ ((type *)((char *)(addr) - DblLnkLst_OffsetOf(type, field))) #define DblLnkLst_ForEach(curr, head) \ for (curr = (head)->next; curr != (head); curr = (curr)->next) /* Safe from list element removal within loop body. */ #define DblLnkLst_ForEachSafe(curr, nextElem, head) \ for (curr = (head)->next, nextElem = (curr)->next; \ curr != (head); \ curr = nextElem, nextElem = (curr)->next) typedef struct DblLnkLst_Links { struct DblLnkLst_Links *prev; struct DblLnkLst_Links *next; } DblLnkLst_Links; /* * Functions * * DblLnkLst_LinkFirst, DblLnkLst_LinkLast, and DblLnkLst_Swap are specific * to anchored lists. The rest are for both circular and anchored lists. */ /* *---------------------------------------------------------------------- * * DblLnkLst_Init -- * * Initialize a member of a doubly linked list * * Result * None * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE void DblLnkLst_Init(DblLnkLst_Links *l) // OUT { l->prev = l->next = l; } /* *---------------------------------------------------------------------- * * DblLnkLst_Link -- * * Merge two doubly linked lists into one * * The operation is commutative * The operation is inversible (its inverse is DblLnkLst_Unlink) * * Result * None * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE void DblLnkLst_Link(DblLnkLst_Links *l1, // IN/OUT DblLnkLst_Links *l2) // IN/OUT { DblLnkLst_Links *tmp; (tmp = l1->prev)->next = l2; (l1->prev = l2->prev)->next = l1; l2->prev = tmp ; } /* *---------------------------------------------------------------------- * * DblLnkLst_Unlink -- * * Split one doubly linked list into two * * No check is performed: the caller must ensure that both members * belong to the same doubly linked list * * The operation is commutative * The operation is inversible (its inverse is DblLnkLst_Link) * * Result * None * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE void DblLnkLst_Unlink(DblLnkLst_Links *l1, // IN/OUT DblLnkLst_Links *l2) // IN/OUT { DblLnkLst_Links *tmp; tmp = l1->prev ; (l1->prev = l2->prev)->next = l1; (l2->prev = tmp )->next = l2; } /* *---------------------------------------------------------------------- * * DblLnkLst_Unlink1 -- * * Unlink an element from its list. * * Result * None * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE void DblLnkLst_Unlink1(DblLnkLst_Links *l) // IN/OUT { DblLnkLst_Unlink(l, l->next); } /* *---------------------------------------------------------------------------- * * DblLnkLst_IsLinked -- * * Determines whether an element is linked with any other elements. * * Results: * TRUE if link is linked, FALSE otherwise. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static INLINE Bool DblLnkLst_IsLinked(DblLnkLst_Links const *l) // IN { /* * A DblLnkLst_Links is either linked to itself (not linked) or linked to * other elements in a list (linked). */ return l->prev != l; } /* *---------------------------------------------------------------------- * * DblLnkLst_LinkFirst -- * * Insert 'l' at the beginning of the list anchored at 'head' * * Result * None * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE void DblLnkLst_LinkFirst(DblLnkLst_Links *head, // IN/OUT DblLnkLst_Links *l) // IN/OUT { DblLnkLst_Link(head->next, l); } /* *---------------------------------------------------------------------- * * DblLnkLst_LinkLast -- * * Insert 'l' at the end of the list anchored at 'head' * * Result * None * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE void DblLnkLst_LinkLast(DblLnkLst_Links *head, // IN/OUT DblLnkLst_Links *l) // IN/OUT { DblLnkLst_Link(head, l); } /* *---------------------------------------------------------------------- * * DblLnkLst_Swap -- * * Swap all entries between the list anchored at 'head1' and the list * anchored at 'head2'. * * The operation is commutative * The operation is inversible (its inverse is itself) * * Result * None * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE void DblLnkLst_Swap(DblLnkLst_Links *head1, // IN/OUT DblLnkLst_Links *head2) // IN/OUT { DblLnkLst_Links const tmp = *head1; if (DblLnkLst_IsLinked(head2)) { (head1->prev = head2->prev)->next = head1; (head1->next = head2->next)->prev = head1; } else { DblLnkLst_Init(head1); } if (tmp.prev != head1) { (head2->prev = tmp.prev)->next = head2; (head2->next = tmp.next)->prev = head2; } else { DblLnkLst_Init(head2); } } #if defined(__cplusplus) } // extern "C" #endif #endif /* _DBLLNKLST_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/debug.h000066400000000000000000000021161321503522500237260ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * debug.h -- * * Platform specific debug routines * */ #ifndef __DEBUG_H__ # define __DEBUG_H__ # include "vm_basic_types.h" void Debug(char const *fmt, ...) PRINTF_DECL(1, 2); #endif /* __DEBUG_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/deployPkg/000077500000000000000000000000001321503522500244255ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/deployPkg/linuxDeployment.h000066400000000000000000000050601321503522500277770ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * linuxDeployment.h -- * * C interface to package deployment. */ #ifndef LINUX_DEPLOYMENT_H #define LINUX_DEPLOYMENT_H #include "vm_basic_types.h" #include "imgcust-common/log.h" #include "imgcust-common/imgcust-api.h" /* *------------------------------------------------------------------------------ * * DeployPkg_SetLogger -- * * Give the deploy package an application specific logger. * * @param logger [in] logger to be used for deploy operation * *------------------------------------------------------------------------------ */ IMGCUST_API void DeployPkg_SetLogger(LogFunction log); /* *------------------------------------------------------------------------------ * * DeployPkg_DeployPackageFromFile -- * * C-style wrapper to decode a package from a file, extract its payload, * expand the payload into a temporary directory, and then execute * the command specified in the package. * * @param file IN: the package file * @return 0 on success * *------------------------------------------------------------------------------ */ IMGCUST_API int DeployPkg_DeployPackageFromFile(const char* file); /* *------------------------------------------------------------------------------ * * ExtractCabPackage -- * * C-style wrapper to extract a package from a file using libmspack. * * @param[in] cabFileName the Cabinet file's path * @param[in] destDir a destination directory where to uncab * * @return TRUE on success, otherwise - FALSE. * *------------------------------------------------------------------------------ */ IMGCUST_API Bool ExtractCabPackage(const char* cabFileName, const char* destDir); #endif // LINUX_DEPLOYMENT_H open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/dictll.h000066400000000000000000000035501321503522500241160ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * dictll.h -- * * Low-level dictionary format --hpreg */ #ifndef __DICTLL_H__ # define __DICTLL_H__ #include "vm_basic_types.h" #include "dynbuf.h" #if defined(__cplusplus) extern "C" { #endif int DictLL_ReadLine(FILE *stream, // IN char **line, // OUT char **name, // OUT char **value); // OUT Bool DictLL_WriteLine(FILE *stream, // IN char const *name, // IN char const *value); // IN const char * DictLL_UnmarshalLine(const char *buf, // IN size_t bufSize, // IN char **line, // OUT char **name, // OUT char **value); // OUT Bool DictLL_MarshalLine(DynBuf *output, // IN/OUT char const *name, // IN/OPT char const *value); // IN Bool DictLL_ReadUTF8BOM(FILE *file); // IN/OUT #if defined(__cplusplus) } // extern "C" #endif #endif /* __DICTLL_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/dynarray.h000066400000000000000000000273341321503522500245020ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * dynarray.h -- * * Dynamic array of objects. * * Use a DynArray to hold a dynamically resizable array * of objects with a fixed width. */ #ifndef _DYNARRAY_H_ #define _DYNARRAY_H_ #include "dynbuf.h" #include "vm_basic_types.h" #include "vm_assert.h" #if defined(__cplusplus) extern "C" { #endif typedef struct DynArray { DynBuf buf; size_t width; } DynArray; /* * The SVGA drivers require the __cdecl calling convention. * The qsort comparison function is compiled with the __stdecl * convention by default, so if we are compiling SVGA (which defines * STD_CALL) we need to explicitly declare the function with __cdecl. */ #if defined(STD_CALL) #define CDECLCONV __cdecl #else #define CDECLCONV #endif typedef int (CDECLCONV *DynArrayCmp)(const void *, const void *); Bool DynArray_Init(DynArray *a, unsigned int count, size_t width); void DynArray_Destroy(DynArray *a); Bool DynArray_SetCount(DynArray *a, unsigned int c); void DynArray_QSort(DynArray *a, DynArrayCmp compare); unsigned int DynArray_AllocCount(const DynArray *a); /* *----------------------------------------------------------------------------- * * DynArray_Trim -- * * Resize the array to fit exactly DynArray_Count() elements. * * Results: * TRUE on success * FALSE on failure (why? who knows...) * * Side effects: * Resizes the array * *----------------------------------------------------------------------------- */ static INLINE Bool DynArray_Trim(DynArray *a) // IN/OUT { ASSERT(a); return DynBuf_Trim(&a->buf); } /* *----------------------------------------------------------------------------- * * DynArray_AddressOf -- * * Fetch a pointer to the address of the ith element. * * Results: * The pointer to the ith element or NULL if the index is out of * bounds. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void * DynArray_AddressOf(const DynArray *a, // IN unsigned int i) // IN { uintptr_t offset = i * a->width; ASSERT(a); if (offset + a->width <= DynBuf_GetSize(&a->buf)) { return offset + (uint8 *)DynBuf_Get(&a->buf); } return NULL; } /* *----------------------------------------------------------------------------- * * DynArray_AddressOfUnsafe -- * * Fetch a pointer to the address of the ith element. Only call * this if you already know that 'i' is valid. The index is not * checked against the size of the array. * * Results: * Always returns a pointer to the ith element. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void * DynArray_AddressOfUnsafe(const DynArray *a, // IN unsigned int i) // IN { uintptr_t offset = i * a->width; ASSERT(a); ASSERT(offset + a->width <= DynBuf_GetSize(&a->buf)); return offset + (uint8 *)DynBuf_Get(&a->buf); } /* *----------------------------------------------------------------------------- * * DynArray_Count -- * * Returns the number of elements in the array. * * XXX: This is relatively slow, since we do an integer division. * Avoid calling this in inner loops. * * Results: * See above. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE unsigned int DynArray_Count(const DynArray *a) // IN { ASSERT(a); return (unsigned int) (DynBuf_GetSize(&a->buf) / a->width); } /* *----------------------------------------------------------------------------- * * DynArray_Copy -- * * Copies all data and metadata from src Dynarray to dest DynArray. * * Dest should be an initialized DynArray of size zero. * * Results: * TRUE on success, FALSE on failure. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE Bool DynArray_Copy(DynArray *src, // IN DynArray *dest) // OUT { ASSERT(src); ASSERT(dest); ASSERT(dest->width); ASSERT(dest->width == src->width); ASSERT(DynArray_AllocCount(dest) == 0); return DynBuf_Copy(&src->buf, &dest->buf); } /* * Use the following macros to define your own DynArray type to * make its usage less cumbersome. You also get type-checking * for free, as demonstrated by this example: * * Assume: * * typedef struct { int n, d; } Fraction; * typedef struct { float r, i; } Complex; * * Without DEFINE_DYNARRAY_TYPE: * * DynArray a1, a2; * DynArray_Init(&a1, 4, sizeof(Fraction)); * DynArray_Init(&a2, 16, sizeof(Complex)); * * Fraction *f2 = (Fraction *)DynArray_AddressOf(&a2, 3); // Runtime Error * * * With DEFINE_DYNARRAY_TYPE: * * DEFINE_DYNARRAY_TYPE(Fraction) * DEFINE_DYNARRAY_TYPE(Complex) * FractionArray a1; * ComplexArray a2; * FractionArray_Init(&a1, 4); * ComplexArray_Init(&a2, 16); * * Fraction *f2 = FractionArray_AddressOf(&a2, 3); // Compile Error * * Yes, it's a poor man's template (but better than nothing). * */ #define DEFINE_DYNARRAY_TYPE(T) DEFINE_DYNARRAY_NAMED_TYPE(T, T) #define DEFINE_DYNARRAY_NAMED_TYPE(T, TYPE) \ DECLARE_DYNARRAY_TYPE(T) \ DEFINEONLY_DYNARRAY_NAMED_TYPE(T, TYPE) #define DECLARE_DYNARRAY_TYPE(T) \ typedef DynArray T##Array; #define DEFINEONLY_DYNARRAY_NAMED_TYPE(T, TYPE) \ \ typedef int (CDECLCONV *DynArray##T##Cmp)(const TYPE *, \ const TYPE *); \ \ static INLINE Bool \ T##Array_Init(T##Array *a, unsigned int count) \ { \ return DynArray_Init((DynArray *)a, count, sizeof(TYPE)); \ } \ \ static INLINE void \ T##Array_Destroy(T##Array *a) \ { \ DynArray_Destroy((DynArray *)a); \ } \ \ static INLINE TYPE* \ T##Array_AddressOf(T##Array *a, unsigned int i) \ { \ return (TYPE*)DynArray_AddressOf((DynArray *)a, i); \ } \ \ static INLINE TYPE* \ T##Array_AddressOfUnsafe(T##Array *a, unsigned int i) \ { \ return (TYPE*)DynArray_AddressOfUnsafe((DynArray *)a, i); \ } \ \ static INLINE unsigned int \ T##Array_Count(const T##Array *a) \ { \ return DynArray_Count((const DynArray *)a); \ } \ \ static INLINE Bool \ T##Array_SetCount(T##Array *a, unsigned int c) \ { \ return DynArray_SetCount((DynArray *)a, c); \ } \ \ static INLINE Bool \ T##Array_Push(T##Array *a, TYPE val) \ { \ unsigned int count = T##Array_Count(a); \ if (!T##Array_SetCount(a, count + 1)) { \ return FALSE; \ } \ *T##Array_AddressOf(a, count) = val; \ return TRUE; \ } \ \ static INLINE unsigned int \ T##Array_AllocCount(T##Array *a) \ { \ return DynArray_AllocCount((DynArray *)a); \ } \ \ static INLINE Bool \ T##Array_Trim(T##Array *a) \ { \ return DynArray_Trim((DynArray *)a); \ } \ static INLINE void \ T##Array_QSort(T##Array *a, DynArray##T##Cmp compare) \ { \ DynArray_QSort((DynArray *)a, (DynArrayCmp)compare); \ } \ static INLINE Bool \ T##Array_Copy(T##Array *src, T##Array *dest) \ { \ return DynArray_Copy((DynArray *)src, (DynArray *)dest); \ } /* Define DynArray of DynBuf. */ DEFINE_DYNARRAY_TYPE(DynBuf) #if defined(__cplusplus) } // extern "C" #endif #endif /* _DYNARRAY_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/dynbuf.h000066400000000000000000000156211321503522500241340ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * dynbuf.h -- * * Dynamic buffers */ #ifndef DYNBUF_H # define DYNBUF_H #include #include "vm_basic_types.h" #include "vm_assert.h" #if defined(__cplusplus) extern "C" { #endif typedef struct DynBuf { char *data; size_t size; size_t allocated; } DynBuf; void DynBuf_Init(DynBuf *b); // OUT void DynBuf_InitWithMemory(DynBuf *b, size_t dataSize, void *data); void DynBuf_Destroy(DynBuf *b); // IN void DynBuf_Attach(DynBuf *b, // IN size_t size, // IN void *data); // IN void * DynBuf_Detach(DynBuf *b); // IN/OUT char * DynBuf_DetachString(DynBuf *b); // IN/OUT Bool DynBuf_Enlarge(DynBuf *b, // IN/OUT size_t min_size); // IN Bool DynBuf_Append(DynBuf *b, // IN/OUT void const *data, // IN size_t size); // IN Bool DynBuf_Trim(DynBuf *b); // IN/OUT Bool DynBuf_Copy(DynBuf *src, // IN DynBuf *dest); // OUT void DynBuf_SafeInternalAppend(DynBuf *b, // IN/OUT void const *data, // IN size_t size, // IN char const *file, // IN unsigned int lineno); // IN #define DynBuf_SafeAppend(_buf, _data, _size) \ DynBuf_SafeInternalAppend(_buf, _data, _size, __FILE__, __LINE__) /* *----------------------------------------------------------------------------- * * DynBuf_Get -- * * Retrieve a pointer to the data contained in a dynamic buffer --hpreg * * Results: * The pointer to the data * * Side effects: * None * *----------------------------------------------------------------------------- */ #if defined(SWIG) static void * #else static INLINE void * #endif DynBuf_Get(DynBuf const *b) // IN { ASSERT(b); return b->data; } /* *----------------------------------------------------------------------------- * * DynBuf_GetString -- * * Results: * Returns a pointer to the dynamic buffer data as a NUL-terminated * string. * * Side effects: * DynBuf might allocate additional memory and will panic if it fails to. * *----------------------------------------------------------------------------- */ #if defined(SWIG) static char * #else static INLINE char * #endif DynBuf_GetString(DynBuf *b) // IN { ASSERT(b); if (b->size == b->allocated) { ASSERT_MEM_ALLOC(DynBuf_Enlarge(b, b->size + 1)); } b->data[b->size] = '\0'; return b->data; } /* *----------------------------------------------------------------------------- * * DynBuf_GetSize -- * * Returns the current size of the dynamic buffer --hpreg * * Results: * The current size of the dynamic buffer * * Side effects: * None * *----------------------------------------------------------------------------- */ #if defined(SWIG) static size_t #else static INLINE size_t #endif DynBuf_GetSize(DynBuf const *b) // IN { ASSERT(b); return b->size; } /* *----------------------------------------------------------------------------- * * DynBuf_SetSize -- * * Set the current size of a dynamic buffer --hpreg * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ #if defined(SWIG) static void #else static INLINE void #endif DynBuf_SetSize(DynBuf *b, // IN/OUT: size_t size) // IN { ASSERT(b); ASSERT(size <= b->allocated); b->size = size; } /* *----------------------------------------------------------------------------- * * DynBuf_GetAllocatedSize -- * * Returns the current allocated size of the dynamic buffer --hpreg * * Results: * The current allocated size of the dynamic buffer * * Side effects: * None * *----------------------------------------------------------------------------- */ #if defined(SWIG) static size_t #else static INLINE size_t #endif DynBuf_GetAllocatedSize(DynBuf const *b) // IN { ASSERT(b); return b->allocated; } /* *---------------------------------------------------------------------------- * * DynBuf_AppendString -- * * Appends the string to the specified DynBuf object, including its NUL * terminator. Note that this is NOT like strcat; repeated calls will * leave embedded NULs in the middle of the buffer. (Compare to * DynBuf_Strcat.) * * Results: * TRUE on success * FALSE on failure (not enough memory) * * Side effects: * DynBuf may change its size or allocate additional memory. * *---------------------------------------------------------------------------- */ #if defined(SWIG) static Bool #else static INLINE Bool #endif DynBuf_AppendString(DynBuf *buf, // IN/OUT const char *string) // IN { return DynBuf_Append(buf, string, strlen(string) + 1 /* NUL */); } /* *---------------------------------------------------------------------------- * * DynBuf_Strcat -- * * A DynBuf version of strcat. Unlike DynBuf_AppendString, does NOT * visibly NUL-terminate the DynBuf, thereby allowing future appends to * do proper string concatenation without leaving embedded NULs in the * middle. * * Results: * TRUE on success * FALSE on failure (not enough memory) * * Side effects: * DynBuf may change its size or allocate additional memory. * *---------------------------------------------------------------------------- */ #if defined(SWIG) static Bool #else static INLINE Bool #endif DynBuf_Strcat(DynBuf *buf, // IN/OUT const char *string) // IN { Bool success; ASSERT(buf != NULL); ASSERT(string != NULL); /* * We actually do NUL-terminate the buffer internally, but this is not * visible to callers, and they should not rely on this. */ success = DynBuf_AppendString(buf, string); if (LIKELY(success)) { ASSERT(buf->size > 0); buf->size--; } return success; } #if defined(__cplusplus) } // extern "C" #endif #endif /* DYNBUF_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/dynxdr.h000066400000000000000000000035011321503522500241470ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _DYNXDR_H_ #define _DYNXDR_H_ /* * dynxdr.h -- * * Functions for creating and destroying an XDR stream that is backed * by a dynamic memory buffer. Uses DynBuf, so requires code using it to * link lib/misc. * * This stream only does encoding. For decoding, we generally have data * already available in the form of a pre-allocated buffer, in which * case we can use the xdrmem_create() function. * * Note: xdr_destroy() is a no-op for this stream. Use DynXdr_Destroy() * instead. Also, XDR_SETPOS and XDR_INLINE are not supported. */ #include #include #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif XDR *DynXdr_Create(XDR *in); Bool DynXdr_AppendRaw(XDR *xdrs, const void *buf, size_t len); void *DynXdr_AllocGet(XDR *xdrs); void *DynXdr_Get(XDR *xdrs); void DynXdr_Destroy(XDR *xdrs, Bool release); #if defined(__cplusplus) } // extern "C" #endif #endif /* _DYNXDR_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/embed_version.h000066400000000000000000000036401321503522500254640ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * embed_version.h -- * * Embeds a version string in an ELF binary that is readable by modinfo. */ #ifndef _EMBED_VERSION_H_ #define _EMBED_VERSION_H_ /* * Using section attributes, embed the specified version in the "modinfo" * section of the ELF binary. We don't do this on Windows, where the PE format * already has version information stuffed inside it, nor on Mac OS X, which * doesn't use ELF. * * We can't declare vm_version as static, otherwise it may get optimized out. * I've seen this when building with gcc 4.1, but not with 3.3. * * The argument to the macro should be the base name for the version number * macros to embed in the final binary, as described in vm_version.h (see * declaration of VM_VERSION_TO_STR). */ #if !defined(_WIN32) && !defined(__APPLE__) #define VM_EMBED_VERSION(ver) \ const char vm_version[] \ __attribute__((section(".modinfo"), unused)) = "version=" ver #else #define VM_EMBED_VERSION(ver) #endif #endif /* _EMBED_VERSION_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/err.h000066400000000000000000000056301321503522500234340ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * err.h -- * * General error handling library */ #ifndef _ERR_H_ #define _ERR_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #if !defined(_WIN32) #include #endif #include "vm_basic_defs.h" #if defined(__cplusplus) extern "C" { #endif #if defined(_WIN32) typedef DWORD Err_Number; #else typedef int Err_Number; #endif #define ERR_INVALID ((Err_Number) -1) const char *Err_ErrString(void); const char *Err_Errno2String(Err_Number errorNumber); Err_Number Err_String2Errno(const char *string); #if defined(VMX86_DEBUG) Err_Number Err_String2ErrnoDebug(const char *string); #endif #if defined(_WIN32) char *Err_SanitizeMessage(const char *msg); #endif /* *---------------------------------------------------------------------- * * Err_Errno -- * * Gets last error in a platform independent way. * * Results: * Last error. * * Side effects: * None. * *---------------------------------------------------------------------- */ #if defined(_WIN32) #define Err_Errno() GetLastError() #else #define Err_Errno() errno #endif /* *---------------------------------------------------------------------- * * Err_SetErrno -- * * Set the last error in a platform independent way. * * Results: * None. * * Side effects: * Yes. * *---------------------------------------------------------------------- */ #if defined(_WIN32) #define Err_SetErrno(e) SetLastError(e) #else #define Err_SetErrno(e) (errno = (e)) #endif /* *---------------------------------------------------------------------- * * WITH_ERRNO -- * * Execute "body" with "e" bound to the last error number * and preserving the last error in surrounding code. * * Results: * None. * * Side effects: * Yes. * *---------------------------------------------------------------------- */ #define WITH_ERRNO(e, body) do { \ Err_Number e = Err_Errno(); \ body; \ Err_SetErrno(e); \ } while (FALSE) #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/escBitvector.h000066400000000000000000000105021321503522500252720ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #ifndef _ESC_BITVECTOR_H_ #define _ESC_BITVECTOR_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_DISTRIBUTE // XXX is this true? #include "includeCheck.h" #ifdef __KERNEL__ #include "driver-config.h" #include /* Don't include these if compiling for the Solaris or Apple kernels. */ #elif !defined _KERNEL && !defined KERNEL #include #include #endif #if defined _KERNEL && defined __FreeBSD__ # include #elif defined KERNEL && defined __APPLE__ # include #endif #include "vm_assert.h" #define ESC_BITVECTOR_INDEX(_x) ((_x)>>5) #define ESC_BITVECTOR_MASK(_x) (1<<((_x)&31)) #define ESC_BITVECTOR_SIZE 256 // hardwired size of the bitvector /* *---------------------------------------------------------------------- * * EscBitVector -- * * Taken from bitvector.h, but hard wired for use with the Escape * routines, which always need a bitvector of 256 bits, are never * used in the monitor, and need to work in the linux kernel. [bac] * * *---------------------------------------------------------------------- */ typedef struct EscBitVector { uint32 vector[ESC_BITVECTOR_SIZE/32]; } EscBitVector; /* *---------------------------------------------------------------------- * * EscBitVector_Init -- * * Clear all the bits in this vector. * * Results: * All bits are cleared * *---------------------------------------------------------------------- */ static INLINE void EscBitVector_Init(EscBitVector *bv) { memset(bv, 0, sizeof(EscBitVector)); } /* *---------------------------------------------------------------------- * * EscBitVector_Set, EscBitVector_Clear, EscBitVector_Test -- * * basic operations * * Results: * insertion/deletion/presence to/from/in the set * * EscBitVector_Test returns non-zero if present, 0 otherwise * * *---------------------------------------------------------------------- */ static INLINE void EscBitVector_Set(EscBitVector *bv,int n) { ASSERT(n>=0 && nvector[0]) :"Ir" (n)); #else bv->vector[ESC_BITVECTOR_INDEX(n)] |= ESC_BITVECTOR_MASK(n); #endif } static INLINE void EscBitVector_Clear(EscBitVector *bv,int n) { ASSERT(n>=0 && nvector[0]) :"Ir" (n)); #else bv->vector[ESC_BITVECTOR_INDEX(n)] &= ~ESC_BITVECTOR_MASK(n); #endif } static INLINE int EscBitVector_Test(EscBitVector const *bv, int n) { ASSERT(n>=0 && nvector[0]),"Ir" (n)); return tmp; } #else return ((bv->vector[ESC_BITVECTOR_INDEX(n)] & ESC_BITVECTOR_MASK(n)) != 0); #endif } #endif /* _ESC_BITVECTOR_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/escape.h000066400000000000000000000051511321503522500241020ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * escape.h -- * * Buffer escaping --hpreg */ #ifndef __ESCAPE_H__ # define __ESCAPE_H__ #include "vmware.h" #if defined(__cplusplus) extern "C" { #endif void * Escape_DoString(const char *escStr, // IN int const *bytesToEsc, // IN void const *bufIn, // IN size_t sizeIn, // IN size_t *sizeOut); // OUT/OPT void * Escape_Do(char escByte, // IN int const *bytesToEsc, // IN void const *bufIn, // IN size_t sizeIn, // IN size_t *sizeOut); // OUT/OPT void * Escape_Undo(char escByte, // IN void const *bufIn, // IN size_t sizeIn, // IN size_t *sizeOut); // OUT/OPT Bool Escape_UndoFixed(char escByte, // IN void const *bufIn, // IN size_t sizeIn, // IN void *bufOut, // IN/OUT size_t bufOutSize); // IN const char * Escape_Strchr(char escByte, // IN const char *bufIn, // IN char c); // IN char * Escape_Unescape(char escByte, // IN const char *bufIn); // IN void * Escape_AnsiToUnix(void const *bufIn, // IN size_t sizeIn, // IN size_t *sizeOut); // OUT/OPT void * Escape_Sh(void const *bufIn, // IN size_t sizeIn, // IN size_t *sizeOut); // OUT/OPT void * Escape_BRE(void const *bufIn, // IN size_t sizeIn, // IN size_t *sizeOut); // OUT/OPT void Escape_UnescapeCString(char *buf); // IN/OUT char * Escape_Comma(const char *string); // IN #if defined(__cplusplus) } // extern "C" #endif #endif /* __ESCAPE_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/file.h000066400000000000000000000273441321503522500235710ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * file.h -- * * Interface to host file system and related utility functions. */ #ifndef _FILE_H_ #define _FILE_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #include "fileIO.h" #include "unicodeTypes.h" #include "err.h" #if defined(_WIN32) #define FILE_MAXPATH MAX_PATH #else # ifdef __FreeBSD__ # include // For __FreeBSD_version # endif # if defined(__FreeBSD__) # include // PATH_MAX # else # include // PATH_MAX # endif #define FILE_MAXPATH PATH_MAX #endif #if defined(__cplusplus) extern "C" { #endif #define FILE_SEARCHPATHTOKEN ";" #define FILE_UNLINK_DEFAULT_WAIT_MS 2000 /* * Opaque, platform-specific stucture for supporting the directory walking API. */ typedef struct WalkDirContextImpl WalkDirContextImpl; typedef WalkDirContextImpl *WalkDirContext; /* * When File_MakeTempEx2 is called, it creates a temporary file or a directory * in a specified directory. File_MakeTempEx2 calls a user-specified callback * function to get the filename. Callback function should be of type * File_MakeTempCreateNameFunc. * * 'num' specifies nth time this function is called. * * 'data' specifies the payload that the user specified when executing * File_MakeTempEx2 function. * * If successful, this function should return a dynamically allocated string * with the filename. * * File_MakeTempEx2 frees the pathName after a successful call to this * function. * */ typedef char *File_MakeTempCreateNameFunc(uint32 num, void *data); #if defined(__APPLE__) typedef enum { FILEMACOS_UNMOUNT_SUCCESS, FILEMACOS_UNMOUNT_SUCCESS_ALREADY, FILEMACOS_UNMOUNT_ERROR, } FileMacosUnmountStatus; FileMacosUnmountStatus FileMacos_UnmountDev(char const *bsdDev, Bool wholeDev, Bool eject, Bool su); void FileMacos_MountDevAsyncNoResult(char const *bsdDev, Bool su); Bool FileMacos_IsOnSparseDmg(int fd); Bool FileMacos_IsSliceDevice(char const *bsdDev); char *FileMacos_DiskDevToUserFriendlyName(char const *bsdDiskDev); char *FileMacos_DiskDevToVolumeName(char const *bsdDiskDev); char *FileMacos_DiskDeviceToUniqueID(char const *bsdPath); char *FileMacos_UniqueIDToDiskDevice(char const *identifier); Bool FileMacOS_MakeSecureLibraryCopies(const char *inDir, const char **dylibName, unsigned numDylibs, char **outDir); #elif defined VMX86_SERVER struct FS_PartitionListResult; int File_GetVMFSAttributes(const char *pathName, struct FS_PartitionListResult **fsAttrs); int File_GetVMFSFSType(const char *pathName, int fd, uint16 *fsTypeNum); int File_GetVMFSVersion(const char *pathName, uint32 *versionNum); int File_GetVMFSBlockSize(const char *pathName, uint32 *blockSize); int File_GetVMFSMountInfo(const char *pathName, char **fsType, uint32 *version, char **remoteIP, char **remoteMountPoint, char **localMountPoint); #endif Bool File_SupportsZeroedThick(const char *pathName); Bool File_SupportsMultiWriter(const char *pathName); Bool File_SupportsOptimisticLock(const char *pathName); Bool File_SupportsMandatoryLock(const char *pathName); Bool File_Exists(const char *pathName); int File_Unlink(const char *pathName); int File_UnlinkIfExists(const char *pathName); int File_UnlinkDelayed(const char *pathName); int File_UnlinkNoFollow(const char *pathName); int File_UnlinkRetry(const char *pathName, uint32 maxWaitTimeMilliSec); void File_SplitName(const char *pathName, char **volume, char **dir, char **base); void File_GetPathName(const char *fullPath, char **pathName, char **base); char *File_StripSlashes(const char *path); char *File_PathJoin(const char *dirName, const char *baseName); Bool File_CreateDirectory(const char *pathName); Bool File_CreateDirectoryEx(const char *pathName, int mask); Bool File_EnsureDirectory(const char *pathName); Bool File_DeleteEmptyDirectory(const char *pathName); Bool File_CreateDirectoryHierarchy(const char *pathName, char **topmostCreated); Bool File_CreateDirectoryHierarchyEx(const char *pathName, int mask, char **topmostCreated); Bool File_DeleteDirectoryContent(const char *pathName); Bool File_DeleteDirectoryTree(const char *pathName); int File_ListDirectory(const char *pathName, char ***ids); Bool File_IsOsfsVolumeEmpty(const char *pathName); #ifndef _WIN32 char * File_StripFwdSlashes(const char *pathName); #endif /* * Simple file-system walk. */ WalkDirContext File_WalkDirectoryStart(const char *parentPath); Bool File_WalkDirectoryNext(WalkDirContext context, char **path); void File_WalkDirectoryEnd(WalkDirContext context); Bool File_IsDirectory(const char *pathName); Bool File_IsFile(const char *pathName); Bool File_IsSymLink(const char *pathName); Bool File_ContainSymLink(const char *pathName); Bool File_IsCharDevice(const char *pathName); Bool File_GetParent(char **canPath); Bool File_IsRemote(const char *pathName); Bool File_IsEmptyDirectory(const char *pathName); char *File_Cwd(const char *drive); // XXX belongs to `process' module char *File_FullPath(const char *pathName); Bool File_IsFullPath(const char *pathName); uint64 File_GetFreeSpace(const char *pathName, Bool doNotAscend); uint64 File_GetCapacity(const char *pathName); int File_MakeTempEx(const char *dir, const char *pathName, char **presult); int File_MakeTempEx2(const char *dir, Bool createTempFile, File_MakeTempCreateNameFunc *createNameFunc, void *createFuncData, char **presult); char *File_MakeSafeTempDir(const char *prefix); int64 File_GetModTime(const char *pathName); char *File_GetModTimeString(const char *pathName); char *File_GetUniqueFileSystemID(const char *pathName); char *File_GetMountPath(const char *pathName, Bool checkEntirePath); #ifdef _WIN32 char *File_GetVolumeGUID(const char *pathName); #endif Bool File_GetTimes(const char *pathName, VmTimeType *createTime, VmTimeType *accessTime, VmTimeType *writeTime, VmTimeType *attrChangeTime); Bool File_SetTimes(const char *pathName, VmTimeType createTime, VmTimeType accessTime, VmTimeType writeTime, VmTimeType attrChangeTime); Bool File_GetFilePermissions(const char *pathName, int *mode); Bool File_SetFilePermissions(const char *pathName, int mode); Bool File_SupportsFileSize(const char *pathName, uint64 fileSize); Bool File_GetMaxFileSize(const char *pathName, uint64 *maxFileSize); Bool File_SupportsLargeFiles(const char *pathName); char *File_MapPathPrefix(const char *oldPath, const char **oldPrefixes, const char **newPrefixes, size_t numPrefixes); Bool File_CopyFromFdToFd(FileIODescriptor src, FileIODescriptor dst); Bool File_CopyFromFd(FileIODescriptor src, const char *dstName, Bool overwriteExisting); Bool File_Copy(const char *srcName, const char *dstName, Bool overwriteExisting); Bool File_MoveTree(const char *srcName, const char *dstName, Bool overwriteExisting, Bool *asMove); Bool File_CopyTree(const char *srcName, const char *dstName, Bool overwriteExisting, Bool followSymlinks); Bool File_Replace(const char *oldFile, const char *newFile); int File_Rename(const char *oldFile, const char *newFile); int File_RenameRetry(const char *oldFile, const char *newFile, uint32 msecMaxWaitTime); Bool File_Move(const char *oldFile, const char *newFile, Bool *asRename); void File_Rotate(const char *pathName, int n, Bool noRename, char **newFileName); int File_GetFSMountInfo(const char *pathName, char **fsType, uint32 *version, char **remoteIP, char **remoteMountPoint, char **localMountPoint); /* Get size only for regular file. */ int64 File_GetSize(const char *pathName); /* Get size for file or directory. */ int64 File_GetSizeEx(const char *pathName); int64 File_GetSizeByPath(const char *pathName); int64 File_GetSizeAlternate(const char *pathName); Bool File_IsSameFile(const char *path1, const char *path2); char *File_PrependToPath(const char *searchPath, const char *elem); Bool File_FindFileInSearchPath(const char *file, const char *searchPath, const char *cwd, char **result); char *File_ReplaceExtension(const char *pathName, const char *newExtension, uint32 numExtensions, ...); char *File_RemoveExtension(const char *pathName); Bool File_MakeCfgFileExecutable(const char *pathName); char *File_ExpandAndCheckDir(const char *dirName); char *File_GetSafeTmpDir(Bool useConf); int File_MakeSafeTemp(const char *tag, char **presult); Bool File_DoesVolumeSupportAcls(const char *pathName); /* *--------------------------------------------------------------------------- * * File_IsDirsep -- * * Is the argument character a directory separator? * * Results: * TRUE Yes * FALSE No * * Side effects: * None * *--------------------------------------------------------------------------- */ static INLINE Bool File_IsDirsep(int c) // IN: { #if defined(_WIN32) return (c == '/') || (c == '\\'); // Until util.h dependencies work out #else return c == '/'; #endif } #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _FILE_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/fileIO.h000066400000000000000000000412531321503522500240140ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * fileIO.h -- * * Host-independent wrapper for low-level fileIO functions. * */ /* * Note: * * . FileIO_[Read|Write]() [read|write]s exactly the number of bytes requested * unless an error occurs * . FileIO_Seek() supports files larger than 2 GB * . If a function returns a generic error, you can call your native function * to retrieve the last error code */ #ifndef _FILEIO_H_ #define _FILEIO_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #include #if !defined(_WIN32) #include #include #endif #include "vm_basic_types.h" #include "unicodeTypes.h" #include "iovector.h" // for struct iovec #if defined(__cplusplus) extern "C" { #endif struct FileLockToken; #if defined(_WIN32) # include typedef struct FileIODescriptor { HANDLE win32; uint32 flags; char *fileName; struct FileLockToken *lockToken; } FileIODescriptor; #else typedef struct FileIODescriptor { int posix; int flags; char *fileName; struct FileLockToken *lockToken; } FileIODescriptor; #endif typedef enum { /* distance is relative to the beginning of the file */ FILEIO_SEEK_BEGIN, /* distance is relative to the current position in the file */ FILEIO_SEEK_CURRENT, /* distance is relative to the end of the file */ FILEIO_SEEK_END, } FileIOSeekOrigin; #define FILEIO_OPEN_ACCESS_READ (1 << 0) #define FILEIO_OPEN_ACCESS_WRITE (1 << 1) /* * Use synchronous writes (no lazy buffer cache flush) */ #define FILEIO_OPEN_SYNC (1 << 2) /* * Delete the file as soon as possible (i.e. when nobody uses it anymore) */ #define FILEIO_OPEN_DELETE_ASAP (1 << 3) #define FILEIO_OPEN_UNBUFFERED (1 << 4) /* * Lock the file on open */ #define FILEIO_OPEN_LOCKED (1 << 5) /* * Asynchronous file I/O */ #define FILEIO_ASYNCHRONOUS (1 << 6) /* * Open non-blocking mode */ #define FILEIO_OPEN_NONBLOCK (1 << 7) /* * Open with more privileges */ #define FILEIO_OPEN_PRIVILEGED (1 << 8) /* * Open exclusive. * On Windows host it doesn't pass the flag FILE_SHARE_(READ|WRITE) to * CreateFile. Right now, EXCLUSIVE_READ is not used and EXCLUSIVE_WRITE * is only used by the cdrom code to implement the exclusive option. * On Linux hosts, it passes O_EXCL if both are set. * By default, we share r/w. -Maxime */ #define FILEIO_OPEN_EXCLUSIVE_READ (1 << 9) #define FILEIO_OPEN_EXCLUSIVE_WRITE (1 << 10) /* * Open sequential. * This flag only changes the behavior on Windows host. It is off by default. */ #define FILEIO_OPEN_SEQUENTIAL_SCAN (1 << 11) /* * Make IOCTL be run by root. This flag only changes the behavior on Linux * host. It is off by default. * * XXX: This has nothing to do with fileIO, but since AIOMgr shares the flags * with fileIO, I had to add it here. In some future it would be nice to * unshare the flags between the two at which point this could be fixed. * --Tommy */ #define FILEIO_OPEN_PRIVILEGED_IOCTL (1 << 12) /* * Lock the file on open with a exclusive leased lock that can be broken * (supported on ESX file systems) */ #define FILEIO_OPEN_EXCLUSIVE_LOCK (1 << 13) /* * Lock the file on open with a multiwriter leased lock that can be broken * (supported on ESX file systems) */ #define FILEIO_OPEN_MULTIWRITER_LOCK (1 << 14) /* * Lock the file on open with an SWMR leased lock that can be broken * (supported on ESX file systems) */ #define FILEIO_OPEN_SWMR_LOCK (1 << 15) /* * Valid only for MacOS. It eventually results into O_EXLOCK flag passed to open * system call. * * O_EXLOCK, O_SHLOCK behavior is tested on Mac OS X Server 10.6, kernel 10.0.0. * * | | Block devices | Regular files * |----------------------|--------------------|---------------- * | Locking behavior | mandatory | advisory * | | | * | If O_NONBLOCK absent | open doesn't block | open blocks * | | on conflicts | on conflicts */ #define FILEIO_OPEN_EXCLUSIVE_LOCK_MACOS (1 << 16) /* * Open file in APPEND-only mode. All writes go to the current end of file, * not to the current file pointer location. */ #define FILEIO_OPEN_APPEND (1 << 17) /* * Valid only on POSIXen. Don't follow a symbolic link. */ #define FILEIO_OPEN_ACCESS_NOFOLLOW (1 << 18) /* * Valid only on Windows. Set FILE_SHARE_DELETE. */ #define FILEIO_OPEN_SHARE_DELETE (1 << 19) /* * Strengths of file lock. * Advisory: * Must use FileIO plus lock flags to get locking. * Never uses kernel/fs-level lock, so naked open() bypasses locking. * Mandatory: * Requires kernel/fs-level, so naked open() respects lock. * Kernel/fs-level locks are available on ESX but not hosted. * Best: * Adaptively picks between mandatory and advisory. * Almost all cases should use the "best" lock. */ #define FILEIO_OPEN_LOCK_BEST FILEIO_OPEN_LOCKED /* historical */ #define FILEIO_OPEN_LOCK_ADVISORY (1 << 20) #define FILEIO_OPEN_LOCK_MANDATORY (1 << 21) /* * Flag passed to open() to enable use of swmr-reader locks on VMFS. This * definition must match USEROBJ_OPEN_SWMR_LOCK in user_vsiTypes.h. */ #define O_SWMR_LOCK (1 << 21) // 0x00200000 /* * OPTIMISTIC is an alternative to EXCLUSIVE and MANDATORY. It applies * only on ESX, and gives VMkernel permission to use a type of lock * called "optimistic" to speed up opens. Rule-of-thumb is to use it * only for read-only opens of small files (< 1KB). */ #define FILEIO_OPEN_OPTIMISTIC_LOCK (1 << 22) // 0x00400000 /* * Flag passed to open() to enable use of oplocks on VMFS. This definition * must match USEROBJ_OPEN_OPTIMISTIC_LOCK in user_vsiTypes.h. */ #define O_OPTIMISTIC_LOCK (1 << 22) // 0x00400000 /* * POSIX specific close the file descriptor when the program uses a variant * of the exec system call capability. This is useful in fork/exec scenarios. */ #define FILEIO_OPEN_CLOSE_ON_EXEC (1 << 23) // 0x00800000 /* * Flag passed to open() to not attempt to get the LUN attributes as part of * the open operation. Applicable only to opening of SCSI devices. This * definition must match the definition of USEROBJ_OPEN_NOATTR in * user_vsiTypes.h and FS_OPEN_NOATTR in fs_public.h */ #define O_NOATTR (1 << 26) // 0x04000000 /* * Flag passed to open() to get multiwriter VMFS lock. This definition must * match USEROBJ_OPEN_MULTIWRITER_LOCK in user_vsiTypes.h. */ #define O_MULTIWRITER_LOCK (1 << 27) // 0x08000000 /* * Flag passed to open() to get exclusive VMFS lock. This definition must * match USEROBJ_OPEN_EXCLUSIVE_LOCK in user_vsiTypes.h. */ #define O_EXCLUSIVE_LOCK (1 << 28) // 0x10000000 /* File Access check args */ #define FILEIO_ACCESS_READ (1 << 0) #define FILEIO_ACCESS_WRITE (1 << 1) #define FILEIO_ACCESS_EXEC (1 << 2) #define FILEIO_ACCESS_EXISTS (1 << 3) typedef enum { // File doesn't exist File exists FILEIO_OPEN, // error FILEIO_OPEN_EMPTY, // error size = 0 FILEIO_OPEN_CREATE, // create FILEIO_OPEN_CREATE_SAFE, // create error FILEIO_OPEN_CREATE_EMPTY, // create size = 0 } FileIOOpenAction; typedef enum { /* * Generic status codes */ /* No error */ FILEIO_SUCCESS, /* The user cancelled the operation */ FILEIO_CANCELLED, /* Generic error */ FILEIO_ERROR, /* * Status codes specific to FileIO_Open() */ /* FILEIO_OPEN_CREATE_SAFE was used and the file already existed */ FILEIO_OPEN_ERROR_EXIST, /* Couldn't obtain the requested lock */ FILEIO_LOCK_FAILED, /* Status codes specific to FileIO_Read() */ /* Tried to read beyond the end of a file */ FILEIO_READ_ERROR_EOF, /* Couldnt locate file */ FILEIO_FILE_NOT_FOUND, /* Insufficient Permissions */ FILEIO_NO_PERMISSION, /* File name too long */ FILEIO_FILE_NAME_TOO_LONG, /* * Status codes specific for FileIO_Write() */ /* Attempts to write file that exceeds maximum file size */ FILEIO_WRITE_ERROR_FBIG, /* The device containint the file has no room for the data */ FILEIO_WRITE_ERROR_NOSPC, /* Attempts to write file that exceeds user's disk quota */ FILEIO_WRITE_ERROR_DQUOT, /* * NB: Until disklib error handling is changed, there must be no more * than 16 total error codes here. */ FILEIO_ERROR_LAST, /* Must be last! */ } FileIOResult; const char *FileIO_MsgError(FileIOResult status); void FileIO_Invalidate(FileIODescriptor *file); Bool FileIO_IsValid(const FileIODescriptor *fd); FileIOResult FileIO_Create(FileIODescriptor *file, const char *pathName, int access, FileIOOpenAction action, int mode); FileIOResult FileIO_CreateRetry(FileIODescriptor *file, const char *pathName, int access, FileIOOpenAction action, int mode, uint32 maxWaitTimeMsec); FileIOResult FileIO_Open(FileIODescriptor *file, const char *pathName, int access, FileIOOpenAction action); FileIOResult FileIO_OpenRetry(FileIODescriptor *file, const char *pathName, int access, FileIOOpenAction action, uint32 maxWaitTimeMsec); uint64 FileIO_Seek(const FileIODescriptor *file, int64 distance, FileIOSeekOrigin origin); FileIOResult FileIO_Read(FileIODescriptor *file, void *buf, size_t requested, size_t *actual); FileIOResult FileIO_Write(FileIODescriptor *file, const void *buf, size_t requested, size_t *actual); char *FileIO_AtomicTempPath(const char *path); FileIOResult FileIO_AtomicTempFile(FileIODescriptor *fileFD, FileIODescriptor *tempFD); Bool FileIO_AtomicUpdate(FileIODescriptor *newFD, FileIODescriptor *currFD); int FileIO_AtomicUpdateEx(FileIODescriptor *newFD, FileIODescriptor *currFD, Bool renameOnNFS); #if !defined(VMX86_TOOLS) || !defined(__FreeBSD__) FileIOResult FileIO_Readv(FileIODescriptor *fd, struct iovec const *v, int count, size_t totalSize, size_t *bytesRead); FileIOResult FileIO_Writev(FileIODescriptor *fd, struct iovec const *v, int count, size_t totalSize, size_t *bytesWritten); #endif FileIOResult FileIO_Preadv( FileIODescriptor *fd, // IN: File descriptor struct iovec const *entries, // IN: Vector to read into int numEntries, // IN: Number of vector entries uint64 offset, // IN: Offset to start reading size_t totalSize, // IN: totalSize (bytes) in entries size_t *actual); // OUT: number of bytes read FileIOResult FileIO_Pwritev( FileIODescriptor *fd, // IN: File descriptor struct iovec const *entries, // IN: Vector to write from int numEntries, // IN: Number of vector entries uint64 offset, // IN: Offset to start writing size_t totalSize, // IN: Total size (bytes) in entries size_t *actual); // OUT: number of bytes written FileIOResult FileIO_Pread( FileIODescriptor *fd, // IN: File descriptor void *buf, // IN: Buffer to read into size_t len, // IN: Length of the buffer uint64 offset); // IN: Offset to start reading FileIOResult FileIO_Pwrite( FileIODescriptor *fd, // IN: File descriptor void const *buf, // IN: Buffer to write from size_t len, // IN: Length of the buffer uint64 offset); // IN: Offset to start writing FileIOResult FileIO_Access(const char *pathName, int accessMode); Bool FileIO_Truncate(FileIODescriptor *file, uint64 newSize); FileIOResult FileIO_Sync(const FileIODescriptor *file); FileIOResult FileIO_GetAllocSize(const FileIODescriptor *fd, uint64 *logicalBytes, uint64 *allocedBytes); int64 FileIO_GetSize(const FileIODescriptor *fd); Bool FileIO_SetAllocSize(const FileIODescriptor *fd, uint64 size); FileIOResult FileIO_GetAllocSizeByPath(const char *pathName, uint64 *logicalBytes, uint64 *allocedBytes); int64 FileIO_GetSizeByPath(const char *pathName); FileIOResult FileIO_Close(FileIODescriptor *file); FileIOResult FileIO_CloseAndUnlink(FileIODescriptor *file); uint32 FileIO_GetFlags(FileIODescriptor *file); #if defined(_WIN32) Bool FileIO_GetVolumeSectorSize(const char *name, uint32 *sectorSize); #endif Bool FileIO_SupportsFileSize(const FileIODescriptor *file, uint64 testSize); int64 FileIO_GetModTime(const FileIODescriptor *fd); FileIOResult FileIO_Lock(FileIODescriptor *file, int access); FileIOResult FileIO_Unlock(FileIODescriptor *file); /* Only users not using FileIO_Open should use these two */ void FileIO_Init(FileIODescriptor *fd, const char *pathName); void FileIO_Cleanup(FileIODescriptor *fd); const char *FileIO_ErrorEnglish(FileIOResult status); void FileIO_OptionalSafeInitialize(void); #if defined(_WIN32) FileIODescriptor FileIO_CreateFDWin32(HANDLE win32, DWORD access, DWORD attributes); #else FileIODescriptor FileIO_CreateFDPosix(int posix, int flags); int FileIO_PrivilegedPosixOpen(const char *pathName, int flags); #endif FILE *FileIO_DescriptorToStream(FileIODescriptor *fd, Bool textMode); const char *FileIO_Filename(FileIODescriptor *fd); /* *------------------------------------------------------------------------- * * FileIO_IsSuccess -- * * Returns TRUE if the error code is success. * * Result: * TRUE/FALSE. * * Side effects: * None. * *------------------------------------------------------------------------- */ #if !defined(sun) || __GNUC__ >= 3 static INLINE Bool FileIO_IsSuccess(FileIOResult res) // IN { return res == FILEIO_SUCCESS; } #else /* * XXX: Crosscompiler used for Solaris tools builds (gcc 2.95.3) complains * whenever the above definition is unused, even though that shouldn't be * a problem for static functions that are also inline. So for Solaris, we * have a separate definition that is neither static nor inline. */ Bool FileIO_IsSuccess(FileIOResult res); #endif Bool FileIO_SupportsPrealloc(const char *pathName, Bool fsCheck); #if defined(__cplusplus) } // extern "C" #endif #endif // _FILEIO_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/fileLock.h000066400000000000000000000052421321503522500243730ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * fileLock.h -- * * Interface to file locking functions */ #ifndef _FILELOCK_H_ #define _FILELOCK_H_ #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #include "unicodeTypes.h" #include "msgList.h" #if defined(__cplusplus) extern "C" { #endif /* The default time, in milliseconds, to wait for a lock before giving up */ #define FILELOCK_DEFAULT_WAIT (vmx86_server ? 7000 : 3500) /* The wait time that provides "try lock" functionality */ #define FILELOCK_TRYLOCK_WAIT 0 /* Wait "forever" to acquire the lock (maximum uint32) */ #define FILELOCK_INFINITE_WAIT 0xFFFFFFFF /* * This is the maximum path length overhead that the file locking code * may introduce via all of its components. */ #define FILELOCK_OVERHEAD 15 /* File locking functions */ typedef struct FileLockToken FileLockToken; char *FileLock_TokenPathName(const FileLockToken *fileLockToken); FileLockToken *FileLock_Lock(const char *filePath, const Bool readOnly, const uint32 maxWaitTimeMsec, int *err, MsgList **msgs); Bool FileLock_Unlock(const FileLockToken *lockToken, int *err, MsgList **msgs); Bool FileLock_IsLocked(const char *filePath, int *err, MsgList **msgs); Bool FileLock_Remove(const char *filePath, int *err, MsgList **msgs); Bool FileLock_CleanupVM(const char *cfgfilePath, int *err, MsgList **msgs); /* Device locking functions, for compatibility */ int FileLock_LockDevice(const char *device); Bool FileLock_UnlockDevice(const char *device); #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _FILELOCK_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/file_extensions.h000066400000000000000000000077101321503522500260430ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _FILE_EXTENSIONS_H_ #define _FILE_EXTENSIONS_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" /* * Virtual disk and related file types. */ #define DISK_FILE_EXTENSION "vmdk" #define REDO_FILE_EXTENSION "REDO" #define SWAP_FILE_EXTENSION "vswp" /* * VM configuration and related file types. */ #define CONFIG_FILE_EXTENSION "vmx" // VM configuration file #define CONFIG_ALT_FILE_EXTENSION "cfg" // Obsolete synonym for .vmx #define EXTENDED_CONFIG_FILE_EXTENSION "vmxf" // Foundry metadata #define MANAGED_CONFIG_FILE_EXTENSION "vmxa" // ACE Master #define VRM_CONFIG_FILE_EXTENSION "vmx" // ACE Instance #define VPX_TEMPLATE_EXTENSION "vmtx" // VirtualCenter template #define TEAM_FILE_EXTENSION "vmtm" // Foundry VM team #define POLICY_FILE_EXTENSION "vmpl" // ACE/VRM policy file #define BUNDLE_FILE_EXTENSION "vmwarevm" // VM configuration bundle directory #define SIDECAR_FILE_EXTENSION "vmfd" // Virtual machine filter data aka sidecar #define HBRPERSIST_FILE_EXTENSION "psf" // HBR/VR persistent state file /* * Snapshot and related file types. */ #define MAINMEM_FILE_EXTENSION "vmem" #define SUSPEND_FILE_EXTENSION "vmss" #define CHECKPOINT_FILE_EXTENSION "vmsn" #define VPLAY_FILE_EXTENSION "vmlog" #define SNAPSHOT_METADATA_EXTENSION "vmsd" #define CHECKPOINT_FILE_EXTENSION_OLD "cpt" // Obsolete synonym for vmsn /* * Foundry scripts. */ #define VIX_ACTION_FILE_EXTENSION "vmac" // Foundry action #define VIX_BATCH_FILE_EXTENSION "vmba" // Foundry batch script /* * ACE/VRM management transit files. */ #define VRM_HOTFIXREQ_FILE_EXTENSION "vmhr" // ACE hotfix request #define VRM_HOTFIX_FILE_EXTENSION "vmhf" // ACE hotfix response /* * VM Download. */ #define RVM_DOWNLOAD_FILE_EXTENSION "vmdownload" // Downloaded file #define RVM_STATE_FILE_EXTENSION "vmstate" // Download metadata #define DOWNLOAD_BUNDLE_FILE_EXTENSION "vmdownload" // VM download bundle directory /* * Other file types. */ #define SCREENSHOT_EXTENSION "png" #define NVRAM_EXTENSION "nvram" #define LOCK_FILE_EXTENSION "lck" #define VIRTUALPC_EXTENSION "vmc" #define SYMANTEC_LIVESTATE_EXTENSION "sv2i" #define STORAGECRAFT_SHADOWSTOR_EXTENSION "spf" #define ACRONIS_EXTENSION "tib" #define OPEN_VM_FORMAT_EXTENSION "ovf" #define ARCHIVED_OPEN_VM_FORMAT_EXTENSION "ova" #define NAMESPACEDB_EXTENSION "db" // "xvm" // VMware console configuration file /* * Extensions repeated with leading period. * Moved from bora/public/dumper.h. */ #define STDPATH_EXT "." SUSPEND_FILE_EXTENSION #define CPTPATH_EXT "." CHECKPOINT_FILE_EXTENSION #define CPTPATH_EXT_OLD "." CHECKPOINT_FILE_EXTENSION_OLD #define CONFIG_EXT "." CONFIG_FILE_EXTENSION #define CONFIG_EXT_ALT "." CONFIG_ALT_FILE_EXTENSION #define CONFIG_EXT_MGD "." MANAGED_CONFIG_FILE_EXTENSION #define CONFIG_EXT_TEAM "." TEAM_FILE_EXTENSION #define VPX_TEMPL_EXT "." VPX_TEMPLATE_EXTENSION #define SCREENSHOT_EXT "." SCREENSHOT_EXTENSION #define SWAPPATH_EXT "." SWAP_FILE_EXTENSION #endif /* _FILE_EXTENSIONS_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/ghIntegrationCommon.h000066400000000000000000000024151321503522500266150ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2014 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * ghIntegrationCommon.h -- * * Common data structures and definitions used by Guest/Host Integration. */ #ifndef _GHINTEGRATIONCOMMON_H_ #define _GHINTEGRATIONCOMMON_H_ /* * Common data structures and definitions used by Guest/Host Integration. */ #define GHI_HGFS_SHARE_URL_UTF8 "x-vmware-share://" #define GHI_HGFS_SHARE_URL _T(GHI_HGFS_SHARE_URL_UTF8) #endif // ifndef _GHINTEGRATIONCOMMON_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/glibUtils.h000066400000000000000000000052531321503522500246030ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2011-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _GLIBUTILS_H_ #define _GLIBUTILS_H_ #if defined(__cplusplus) extern "C" { #endif /** * @file glibUtils.h * * A collection of utility functions that depend only on glib. * * These functions are guaranteed to have no dependencies on bora/lib libraries * or headers. */ #include #if defined(_WIN32) # include #endif /** * @brief Description for a logger. * * Contains information about a logger. The properties here are aimed at * helping the logging code using this library to construct and appropriate * log message depending on the output being used. * * For example, some sinks (like syslog) already add a timestamp to every log * message. So if the @a addsTimestamp field is TRUE, the logging code can * choose to rely on that and not add a redundant timestamp field to the log * message. */ typedef struct GlibLogger { gboolean shared; /**< Output is shared with other processes. */ gboolean addsTimestamp; /**< Output adds timestamp automatically. */ GLogFunc logfn; /**< The function that writes to the output. */ GDestroyNotify dtor; /**< Destructor. */ } GlibLogger; GlibLogger * GlibUtils_CreateFileLogger(const char *path, gboolean append, guint maxSize, guint maxFiles); GlibLogger * GlibUtils_CreateStdLogger(void); #if defined(_WIN32) gboolean GlibUtils_AttachConsole(void); GlibLogger * GlibUtils_CreateDebugLogger(void); GlibLogger * GlibUtils_CreateEventLogger(const wchar_t *source, DWORD eventId); #else GlibLogger * GlibUtils_CreateSysLogger(const char *domain, const char *facility); #endif #if defined(__cplusplus) } // extern "C" #endif #endif /* _GLIBUTILS_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/guestApp.h000066400000000000000000000025651321503522500244400ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * guestApp.h -- * * Utility functions common to all guest applications */ #ifndef __GUESTAPP_H__ # define __GUESTAPP_H__ #include "vm_basic_types.h" #if defined(_WIN32) #include #endif #ifdef __cplusplus extern "C" { #endif const char * GuestApp_GetDefaultScript(const char *confName); // IN #ifdef _WIN32 LPWSTR GuestApp_GetInstallPathW(void); #endif char * GuestApp_GetInstallPath(void); char * GuestApp_GetConfPath(void); #ifdef __cplusplus } #endif #endif /* __GUESTAPP_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/guestInfo.h000066400000000000000000000057371321503522500246170ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /** * @file guestInfo.h * * Common declarations that aid in sending guest information to the host. */ /** * @defgroup vmtools_guestInfoAPI GuestInfo API Reference * @{ * * @brief APIs implementing the GuestInfo feature. * * Definitions below are used for communication across the backdoor between * the VMware Tools Service (running in the guest) and the VMX (running in * the host). * * @sa @ref vmtools_guestInfo for a high level overview. */ #ifndef _GUEST_INFO_H_ #define _GUEST_INFO_H_ #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #include "vm_basic_types.h" #include "dbllnklst.h" #include "guestrpc/nicinfo.h" #define GUEST_INFO_COMMAND "SetGuestInfo" #define MAX_VALUE_LEN 100 #define MAX_NICS 16 #define MAX_IPS 8 // Max number of IP addresses for a single NIC #define INFO_IPADDRESS_V2_MAX_IPS 64 #define MAC_ADDR_SIZE 19 #define IP_ADDR_SIZE 16 #define PARTITION_NAME_SIZE MAX_VALUE_LEN /* Value to be used when "primary" IP address is indeterminable. */ #define GUESTINFO_IP_UNKNOWN "unknown" typedef enum { INFO_ERROR, /* Zero is unused so that errors in atoi can be caught. */ INFO_DNS_NAME, INFO_IPADDRESS, INFO_DISK_FREE_SPACE, INFO_BUILD_NUMBER, INFO_OS_NAME_FULL, INFO_OS_NAME, INFO_UPTIME, INFO_MEMORY, INFO_IPADDRESS_V2, INFO_IPADDRESS_V3, INFO_MAX } GuestInfoType; typedef enum { INFO_IP_ADDRESS_FAMILY_IPV4, INFO_IP_ADDRESS_FAMILY_IPV6 } GuestInfoIPAddressFamilyType; typedef struct NicEntryV1 { unsigned int numIPs; char macAddress[MAC_ADDR_SIZE]; // In the format "12-23-34-45-56-67" char ipAddress[MAX_IPS][IP_ADDR_SIZE]; } NicEntryV1; typedef struct GuestNicInfoV1 { unsigned int numNicEntries; NicEntryV1 nicList[MAX_NICS]; } GuestNicInfoV1; typedef #include "vmware_pack_begin.h" struct _PartitionEntry { uint64 freeBytes; uint64 totalBytes; char name[PARTITION_NAME_SIZE]; } #include "vmware_pack_end.h" PartitionEntry, *PPartitionEntry; typedef struct _DiskInfo { unsigned int numEntries; PPartitionEntry partitionList; } GuestDiskInfo, *PGuestDiskInfo; /** * @} */ #endif // _GUEST_INFO_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/guestStats.h000066400000000000000000000261751321503522500250210ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /** * @file guestStats.h * * Common declarations that aid in sending guest statistics to the vmx * and may be further to vmkernel. */ #ifndef _GUEST_STATS_H_ #define _GUEST_STATS_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include "vm_assert.h" #include "vm_basic_types.h" /* * Version 1: Legacy data * Version 2: Dead * Version 3: Dead * Version 4: Dead * Version 5: Legacy structure followed by one or more GuestStat * structures and data. */ #define GUESTMEMINFO_V1 1 #define GUESTMEMINFO_V2 2 #define GUESTMEMINFO_V3 3 #define GUESTMEMINFO_V4 4 #define GUESTMEMINFO_V5 5 /* * Flags for legacy GuestMemInfo * * This is deprecated. All new values are returned via a GuestStat list. */ #define MEMINFO_MEMTOTAL (1 << 0) #define MEMINFO_DEPRECATED1 (1 << 1) #define MEMINFO_DEPRECATED2 (1 << 2) #define MEMINFO_DEPRECATED3 (1 << 3) #define MEMINFO_DEPRECATED4 (1 << 4) #define MEMINFO_DEPRECATED5 (1 << 5) #define MEMINFO_DEPRECATED6 (1 << 6) #define MEMINFO_DEPRECATED7 (1 << 7) #define MEMINFO_DEPRECATED8 (1 << 8) #define MEMINFO_DEPRECATED9 (1 << 9) #define MEMINFO_HUGEPAGESTOTAL (1 << 10) #define MEMINFO_DEPRECATED10 (1 << 11) #define MEMINFO_DEPRECATED11 (1 << 12) /* * Legacy GuestMemInfo structure. * * It should stay the same to ensure binary compatibility. */ typedef #include "vmware_pack_begin.h" struct GuestMemInfo { uint32 version; ///< MemInfo structure version. uint32 flags; ///< Indicates which stats are valid. uint64 memTotal; ///< Total physical memory in Kb. uint64 deprecated1[9]; ///< No longer used. uint64 hugePagesTotal; ///< Total number of huge pages. uint64 deprecated2[2]; ///< No longer used. } #include "vmware_pack_end.h" GuestMemInfo; /* * A stat begins with a header. The header has a mask which says what data * follows. Each datum has a size field which says how much data follows so it * can be used or ignored. The order of the data that follows is that of the * bits, lowest order bit to highest. */ typedef enum { GUEST_DATUM_PRAGMA = 0x0001, // escape hatch (future expansion) GUEST_DATUM_NAMESPACE = 0x0002, // UTF8 string GUEST_DATUM_ID = 0x0004, // uint8 - uint64 GUEST_DATUM_VALUE_TYPE_ENUM = 0x0008, // uint8 - uint32 GUEST_DATUM_VALUE_TYPE_STRING = 0x0010, // UTF8 string GUEST_DATUM_VALUE_UNIT_ENUM = 0x0020, // uint8 - uint32 GUEST_DATUM_VALUE_UNIT_STRING = 0x0040, // UTF8 string GUEST_DATUM_VALUE = 0x0080, // value data } GuestDatum; typedef #include "vmware_pack_begin.h" struct GuestStatHeader { GuestDatum datumFlags; // Indicates how many and which data follow } #include "vmware_pack_end.h" GuestStatHeader; typedef #include "vmware_pack_begin.h" struct GuestDatumHeader { uint16 dataSize; // dataSize - May be zero char data[0]; // data - if dataSize is not zero. } #include "vmware_pack_end.h" GuestDatumHeader; /* * Units datum enum. * Note: The entirety (all bits) of the units must always be understood by a client. * * First we define some modifiers, then the enum itself * * bits 0-5 define base types (information, time, etc.) * bits 6-10 are modifiers, four of which are reserved (in the future, we could * define two of them as custom modifiers, for things like changing the radix from 2^10 * to 10^3 for storage, or for denoting rates are in 100ns units). */ #define GuestUnitsModifier_Rate 0x0040 #define GuestUnitsModifier_Reserved0 0x0080 #define GuestUnitsModifier_Reserved1 0x0100 #define GuestUnitsModifier_Reserved2 0x0200 #define GuestUnitsModifier_Reserved3 0x0400 /* * bits 11-15 are scale modifiers: * This includes common scales: (P)ositive powers, (N)egative powers, * and (C)ustom scales (bits, pages, etc.), which are always type specific. */ #define GuestUnitsScale_P0 0x0000 #define GuestUnitsScale_P1 0x0800 #define GuestUnitsScale_P2 0x1000 #define GuestUnitsScale_P3 0x1800 #define GuestUnitsScale_P4 0x2000 #define GuestUnitsScale_P5 0x2800 #define GuestUnitsScale_P6 0x3000 #define GuestUnitsScale_Reserved0 0x3800 #define GuestUnitsScale_N1 0x4000 #define GuestUnitsScale_N2 0x4800 #define GuestUnitsScale_N3 0x5000 #define GuestUnitsScale_N4 0x5800 #define GuestUnitsScale_N5 0x6000 #define GuestUnitsScale_N6 0x6800 #define GuestUnitsScale_Reserved1 0x7000 #define GuestUnitsScale_Reserved2 0x7800 #define GuestUnitsScale_C0 0x8000 #define GuestUnitsScale_C1 0x8800 #define GuestUnitsScale_C2 0x9000 #define GuestUnitsScale_C3 0x9800 // 0xA000-0xF800 are reserved. typedef enum { GuestUnitsInvalid = 0, // Must never be sent GuestUnitsNone = 1, // A valid value, but not any of the below units. GuestUnitsNumber = 2, // default radix is 1000 GuestUnitsInformation = 3, // default radix is 1024 GuestUnitsDuration = 4, // default radix is 1000 GuestUnitsCycles = 5, // default radix is 1000 GuestUnitsBytes = GuestUnitsInformation | GuestUnitsScale_P0, GuestUnitsKiB = GuestUnitsInformation | GuestUnitsScale_P1, GuestUnitsMiB = GuestUnitsInformation | GuestUnitsScale_P2, GuestUnitsPages = GuestUnitsInformation | GuestUnitsScale_C0, GuestUnitsHugePages = GuestUnitsInformation | GuestUnitsScale_C1, GuestUnitsBytesPerSecond = GuestUnitsBytes | GuestUnitsModifier_Rate, GuestUnitsKiBPerSecond = GuestUnitsKiB | GuestUnitsModifier_Rate, GuestUnitsMiBPerSecond = GuestUnitsMiB | GuestUnitsModifier_Rate, GuestUnitsPagesPerSecond = GuestUnitsPages | GuestUnitsModifier_Rate, GuestUnitsHugePagesPerSecond = GuestUnitsHugePages | GuestUnitsModifier_Rate, GuestUnitsAttoSeconds = GuestUnitsDuration | GuestUnitsScale_N6, GuestUnitsFemtoSeconds = GuestUnitsDuration | GuestUnitsScale_N5, GuestUnitsPicoSeconds = GuestUnitsDuration | GuestUnitsScale_N4, GuestUnitsNanoSeconds = GuestUnitsDuration | GuestUnitsScale_N3, GuestUnitsMicroSeconds = GuestUnitsDuration | GuestUnitsScale_N2, GuestUnitsMilliSeconds = GuestUnitsDuration | GuestUnitsScale_N1, GuestUnitsSeconds = GuestUnitsDuration | GuestUnitsScale_P0, GuestUnitsHz = GuestUnitsCycles | GuestUnitsScale_P0 | GuestUnitsModifier_Rate, GuestUnitsKiloHz = GuestUnitsCycles | GuestUnitsScale_P1 | GuestUnitsModifier_Rate, GuestUnitsMegaHz = GuestUnitsCycles | GuestUnitsScale_P2 | GuestUnitsModifier_Rate, GuestUnitsGigaHz = GuestUnitsCycles | GuestUnitsScale_P3 | GuestUnitsModifier_Rate, GuestUnitsTeraHz = GuestUnitsCycles | GuestUnitsScale_P4 | GuestUnitsModifier_Rate, GuestUnitsPercent = GuestUnitsNumber | GuestUnitsScale_C0, // integers: must be 0...100; FP: 0.0...1.0 GuestUnitsNumberPerSecond = GuestUnitsNumber | GuestUnitsModifier_Rate, } GuestValueUnits; /* * Data type datum enum. * Note: The entirety (all bits) of the type must always be understood by a client. * * Bits 0-5 are for types. * Bits 6-15 are reserved. In the future, one bit will denote arrays. */ #define GuestTypeModifier_Reserved0 0x0040 // More Reserved1-9 not shown. typedef enum { GuestTypeInvalid, // Must never be sent GuestTypeNil, // A stat that has no value GuestTypeInt8, // Little endian GuestTypeUint8, // Little endian GuestTypeInt16, // Little endian GuestTypeUint16, // Little endian GuestTypeInt32, // Little endian GuestTypeUint32, // Little endian GuestTypeInt64, // Little endian GuestTypeUint64, // Little endian GuestTypeFloat, // IEEE 754 GuestTypeDouble, // IEEE 754 GuestTypeString, // NUL terminated UTF8 GuestTypeBinary, // Binary blob } GuestValueType; /* * Defines the namespace used for guest tools buildin query. */ #define GUEST_TOOLS_NAMESPACE "_tools/v1" /* * Defined stat IDs for guest tools builtin query. * See vmx/vigorapi/GuestStats.java for documentation * * NOTE: These IDs are relative to GUEST_TOOLS_NAMESPACE * NOTE: DO NOT re-order or remove the IDs. IDs can only be added to the end, * unless you make the totally backward-compatibility breaking change * of bumping the namespace version. */ #define GUEST_STAT_TOOLS_IDS \ DEFINE_GUEST_STAT(GuestStatID_Invalid, 0, "__INVALID__") \ DEFINE_GUEST_STAT(GuestStatID_None, 1, "__NONE__") \ DEFINE_GUEST_STAT(GuestStatID_ContextSwapRate, 2, "guest.contextSwapRate") \ DEFINE_GUEST_STAT(GuestStatID_MemActiveFileCache, 3, "guest.mem.activeFileCache") \ DEFINE_GUEST_STAT(GuestStatID_MemFree, 4, "guest.mem.free") \ DEFINE_GUEST_STAT(GuestStatID_MemNeeded, 5, "guest.mem.needed") \ DEFINE_GUEST_STAT(GuestStatID_MemPhysUsable, 6, "guest.mem.physUsable") \ DEFINE_GUEST_STAT(GuestStatID_PageInRate, 7, "guest.page.inRate") \ DEFINE_GUEST_STAT(GuestStatID_PageOutRate, 8, "guest.page.outRate") \ DEFINE_GUEST_STAT(GuestStatID_SwapSpaceRemaining, 9, "guest.swap.spaceRemaining") \ DEFINE_GUEST_STAT(GuestStatID_PhysicalPageSize, 10, "guest.page.size") \ DEFINE_GUEST_STAT(GuestStatID_HugePageSize, 11, "guest.hugePage.size") \ DEFINE_GUEST_STAT(GuestStatID_Linux_HugePagesTotal, 12, "guest.hugePage.total") \ DEFINE_GUEST_STAT(GuestStatID_Max, 13, "__MAX__") /* * Define stats enumeration */ #undef DEFINE_GUEST_STAT #define DEFINE_GUEST_STAT(x,y,z) x, typedef enum GuestStatToolsID { GUEST_STAT_TOOLS_IDS } GuestStatToolsID; /* * Enforce ordering and compactness of the enumeration */ #undef DEFINE_GUEST_STAT #define DEFINE_GUEST_STAT(x,y,z) ASSERT_ON_COMPILE(x==y); MY_ASSERTS(GUEST_STAT_IDS_ARE_WELL_ORDERED, GUEST_STAT_TOOLS_IDS) #undef DEFINE_GUEST_STAT #endif // _GUEST_STATS_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/guest_msg_def.h000066400000000000000000000067621321503522500254660ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * guest_msg_def.h -- * * Second layer of the internal communication channel between guest * applications and vmware * */ #ifndef _GUEST_MSG_DEF_H_ #define _GUEST_MSG_DEF_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" /* Basic request types */ typedef enum { MESSAGE_TYPE_OPEN, MESSAGE_TYPE_SENDSIZE, MESSAGE_TYPE_SENDPAYLOAD, MESSAGE_TYPE_RECVSIZE, MESSAGE_TYPE_RECVPAYLOAD, MESSAGE_TYPE_RECVSTATUS, MESSAGE_TYPE_CLOSE, } MessageType; /* Reply statuses */ /* The basic request succeeded */ #define MESSAGE_STATUS_SUCCESS 0x0001 /* vmware has a message available for its party */ #define MESSAGE_STATUS_DORECV 0x0002 /* The channel has been closed */ #define MESSAGE_STATUS_CLOSED 0x0004 /* vmware removed the message before the party fetched it */ #define MESSAGE_STATUS_UNSENT 0x0008 /* A checkpoint occurred */ #define MESSAGE_STATUS_CPT 0x0010 /* An underlying device is powering off */ #define MESSAGE_STATUS_POWEROFF 0x0020 /* vmware has detected a timeout on the channel */ #define MESSAGE_STATUS_TIMEOUT 0x0040 /* vmware supports high-bandwidth for sending and receiving the payload */ #define MESSAGE_STATUS_HB 0x0080 /* * This mask defines the status bits that the guest is allowed to set; * we use this to mask out all other bits when receiving the status * from the guest. Otherwise, the guest can manipulate VMX state by * setting status bits that are only supposed to be changed by the * VMX. See bug 45385. */ #define MESSAGE_STATUS_GUEST_MASK MESSAGE_STATUS_SUCCESS /* * Max number of channels. * Unfortunately this has to be public because the monitor part * of the backdoor needs it for its trivial-case optimization. [greg] */ #define GUESTMSG_MAX_CHANNEL 8 /* Flags to open a channel. --hpreg */ #define GUESTMSG_FLAG_COOKIE 0x80000000 #define GUESTMSG_FLAG_ALL GUESTMSG_FLAG_COOKIE /* * Maximum size of incoming message. This is to prevent denial of host service * attacks from guest applications. */ #define GUESTMSG_MAX_IN_SIZE (64 * 1024) #endif /* _GUEST_MSG_DEF_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/guest_os.h000066400000000000000000000615171321503522500245020ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _GUEST_OS_H_ #define _GUEST_OS_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #include "guest_os_tables.h" #if defined(__cplusplus) extern "C" { #endif /* * There's no practical max to the number of guests that can be defined in * the list below (guest IDs are limited to 2^32), but there is a maximum * of MAXGOSSET guests that can comprise a set, such as ALLLINUX, ALLDARWIN, * or ALLWIN64. * * Be conservative and only declare entries in this list if you need to refer * to the guest specifically in vmx/main/guest_os.c, * vmcore/vmx/main/monitorControl.c, or similar. Don't rely on every supported * guest having an entry in this list. */ typedef enum GuestOSType { GUEST_OS_BASE = 0x5000, GUEST_OS_BASE_MINUS_ONE = 0x4fff, /* So that ANY is equal to BASE */ #define GOT(_name) _name, GUEST_OS_TYPE_GEN #undef GOT } GuestOSType; /* * Maximum number of guests in a set, must be <= LIST_SIZE in geninfo.h */ #define MAXGOSSET 64 typedef enum GuestOSFamilyType { GUEST_OS_FAMILY_ANY = 0x0000, GUEST_OS_FAMILY_LINUX = 0x0001, GUEST_OS_FAMILY_WINDOWS = 0x0002, GUEST_OS_FAMILY_WIN9X = 0x0004, GUEST_OS_FAMILY_WINNT = 0x0008, GUEST_OS_FAMILY_WIN2000 = 0x0010, GUEST_OS_FAMILY_WINXP = 0x0020, GUEST_OS_FAMILY_WINNET = 0x0040, GUEST_OS_FAMILY_NETWARE = 0x0080, GUEST_OS_FAMILY_DARWIN = 0x0100 } GuestOSFamilyType; #define ALLOS GUEST_OS_ANY #define BS(suf) GUEST_OS_##suf #define GOS_IN_SET(gos, ...) Gos_InSet(gos, __VA_ARGS__, 0) #define GOS_IN_SET_ARRAY(gos, set) Gos_InSetArray(gos, set) Bool Gos_InSet(uint32 gos, ...); Bool Gos_InSetArray(uint32 gos, const uint32 *set); #define ALLWIN9X BS(WIN95), BS(WIN98), BS(WINME) #define ALLWIN2000 BS(WIN2000) #define ALLWINXP32 BS(WINXP) #define ALLWINXP64 BS(WINXPPRO_64) #define ALLWINXP ALLWINXP32, ALLWINXP64 #define ALLFREEBSD BS(FREEBSD), BS(FREEBSD_64), \ BS(FREEBSD11), BS(FREEBSD11_64), \ BS(FREEBSD12), BS(FREEBSD12_64) #define ALLWINNET32 BS(WINNET) #define ALLWINNET64 BS(WINNET_64) #define ALLWINNET ALLWINNET32, ALLWINNET64 #define ALLWINLONGHORN32 BS(LONGHORN) #define ALLWINLONGHORN64 BS(LONGHORN_64) #define ALLWINLONGHORN ALLWINLONGHORN32, ALLWINLONGHORN64 #define ALLWINVISTA32 BS(WINVISTA) #define ALLWINVISTA64 BS(WINVISTA_64) #define ALLWINVISTA ALLWINVISTA32, ALLWINVISTA64 #define ALLWIN2008R2_64 BS(WIN2008R2_64) #define ALLWIN2008R2 ALLWIN2008R2_64 #define ALLWINSEVEN32 BS(WINSEVEN) #define ALLWINSEVEN64 BS(WINSEVEN_64) #define ALLWINSEVEN ALLWINSEVEN32, ALLWINSEVEN64 #define ALLWINEIGHTSERVER64 BS(WINEIGHTSERVER_64) #define ALLWINEIGHTSERVER ALLWINEIGHTSERVER64 #define ALLWINEIGHTCLIENT32 BS(WINEIGHT) #define ALLWINEIGHTCLIENT64 BS(WINEIGHT_64) #define ALLWINEIGHTCLIENT ALLWINEIGHTCLIENT32, ALLWINEIGHTCLIENT64 #define ALLWINEIGHT ALLWINEIGHTSERVER, ALLWINEIGHTCLIENT #define ALLWINTENSERVER64 BS(WINTENSERVER_64) #define ALLWINTENSERVER ALLWINTENSERVER64 #define ALLWINTENCLIENT32 BS(WINTEN) #define ALLWINTENCLIENT64 BS(WINTEN_64) #define ALLWINTENCLIENT ALLWINTENCLIENT32, ALLWINTENCLIENT64 #define ALLWINTEN32 ALLWINTENCLIENT32 #define ALLWINTEN64 ALLWINTENCLIENT64, ALLWINTENSERVER #define ALLWINTEN ALLWINTENCLIENT, ALLWINTENSERVER #define ALLHYPER_V BS(HYPER_V) #define ALLWINVISTA_OR_HIGHER ALLWINVISTA, ALLWINLONGHORN, \ ALLWIN2008R2, ALLWINSEVEN, \ ALLWINEIGHTSERVER, ALLWINEIGHTCLIENT, \ ALLWINTENSERVER, ALLWINTENCLIENT, \ ALLHYPER_V \ #define ALLWINNT32 BS(WINNT), ALLWIN2000, ALLWINXP32, \ ALLWINNET32, ALLWINVISTA32, \ ALLWINLONGHORN32, ALLWINSEVEN32, \ ALLWINEIGHTCLIENT32, ALLWINTENCLIENT32 #define ALLWINNT64 ALLWINXP64, ALLWINNET64, \ ALLWINVISTA64, ALLWINLONGHORN64, \ ALLWINSEVEN64, ALLWIN2008R2_64, \ ALLWINEIGHTCLIENT64, ALLWINEIGHTSERVER,\ ALLWINTENCLIENT64, ALLWINTENSERVER, \ ALLHYPER_V #define ALLWINNT ALLWINNT32, ALLWINNT64 #define ALLWIN32 ALLWIN9X, ALLWINNT32 #define ALLWIN64 ALLWINNT64 #define ALLWIN ALLWIN32, ALLWIN64 #define ALLOTHER BS(OTHER), BS(OTHER_64) #define ALLPHOTON BS(PHOTON_64) #define ALLSOLARIS11_OR_HIGHER \ BS(SOLARIS11_64) #define ALLSOLARIS10_OR_HIGHER \ BS(SOLARIS10), BS(SOLARIS10_64), \ ALLSOLARIS11_OR_HIGHER #define ALLSOLARIS BS(SOLARIS_6_AND_7), \ BS(SOLARIS8), \ BS(SOLARIS9), \ ALLSOLARIS10_OR_HIGHER #define ALLNETWARE BS(NETWARE4), BS(NETWARE5), BS(NETWARE6) #define ALL26XLINUX32 BS(OTHER26XLINUX), BS(DEBIAN), BS(RHEL), \ BS(UBUNTU), BS(CENTOS), BS(ORACLE) #define ALL26XLINUX64 BS(OTHER26XLINUX_64), BS(DEBIAN_64), \ BS(RHEL_64), BS(CENTOS_64), BS(ORACLE_64) #define ALL3XLINUX32 BS(OTHER3XLINUX), BS(CENTOS6), BS(ORACLE6) #define ALL3XLINUX64 BS(OTHER3XLINUX_64), \ BS(CENTOS6_64), BS(CENTOS7_64), \ BS(ORACLE6_64), BS(ORACLE7_64) #define ALL4XLINUX32 BS(OTHER4XLINUX) #define ALL4XLINUX64 BS(OTHER4XLINUX_64), BS(PHOTON_64), \ BS(CENTOS8_64), BS(ORACLE8_64) #define ALLVMKERNEL BS(VMKERNEL), BS(VMKERNEL5), BS(VMKERNEL6), \ BS(VMKERNEL65) #define ALLLINUX32 BS(OTHER24XLINUX), ALL26XLINUX32, ALL3XLINUX32, \ ALL4XLINUX32, BS(OTHERLINUX), BS(VMKERNEL) #define ALLLINUX64 BS(OTHER24XLINUX_64), ALL26XLINUX64, \ ALL3XLINUX64, ALL4XLINUX64, BS(OTHERLINUX_64) #define ALLLINUX ALLLINUX32, ALLLINUX64 #define ALLDARWIN32 BS(DARWIN9), BS(DARWIN10), BS(DARWIN11) #define ALLDARWIN64 BS(DARWIN9_64), BS(DARWIN10_64), \ BS(DARWIN11_64), BS(DARWIN12_64), \ BS(DARWIN13_64), BS(DARWIN14_64), \ BS(DARWIN15_64), BS(DARWIN16_64), \ BS(DARWIN17_64), BS(DARWIN18_64) #define ALLDARWIN ALLDARWIN32, ALLDARWIN64 #define ALL64 ALLWIN64, ALLLINUX64, BS(SOLARIS10_64), \ BS(FREEBSD_64), BS(FREEBSD11_64), \ BS(FREEBSD12_64), BS(OTHER_64), \ ALLDARWIN64, ALLVMKERNEL #define ALLECOMSTATION BS(ECOMSTATION), BS(ECOMSTATION2) #define ALLOS2 BS(OS2), ALLECOMSTATION /* * These constants are generated by GuestInfoGetOSName which is in * the bora-vmsoft subtree. */ /* vmkernel (ESX) */ #define STR_OS_ESX_4 "VMware ESX/ESXi 4.x" #define STR_OS_ESX_5 "VMware ESXi 5.x" #define STR_OS_ESX_6 "VMware ESXi 6.0" #define STR_OS_ESX_65 "VMware ESXi 6.5" /* Linux */ #define STR_OS_ANNVIX "Annvix" #define STR_OS_ARCH "Arch" #define STR_OS_ARKLINUX "Arklinux" #define STR_OS_ASIANUX_3 "asianux3" #define STR_OS_ASIANUX_4 "asianux4" #define STR_OS_ASIANUX_5 "asianux5" #define STR_OS_ASIANUX_7 "asianux7" #define STR_OS_ASIANUX_8 "asianux8" #define STR_OS_AUROX "Aurox" #define STR_OS_ASIANUX "asianux" #define STR_OS_BLACKCAT "BlackCat" #define STR_OS_CENTOS "centos" #define STR_OS_CENTOS6 "centos6" #define STR_OS_CENTOS7 "centos7" #define STR_OS_CENTOS8 "centos8" #define STR_OS_COBALT "Cobalt" #define STR_OS_CONECTIVA "Conectiva" #define STR_OS_DEBIAN "Debian" #define STR_OS_DEBIAN_4 "debian4" #define STR_OS_DEBIAN_5 "debian5" #define STR_OS_DEBIAN_6 "debian6" #define STR_OS_DEBIAN_7 "debian7" #define STR_OS_DEBIAN_7_1 "debian7" #define STR_OS_DEBIAN_8 "debian8" #define STR_OS_DEBIAN_9 "debian9" #define STR_OS_DEBIAN_10 "debian10" #define STR_OS_FEDORA "Fedora" #define STR_OS_GENTOO "Gentoo" #define STR_OS_IMMUNIX "Immunix" #define STR_OS_LINUX "linux" #define STR_OS_LINUX_FROM_SCRATCH "Linux-From-Scratch" #define STR_OS_LINUX_FULL "Other Linux" #define STR_OS_LINUX_PPC "Linux-PPC" #define STR_OS_MANDRAKE "mandrake" #define STR_OS_MANDRAKE_FULL "Mandrake Linux" #define STR_OS_MANDRIVA "mandriva" #define STR_OS_MKLINUX "MkLinux" #define STR_OS_NOVELL "nld9" #define STR_OS_NOVELL_FULL "Novell Linux Desktop 9" #define STR_OS_ORACLE6 "oraclelinux6" #define STR_OS_ORACLE7 "oraclelinux7" #define STR_OS_ORACLE8 "oraclelinux8" #define STR_OS_ORACLE "oraclelinux" #define STR_OS_OTHER "otherlinux" #define STR_OS_OTHER_FULL "Other Linux" #define STR_OS_OTHER_24 "other24xlinux" #define STR_OS_OTHER_24_FULL "Other Linux 2.4.x kernel" #define STR_OS_OTHER_26 "other26xlinux" #define STR_OS_OTHER_26_FULL "Other Linux 2.6.x kernel" #define STR_OS_OTHER_3X "other3xlinux" #define STR_OS_OTHER_3X_FULL "Other Linux 3.x kernel" #define STR_OS_OTHER_4X "other4xlinux" #define STR_OS_OTHER_4X_FULL "Other Linux 4.x or later kernel" #define STR_OS_PHOTON "vmware-photon" #define STR_OS_PHOTON_FULL "VMware Photon OS" #define STR_OS_PLD "PLD" #define STR_OS_RED_HAT "redhat" #define STR_OS_RED_HAT_EN "rhel" #define STR_OS_RED_HAT_FULL "Red Hat Linux" #define STR_OS_SLACKWARE "Slackware" #define STR_OS_SLES "sles" #define STR_OS_SLES_FULL "SUSE Linux Enterprise Server" #define STR_OS_SLES_10 "sles10" #define STR_OS_SLES_10_FULL "SUSE Linux Enterprise Server 10" #define STR_OS_SLES_11 "sles11" #define STR_OS_SLES_11_FULL "SUSE Linux Enterprise Server 11" #define STR_OS_SLES_12 "sles12" #define STR_OS_SLES_12_FULL "SUSE Linux Enterprise Server 12" #define STR_OS_SLES_15 "sles15" #define STR_OS_SLES_15_FULL "SUSE Linux Enterprise Server 15" #define STR_OS_SUSE "suse" #define STR_OS_SUSE_FULL "SUSE Linux" #define STR_OS_OPENSUSE "opensuse" #define STR_OS_SMESERVER "SMEServer" #define STR_OS_SUN_DESK "sjds" #define STR_OS_SUN_DESK_FULL "Sun Java Desktop System" #define STR_OS_TINYSOFA "Tiny Sofa" #define STR_OS_TURBO "turbolinux" #define STR_OS_TURBO_FULL "Turbolinux" #define STR_OS_UBUNTU "ubuntu" #define STR_OS_ULTRAPENGUIN "UltraPenguin" #define STR_OS_UNITEDLINUX "UnitedLinux" #define STR_OS_VALINUX "VALinux" #define STR_OS_YELLOW_DOG "Yellow Dog" #define STR_OS_ECOMSTATION "eComStation" /* Windows */ #define STR_OS_WIN_31 "win31" #define STR_OS_WIN_31_FULL "Windows 3.1" #define STR_OS_WIN_95 "win95" #define STR_OS_WIN_95_FULL "Windows 95" #define STR_OS_WIN_98 "win98" #define STR_OS_WIN_98_FULL "Windows 98" #define STR_OS_WIN_ME "winMe" #define STR_OS_WIN_ME_FULL "Windows Me" #define STR_OS_WIN_NT "winNT" #define STR_OS_WIN_NT_FULL "Windows NT" #define STR_OS_WIN_2000_PRO "win2000Pro" #define STR_OS_WIN_2000_PRO_FULL "Windows 2000 Professional" #define STR_OS_WIN_2000_SERV "win2000Serv" #define STR_OS_WIN_2000_SERV_FULL "Windows 2000 Server" #define STR_OS_WIN_2000_ADV_SERV "win2000AdvServ" #define STR_OS_WIN_2000_ADV_SERV_FULL "Windows 2000 Advanced Server" #define STR_OS_WIN_2000_DATACENT_SERV "win2000DataCentServ" #define STR_OS_WIN_2000_DATACENT_SERV_FULL "Windows 2000 Data Center Server" #define STR_OS_WIN_XP_HOME "winXPHome" #define STR_OS_WIN_XP_HOME_FULL "Windows XP Home Edition" #define STR_OS_WIN_XP_PRO "winXPPro" #define STR_OS_WIN_XP_PRO_FULL "Windows XP Professional" #define STR_OS_WIN_XP_PRO_X64 "winXPPro-64" #define STR_OS_WIN_XP_PRO_X64_FULL "Windows XP Professional x64 Edition" #define STR_OS_WIN_NET_WEB "winNetWeb" #define STR_OS_WIN_NET_WEB_FULL "Windows Server 2003 Web Edition" #define STR_OS_WIN_NET_ST "winNetStandard" #define STR_OS_WIN_NET_ST_FULL "Windows Server 2003 Standard Edition" #define STR_OS_WIN_NET_EN "winNetEnterprise" #define STR_OS_WIN_NET_EN_FULL "Windows Server 2003 Enterprise Edition" #define STR_OS_WIN_NET_BUS "winNetBusiness" #define STR_OS_WIN_NET_BUS_FULL "Windows Server 2003 Small Business" #define STR_OS_WIN_NET_COMPCLUSTER "winNetComputeCluster" #define STR_OS_WIN_NET_COMPCLUSTER_FULL "Windows Server 2003 Compute Cluster Edition" #define STR_OS_WIN_NET_STORAGESERVER "winNetStorageSvr" #define STR_OS_WIN_NET_STORAGESERVER_FULL "Windows Storage Server 2003" #define STR_OS_WIN_NET_DC_FULL "Windows Server 2003 Datacenter Edition" #define STR_OS_WIN_NET_DC "winNetDatacenter" #define STR_OS_WIN_LONG "longhorn" #define STR_OS_WIN_VISTA "winVista" #define STR_OS_WIN_VISTA_FULL "Windows Vista" #define STR_OS_WIN_VISTA_X64 "winVista-64" #define STR_OS_WIN_VISTA_X64_FULL "Windows Vista x64 Edition" #define STR_OS_WIN_VISTA_ULTIMATE "winVistaUltimate-32" #define STR_OS_WIN_VISTA_ULTIMATE_FULL "Windows Vista Ultimate Edition" #define STR_OS_WIN_VISTA_HOME_PREMIUM "winVistaHomePremium-32" #define STR_OS_WIN_VISTA_HOME_PREMIUM_FULL "Windows Vista Home Premium Edition" #define STR_OS_WIN_VISTA_HOME_BASIC "winVistaHomeBasic-32" #define STR_OS_WIN_VISTA_HOME_BASIC_FULL "Windows Vista Home Basic Edition" #define STR_OS_WIN_VISTA_ENTERPRISE "winVistaEnterprise-32" #define STR_OS_WIN_VISTA_ENTERPRISE_FULL "Windows Vista Enterprise Edition" #define STR_OS_WIN_VISTA_BUSINESS "winVistaBusiness-32" #define STR_OS_WIN_VISTA_BUSINESS_FULL "Windows Vista Business Edition" #define STR_OS_WIN_VISTA_STARTER "winVistaStarter-32" #define STR_OS_WIN_VISTA_STARTER_FULL "Windows Vista Starter Edition" #define STR_OS_WIN_2008_CLUSTER "winServer2008Cluster-32" #define STR_OS_WIN_2008_CLUSTER_FULL "Windows Server 2008 Cluster Server Edition" #define STR_OS_WIN_2008_DATACENTER "winServer2008Datacenter-32" #define STR_OS_WIN_2008_DATACENTER_FULL "Windows Server 2008 Datacenter Edition" #define STR_OS_WIN_2008_DATACENTER_CORE "winServer2008DatacenterCore-32" #define STR_OS_WIN_2008_DATACENTER_CORE_FULL "Windows Server 2008 Datacenter Edition (core installation)" #define STR_OS_WIN_2008_ENTERPRISE "winServer2008Enterprise-32" #define STR_OS_WIN_2008_ENTERPRISE_FULL "Windows Server 2008 Enterprise Edition" #define STR_OS_WIN_2008_ENTERPRISE_CORE "winServer2008EnterpriseCore-32" #define STR_OS_WIN_2008_ENTERPRISE_CORE_FULL "Windows Server 2008 Enterprise Edition (core installation)" #define STR_OS_WIN_2008_ENTERPRISE_ITANIUM "winServer2008EnterpriseItanium-32" #define STR_OS_WIN_2008_ENTERPRISE_ITANIUM_FULL "Windows Server 2008 Enterprise Edition for Itanium-based Systems" #define STR_OS_WIN_2008_MEDIUM_MANAGEMENT "winServer2008MediumManagement-32" #define STR_OS_WIN_2008_MEDIUM_MANAGEMENT_FULL "Windows Essential Business Server Management Server" #define STR_OS_WIN_2008_MEDIUM_MESSAGING "winServer2008MediumMessaging-32" #define STR_OS_WIN_2008_MEDIUM_MESSAGING_FULL "Windows Essential Business Server Messaging Server" #define STR_OS_WIN_2008_MEDIUM_SECURITY "winServer2008MediumSecurity-32" #define STR_OS_WIN_2008_MEDIUM_SECURITY_FULL "Windows Essential Business Server Security Server" #define STR_OS_WIN_2008_SERVER_FOR_SMALLBUSINESS "winServer2008ForSmallBusiness-32" #define STR_OS_WIN_2008_SERVER_FOR_SMALLBUSINESS_FULL "Windows Server 2008 for Windows Essential Server Solutions" #define STR_OS_WIN_2008_SMALL_BUSINESS "winServer2008SmallBusiness-32" #define STR_OS_WIN_2008_SMALL_BUSINESS_FULL "Windows Server 2008 Small Business Server" #define STR_OS_WIN_2008_SMALL_BUSINESS_PREMIUM "winServer2008SmallBusinessPremium-32" #define STR_OS_WIN_2008_SMALL_BUSINESS_PREMIUM_FULL "Windows Server 2008 Small Business Server Premium Edition" #define STR_OS_WIN_2008_STANDARD "winServer2008Standard-32" #define STR_OS_WIN_2008_STANDARD_FULL "Windows Server 2008 Standard Edition" #define STR_OS_WIN_2008_STANDARD_CORE "winServer2008StandardCore-32" #define STR_OS_WIN_2008_STANDARD_CORE_FULL "Windows Server 2008 Standard Edition (core installation)" #define STR_OS_WIN_2008_STORAGE_ENTERPRISE "winServer2008StorageEnterprise-32" #define STR_OS_WIN_2008_STORAGE_ENTERPRISE_FULL "Windows Server 2008 Storage Server Enterprise" #define STR_OS_WIN_2008_STORAGE_EXPRESS "winServer2008StorageExpress-32" #define STR_OS_WIN_2008_STORAGE_EXPRESS_FULL "Windows Server 2008 Storage Server Express" #define STR_OS_WIN_2008_STORAGE_STANDARD "winServer2008StorageStandard-32" #define STR_OS_WIN_2008_STORAGE_STANDARD_FULL "Windows Server 2008 Storage Server Standard" #define STR_OS_WIN_2008_STORAGE_WORKGROUP "winServer2008StorageWorkgroup-32" #define STR_OS_WIN_2008_STORAGE_WORKGROUP_FULL "Windows Server 2008 Storage Server Workgroup" #define STR_OS_WIN_2008_WEB_SERVER "winServer2008Web-32" #define STR_OS_WIN_2008_WEB_SERVER_FULL "Windows Server 2008 Web Server Edition" /* Windows 64-bit */ #define STR_OS_WIN_VISTA_ULTIMATE_X64 "winVistaUltimate-64" #define STR_OS_WIN_VISTA_HOME_PREMIUM_X64 "winVistaHomePremium-64" #define STR_OS_WIN_VISTA_HOME_BASIC_X64 "winVistaHomeBasic-64" #define STR_OS_WIN_VISTA_ENTERPRISE_X64 "winVistaEnterprise-64" #define STR_OS_WIN_VISTA_BUSINESS_X64 "winVistaBusiness-64" #define STR_OS_WIN_VISTA_STARTER_X64 "winVistaStarter-64" #define STR_OS_WIN_2008_CLUSTER_X64 "winServer2008Cluster-64" #define STR_OS_WIN_2008_DATACENTER_X64 "winServer2008Datacenter-64" #define STR_OS_WIN_2008_DATACENTER_CORE_X64 "winServer2008DatacenterCore-64" #define STR_OS_WIN_2008_ENTERPRISE_X64 "winServer2008Enterprise-64" #define STR_OS_WIN_2008_ENTERPRISE_CORE_X64 "winServer2008EnterpriseCore-64" #define STR_OS_WIN_2008_ENTERPRISE_ITANIUM_X64 "winServer2008EnterpriseItanium-64" #define STR_OS_WIN_2008_MEDIUM_MANAGEMENT_X64 "winServer2008MediumManagement-64" #define STR_OS_WIN_2008_MEDIUM_MESSAGING_X64 "winServer2008MediumMessaging-64" #define STR_OS_WIN_2008_MEDIUM_SECURITY_X64 "winServer2008MediumSecurity-64" #define STR_OS_WIN_2008_SERVER_FOR_SMALLBUSINESS_X64 "winServer2008ForSmallBusiness-64" #define STR_OS_WIN_2008_SMALL_BUSINESS_X64 "winServer2008SmallBusiness-64" #define STR_OS_WIN_2008_SMALL_BUSINESS_PREMIUM_X64 "winServer2008SmallBusinessPremium-64" #define STR_OS_WIN_2008_STANDARD_X64 "winServer2008Standard-64" #define STR_OS_WIN_2008_STANDARD_CORE_X64 "winServer2008StandardCore-64" #define STR_OS_WIN_2008_STORAGE_ENTERPRISE_X64 "winServer2008StorageEnterprise-64" #define STR_OS_WIN_2008_STORAGE_EXPRESS_X64 "winServer2008StorageExpress-64" #define STR_OS_WIN_2008_STORAGE_STANDARD_X64 "winServer2008StorageStandard-64" #define STR_OS_WIN_2008_STORAGE_WORKGROUP_X64 "winServer2008StorageWorkgroup-64" #define STR_OS_WIN_2008_WEB_SERVER_X64 "winServer2008Web-64" /* Windows 7 */ #define STR_OS_WIN_SEVEN "windows7" #define STR_OS_WIN_SEVEN_X64 "windows7-64" #define STR_OS_WIN_SEVEN_GENERIC "Windows 7" #define STR_OS_WIN_SEVEN_STARTER_FULL "Windows 7 Starter" #define STR_OS_WIN_SEVEN_HOME_BASIC_FULL "Windows 7 Home Basic" #define STR_OS_WIN_SEVEN_HOME_PREMIUM_FULL "Windows 7 Home Premium" #define STR_OS_WIN_SEVEN_ULTIMATE_FULL "Windows 7 Ultimate" #define STR_OS_WIN_SEVEN_PROFESSIONAL_FULL "Windows 7 Professional" #define STR_OS_WIN_SEVEN_ENTERPRISE_FULL "Windows 7 Enterprise" /* Windows Server 2008 R2 (based on Windows 7) */ #define STR_OS_WIN_2008R2_X64 "windows7srv-64" #define STR_OS_WIN_2008R2_FOUNDATION_FULL "Windows Server 2008 R2 Foundation Edition" #define STR_OS_WIN_2008R2_STANDARD_FULL "Windows Server 2008 R2 Standard Edition" #define STR_OS_WIN_2008R2_ENTERPRISE_FULL "Windows Server 2008 R2 Enterprise Edition" #define STR_OS_WIN_2008R2_DATACENTER_FULL "Windows Server 2008 R2 Datacenter Edition" #define STR_OS_WIN_2008R2_WEB_SERVER_FULL "Windows Web Server 2008 R2 Edition" /* Windows 8 */ #define STR_OS_WIN_EIGHT "windows8" #define STR_OS_WIN_EIGHT_X64 "windows8-64" #define STR_OS_WIN_EIGHT_GENERIC_FULL "Windows 8%s" #define STR_OS_WIN_EIGHTSERVER_GENERIC_FULL "Windows Server%s 2012" #define STR_OS_WIN_EIGHT_FULL "Windows 8%s" #define STR_OS_WIN_EIGHT_PRO_FULL "Windows 8%s Pro" #define STR_OS_WIN_EIGHT_ENTERPRISE_FULL "Windows 8%s Enterprise" /* Windows Server 2012 */ #define STR_OS_WIN_EIGHTSERVER_X64 "windows8srv-64" #define STR_OS_WIN_2012_FOUNDATION_FULL "Windows Server 2012%s Foundation Edition" #define STR_OS_WIN_2012_ESSENTIALS_FULL "Windows Server 2012%s Essentials Edition" #define STR_OS_WIN_2012_STANDARD_FULL "Windows Server 2012%s Standard Edition" #define STR_OS_WIN_2012_ENTERPRISE_FULL "Windows Server 2012%s Enterprise Edition" #define STR_OS_WIN_2012_DATACENTER_FULL "Windows Server 2012%s Datacenter Edition" #define STR_OS_WIN_2012_STORAGESERVER_FULL "Windows Server 2012%s Storage Server" #define STR_OS_WIN_2012_WEB_SERVER_FULL "Windows Web Server 2012%s Edition" #define STR_OS_WIN_2012_MULTIPOINT_STANDARD_FULL "Windows MultiPoint Server 2012%s Standard" #define STR_OS_WIN_2012_MULTIPOINT_PREMIUM_FULL "Windows MultiPoint Server 2012%s Premium" /* * Windows 10 * * Microsoft renamed Windows 9 to Windows 10; Windows 9 was never released. * So as to not invalidate any existing VMs or released software we retain * the Windows 9 identifier strings as Windows 10. */ #define STR_OS_WIN_TEN "windows9" #define STR_OS_WIN_TEN_X64 "windows9-64" /* THIS SPACE FOR RENT (Windows 10 official variant names) */ #define STR_OS_WIN_TEN_GENERIC_FULL "Windows 10" /* Windows Server 2016 */ #define STR_OS_WIN_TENSERVER_X64 "windows9srv-64" /* THIS SPACE FOR RENT (Windows 10 official server variant names) */ #define STR_OS_WIN_TENSERVER_GENERIC_FULL "Windows Server 2016" /* Microsoft Hyper-V */ #define STR_OS_HYPER_V "winHyperV" #define STR_OS_HYPER_V_FULL "Hyper-V Server" /* Windows Future/Unknown */ #define STR_OS_WIN_FUTURE "windowsUnknown" #define STR_OS_WIN_FUTURE_X64 "windowsUnknown-64" #define STR_OS_WIN_FUTURE_GENERIC "Windows Unknown" /* Modifiers for Windows Vista, Windows Server 2008, and later. */ #define STR_OS_WIN_32_BIT_EXTENSION ", 32-bit" #define STR_OS_WIN_64_BIT_EXTENSION ", 64-bit" /* FreeBSD */ #define STR_OS_FREEBSD "freeBSD" #define STR_OS_FREEBSD11 "freeBSD11" #define STR_OS_FREEBSD12 "freeBSD12" /* Solaris */ #define STR_OS_SOLARIS "solaris" /* Mac OS */ #define STR_OS_MACOS "darwin" /* All */ #define STR_OS_64BIT_SUFFIX "-64" #define STR_OS_64BIT_SUFFIX_FULL " (64 bit)" #define STR_OS_EMPTY "" #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/guest_os_tables.h000066400000000000000000001317011321503522500260250ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _GUEST_OS_TABLES_H_ #define _GUEST_OS_TABLES_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #if defined(__cplusplus) extern "C" { #endif #define GUEST_OS_TYPE_GEN \ GOT(GUEST_OS_ANY) \ GOT(GUEST_OS_DOS) \ GOT(GUEST_OS_WIN31) \ GOT(GUEST_OS_WIN95) \ GOT(GUEST_OS_WIN98) \ GOT(GUEST_OS_WINME) \ GOT(GUEST_OS_WINNT) \ GOT(GUEST_OS_WIN2000) \ GOT(GUEST_OS_WINXP) \ GOT(GUEST_OS_WINXPPRO_64) \ GOT(GUEST_OS_WINNET) \ GOT(GUEST_OS_WINNET_64) \ GOT(GUEST_OS_LONGHORN) \ GOT(GUEST_OS_LONGHORN_64) \ GOT(GUEST_OS_WINVISTA) \ GOT(GUEST_OS_WINVISTA_64) \ GOT(GUEST_OS_WINSEVEN) /* Windows 7 */ \ GOT(GUEST_OS_WINSEVEN_64) /* Windows 7 */ \ GOT(GUEST_OS_WIN2008R2_64) /* Server 2008 R2 */ \ GOT(GUEST_OS_WINEIGHT) /* Windows 8 */ \ GOT(GUEST_OS_WINEIGHT_64) /* Windows 8 x64 */ \ GOT(GUEST_OS_WINEIGHTSERVER_64) /* Windows 8 Server X64 */ \ GOT(GUEST_OS_WINTEN) /* Windows 10 */ \ GOT(GUEST_OS_WINTEN_64) /* Windows 10 x64 */ \ GOT(GUEST_OS_WINTENSERVER_64) /* Windows 10 Server X64 */ \ GOT(GUEST_OS_HYPER_V) /* Microsoft Hyper-V */ \ GOT(GUEST_OS_OS2) \ GOT(GUEST_OS_ECOMSTATION) /* OS/2 variant; 1.x */ \ GOT(GUEST_OS_ECOMSTATION2) /* OS/2 variant; 2.x */ \ GOT(GUEST_OS_OTHER24XLINUX) \ GOT(GUEST_OS_OTHER24XLINUX_64) \ GOT(GUEST_OS_OTHER26XLINUX) \ GOT(GUEST_OS_OTHER26XLINUX_64) \ GOT(GUEST_OS_OTHER3XLINUX) /* Linux 3.x */ \ GOT(GUEST_OS_OTHER3XLINUX_64) /* Linux 3.x X64 */ \ GOT(GUEST_OS_OTHER4XLINUX) /* Linux 4.x and later */ \ GOT(GUEST_OS_OTHER4XLINUX_64) /* Linux 4.x and later X64 */ \ GOT(GUEST_OS_OTHERLINUX) \ GOT(GUEST_OS_OTHERLINUX_64) \ GOT(GUEST_OS_OTHER) \ GOT(GUEST_OS_OTHER_64) \ GOT(GUEST_OS_UBUNTU) \ GOT(GUEST_OS_DEBIAN) \ GOT(GUEST_OS_DEBIAN_64) \ GOT(GUEST_OS_RHEL) \ GOT(GUEST_OS_RHEL_64) \ GOT(GUEST_OS_FREEBSD) \ GOT(GUEST_OS_FREEBSD_64) \ GOT(GUEST_OS_FREEBSD11) \ GOT(GUEST_OS_FREEBSD11_64) \ GOT(GUEST_OS_FREEBSD12) \ GOT(GUEST_OS_FREEBSD12_64) \ GOT(GUEST_OS_SOLARIS_6_AND_7) \ GOT(GUEST_OS_SOLARIS8) \ GOT(GUEST_OS_SOLARIS9) \ GOT(GUEST_OS_SOLARIS10) \ GOT(GUEST_OS_SOLARIS10_64) \ GOT(GUEST_OS_SOLARIS11_64) \ GOT(GUEST_OS_DARWIN9) /* Mac OS 10.5 */ \ GOT(GUEST_OS_DARWIN9_64) \ GOT(GUEST_OS_DARWIN10) /* Mac OS 10.6 */ \ GOT(GUEST_OS_DARWIN10_64) \ GOT(GUEST_OS_DARWIN11) /* Mac OS 10.7 */ \ GOT(GUEST_OS_DARWIN11_64) \ GOT(GUEST_OS_DARWIN12_64) /* Mac OS 10.8 */ \ GOT(GUEST_OS_DARWIN13_64) /* Mac OS 10.9 */ \ GOT(GUEST_OS_DARWIN14_64) /* Mac OS 10.10 */ \ GOT(GUEST_OS_DARWIN15_64) /* Mac OS 10.11 */ \ GOT(GUEST_OS_DARWIN16_64) /* Mac OS 10.12 */ \ GOT(GUEST_OS_DARWIN17_64) /* Mac OS 10.13 */ \ GOT(GUEST_OS_DARWIN18_64) /* Mac OS 10.14 */ \ GOT(GUEST_OS_OPENSERVER_5_AND_6) \ GOT(GUEST_OS_UNIXWARE7) \ GOT(GUEST_OS_NETWARE4) \ GOT(GUEST_OS_NETWARE5) \ GOT(GUEST_OS_NETWARE6) \ GOT(GUEST_OS_VMKERNEL) /* ESX 4.x */ \ GOT(GUEST_OS_VMKERNEL5) /* ESX 5.x */ \ GOT(GUEST_OS_VMKERNEL6) /* ESX 6 */ \ GOT(GUEST_OS_VMKERNEL65) /* ESX 6.5 and later */ \ GOT(GUEST_OS_PHOTON_64) /* VMware Photon IA 64-bit */ \ GOT(GUEST_OS_ORACLE) \ GOT(GUEST_OS_ORACLE_64) \ GOT(GUEST_OS_ORACLE6) \ GOT(GUEST_OS_ORACLE6_64) \ GOT(GUEST_OS_ORACLE7_64) \ GOT(GUEST_OS_ORACLE8_64) \ GOT(GUEST_OS_CENTOS) \ GOT(GUEST_OS_CENTOS_64) \ GOT(GUEST_OS_CENTOS6) \ GOT(GUEST_OS_CENTOS6_64) \ GOT(GUEST_OS_CENTOS7_64) \ GOT(GUEST_OS_CENTOS8_64) \ /* This list must be sorted alphabetically (non-case-sensitive) by gos name. */ #define GUEST_OS_LIST_GEN \ GOSL(STR_OS_ASIANUX "3", GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_ASIANUX "3-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_ASIANUX "4", GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_ASIANUX "4-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_ASIANUX "5-64", GUEST_OS_OTHER3XLINUX_64, "linux.iso") \ GOSL(STR_OS_ASIANUX "7-64", GUEST_OS_OTHER3XLINUX_64, "linux.iso") \ GOSL(STR_OS_ASIANUX "8-64", GUEST_OS_OTHER3XLINUX_64, "linux.iso") \ GOSL(STR_OS_CENTOS, GUEST_OS_CENTOS, "linux.iso") \ GOSL(STR_OS_CENTOS "-64", GUEST_OS_CENTOS_64, "linux.iso") \ GOSL(STR_OS_CENTOS "6", GUEST_OS_CENTOS6, "linux.iso") \ GOSL(STR_OS_CENTOS "6-64", GUEST_OS_CENTOS6_64, "linux.iso") \ GOSL(STR_OS_CENTOS "7-64", GUEST_OS_CENTOS7_64, "linux.iso") \ GOSL(STR_OS_CENTOS "8-64", GUEST_OS_CENTOS8_64, "linux.iso") \ GOSL("coreos-64", GUEST_OS_OTHER3XLINUX_64, NULL) \ GOSL(STR_OS_MACOS, GUEST_OS_DARWIN9, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "-64", GUEST_OS_DARWIN9_64, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "10", GUEST_OS_DARWIN10, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "10-64", GUEST_OS_DARWIN10_64, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "11", GUEST_OS_DARWIN11, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "11-64", GUEST_OS_DARWIN11_64, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "12-64", GUEST_OS_DARWIN12_64, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "13-64", GUEST_OS_DARWIN13_64, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "14-64", GUEST_OS_DARWIN14_64, "darwinPre15.iso") \ GOSL(STR_OS_MACOS "15-64", GUEST_OS_DARWIN15_64, "darwin.iso") \ GOSL(STR_OS_MACOS "16-64", GUEST_OS_DARWIN16_64, "darwin.iso") \ GOSL(STR_OS_MACOS "17-64", GUEST_OS_DARWIN17_64, "darwin.iso") \ GOSL(STR_OS_MACOS "18-64", GUEST_OS_DARWIN18_64, "darwin.iso") \ GOSL(STR_OS_DEBIAN_10, GUEST_OS_DEBIAN, "linux.iso") \ GOSL(STR_OS_DEBIAN_10 "-64", GUEST_OS_DEBIAN_64, "linux.iso") \ GOSL(STR_OS_DEBIAN_4, GUEST_OS_DEBIAN, "linuxPreGlibc25.iso") \ GOSL(STR_OS_DEBIAN_4 "-64", GUEST_OS_DEBIAN_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_DEBIAN_5, GUEST_OS_DEBIAN, "linuxPreGlibc25.iso") \ GOSL(STR_OS_DEBIAN_5 "-64", GUEST_OS_DEBIAN_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_DEBIAN_6, GUEST_OS_DEBIAN, "linux.iso") \ GOSL(STR_OS_DEBIAN_6 "-64", GUEST_OS_DEBIAN_64, "linux.iso") \ GOSL(STR_OS_DEBIAN_7, GUEST_OS_DEBIAN, "linux.iso") \ GOSL(STR_OS_DEBIAN_7 "-64", GUEST_OS_DEBIAN_64, "linux.iso") \ GOSL(STR_OS_DEBIAN_8, GUEST_OS_DEBIAN, "linux.iso") \ GOSL(STR_OS_DEBIAN_8 "-64", GUEST_OS_DEBIAN_64, "linux.iso") \ GOSL(STR_OS_DEBIAN_9, GUEST_OS_DEBIAN, "linux.iso") \ GOSL(STR_OS_DEBIAN_9 "-64", GUEST_OS_DEBIAN_64, "linux.iso") \ GOSL("dos", GUEST_OS_DOS, NULL) \ GOSL(STR_OS_ECOMSTATION, GUEST_OS_ECOMSTATION, NULL) \ GOSL(STR_OS_ECOMSTATION "2", GUEST_OS_ECOMSTATION2, NULL) \ GOSL("fedora", GUEST_OS_OTHER26XLINUX, "linux.iso") \ GOSL("fedora-64", GUEST_OS_OTHER26XLINUX_64, "linux.iso") \ GOSL(STR_OS_FREEBSD, GUEST_OS_FREEBSD, "freebsd.iso") \ GOSL(STR_OS_FREEBSD "-64", GUEST_OS_FREEBSD_64, "freebsd.iso") \ GOSL(STR_OS_FREEBSD "11", GUEST_OS_FREEBSD11, "freebsd.iso") \ GOSL(STR_OS_FREEBSD "11-64", GUEST_OS_FREEBSD11_64, "freebsd.iso") \ GOSL(STR_OS_FREEBSD "12", GUEST_OS_FREEBSD12, "freebsd.iso") \ GOSL(STR_OS_FREEBSD "12-64", GUEST_OS_FREEBSD12_64, "freebsd.iso") \ GOSL("linux", GUEST_OS_OTHERLINUX, "linuxPreGlibc25.iso") /* old */ \ GOSL(STR_OS_WIN_LONG, GUEST_OS_LONGHORN, "windows.iso") \ GOSL("longhorn-64", GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_MANDRAKE, GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_MANDRAKE "-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_MANDRIVA, GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_MANDRIVA "-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL("netware4", GUEST_OS_NETWARE4, "netware.iso") \ GOSL("netware5", GUEST_OS_NETWARE5, "netware.iso") \ GOSL("netware6", GUEST_OS_NETWARE6, "netware.iso") \ GOSL(STR_OS_NOVELL, GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL("nt4", GUEST_OS_WINNT, "winPre2k.iso") /* old */ \ GOSL("oes", GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL("openserver5", GUEST_OS_OPENSERVER_5_AND_6, NULL) \ GOSL("openserver6", GUEST_OS_OPENSERVER_5_AND_6, NULL) \ GOSL(STR_OS_OPENSUSE, GUEST_OS_OTHER26XLINUX, "linux.iso") \ GOSL(STR_OS_OPENSUSE "-64", GUEST_OS_OTHER26XLINUX_64, "linux.iso") \ GOSL(STR_OS_ORACLE, GUEST_OS_ORACLE, "linux.iso") \ GOSL(STR_OS_ORACLE "-64", GUEST_OS_ORACLE_64, "linux.iso") \ GOSL(STR_OS_ORACLE "6", GUEST_OS_ORACLE6, "linux.iso") \ GOSL(STR_OS_ORACLE "6-64", GUEST_OS_ORACLE6_64, "linux.iso") \ GOSL(STR_OS_ORACLE "7-64", GUEST_OS_ORACLE7_64, "linux.iso") \ GOSL(STR_OS_ORACLE "8-64", GUEST_OS_ORACLE8_64, "linux.iso") \ GOSL("os2", GUEST_OS_OS2, NULL) \ GOSL("os2experimental", GUEST_OS_OS2, NULL) \ GOSL("other", GUEST_OS_OTHER, NULL) \ GOSL("other-64", GUEST_OS_OTHER_64, NULL) \ GOSL(STR_OS_OTHER_24, GUEST_OS_OTHER24XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_OTHER_24 "-64", GUEST_OS_OTHER24XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_OTHER_26, GUEST_OS_OTHER26XLINUX, "linux.iso") \ GOSL(STR_OS_OTHER_26 "-64", GUEST_OS_OTHER26XLINUX_64, "linux.iso") \ GOSL(STR_OS_OTHER_3X, GUEST_OS_OTHER3XLINUX, "linux.iso") \ GOSL(STR_OS_OTHER_3X "-64", GUEST_OS_OTHER3XLINUX_64, "linux.iso") \ GOSL(STR_OS_OTHER_4X, GUEST_OS_OTHER4XLINUX, "linux.iso") \ GOSL(STR_OS_OTHER_4X "-64", GUEST_OS_OTHER4XLINUX_64, "linux.iso") \ GOSL(STR_OS_OTHER, GUEST_OS_OTHERLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_OTHER "-64", GUEST_OS_OTHERLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_RED_HAT, GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_RED_HAT_EN "2", GUEST_OS_OTHER24XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_RED_HAT_EN "3", GUEST_OS_OTHER24XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_RED_HAT_EN "3-64", GUEST_OS_OTHER24XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_RED_HAT_EN "4", GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_RED_HAT_EN "4-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_RED_HAT_EN "5", GUEST_OS_OTHER26XLINUX, "linux.iso") \ GOSL(STR_OS_RED_HAT_EN "5-64", GUEST_OS_OTHER26XLINUX_64, "linux.iso") \ GOSL(STR_OS_RED_HAT_EN "6", GUEST_OS_RHEL, "linux.iso") \ GOSL(STR_OS_RED_HAT_EN "6-64", GUEST_OS_RHEL_64, "linux.iso") \ GOSL(STR_OS_RED_HAT_EN "7", GUEST_OS_RHEL, "linux.iso") \ GOSL(STR_OS_RED_HAT_EN "7-64", GUEST_OS_RHEL_64, "linux.iso") \ GOSL(STR_OS_RED_HAT_EN "8-64", GUEST_OS_RHEL_64, "linux.iso") \ GOSL(STR_OS_SUN_DESK, GUEST_OS_OTHER24XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_SLES, GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_SLES "-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_SLES "10", GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_SLES "10-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_SLES "11", GUEST_OS_OTHER26XLINUX, "linux.iso") \ GOSL(STR_OS_SLES "11-64", GUEST_OS_OTHER26XLINUX_64, "linux.iso") \ GOSL(STR_OS_SLES "12", GUEST_OS_OTHER26XLINUX, "linux.iso") \ GOSL(STR_OS_SLES "12-64", GUEST_OS_OTHER26XLINUX_64, "linux.iso") \ GOSL(STR_OS_SLES "15-64", GUEST_OS_OTHER3XLINUX_64, "linux.iso") \ GOSL(STR_OS_SOLARIS "10", GUEST_OS_SOLARIS10, "solaris.iso") \ GOSL(STR_OS_SOLARIS "10-64", GUEST_OS_SOLARIS10_64, "solaris.iso") \ GOSL(STR_OS_SOLARIS "11-64", GUEST_OS_SOLARIS11_64, "solaris.iso") \ GOSL(STR_OS_SOLARIS "6", GUEST_OS_SOLARIS_6_AND_7, "solaris.iso") \ GOSL(STR_OS_SOLARIS "7", GUEST_OS_SOLARIS_6_AND_7, "solaris.iso") \ GOSL(STR_OS_SOLARIS "8", GUEST_OS_SOLARIS8, "solaris.iso") \ GOSL(STR_OS_SOLARIS "9", GUEST_OS_SOLARIS9, "solaris.iso") \ GOSL(STR_OS_SUSE, GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_SUSE "-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_TURBO, GUEST_OS_OTHER26XLINUX, "linuxPreGlibc25.iso") \ GOSL(STR_OS_TURBO "-64", GUEST_OS_OTHER26XLINUX_64, "linuxPreGlibc25.iso") \ GOSL(STR_OS_UBUNTU, GUEST_OS_UBUNTU, "linux.iso") \ GOSL(STR_OS_UBUNTU "-64", GUEST_OS_OTHER26XLINUX_64, "linux.iso") \ GOSL("unixware7", GUEST_OS_UNIXWARE7, NULL) \ GOSL("vmkernel", GUEST_OS_VMKERNEL, NULL) \ GOSL("vmkernel5", GUEST_OS_VMKERNEL5, NULL) \ GOSL("vmkernel6", GUEST_OS_VMKERNEL6, NULL) \ GOSL("vmkernel65", GUEST_OS_VMKERNEL65, NULL) \ GOSL(STR_OS_PHOTON "-64", GUEST_OS_PHOTON_64, NULL) \ GOSL("whistler", GUEST_OS_WINXP, "winPreVista.iso") /* old */ \ GOSL("win2000", GUEST_OS_WIN2000, "winPreVista.iso") /* old */ \ GOSL(STR_OS_WIN_2000_ADV_SERV, GUEST_OS_WIN2000, "winPreVista.iso") \ GOSL(STR_OS_WIN_2000_PRO, GUEST_OS_WIN2000, "winPreVista.iso") \ GOSL(STR_OS_WIN_2000_SERV, GUEST_OS_WIN2000, "winPreVista.iso") \ GOSL(STR_OS_WIN_31, GUEST_OS_WIN31, "winPre2k.iso") \ GOSL(STR_OS_WIN_95, GUEST_OS_WIN95, "winPre2k.iso") \ GOSL(STR_OS_WIN_98, GUEST_OS_WIN98, "winPre2k.iso") \ GOSL(STR_OS_WIN_SEVEN, GUEST_OS_WINSEVEN, "windows.iso") \ GOSL(STR_OS_WIN_SEVEN_X64, GUEST_OS_WINSEVEN_64, "windows.iso") \ GOSL("windows7Server64Guest", GUEST_OS_WIN2008R2_64, "windows.iso") \ GOSL(STR_OS_WIN_2008R2_X64, GUEST_OS_WIN2008R2_64, "windows.iso") \ GOSL(STR_OS_WIN_EIGHT, GUEST_OS_WINEIGHT, "windows.iso") \ GOSL(STR_OS_WIN_EIGHT_X64, GUEST_OS_WINEIGHT_64, "windows.iso") \ GOSL(STR_OS_WIN_EIGHTSERVER_X64, GUEST_OS_WINEIGHTSERVER_64, "windows.iso") \ GOSL(STR_OS_WIN_TEN, GUEST_OS_WINTEN, "windows.iso") \ GOSL(STR_OS_WIN_TEN_X64, GUEST_OS_WINTEN_64, "windows.iso") \ GOSL(STR_OS_WIN_TENSERVER_X64, GUEST_OS_WINTENSERVER_64, "windows.iso") \ GOSL(STR_OS_HYPER_V, GUEST_OS_HYPER_V, NULL) \ GOSL("winLonghorn64Guest", GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL("winLonghornGuest", GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_ME, GUEST_OS_WINME, "winPre2k.iso") \ GOSL(STR_OS_WIN_NET_BUS, GUEST_OS_WINNET, "winPreVista.iso") \ GOSL("winNetDatacenter", GUEST_OS_WINNET, "winPreVista.iso") \ GOSL("winNetDatacenter-64", GUEST_OS_WINNET_64, "winPreVista.iso") \ GOSL(STR_OS_WIN_NET_EN, GUEST_OS_WINNET, "winPreVista.iso") \ GOSL("winNetEnterprise-64", GUEST_OS_WINNET_64, "winPreVista.iso") \ GOSL(STR_OS_WIN_NET_ST, GUEST_OS_WINNET, "winPreVista.iso") \ GOSL("winNetStandard-64", GUEST_OS_WINNET_64, "winPreVista.iso") \ GOSL(STR_OS_WIN_NET_WEB, GUEST_OS_WINNET, "winPreVista.iso") \ GOSL(STR_OS_WIN_NT, GUEST_OS_WINNT, "winPre2k.iso") \ GOSL(STR_OS_WIN_2008_CLUSTER, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_CLUSTER_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_DATACENTER, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_DATACENTER_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_DATACENTER_CORE, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_DATACENTER_CORE_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_ENTERPRISE, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_ENTERPRISE_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_ENTERPRISE_CORE, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_ENTERPRISE_CORE_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_SMALL_BUSINESS, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_SMALL_BUSINESS_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_SMALL_BUSINESS_PREMIUM, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_SMALL_BUSINESS_PREMIUM_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_STANDARD, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_STANDARD_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_STANDARD_CORE, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_STANDARD_CORE_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_2008_WEB_SERVER, GUEST_OS_LONGHORN, "windows.iso") \ GOSL(STR_OS_WIN_2008_WEB_SERVER_X64, GUEST_OS_LONGHORN_64, "windows.iso") \ GOSL(STR_OS_WIN_VISTA, GUEST_OS_WINVISTA, "windows.iso") \ GOSL(STR_OS_WIN_VISTA_X64, GUEST_OS_WINVISTA_64, "windows.iso") \ GOSL(STR_OS_WIN_XP_HOME, GUEST_OS_WINXP, "winPreVista.iso") \ GOSL(STR_OS_WIN_XP_PRO, GUEST_OS_WINXP, "winPreVista.iso") \ GOSL(STR_OS_WIN_XP_PRO_X64, GUEST_OS_WINXPPRO_64, "winPreVista.iso") \ /* * Mappings between VIM guest OS keys and the rest of the civilized world. * * Format: GOKM(vmxKey, vimKey, reversible) */ #define GUEST_OS_KEY_MAP \ /* Windows guests */ \ GOKM("win31", win31Guest, TRUE) \ GOKM("win95", win95Guest, TRUE) \ GOKM("win98", win98Guest, TRUE) \ GOKM("winMe", winMeGuest, TRUE) \ GOKM("winNT", winNTGuest, TRUE) \ GOKM("nt4", winNTGuest, FALSE) \ GOKM("win2000", win2000ProGuest, FALSE) \ GOKM("win2000Pro", win2000ProGuest, TRUE) \ GOKM("win2000Serv", win2000ServGuest, TRUE) \ GOKM("win2000AdvServ", win2000AdvServGuest, TRUE) \ GOKM("winXPHome", winXPHomeGuest, TRUE) \ GOKM("whistler", winXPHomeGuest, FALSE) \ GOKM("winXPPro", winXPProGuest, TRUE) \ GOKM("winXPPro-64", winXPPro64Guest, TRUE) \ GOKM("winNetWeb", winNetWebGuest, TRUE) \ GOKM("winNetStandard", winNetStandardGuest, TRUE) \ GOKM("winNetEnterprise", winNetEnterpriseGuest, TRUE) \ GOKM("winNetDatacenter", winNetDatacenterGuest, TRUE) \ GOKM("winNetBusiness", winNetBusinessGuest, TRUE) \ GOKM("winNetStandard-64", winNetStandard64Guest, TRUE) \ GOKM("winNetEnterprise-64", winNetEnterprise64Guest, TRUE) \ GOKM("winNetDatacenter-64", winNetDatacenter64Guest, TRUE) \ GOKM("longhorn", winLonghornGuest, TRUE) \ GOKM("longhorn-64", winLonghorn64Guest, TRUE) \ GOKM("winvista", winVistaGuest, TRUE) \ GOKM("winvista-64", winVista64Guest, TRUE) \ GOKM("windows7", windows7Guest, TRUE) \ GOKM("windows7-64", windows7_64Guest, TRUE) \ GOKM("windows7srv-64", windows7Server64Guest, TRUE) \ GOKM("windows8", windows8Guest, TRUE) \ GOKM("windows8-64", windows8_64Guest, TRUE) \ GOKM("windows8srv-64", windows8Server64Guest, TRUE) \ GOKM("windows9", windows9Guest, TRUE) \ GOKM("windows9-64", windows9_64Guest, TRUE) \ GOKM("windows9srv-64", windows9Server64Guest, TRUE) \ GOKM("winHyperV", windowsHyperVGuest, TRUE) \ GOKM("winServer2008Cluster-32", winLonghornGuest, FALSE) \ GOKM("winServer2008Datacenter-32", winLonghornGuest, FALSE) \ GOKM("winServer2008DatacenterCore-32", winLonghornGuest, FALSE) \ GOKM("winServer2008Enterprise-32", winLonghornGuest, FALSE) \ GOKM("winServer2008EnterpriseCore-32", winLonghornGuest, FALSE) \ GOKM("winServer2008EnterpriseItanium-32", winLonghornGuest, FALSE) \ GOKM("winServer2008SmallBusiness-32", winLonghornGuest, FALSE) \ GOKM("winServer2008SmallBusinessPremium-32", winLonghornGuest, FALSE) \ GOKM("winServer2008Standard-32", winLonghornGuest, FALSE) \ GOKM("winServer2008StandardCore-32", winLonghornGuest, FALSE) \ GOKM("winServer2008MediumManagement-32", winLonghornGuest, FALSE) \ GOKM("winServer2008MediumMessaging-32", winLonghornGuest, FALSE) \ GOKM("winServer2008MediumSecurity-32", winLonghornGuest, FALSE) \ GOKM("winServer2008ForSmallBusiness-32", winLonghornGuest, FALSE) \ GOKM("winServer2008StorageEnterprise-32", winLonghornGuest, FALSE) \ GOKM("winServer2008StorageExpress-32", winLonghornGuest, FALSE) \ GOKM("winServer2008StorageStandard-32", winLonghornGuest, FALSE) \ GOKM("winServer2008StorageWorkgroup-32", winLonghornGuest, FALSE) \ GOKM("winServer2008Web-32", winLonghornGuest, FALSE) \ GOKM("winServer2008Cluster-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008Datacenter-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008DatacenterCore-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008Enterprise-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008EnterpriseCore-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008EnterpriseItanium-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008SmallBusiness-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008SmallBusinessPremium-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008Standard-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008StandardCore-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008MediumManagement-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008MediumMessaging-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008MediumSecurity-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008ForSmallBusiness-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008StorageEnterprise-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008StorageExpress-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008StorageStandard-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008StorageWorkgroup-64", winLonghorn64Guest, FALSE) \ GOKM("winServer2008Web-64", winLonghorn64Guest, FALSE) \ GOKM("winVistaUltimate-32", winVistaGuest, FALSE) \ GOKM("winVistaHomePremium-32", winVistaGuest, FALSE) \ GOKM("winVistaHomeBasic-32", winVistaGuest, FALSE) \ GOKM("winVistaEnterprise-32", winVistaGuest, FALSE) \ GOKM("winVistaBusiness-32", winVistaGuest, FALSE) \ GOKM("winVistaStarter-32", winVistaGuest, FALSE) \ GOKM("winVistaUltimate-64", winVista64Guest, FALSE) \ GOKM("winVistaHomePremium-64", winVista64Guest, FALSE) \ GOKM("winVistaHomeBasic-64", winVista64Guest, FALSE) \ GOKM("winVistaEnterprise-64", winVista64Guest, FALSE) \ GOKM("winVistaBusiness-64", winVista64Guest, FALSE) \ GOKM("winVistaStarter-64", winVista64Guest, FALSE) \ /* Linux guests */ \ GOKM("redhat", redhatGuest, TRUE) \ GOKM("rhel2", rhel2Guest, TRUE) \ GOKM("rhel3", rhel3Guest, TRUE) \ GOKM("rhel3-64", rhel3_64Guest, TRUE) \ GOKM("rhel4", rhel4Guest, TRUE) \ GOKM("rhel4-64", rhel4_64Guest, TRUE) \ GOKM("rhel5", rhel5Guest, TRUE) \ GOKM("rhel5-64", rhel5_64Guest, TRUE) \ GOKM("rhel6", rhel6Guest, TRUE) \ GOKM("rhel6-64", rhel6_64Guest, TRUE) \ GOKM("rhel7", rhel7Guest, TRUE) \ GOKM("rhel7-64", rhel7_64Guest, TRUE) \ GOKM("rhel8-64", rhel8_64Guest, TRUE) \ GOKM("centos", centosGuest, TRUE) \ GOKM("centos-64", centos64Guest, TRUE) \ GOKM("centos6", centos6Guest, TRUE) \ GOKM("centos6-64", centos6_64Guest, TRUE) \ GOKM("centos7", centos7Guest, FALSE) \ GOKM("centos7-64", centos7_64Guest, TRUE) \ GOKM("centos8-64", centos8_64Guest, TRUE) \ GOKM("oraclelinux", oracleLinuxGuest, TRUE) \ GOKM("oraclelinux-64", oracleLinux64Guest, TRUE) \ GOKM("oraclelinux6", oracleLinux6Guest, TRUE) \ GOKM("oraclelinux6-64", oracleLinux6_64Guest, TRUE) \ GOKM("oraclelinux7", oracleLinux7Guest, FALSE) \ GOKM("oraclelinux7-64", oracleLinux7_64Guest, TRUE) \ GOKM("oraclelinux8-64", oracleLinux8_64Guest, TRUE) \ GOKM("suse", suseGuest, TRUE) \ GOKM("suse-64", suse64Guest, TRUE) \ GOKM("sles", slesGuest, TRUE) \ GOKM("sles-64", sles64Guest, TRUE) \ GOKM("sles10", sles10Guest, TRUE) \ GOKM("sles10-64", sles10_64Guest, TRUE) \ GOKM("sles11", sles11Guest, TRUE) \ GOKM("sles11-64", sles11_64Guest, TRUE) \ GOKM("sles12", sles12Guest, TRUE) \ GOKM("sles12-64", sles12_64Guest, TRUE) \ GOKM("sles15-64", sles15_64Guest, TRUE) \ GOKM("mandrake", mandrakeGuest, TRUE) \ GOKM("mandrake-64", mandriva64Guest, FALSE) \ GOKM("mandriva", mandrivaGuest, TRUE) \ GOKM("mandriva-64", mandriva64Guest, TRUE) \ GOKM("turbolinux", turboLinuxGuest, TRUE) \ GOKM("turbolinux-64", turboLinux64Guest, TRUE) \ GOKM("ubuntu", ubuntuGuest, TRUE) \ GOKM("ubuntu-64", ubuntu64Guest, TRUE) \ GOKM("debian4", debian4Guest, TRUE) \ GOKM("debian4-64", debian4_64Guest, TRUE) \ GOKM("debian5", debian5Guest, TRUE) \ GOKM("debian5-64", debian5_64Guest, TRUE) \ GOKM("debian6", debian6Guest, TRUE) \ GOKM("debian6-64", debian6_64Guest, TRUE) \ GOKM("debian7", debian7Guest, TRUE) \ GOKM("debian7-64", debian7_64Guest, TRUE) \ GOKM("debian8", debian8Guest, TRUE) \ GOKM("debian8-64", debian8_64Guest, TRUE) \ GOKM("debian9", debian9Guest, TRUE) \ GOKM("debian9-64", debian9_64Guest, TRUE) \ GOKM("debian10", debian10Guest, TRUE) \ GOKM("debian10-64", debian10_64Guest, TRUE) \ GOKM("asianux3", asianux3Guest, TRUE) \ GOKM("asianux3-64", asianux3_64Guest, TRUE) \ GOKM("asianux4", asianux4Guest, TRUE) \ GOKM("asianux4-64", asianux4_64Guest, TRUE) \ GOKM("asianux5-64", asianux5_64Guest, TRUE) \ GOKM("asianux7-64", asianux7_64Guest, TRUE) \ GOKM("asianux8-64", asianux8_64Guest, TRUE) \ GOKM("nld9", nld9Guest, TRUE) \ GOKM("oes", oesGuest, TRUE) \ GOKM("sjds", sjdsGuest, TRUE) \ GOKM("opensuse", opensuseGuest, TRUE) \ GOKM("opensuse-64", opensuse64Guest, TRUE) \ GOKM("fedora", fedoraGuest, TRUE) \ GOKM("fedora-64", fedora64Guest, TRUE) \ GOKM("coreos-64", coreos64Guest, TRUE) \ GOKM("vmware-photon-64", vmwarePhoton64Guest, TRUE) \ GOKM("other24xlinux", other24xLinuxGuest, TRUE) \ GOKM("other24xlinux-64", other24xLinux64Guest, TRUE) \ GOKM("other26xlinux", other26xLinuxGuest, TRUE) \ GOKM("other26xlinux-64", other26xLinux64Guest, TRUE) \ GOKM("other3xlinux", other3xLinuxGuest, TRUE) \ GOKM("other3xlinux-64", other3xLinux64Guest, TRUE) \ GOKM("other4xlinux", other4xLinuxGuest, TRUE) \ GOKM("other4xlinux-64", other4xLinux64Guest, TRUE) \ GOKM("linux", otherLinuxGuest, FALSE) \ GOKM("otherlinux", otherLinuxGuest, TRUE) \ GOKM("otherlinux-64", otherLinux64Guest, TRUE) \ GOKM("genericlinux", genericLinuxGuest, TRUE) \ /* Netware guests */ \ GOKM("netware4", netware4Guest, TRUE) \ GOKM("netware5", netware5Guest, TRUE) \ GOKM("netware6", netware6Guest, TRUE) \ /* Solaris guests */ \ GOKM("solaris6", solaris6Guest, TRUE) \ GOKM("solaris7", solaris7Guest, TRUE) \ GOKM("solaris8", solaris8Guest, TRUE) \ GOKM("solaris9", solaris9Guest, TRUE) \ GOKM("solaris10", solaris10Guest, TRUE) \ GOKM("solaris10-64", solaris10_64Guest, TRUE) \ GOKM("solaris11-64", solaris11_64Guest, TRUE) \ /* macOS guests */ \ GOKM("darwin", darwinGuest, TRUE) \ GOKM("darwin-64", darwin64Guest, TRUE) \ GOKM("darwin10", darwin10Guest, TRUE) \ GOKM("darwin10-64", darwin10_64Guest, TRUE) \ GOKM("darwin11", darwin11Guest, TRUE) \ GOKM("darwin11-64", darwin11_64Guest, TRUE) \ GOKM("darwin12-64", darwin12_64Guest, TRUE) \ GOKM("darwin13-64", darwin13_64Guest, TRUE) \ GOKM("darwin14-64", darwin14_64Guest, TRUE) \ GOKM("darwin15-64", darwin15_64Guest, TRUE) \ GOKM("darwin16-64", darwin16_64Guest, TRUE) \ GOKM("darwin17-64", darwin17_64Guest, TRUE) \ GOKM("darwin18-64", darwin18_64Guest, TRUE) \ /* ESX guests */ \ GOKM("vmkernel", vmkernelGuest, TRUE) \ GOKM("vmkernel5", vmkernel5Guest, TRUE) \ GOKM("vmkernel6", vmkernel6Guest, TRUE) \ GOKM("vmkernel65", vmkernel65Guest, TRUE) \ /* Other guests */ \ GOKM("dos", dosGuest, TRUE) \ GOKM("os2", os2Guest, TRUE) \ GOKM("os2experimental", os2Guest, FALSE) \ GOKM("eComStation", eComStationGuest, TRUE) \ GOKM("eComStation2", eComStation2Guest, TRUE) \ GOKM("freeBSD", freebsdGuest, TRUE) \ GOKM("freeBSD-64", freebsd64Guest, TRUE) \ GOKM("freeBSD11", freebsd11Guest, TRUE) \ GOKM("freeBSD11-64", freebsd11_64Guest, TRUE) \ GOKM("freeBSD12", freebsd12Guest, TRUE) \ GOKM("freeBSD12-64", freebsd12_64Guest, TRUE) \ GOKM("openserver5", openServer5Guest, TRUE) \ GOKM("openserver6", openServer6Guest, TRUE) \ GOKM("unixware7", unixWare7Guest, TRUE) \ GOKM("other", otherGuest, TRUE) \ GOKM("other-64", otherGuest64, TRUE) \ #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hashMap.h000066400000000000000000000055771321503522500242370ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #ifndef _HASHMAP_H_ #define _HASHMAP_H_ #include #ifdef VMX86_SERVER #include "aioMgr.h" #endif #if defined(__cplusplus) extern "C" { #endif typedef struct HashMap HashMap; /* * ---------------------------------------------------------------------------- * * HashMapIteratorFn -- * * A function pointer definition that should be passed to HashMap_Iterate, * it will be called for all entries in the hashmap. The key and data will * be set appropriately and the user data pointer will be passed untouched * from the HashMap_Iterate call. * * Results: * void * * Side Effects: * Implementation dependent. * * ---------------------------------------------------------------------------- */ typedef void (* HashMapIteratorFn)(void *key, void *data, void *userData); HashMap *HashMap_AllocMap(uint32 numEntries, size_t keySize, size_t dataSize); HashMap *HashMap_AllocMapAlpha(uint32 numEntries, uint32 alpha, size_t keySize, size_t dataSize); void HashMap_DestroyMap(HashMap *map); Bool HashMap_Put(HashMap *map, const void *key, const void *data); void *HashMap_Get(HashMap *map, const void *key); void HashMap_Clear(HashMap *map); Bool HashMap_Remove(HashMap *map, const void *key); uint32 HashMap_Count(HashMap *map); void HashMap_Iterate(HashMap* map, HashMapIteratorFn mapFn, Bool clear, void *userData); Bool HashMap_DoTests(void); #if defined(__cplusplus) } // extern "C" #endif #endif /* _HASHMAP_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hashTable.h000066400000000000000000000136651321503522500245460ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hashTable.h -- * * Hash table. */ #ifndef _HASH_TABLE_H_ #define _HASH_TABLE_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_defs.h" #include "vm_atomic.h" #if defined(__cplusplus) extern "C" { #endif typedef struct HashTable HashTable; typedef struct PtrHashTable PtrHashTable; typedef void (*HashTableFreeEntryFn)(void *clientData); typedef int (*HashTableForEachCallback)(const char *key, void *value, void *clientData); #define HASH_STRING_KEY 0 // case-sensitive string key #define HASH_ISTRING_KEY 1 // case-insensitive string key #define HASH_INT_KEY 2 // uintptr_t or pointer key /* * The flag bits are ored into the type field. * Atomic hash tables only support insert, lookup, and replace. */ #define HASH_TYPE_MASK 7 #define HASH_FLAG_MASK (~HASH_TYPE_MASK) #define HASH_FLAG_ATOMIC 0x08 // thread-safe hash table #define HASH_FLAG_COPYKEY 0x10 // copy string key HashTable * HashTable_Alloc(uint32 numEntries, // IN: int keyType, // IN: HashTableFreeEntryFn fn); // IN/OPT: HashTable * HashTable_AllocOnce(Atomic_Ptr *var, // IN/OUT: uint32 numEntries, // IN: int keyType, // IN: HashTableFreeEntryFn fn); // IN/OPT: void HashTable_Free(HashTable *hashTable); // IN/OUT: void HashTable_FreeUnsafe(HashTable *hashTable); // IN/OUT: Bool HashTable_Insert(HashTable *hashTable, // IN/OUT: const void *keyStr, // IN: void *clientData); // IN/OPT: Bool HashTable_Lookup(const HashTable *hashTable, // IN: const void *keyStr, // IN: void **clientData); // OUT/OPT: void * HashTable_LookupOrInsert(HashTable *hashTable, // IN/OUT: const void *keyStr, // IN: void *clientData); // IN/OPT: Bool HashTable_ReplaceOrInsert(HashTable *hashTable, // IN/OUT: const void *keyStr, // IN: void *clientData); // IN/OPT Bool HashTable_ReplaceIfEqual(HashTable *hashTable, // IN/OUT: const void *keyStr, // IN: void *oldClientData, // IN/OPT void *newClientData); // IN/OPT Bool HashTable_Delete(HashTable *hashTable, // IN/OUT: const void *keyStr); // IN: Bool HashTable_LookupAndDelete(HashTable *hashTable, // IN/OUT: const void *keyStr, // IN: void **clientData); // OUT: void HashTable_Clear(HashTable *ht); // IN/OUT: void HashTable_ToArray(const HashTable *ht, // IN: void ***clientDatas, // OUT: size_t *size); // OUT: void HashTable_KeyArray(const HashTable *ht, // IN: const void ***keys, // OUT: size_t *size); // OUT: size_t HashTable_GetNumElements(const HashTable *ht); // IN: int HashTable_ForEach(const HashTable *ht, // IN: HashTableForEachCallback cb, // IN: void *clientData); // IN: /* * Specialize hash table that uses the callers data structure as its * hash entry as well, the hash key being an address that must be unique. */ typedef struct PtrHashEntry { struct PtrHashEntry *next; void *ptr; } PtrHashEntry; /* * PTRHASH_CONTAINER - get the struct for this entry (like PtrHashEntry) * @ptr: the &struct PtrHashEntry pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list struct within the struct. */ #define PTRHASH_CONTAINER(ptr, type, member) \ ((type *)((char *)(ptr) - vmw_offsetof(type, member))) typedef int (*PtrHashForEachCallback)(PtrHashEntry *entry, const void *clientData); PtrHashTable *PtrHash_Alloc(uint32 numBuckets); void PtrHash_Free(PtrHashTable *hashTable); size_t PtrHash_AllocSize(PtrHashTable *ht); size_t PtrHash_GetNumElements(const PtrHashTable *ht); int PtrHash_ForEach(const PtrHashTable *ht, PtrHashForEachCallback cb, const void *clientData); PtrHashEntry *PtrHash_Lookup(const PtrHashTable *hashTable, const void *keyPtr); PtrHashEntry *PtrHash_LookupAndDelete(PtrHashTable *hashTable, const void *keyPtr); Bool PtrHash_Insert(PtrHashTable *hashTable, PtrHashEntry *entry); Bool PtrHash_Delete(PtrHashTable *hashTable, const void *keyPtr); #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfs.h000066400000000000000000000216601321503522500235740ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfs.h -- * * Header file for public common data types used in the VMware * Host/Guest File System (hgfs). * * This file is included by hgfsProto.h, which defines message formats * used in the hgfs protocol, and by hgfsDev.h, which defines the * interface between the kernel and the hgfs pserver. [bac] */ #ifndef _HGFS_H_ # define _HGFS_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_DISTRIBUTE #include "includeCheck.h" #include "vm_assert.h" /* * Maximum number of pages to transfer to/from the HGFS server for V3 protocol * operations that support large requests/replies, e.g. reads and writes. */ #define HGFS_LARGE_IO_MAX_PAGES 15 /* * Maximum allowed packet size in bytes. All hgfs code should be made * safe with respect to this limit. */ #define HGFS_PACKET_MAX 6144 /* * The HGFS_LARGE_PACKET_MAX size is used to allow guests to make * read / write requests of sizes larger than HGFS_PACKET_MAX. The larger size * can only be used with server operations that are specified to be large packet * capable in hgfsProto.h. */ #define HGFS_LARGE_PACKET_MAX ((4096 * HGFS_LARGE_IO_MAX_PAGES) + 2048) /* Maximum number of bytes to read or write to a hgfs server in a single packet. */ #define HGFS_IO_MAX 4096 /* Maximum number of bytes to read or write to a V3 server in a single hgfs packet. */ #define HGFS_LARGE_IO_MAX (HGFS_LARGE_IO_MAX_PAGES * 4096) /* * File type * * File types, used in HgfsAttr. We support regular files, * directories, and symlinks. * * Changing the order of this enum will break the protocol; new types * should be added at the end. * * * This definition is used in some places that don't include * hgfsProto.h, which is why it is here instead of there. */ typedef enum { HGFS_FILE_TYPE_REGULAR, HGFS_FILE_TYPE_DIRECTORY, HGFS_FILE_TYPE_SYMLINK, } HgfsFileType; /* * Open mode * * These are equivalent to the O_RDONLY, O_WRONLY, O_RDWR open flags * in Unix; they specify which type of access is being requested. These three * modes are mutually exclusive and one is required; all other flags are * modifiers to the mode and must come afterwards as a bitmask. Beware that * HGFS_OPEN_MODE_READ_ONLY contains the value 0 so simply masking another * variable with it to detect its presence is not safe. The _ACCMODES entry in * the enum serves as a bitmask for the others. * * Changing the order of this enum will break stuff. * * This definition is used in some places that don't include * hgfsProto.h, which is why it is here instead of there. */ typedef enum { HGFS_OPEN_MODE_READ_ONLY, HGFS_OPEN_MODE_WRITE_ONLY, HGFS_OPEN_MODE_READ_WRITE, HGFS_OPEN_MODE_ACCMODES, /* You cannot add anything else here. Really. */ } HgfsOpenMode; /* * Open flags. * * Each should be shifted left by HGFS_OPEN_MODE_READ_WRITE plus whatever flag * number they are, starting with zero. * * The sequential flag indicates that reads and writes on this handle should * not seek on each operation; instead, the system's file pointer will be used * so each operation is performed where the last one finished. This flag is * necessary when reading from or writing to non-seekable files (such as procfs * nodes on Linux) but can also lead to inconsistent results if a client shares * a handle amongst several of its callers. This flag should only be used when * the client knows the file is non-seekable and the burden of ensuring file * handles aren't shared falls upon the hgfs client, not the server. */ #define HGFS_OPEN_SEQUENTIAL (1 << HGFS_OPEN_MODE_READ_WRITE) /* Masking helpers. */ #define HGFS_OPEN_MODE_ACCMODE(mode) (mode & HGFS_OPEN_MODE_ACCMODES) #define HGFS_OPEN_MODE_FLAGS(mode) (mode & ~HGFS_OPEN_MODE_ACCMODES) #define HGFS_OPEN_MODE_IS_VALID_MODE(mode) \ (HGFS_OPEN_MODE_ACCMODE(mode) == HGFS_OPEN_MODE_READ_ONLY || \ HGFS_OPEN_MODE_ACCMODE(mode) == HGFS_OPEN_MODE_WRITE_ONLY || \ HGFS_OPEN_MODE_ACCMODE(mode) == HGFS_OPEN_MODE_READ_WRITE) /* * Return status for replies from the server. * * Changing the order of this enum will break the protocol; new status * types should be added at the end. * * This definition is used in some places that don't include * hgfsProto.h, which is why it is here instead of there. * * XXX: So we have a problem here. At some point, HGFS_STATUS_INVALID_NAME was * added to the list of errors. Later, HGFS_STATUS_GENERIC_ERROR was added, but * it was added /before/ HGFS_STATUS_INVALID_NAME. Nobody noticed because the * error codes travelled from hgfsProto.h to hgfs.h in that same change. Worse, * we GA'ed a product (Server 1.0) this way. * * XXX: I've reversed the order because otherwise new HGFS clients working * against WS55-era HGFS servers will think they got HGFS_STATUS_GENERIC_ERROR * when the server sent them HGFS_STATUS_INVALID_NAME. This was a problem * the Linux client converts HGFS_STATUS_GENERIC_ERROR to -EIO, which causes * HgfsLookup to fail unexpectedly (normally HGFS_STATUS_INVALID_NAME is * converted to -ENOENT, an expected result in HgfsLookup). */ typedef enum { HGFS_STATUS_SUCCESS, HGFS_STATUS_NO_SUCH_FILE_OR_DIR, HGFS_STATUS_INVALID_HANDLE, HGFS_STATUS_OPERATION_NOT_PERMITTED, HGFS_STATUS_FILE_EXISTS, HGFS_STATUS_NOT_DIRECTORY, HGFS_STATUS_DIR_NOT_EMPTY, HGFS_STATUS_PROTOCOL_ERROR, HGFS_STATUS_ACCESS_DENIED, HGFS_STATUS_INVALID_NAME, HGFS_STATUS_GENERIC_ERROR, HGFS_STATUS_SHARING_VIOLATION, HGFS_STATUS_NO_SPACE, HGFS_STATUS_OPERATION_NOT_SUPPORTED, HGFS_STATUS_NAME_TOO_LONG, HGFS_STATUS_INVALID_PARAMETER, HGFS_STATUS_NOT_SAME_DEVICE, /* * Following error codes are for V4 and above protocol only. * Server must never retun these codes for legacy clients. */ HGFS_STATUS_STALE_SESSION, HGFS_STATUS_TOO_MANY_SESSIONS, HGFS_STATUS_TRANSPORT_ERROR, } HgfsStatus; /* * HGFS RPC commands * * HGFS servers can run in a variety of places across several different * transport layers. These definitions constitute all known RPC commands. * * For each definition, there is both the server string (the command itself) * as well as a client "prefix", which is the command followed by a space. * This is provided for convenience, since clients will need to copy both * the command and the space into some buffer that is then sent over the * backdoor. * * In Host --> Guest RPC traffic, the host endpoint is TCLO and the guest * endpoint is RpcIn. TCLO is a particularly confusing name choice which dates * back to when the host was to send raw TCL code to the guest (TCL Out == * TCLO). * * In Guest --> Host RPC traffic, the guest endpoint is RpcOut and the host * endpoint is RPCI. */ /* * When an RPCI listener registers for this command, HGFS requests are expected * to be synchronously sent from the guest and replies are expected to be * synchronously returned. * * When an RpcIn listener registers for this command, requests are expected to * be asynchronously sent from the host and synchronously returned from the * guest. * * In short, an endpoint sending this command is sending a request whose reply * should be returned synchronously. */ #define HGFS_SYNC_REQREP_CMD "f" #define HGFS_SYNC_REQREP_CLIENT_CMD HGFS_SYNC_REQREP_CMD " " #define HGFS_SYNC_REQREP_CLIENT_CMD_LEN (sizeof HGFS_SYNC_REQREP_CLIENT_CMD - 1) /* * This is just for the sake of macro naming. Since we are guaranteed * equal command lengths, defining command length via a generalized macro name * will prevent confusion. */ #define HGFS_CLIENT_CMD_LEN HGFS_SYNC_REQREP_CLIENT_CMD_LEN #endif // _HGFS_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsBd.h000066400000000000000000000040331321503522500240350ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #ifndef _HGFS_BD_H_ # define _HGFS_BD_H_ /* * hgfsBd.h -- * * Backdoor calls used by hgfs clients. */ #include "rpcout.h" char *HgfsBd_GetBuf(void); char *HgfsBd_GetLargeBuf(void); void HgfsBd_PutBuf(char *); RpcOut *HgfsBd_GetChannel(void); Bool HgfsBd_CloseChannel(RpcOut *out); int HgfsBd_Dispatch(RpcOut *out, char *packetIn, size_t *packetSize, char const **packetOut); Bool HgfsBd_Enabled(RpcOut *out, char *requestPacket); Bool HgfsBd_OpenBackdoor(RpcOut **out); Bool HgfsBd_CloseBackdoor(RpcOut **out); #endif // _HGFS_BD_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsDevLinux.h000066400000000000000000000117571321503522500252610ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsDev.h -- * * Header for code shared between the hgfs linux kernel module driver * and the pserver. */ #ifndef _HGFS_DEV_H_ #define _HGFS_DEV_H_ #include "vm_basic_types.h" #include "hgfs.h" #define HGFS_NAME "vmhgfs" // Name of FS (e.g. "mount -t vmhgfs") #define HGFS_FUSENAME "vmhgfs-fuse" // Name of FS (e.g. "-o subtype=vmhgfs-fuse") #define HGFS_FUSETYPE "fuse." HGFS_FUSENAME // Type of FS (e.g. "fuse.vmhgfs-fuse") #define HGFS_MOUNT_POINT "/mnt/hgfs" // Type of FS (e.g. vmhgfs-fuse ) #define HGFS_DEVICE_NAME "dev" // Name of our device under /proc/fs/HGFS_NAME/ #define HGFS_SUPER_MAGIC 0xbacbacbc // Superblock magic number #define HGFS_DEFAULT_TTL 1 // Default TTL for dentries typedef enum { HGFS_MOUNTINFO_VERSION_NONE, HGFS_MOUNTINFO_VERSION_1, HGFS_MOUNTINFO_VERSION_2, } HgfsMountInfoVersion; /* * The mount info flags. * These specify flags from options parsed on the mount command line. */ #define HGFS_MNTINFO_SERVER_INO (1 << 0) /* Use server inode numbers? */ /* * Mount information, passed from pserver process to kernel * at mount time. * * XXX: I'm hijacking this struct. In the future, when the Solaris HGFS driver * loses its pserver, the struct will be used by /sbin/mount.vmhgfs solely. * As is, it is also used by the Solaris pserver. */ typedef struct HgfsMountInfo { uint32 magicNumber; // hgfs magic number uint32 infoSize; // HgfsMountInfo structure size HgfsMountInfoVersion version; // HgfsMountInfo structure version uint32 fd; // file descriptor of client file uint32 flags; // hgfs specific mount flags #ifndef sun uid_t uid; // desired owner of files Bool uidSet; // is the owner actually set? gid_t gid; // desired group of files Bool gidSet; // is the group actually set? unsigned short fmask; // desired file mask unsigned short dmask; // desired directory mask uint32 ttl; // number of seconds before revalidating dentries #if defined __APPLE__ char shareNameHost[MAXPATHLEN]; // must be ".host" char shareNameDir[MAXPATHLEN]; // desired share name for mounting #else const char *shareNameHost; // must be ".host" const char *shareNameDir; // desired share name for mounting #endif #endif } #if __GNUC__ __attribute__((__packed__)) #else # error Compiler packing... #endif HgfsMountInfo; /* * Version 1 of the MountInfo object. * This is used so that newer kernel clients can allow mounts using * older versions of the mounter application for backwards compatibility. */ typedef struct HgfsMountInfoV1 { uint32 magicNumber; // hgfs magic number uint32 version; // protocol version uint32 fd; // file descriptor of client file #ifndef sun uid_t uid; // desired owner of files Bool uidSet; // is the owner actually set? gid_t gid; // desired group of files Bool gidSet; // is the group actually set? unsigned short fmask; // desired file mask unsigned short dmask; // desired directory mask uint32 ttl; // number of seconds before revalidating dentries #if defined __APPLE__ char shareNameHost[MAXPATHLEN]; // must be ".host" char shareNameDir[MAXPATHLEN]; // desired share name for mounting #else const char *shareNameHost; // must be ".host" const char *shareNameDir; // desired share name for mounting #endif #endif } HgfsMountInfoV1; #endif //ifndef _HGFS_DEV_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsEscape.h000066400000000000000000000036261321503522500247170ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsEscape.h -- * * Escape and unescape filenames that are not legal on a particular * platform. * */ #ifndef __HGFS_ESCAPE_H__ #define __HGFS_ESCAPE_H__ int HgfsEscape_GetSize(char const *bufIn, uint32 sizeIn); int HgfsEscape_Do(char const *bufIn, uint32 sizeIn, uint32 sizeBufOut, char *bufOut); uint32 HgfsEscape_Undo(char *bufIn, uint32 sizeIn); #endif // __HGFS_ESCAPE_H__ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsHelper.h000066400000000000000000000024551321503522500247350ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsClient.h * * Provides a helper library for guest applications to access * the HGFS file system. */ #ifndef _HGFS_HELPER_H_ #define _HGFS_HELPER_H_ #include "vm_basic_types.h" #include "unicode.h" Bool HgfsHlpr_QuerySharesDefaultRootPath(char **hgfsRootPath); void HgfsHlpr_FreeSharesRootPath(char *hgfsRootPath); #if defined(_WIN32) Bool HgfsHlpr_ReadRegistryDefaultRootPath(char **hgfsRootPath); #endif // _WIN32 #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsProto.h000066400000000000000000002570541321503522500246300ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsProto.h -- * * Header file for data types and message formats used in the * Host/Guest File System (hgfs) protocol. */ #ifndef _HGFS_PROTO_H_ # define _HGFS_PROTO_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_DISTRIBUTE #include "includeCheck.h" #include "vm_basic_types.h" #include "hgfs.h" /* * Handle used by the server to identify files and searches. Used * by the driver to match server replies with pending requests. */ typedef uint32 HgfsHandle; #define HGFS_INVALID_HANDLE ((HgfsHandle)~((HgfsHandle)0)) /* * Opcodes for server operations. * * Changing the ordering of this enum will break the protocol; new ops * should be added at the end (but before HGFS_OP_MAX). */ typedef enum { HGFS_OP_OPEN, /* Open file */ HGFS_OP_READ, /* Read from file */ HGFS_OP_WRITE, /* Write to file */ HGFS_OP_CLOSE, /* Close file */ HGFS_OP_SEARCH_OPEN, /* Start new search */ HGFS_OP_SEARCH_READ, /* Get next search response */ HGFS_OP_SEARCH_CLOSE, /* End a search */ HGFS_OP_GETATTR, /* Get file attributes */ HGFS_OP_SETATTR, /* Set file attributes */ HGFS_OP_CREATE_DIR, /* Create new directory */ HGFS_OP_DELETE_FILE, /* Delete a file */ HGFS_OP_DELETE_DIR, /* Delete a directory */ HGFS_OP_RENAME, /* Rename a file or directory */ HGFS_OP_QUERY_VOLUME_INFO, /* Query volume information */ /* * The following operations are only available in version 2 of the hgfs * protocol. The corresponding version 1 opcodes above are deprecated. */ HGFS_OP_OPEN_V2, /* Open file */ HGFS_OP_GETATTR_V2, /* Get file attributes */ HGFS_OP_SETATTR_V2, /* Set file attributes */ HGFS_OP_SEARCH_READ_V2, /* Get next search response */ HGFS_OP_CREATE_SYMLINK, /* Create a symlink */ HGFS_OP_SERVER_LOCK_CHANGE, /* Change the oplock on a file */ HGFS_OP_CREATE_DIR_V2, /* Create a directory */ HGFS_OP_DELETE_FILE_V2, /* Delete a file */ HGFS_OP_DELETE_DIR_V2, /* Delete a directory */ HGFS_OP_RENAME_V2, /* Rename a file or directory */ /* * Operations for version 3, deprecating version 2 operations. */ HGFS_OP_OPEN_V3, /* Open file */ HGFS_OP_READ_V3, /* Read from file */ HGFS_OP_WRITE_V3, /* Write to file */ HGFS_OP_CLOSE_V3, /* Close file */ HGFS_OP_SEARCH_OPEN_V3, /* Start new search */ HGFS_OP_SEARCH_READ_V3, /* Read V3 directory entries */ HGFS_OP_SEARCH_CLOSE_V3, /* End a search */ HGFS_OP_GETATTR_V3, /* Get file attributes */ HGFS_OP_SETATTR_V3, /* Set file attributes */ HGFS_OP_CREATE_DIR_V3, /* Create new directory */ HGFS_OP_DELETE_FILE_V3, /* Delete a file */ HGFS_OP_DELETE_DIR_V3, /* Delete a directory */ HGFS_OP_RENAME_V3, /* Rename a file or directory */ HGFS_OP_QUERY_VOLUME_INFO_V3, /* Query volume information */ HGFS_OP_CREATE_SYMLINK_V3, /* Create a symlink */ HGFS_OP_SERVER_LOCK_CHANGE_V3, /* Change the oplock on a file */ HGFS_OP_WRITE_WIN32_STREAM_V3, /* Write WIN32_STREAM_ID format data to file */ /* * Operations for version 4, deprecating version 3 operations. */ HGFS_OP_CREATE_SESSION_V4, /* Create a session and return host capabilities. */ HGFS_OP_DESTROY_SESSION_V4, /* Destroy/close session. */ HGFS_OP_READ_FAST_V4, /* Read */ HGFS_OP_WRITE_FAST_V4, /* Write */ HGFS_OP_SET_WATCH_V4, /* Start monitoring directory changes. */ HGFS_OP_REMOVE_WATCH_V4, /* Stop monitoring directory changes. */ HGFS_OP_NOTIFY_V4, /* Notification for a directory change event. */ HGFS_OP_SEARCH_READ_V4, /* Read V4 directory entries. */ HGFS_OP_OPEN_V4, /* Open file */ HGFS_OP_ENUMERATE_STREAMS_V4, /* Enumerate alternative named streams for a file. */ HGFS_OP_GETATTR_V4, /* Get file attributes */ HGFS_OP_SETATTR_V4, /* Set file attributes */ HGFS_OP_DELETE_V4, /* Delete a file or a directory */ HGFS_OP_LINKMOVE_V4, /* Rename/move/create hard link. */ HGFS_OP_FSCTL_V4, /* Sending FS control requests. */ HGFS_OP_ACCESS_CHECK_V4, /* Access check. */ HGFS_OP_FSYNC_V4, /* Flush all cached data to the disk. */ HGFS_OP_QUERY_VOLUME_INFO_V4, /* Query volume information. */ HGFS_OP_OPLOCK_ACQUIRE_V4, /* Acquire OPLOCK. */ HGFS_OP_OPLOCK_BREAK_V4, /* Break or downgrade OPLOCK. */ HGFS_OP_LOCK_BYTE_RANGE_V4, /* Acquire byte range lock. */ HGFS_OP_UNLOCK_BYTE_RANGE_V4, /* Release byte range lock. */ HGFS_OP_QUERY_EAS_V4, /* Query extended attributes. */ HGFS_OP_SET_EAS_V4, /* Add or modify extended attributes. */ HGFS_OP_MAX, /* Dummy op, must be last in enum */ HGFS_OP_NEW_HEADER = 0xff, /* Header op, must be unique, distinguishes packet headers. */ } HgfsOp; /* * If we get to where the OP table has grown such that we hit the invalid opcode to * distinguish between header structures in the packet, then we must ensure that there * is no valid HGFS opcode with that same value. * The following assert is designed to force anyone who adds new opcodes which cause the * above condition to occur to verify the opcode values and then can remove this check. */ MY_ASSERTS(hgfsOpValuesAsserts, ASSERT_ON_COMPILE(HGFS_OP_MAX < HGFS_OP_NEW_HEADER); ) /* HGFS protocol versions. */ typedef enum { HGFS_PROTOCOL_VERSION_NONE, HGFS_PROTOCOL_VERSION_1, HGFS_PROTOCOL_VERSION_2, HGFS_PROTOCOL_VERSION_3, HGFS_PROTOCOL_VERSION_4, } HgfsProtocolVersion; /* XXX: Needs change when VMCI is supported. */ #define HGFS_REQ_PAYLOAD_SIZE_V3(hgfsReq) (sizeof *hgfsReq + sizeof(HgfsRequest)) #define HGFS_REP_PAYLOAD_SIZE_V3(hgfsRep) (sizeof *hgfsRep + sizeof(HgfsReply)) /* XXX: Needs change when VMCI is supported. */ #define HGFS_REQ_GET_PAYLOAD_V3(hgfsReq) ((char *)(hgfsReq) + sizeof(HgfsRequest)) #define HGFS_REP_GET_PAYLOAD_V3(hgfsRep) ((char *)(hgfsRep) + sizeof(HgfsReply)) /* * Open flags. * * Changing the order of this enum will break stuff. Do not add any flags to * this enum: it has been frozen and all new flags should be added to * HgfsOpenMode. This was done because HgfsOpenMode could still be converted * to a bitmask (so that it's easier to add flags to) whereas this enum was * already too large. */ typedef enum { // File doesn't exist File exists HGFS_OPEN, // error HGFS_OPEN_EMPTY, // error size = 0 HGFS_OPEN_CREATE, // create HGFS_OPEN_CREATE_SAFE, // create error HGFS_OPEN_CREATE_EMPTY, // create size = 0 } HgfsOpenFlags; /* * Write flags. */ typedef uint8 HgfsWriteFlags; #define HGFS_WRITE_APPEND 1 /* * Permissions bits. * * These are intentionally similar to Unix permissions bits, and we * convert to/from Unix permissions using simple shift operations, so * don't change these or you will break things. */ typedef uint8 HgfsPermissions; #define HGFS_PERM_READ 4 #define HGFS_PERM_WRITE 2 #define HGFS_PERM_EXEC 1 /* * Access mode bits. * * Different operating systems have different set of file access mode. * Here are constants that are rich enough to describe all access modes in an OS * independent way. */ typedef uint32 HgfsAccessMode; /* * Generic access rights control coarse grain access for the file. * A particular generic rigth can be expanded into different set of specific rights * on different OS. */ /* * HGFS_MODE_GENERIC_READ means ability to read file data and read various file * attributes and properties. */ #define HGFS_MODE_GENERIC_READ (1 << 0) /* * HGFS_MODE_GENERIC_WRITE means ability to write file data and updaate various file * attributes and properties. */ #define HGFS_MODE_GENERIC_WRITE (1 << 1) /* * HGFS_MODE_GENERIC_EXECUE means ability to execute file. For network redirectors * ability to execute usualy implies ability to read data; for local file systems * HGFS_MODE_GENERIC_EXECUTE does not imply ability to read data. */ #define HGFS_MODE_GENERIC_EXECUTE (1 << 2) /* Specific rights define fine grain access modes. */ #define HGFS_MODE_READ_DATA (1 << 3) // Ability to read file data #define HGFS_MODE_WRITE_DATA (1 << 4) // Ability to writge file data #define HGFS_MODE_APPEND_DATA (1 << 5) // Appending data to the end of file #define HGFS_MODE_DELETE (1 << 6) // Ability to delete the file #define HGFS_MODE_TRAVERSE_DIRECTORY (1 << 7) // Ability to access files in a directory #define HGFS_MODE_LIST_DIRECTORY (1 << 8) // Ability to list file names #define HGFS_MODE_ADD_SUBDIRECTORY (1 << 9) // Ability to create a new subdirectory #define HGFS_MODE_ADD_FILE (1 << 10) // Ability to create a new file #define HGFS_MODE_DELETE_CHILD (1 << 11) // Ability to delete file/subdirectory #define HGFS_MODE_READ_ATTRIBUTES (1 << 12) // Ability to read attributes #define HGFS_MODE_WRITE_ATTRIBUTES (1 << 13) // Ability to write attributes #define HGFS_MODE_READ_EXTATTRIBUTES (1 << 14) // Ability to read extended attributes #define HGFS_MODE_WRITE_EXTATTRIBUTES (1 << 15) // Ability to write extended attributes #define HGFS_MODE_READ_SECURITY (1 << 16) // Ability to read permissions/ACLs/owner #define HGFS_MODE_WRITE_SECURITY (1 << 17) // Ability to change permissions/ACLs #define HGFS_MODE_TAKE_OWNERSHIP (1 << 18) // Ability to change file owner/group /* * Server-side locking (oplocks and leases). * * The client can ask the server to acquire opportunistic locking/leasing * from the host FS on its behalf. This is communicated as part of an open request. * * HGFS_LOCK_OPPORTUNISTIC means that the client trusts the server * to decide what kind of locking to request from the host FS. * All other values tell the server explicitly the type of lock to * request. * * The server will attempt to acquire the desired lock and will notify the client * which type of lock was acquired as part of the reply to the open request. * Note that HGFS_LOCK_OPPORTUNISTIC should not be specified as the type of * lock acquired by the server, since HGFS_LOCK_OPPORTUNISTIC is not an * actual lock. */ typedef enum { HGFS_LOCK_NONE, HGFS_LOCK_OPPORTUNISTIC, HGFS_LOCK_EXCLUSIVE, HGFS_LOCK_SHARED, HGFS_LOCK_BATCH, HGFS_LOCK_LEASE, } HgfsLockType; /* * Flags to indicate in a setattr request which fields should be * updated. Deprecated. */ typedef uint8 HgfsAttrChanges; #define HGFS_ATTR_SIZE (1 << 0) #define HGFS_ATTR_CREATE_TIME (1 << 1) #define HGFS_ATTR_ACCESS_TIME (1 << 2) #define HGFS_ATTR_WRITE_TIME (1 << 3) #define HGFS_ATTR_CHANGE_TIME (1 << 4) #define HGFS_ATTR_PERMISSIONS (1 << 5) #define HGFS_ATTR_ACCESS_TIME_SET (1 << 6) #define HGFS_ATTR_WRITE_TIME_SET (1 << 7) /* * Hints to indicate in a getattr or setattr which attributes * are valid for the request. * For setattr only, attributes should be set by host even if * no valid values are specified by the guest. */ typedef uint64 HgfsAttrHint; #define HGFS_ATTR_HINT_SET_ACCESS_TIME (1 << 0) #define HGFS_ATTR_HINT_SET_WRITE_TIME (1 << 1) #define HGFS_ATTR_HINT_USE_FILE_DESC (1 << 2) /* * Hint to determine using a name or a handle to determine * what to delete. */ typedef uint64 HgfsDeleteHint; #define HGFS_DELETE_HINT_USE_FILE_DESC (1 << 0) /* * Hint to determine using a name or a handle to determine * what to renames. */ typedef uint64 HgfsRenameHint; #define HGFS_RENAME_HINT_USE_SRCFILE_DESC (1 << 0) #define HGFS_RENAME_HINT_USE_TARGETFILE_DESC (1 << 1) #define HGFS_RENAME_HINT_NO_REPLACE_EXISTING (1 << 2) #define HGFS_RENAME_HINT_NO_COPY_ALLOWED (1 << 3) /* * File attributes. * * The four time fields below are in Windows NT format, which is in * units of 100ns since Jan 1, 1601, UTC. */ /* * Version 1 attributes. Deprecated. * Version 2 should be using HgfsAttrV2. */ typedef #include "vmware_pack_begin.h" struct HgfsAttr { HgfsFileType type; /* File type */ uint64 size; /* File size (in bytes) */ uint64 creationTime; /* Creation time. Ignored by POSIX */ uint64 accessTime; /* Time of last access */ uint64 writeTime; /* Time of last write */ uint64 attrChangeTime; /* Time file attributess were last * changed. Ignored by Windows */ HgfsPermissions permissions; /* Permissions bits */ } #include "vmware_pack_end.h" HgfsAttr; /* Various flags and Windows attributes. */ typedef uint64 HgfsAttrFlags; #define HGFS_ATTR_HIDDEN (1 << 0) #define HGFS_ATTR_SYSTEM (1 << 1) #define HGFS_ATTR_ARCHIVE (1 << 2) #define HGFS_ATTR_HIDDEN_FORCED (1 << 3) #define HGFS_ATTR_REPARSE_POINT (1 << 4) /* V4 additional definitions for hgfsAttrFlags. */ #define HGFS_ATTR_COMPRESSED (1 << 5) #define HGFS_ATTR_ENCRYPTED (1 << 6) #define HGFS_ATTR_OFFLINE (1 << 7) #define HGFS_ATTR_READONLY (1 << 8) #define HGFS_ATTR_SPARSE (1 << 9) #define HGFS_ATTR_TEMPORARY (1 << 10) #define HGFS_ATTR_SEQUENTIAL_ONLY (1 << 11) /* * Specifies which open request fields contain * valid values. */ typedef uint64 HgfsOpenValid; #define HGFS_OPEN_VALID_NONE 0 #define HGFS_OPEN_VALID_MODE (1 << 0) #define HGFS_OPEN_VALID_FLAGS (1 << 1) #define HGFS_OPEN_VALID_SPECIAL_PERMS (1 << 2) #define HGFS_OPEN_VALID_OWNER_PERMS (1 << 3) #define HGFS_OPEN_VALID_GROUP_PERMS (1 << 4) #define HGFS_OPEN_VALID_OTHER_PERMS (1 << 5) #define HGFS_OPEN_VALID_FILE_ATTR (1 << 6) #define HGFS_OPEN_VALID_ALLOCATION_SIZE (1 << 7) #define HGFS_OPEN_VALID_DESIRED_ACCESS (1 << 8) #define HGFS_OPEN_VALID_SHARE_ACCESS (1 << 9) #define HGFS_OPEN_VALID_SERVER_LOCK (1 << 10) #define HGFS_OPEN_VALID_FILE_NAME (1 << 11) /* V4 additional open mask flags. */ #define HGFS_OPEN_VALID_EA (1 << 12) #define HGFS_OPEN_VALID_ACL (1 << 13) #define HGFS_OPEN_VALID_STREAM_NAME (1 << 14) /* * Specifies which attribute fields contain * valid values. */ typedef uint64 HgfsAttrValid; #define HGFS_ATTR_VALID_NONE 0 #define HGFS_ATTR_VALID_TYPE (1 << 0) #define HGFS_ATTR_VALID_SIZE (1 << 1) #define HGFS_ATTR_VALID_CREATE_TIME (1 << 2) #define HGFS_ATTR_VALID_ACCESS_TIME (1 << 3) #define HGFS_ATTR_VALID_WRITE_TIME (1 << 4) #define HGFS_ATTR_VALID_CHANGE_TIME (1 << 5) #define HGFS_ATTR_VALID_SPECIAL_PERMS (1 << 6) #define HGFS_ATTR_VALID_OWNER_PERMS (1 << 7) #define HGFS_ATTR_VALID_GROUP_PERMS (1 << 8) #define HGFS_ATTR_VALID_OTHER_PERMS (1 << 9) #define HGFS_ATTR_VALID_FLAGS (1 << 10) #define HGFS_ATTR_VALID_ALLOCATION_SIZE (1 << 11) #define HGFS_ATTR_VALID_USERID (1 << 12) #define HGFS_ATTR_VALID_GROUPID (1 << 13) #define HGFS_ATTR_VALID_FILEID (1 << 14) #define HGFS_ATTR_VALID_VOLID (1 << 15) /* * Add our file and volume identifiers. * NOTE: On Windows hosts, the file identifier is not guaranteed to be valid * particularly with FAT. A defrag operation could cause it to change. * Therefore, to not confuse older clients, and non-Windows * clients we have added a separate flag. * The Windows client will check for both flags for the * file ID, and return the information to the guest application. * However, it will use the ID internally, when it has an open * handle on the server. * Non-Windows clients need the file ID to be always guaranteed, * which is to say, that the ID remains constant over the course of the * file's lifetime, and will use the HGFS_ATTR_VALID_FILEID flag * only to determine if the ID is valid. */ #define HGFS_ATTR_VALID_NON_STATIC_FILEID (1 << 16) /* * File permissions that are in effect for the user which runs HGFS server. * Client needs to know effective permissions in order to implement access(2). * Client can't derive it from group/owner/other permissions because of two resaons: * 1. It does not know user/group id of the user which runs HGFS server * 2. Effective permissions account for additional restrictions that may be imposed * by host file system, for example by ACL. */ #define HGFS_ATTR_VALID_EFFECTIVE_PERMS (1 << 17) #define HGFS_ATTR_VALID_EXTEND_ATTR_SIZE (1 << 18) #define HGFS_ATTR_VALID_REPARSE_POINT (1 << 19) #define HGFS_ATTR_VALID_SHORT_NAME (1 << 20) /* * Specifies which create dir request fields contain * valid values. */ typedef uint64 HgfsCreateDirValid; #define HGFS_CREATE_DIR_VALID_NONE 0 #define HGFS_CREATE_DIR_VALID_SPECIAL_PERMS (1 << 0) #define HGFS_CREATE_DIR_VALID_OWNER_PERMS (1 << 1) #define HGFS_CREATE_DIR_VALID_GROUP_PERMS (1 << 2) #define HGFS_CREATE_DIR_VALID_OTHER_PERMS (1 << 3) #define HGFS_CREATE_DIR_VALID_FILE_NAME (1 << 4) #define HGFS_CREATE_DIR_VALID_FILE_ATTR (1 << 5) /* * Version 2 of HgfsAttr */ typedef #include "vmware_pack_begin.h" struct HgfsAttrV2 { HgfsAttrValid mask; /* A bit mask to determine valid attribute fields */ HgfsFileType type; /* File type */ uint64 size; /* File size (in bytes) */ uint64 creationTime; /* Creation time. Ignored by POSIX */ uint64 accessTime; /* Time of last access */ uint64 writeTime; /* Time of last write */ uint64 attrChangeTime; /* Time file attributes were last * changed. Ignored by Windows */ HgfsPermissions specialPerms; /* Special permissions bits (suid, etc.). * Ignored by Windows */ HgfsPermissions ownerPerms; /* Owner permissions bits */ HgfsPermissions groupPerms; /* Group permissions bits. Ignored by * Windows */ HgfsPermissions otherPerms; /* Other permissions bits. Ignored by * Windows */ HgfsAttrFlags flags; /* Various flags and Windows 'attributes' */ uint64 allocationSize; /* Actual size of file on disk */ uint32 userId; /* User identifier, ignored by Windows */ uint32 groupId; /* group identifier, ignored by Windows */ uint64 hostFileId; /* File Id of the file on host: inode_t on Linux */ uint32 volumeId; /* volume identifier, non-zero is valid. */ uint32 effectivePerms; /* Permissions in effect for the user on the host. */ uint64 reserved2; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsAttrV2; /* * Cross-platform filename representation * * Cross-platform (CP) names are represented by a string with each * path component separated by NULs, and terminated with a final NUL, * but with no leading path separator. * * For example, the representations of a POSIX and Windows name * are as follows, with "0" meaning NUL. * * Original name Cross-platform name * ----------------------------------------------------- * "/home/bac/temp" -> "home0bac0temp0" * "C:\temp\file.txt" -> "C0temp0file.txt0" * * Note that as in the example above, Windows should strip the colon * off of drive letters as part of the conversion. Aside from that, * all characters in each path component should be left unescaped and * unmodified. Each OS is responsible for escaping any characters that * are not legal in its filenames when converting FROM the CP name * format, and unescaping them when converting TO the CP name format. * * In some requests (OPEN, GETATTR, SETATTR, DELETE, CREATE_DIR) the * CP name is used to represent a particular file, but it is also used * to represent a search pattern for looking up files using * SEARCH_OPEN. * * In the current HGFS server implementation, each request has a minimum packet * size that must be met for it to be considered valid. This minimum is simply * the sizeof the particular request, which includes the solitary byte from the * HgfsFileName struct. For these particular requests, clients add an extra * byte to their payload size, without that byte being present anywhere. * * It isn't clear that this behavior is correct, but the end result is that * neither end malfunctions, as an extra byte gets sent by the client and is * ignored by the server. Unfortunately, it cannot be easily fixed. The * server's minimum packet size can be changed, but the client should continue * to send an extra byte, otherwise older servers with a slightly longer * minimum packet size may consider the new client's packets to be too short. * * UTF-8 representation * -------------------- * XXX: It is expected that file names in the HGFS protocol will be a valid UTF-8 * encoding. * See RFC 3629 (http://tools.ietf.org/html/rfc3629) * * Unicode Format * -------------- * HGFS protocol requests that contain file names as in the structure below, * should contain unicode normal form C (precomposed see explanation below) * characters therefore hosts such as Mac OS which * use HFS+ and unicode form D should convert names before * processing or sending HGFS requests. * * Precomposed (normal form C) versus Decomposed (normal form D) * ------------------------------------------------------------- * Certain Unicode characters can be encoded in more than one way. * For example, an (A acute) can be encoded either precomposed, * as U+00C1 (LATIN CAPITAL LETTER A WITH ACUTE), or decomposed, * as U+0041 U+0301 (LATIN CAPITAL LETTER A followed by a COMBINING ACUTE ACCENT). * Precomposed characters are more common in the Windows world, * whereas decomposed characters are more common on the Mac. * * See UAX 15 (http://unicode.org/reports/tr15/) */ typedef #include "vmware_pack_begin.h" struct HgfsFileName { uint32 length; /* Does NOT include terminating NUL */ char name[1]; } #include "vmware_pack_end.h" HgfsFileName; /* * Windows hosts only: the server may return the DOS 8 dot 3 format * name as part of the directory entry. */ typedef #include "vmware_pack_begin.h" struct HgfsShortFileName { uint32 length; /* Does NOT include terminating NUL */ char name[12 * 4]; /* UTF8 max char size is 4 bytes. */ } #include "vmware_pack_end.h" HgfsShortFileName; /* * Case-sensitiviy flags are only used when any lookup is * involved on the server side. */ typedef enum { HGFS_FILE_NAME_DEFAULT_CASE, HGFS_FILE_NAME_CASE_SENSITIVE, HGFS_FILE_NAME_CASE_INSENSITIVE, } HgfsCaseType; /* * HgfsFileNameV3 - new header to incorporate case-sensitivity flags along with * Hgfs file handle. */ typedef #include "vmware_pack_begin.h" struct HgfsFileNameV3 { uint32 length; /* Does NOT include terminating NUL */ uint32 flags; /* Flags described below. */ HgfsCaseType caseType; /* Case-sensitivity type. */ HgfsHandle fid; char name[1]; } #include "vmware_pack_end.h" HgfsFileNameV3; /* * HgfsFileNameV3 flags. Case-sensitiviy flags are only used when any lookup is * involved on the server side. */ #define HGFS_FILE_NAME_USE_FILE_DESC (1 << 0) /* Case type ignored if set. */ /* * Request/reply structs. These are the first members of all * operation request and reply messages, respectively. */ typedef #include "vmware_pack_begin.h" struct HgfsRequest { HgfsHandle id; /* Opaque request ID used by the requestor */ HgfsOp op; } #include "vmware_pack_end.h" HgfsRequest; typedef #include "vmware_pack_begin.h" struct HgfsReply { HgfsHandle id; /* Opaque request ID used by the requestor */ HgfsStatus status; } #include "vmware_pack_end.h" HgfsReply; /* * Messages for our file operations. */ /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestOpen { HgfsRequest header; HgfsOpenMode mode; /* Which type of access is requested */ HgfsOpenFlags flags; /* Which flags to open the file with */ HgfsPermissions permissions; /* Which permissions to *create* a new file with */ HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestOpen; /* Version 2 of HgfsRequestOpen */ typedef #include "vmware_pack_begin.h" struct HgfsRequestOpenV2 { HgfsRequest header; HgfsOpenValid mask; /* Bitmask that specified which fields are valid. */ HgfsOpenMode mode; /* Which type of access requested. See desiredAccess */ HgfsOpenFlags flags; /* Which flags to open the file with */ HgfsPermissions specialPerms; /* Desired 'special' permissions for file creation */ HgfsPermissions ownerPerms; /* Desired 'owner' permissions for file creation */ HgfsPermissions groupPerms; /* Desired 'group' permissions for file creation */ HgfsPermissions otherPerms; /* Desired 'other' permissions for file creation */ HgfsAttrFlags attr; /* Attributes, if any, for file creation */ uint64 allocationSize; /* How much space to pre-allocate during creation */ uint32 desiredAccess; /* Extended support for windows access modes */ uint32 shareAccess; /* Windows only, share access modes */ HgfsLockType desiredLock; /* The type of lock desired by the client */ uint64 reserved1; /* Reserved for future use */ uint64 reserved2; /* Reserved for future use */ HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestOpenV2; /* Version 3 of HgfsRequestOpen */ typedef #include "vmware_pack_begin.h" struct HgfsRequestOpenV3 { HgfsOpenValid mask; /* Bitmask that specified which fields are valid. */ HgfsOpenMode mode; /* Which type of access requested. See desiredAccess */ HgfsOpenFlags flags; /* Which flags to open the file with */ HgfsPermissions specialPerms; /* Desired 'special' permissions for file creation */ HgfsPermissions ownerPerms; /* Desired 'owner' permissions for file creation */ HgfsPermissions groupPerms; /* Desired 'group' permissions for file creation */ HgfsPermissions otherPerms; /* Desired 'other' permissions for file creation */ HgfsAttrFlags attr; /* Attributes, if any, for file creation */ uint64 allocationSize; /* How much space to pre-allocate during creation */ uint32 desiredAccess; /* Extended support for windows access modes */ uint32 shareAccess; /* Windows only, share access modes */ HgfsLockType desiredLock; /* The type of lock desired by the client */ uint64 reserved1; /* Reserved for future use */ uint64 reserved2; /* Reserved for future use */ HgfsFileNameV3 fileName; } #include "vmware_pack_end.h" HgfsRequestOpenV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplyOpen { HgfsReply header; HgfsHandle file; /* Opaque file ID used by the server */ } #include "vmware_pack_end.h" HgfsReplyOpen; /* Version 2 of HgfsReplyOpen */ typedef #include "vmware_pack_begin.h" struct HgfsReplyOpenV2 { HgfsReply header; HgfsHandle file; /* Opaque file ID used by the server */ HgfsLockType acquiredLock; /* The type of lock acquired by the server */ } #include "vmware_pack_end.h" HgfsReplyOpenV2; /* Version 3 of HgfsReplyOpen */ /* * The HGFS open V3 can acquire locks and reserve disk space when requested. * However, current versions of the server don't implement the locking or allocation of * disk space on a create. These results flags indicate to the client if the server * implements handling those fields and so the clients can respond accordingly. */ typedef uint32 HgfsReplyOpenFlags; #define HGFS_OPEN_REPLY_ALLOC_DISK_SPACE (1 << 0) #define HGFS_OPEN_REPLY_LOCKED_FILE (1 << 1) typedef #include "vmware_pack_begin.h" struct HgfsReplyOpenV3 { HgfsHandle file; /* Opaque file ID used by the server */ HgfsLockType acquiredLock; /* The type of lock acquired by the server */ HgfsReplyOpenFlags flags; /* Opened file flags */ uint32 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplyOpenV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestRead { HgfsRequest header; HgfsHandle file; /* Opaque file ID used by the server */ uint64 offset; uint32 requiredSize; } #include "vmware_pack_end.h" HgfsRequestRead; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplyRead { HgfsReply header; uint32 actualSize; char payload[1]; } #include "vmware_pack_end.h" HgfsReplyRead; /* * Version 3 of HgfsRequestRead. * Server must support HGFS_LARGE_PACKET_MAX to implement this op. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestReadV3 { HgfsHandle file; /* Opaque file ID used by the server */ uint64 offset; uint32 requiredSize; uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsRequestReadV3; typedef #include "vmware_pack_begin.h" struct HgfsReplyReadV3 { uint32 actualSize; uint64 reserved; /* Reserved for future use */ char payload[1]; } #include "vmware_pack_end.h" HgfsReplyReadV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestWrite { HgfsRequest header; HgfsHandle file; /* Opaque file ID used by the server */ HgfsWriteFlags flags; uint64 offset; uint32 requiredSize; char payload[1]; } #include "vmware_pack_end.h" HgfsRequestWrite; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplyWrite { HgfsReply header; uint32 actualSize; } #include "vmware_pack_end.h" HgfsReplyWrite; /* * Version 3 of HgfsRequestWrite. * Server must support HGFS_LARGE_PACKET_MAX to implement this op. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestWriteV3 { HgfsHandle file; /* Opaque file ID used by the server */ HgfsWriteFlags flags; uint64 offset; uint32 requiredSize; uint64 reserved; /* Reserved for future use */ char payload[1]; } #include "vmware_pack_end.h" HgfsRequestWriteV3; typedef #include "vmware_pack_begin.h" struct HgfsReplyWriteV3 { uint32 actualSize; uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplyWriteV3; /* Stream write flags */ typedef enum { HGFS_WIN32_STREAM_IGNORE_SECURITY = (1<<0), } HgfsWin32StreamFlags; /* * HgfsRequestWriteWin32Stream. * Server must support HGFS_LARGE_PACKET_MAX to implement this op. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestWriteWin32StreamV3 { HgfsHandle file; /* Opaque file ID used by the server */ HgfsWin32StreamFlags flags; uint32 reserved1; uint32 requiredSize; uint64 reserved2; /* Reserved for future use */ char payload[1]; } #include "vmware_pack_end.h" HgfsRequestWriteWin32StreamV3; typedef #include "vmware_pack_begin.h" struct HgfsReplyWriteWin32StreamV3 { uint32 actualSize; uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplyWriteWin32StreamV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestClose { HgfsRequest header; HgfsHandle file; /* Opaque file ID used by the server */ } #include "vmware_pack_end.h" HgfsRequestClose; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplyClose { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplyClose; typedef #include "vmware_pack_begin.h" struct HgfsRequestCloseV3 { HgfsHandle file; /* Opaque file ID used by the server */ uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsRequestCloseV3; typedef #include "vmware_pack_begin.h" struct HgfsReplyCloseV3 { uint64 reserved; } #include "vmware_pack_end.h" HgfsReplyCloseV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSearchOpen { HgfsRequest header; HgfsFileName dirName; } #include "vmware_pack_end.h" HgfsRequestSearchOpen; typedef #include "vmware_pack_begin.h" struct HgfsRequestSearchOpenV3 { uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 dirName; } #include "vmware_pack_end.h" HgfsRequestSearchOpenV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplySearchOpen { HgfsReply header; HgfsHandle search; /* Opaque search ID used by the server */ } #include "vmware_pack_end.h" HgfsReplySearchOpen; typedef #include "vmware_pack_begin.h" struct HgfsReplySearchOpenV3 { HgfsHandle search; /* Opaque search ID used by the server */ uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplySearchOpenV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSearchRead { HgfsRequest header; HgfsHandle search; /* Opaque search ID used by the server */ uint32 offset; /* The first result is offset 0 */ } #include "vmware_pack_end.h" HgfsRequestSearchRead; /* Version 2 of HgfsRequestSearchRead */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSearchReadV2 { HgfsRequest header; HgfsHandle search; /* Opaque search ID used by the server */ uint32 offset; /* The first result is offset 0 */ } #include "vmware_pack_end.h" HgfsRequestSearchReadV2; typedef #include "vmware_pack_begin.h" struct HgfsRequestSearchReadV3 { HgfsHandle search; /* Opaque search ID used by the server */ uint32 offset; /* The first result is offset 0 */ uint32 flags; /* Reserved for reading multiple directory entries. */ uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsRequestSearchReadV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplySearchRead { HgfsReply header; HgfsAttr attr; HgfsFileName fileName; /* fileName.length = 0 means "no entry at this offset" */ } #include "vmware_pack_end.h" HgfsReplySearchRead; /* Version 2 of HgfsReplySearchRead */ typedef #include "vmware_pack_begin.h" struct HgfsReplySearchReadV2 { HgfsReply header; HgfsAttrV2 attr; /* * fileName.length = 0 means "no entry at this offset" * If the file is a symlink (as specified in attr) * this name is the name of the symlink, not the target. */ HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsReplySearchReadV2; /* Directory entry structure. */ typedef struct HgfsDirEntry { uint32 nextEntry; HgfsAttrV2 attr; /* * fileName.length = 0 means "no entry at this offset" * If the file is a symlink (as specified in attr) * this name is the name of the symlink, not the target. */ HgfsFileNameV3 fileName; } HgfsDirEntry; typedef #include "vmware_pack_begin.h" struct HgfsReplySearchReadV3 { uint64 count; /* Number of directory entries. */ uint64 reserved; /* Reserved for future use. */ char payload[1]; /* Directory entries. */ } #include "vmware_pack_end.h" HgfsReplySearchReadV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSearchClose { HgfsRequest header; HgfsHandle search; /* Opaque search ID used by the server */ } #include "vmware_pack_end.h" HgfsRequestSearchClose; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplySearchClose { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplySearchClose; typedef #include "vmware_pack_begin.h" struct HgfsRequestSearchCloseV3 { HgfsHandle search; /* Opaque search ID used by the server */ uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsRequestSearchCloseV3; typedef #include "vmware_pack_begin.h" struct HgfsReplySearchCloseV3 { uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplySearchCloseV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestGetattr { HgfsRequest header; HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestGetattr; /* Version 2 of HgfsRequestGetattr */ typedef #include "vmware_pack_begin.h" struct HgfsRequestGetattrV2 { HgfsRequest header; HgfsAttrHint hints; /* Flags for file handle valid. */ HgfsHandle file; /* Opaque file ID used by the server. */ HgfsFileName fileName; /* Filename used when file handle invalid. */ } #include "vmware_pack_end.h" HgfsRequestGetattrV2; typedef #include "vmware_pack_begin.h" struct HgfsRequestGetattrV3 { HgfsAttrHint hints; /* Flags for file handle valid. */ uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 fileName; /* Filename used when file handle invalid. */ } #include "vmware_pack_end.h" HgfsRequestGetattrV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplyGetattr { HgfsReply header; HgfsAttr attr; } #include "vmware_pack_end.h" HgfsReplyGetattr; /* Version 2 of HgfsReplyGetattr */ typedef #include "vmware_pack_begin.h" struct HgfsReplyGetattrV2 { HgfsReply header; HgfsAttrV2 attr; /* * If the file is a symlink, as specified in attr.type, then this is * the target for the symlink. If the file is not a symlink, this should * be ignored. * * This filename is in "CPNameLite" format. See CPNameLite.c for details. */ HgfsFileName symlinkTarget; } #include "vmware_pack_end.h" HgfsReplyGetattrV2; typedef #include "vmware_pack_begin.h" struct HgfsReplyGetattrV3 { HgfsAttrV2 attr; /* * If the file is a symlink, as specified in attr.type, then this is * the target for the symlink. If the file is not a symlink, this should * be ignored. * * This filename is in "CPNameLite" format. See CPNameLite.c for details. */ uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 symlinkTarget; } #include "vmware_pack_end.h" HgfsReplyGetattrV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSetattr { HgfsRequest header; HgfsAttrChanges update; /* Which fields need to be updated */ HgfsAttr attr; HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestSetattr; /* Version 2 of HgfsRequestSetattr */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSetattrV2 { HgfsRequest header; HgfsAttrHint hints; HgfsAttrV2 attr; HgfsHandle file; /* Opaque file ID used by the server. */ HgfsFileName fileName; /* Filename used when file handle invalid. */ } #include "vmware_pack_end.h" HgfsRequestSetattrV2; typedef #include "vmware_pack_begin.h" struct HgfsRequestSetattrV3 { HgfsAttrHint hints; HgfsAttrV2 attr; uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 fileName; /* Filename used when file handle invalid. */ } #include "vmware_pack_end.h" HgfsRequestSetattrV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplySetattr { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplySetattr; /* Version 2 of HgfsReplySetattr */ typedef #include "vmware_pack_begin.h" struct HgfsReplySetattrV2 { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplySetattrV2; typedef #include "vmware_pack_begin.h" struct HgfsReplySetattrV3 { uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplySetattrV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestCreateDir { HgfsRequest header; HgfsPermissions permissions; HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestCreateDir; /* Version 2 of HgfsRequestCreateDir */ typedef #include "vmware_pack_begin.h" struct HgfsRequestCreateDirV2 { HgfsRequest header; HgfsCreateDirValid mask; HgfsPermissions specialPerms; HgfsPermissions ownerPerms; HgfsPermissions groupPerms; HgfsPermissions otherPerms; HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestCreateDirV2; /* Version 3 of HgfsRequestCreateDir */ typedef #include "vmware_pack_begin.h" struct HgfsRequestCreateDirV3 { HgfsCreateDirValid mask; HgfsPermissions specialPerms; HgfsPermissions ownerPerms; HgfsPermissions groupPerms; HgfsPermissions otherPerms; HgfsAttrFlags fileAttr; HgfsFileNameV3 fileName; } #include "vmware_pack_end.h" HgfsRequestCreateDirV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplyCreateDir { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplyCreateDir; /* Version 2 of HgfsReplyCreateDir */ typedef #include "vmware_pack_begin.h" struct HgfsReplyCreateDirV2 { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplyCreateDirV2; /* Version 3 of HgfsReplyCreateDir */ typedef #include "vmware_pack_begin.h" struct HgfsReplyCreateDirV3 { uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplyCreateDirV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsRequestDelete { HgfsRequest header; HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestDelete; /* Version 2 of HgfsRequestDelete */ typedef #include "vmware_pack_begin.h" struct HgfsRequestDeleteV2 { HgfsRequest header; HgfsDeleteHint hints; HgfsHandle file; /* Opaque file ID used by the server. */ HgfsFileName fileName; /* Name used if the file is HGFS_HANDLE_INVALID */ } #include "vmware_pack_end.h" HgfsRequestDeleteV2; /* Version 3 of HgfsRequestDelete */ typedef #include "vmware_pack_begin.h" struct HgfsRequestDeleteV3 { HgfsDeleteHint hints; uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 fileName; /* Name used if the file is HGFS_HANDLE_INVALID */ } #include "vmware_pack_end.h" HgfsRequestDeleteV3; /* Deprecated */ typedef #include "vmware_pack_begin.h" struct HgfsReplyDelete { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplyDelete; /* Version 2 of HgfsReplyDelete */ typedef #include "vmware_pack_begin.h" struct HgfsReplyDeleteV2 { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplyDeleteV2; /* Version 2 of HgfsReplyDelete */ typedef #include "vmware_pack_begin.h" struct HgfsReplyDeleteV3 { uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplyDeleteV3; /* * The size of the HgfsFileName struct is variable depending on the * length of the name, so you can't use request->newName to get the * actual address of the new name, because where it starts is * dependant on how long the oldName is. To get the address of * newName, use this: * * &oldName + sizeof(HgfsFileName) + oldName.length */ typedef #include "vmware_pack_begin.h" struct HgfsRequestRename { HgfsRequest header; HgfsFileName oldName; HgfsFileName newName; } #include "vmware_pack_end.h" HgfsRequestRename; typedef #include "vmware_pack_begin.h" struct HgfsReplyRename { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplyRename; typedef #include "vmware_pack_begin.h" struct HgfsRequestRenameV2 { HgfsRequest header; HgfsRenameHint hints; HgfsHandle srcFile; /* Opaque file ID to "old name" used by the server. */ HgfsHandle targetFile; /* Opaque file ID to "old name" used by the server. */ HgfsFileName oldName; HgfsFileName newName; } #include "vmware_pack_end.h" HgfsRequestRenameV2; typedef #include "vmware_pack_begin.h" struct HgfsReplyRenameV2 { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplyRenameV2; /* HgfsRequestRename and HgfsReplyRename for v3. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestRenameV3 { HgfsRenameHint hints; uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 oldName; HgfsFileNameV3 newName; } #include "vmware_pack_end.h" HgfsRequestRenameV3; typedef #include "vmware_pack_begin.h" struct HgfsReplyRenameV3 { uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplyRenameV3; typedef #include "vmware_pack_begin.h" struct HgfsRequestQueryVolume { HgfsRequest header; HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestQueryVolume; typedef #include "vmware_pack_begin.h" struct HgfsReplyQueryVolume { HgfsReply header; uint64 freeBytes; uint64 totalBytes; } #include "vmware_pack_end.h" HgfsReplyQueryVolume; /* HgfsRequestQueryVolume and HgfsReplyQueryVolume for v3. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestQueryVolumeV3 { uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 fileName; } #include "vmware_pack_end.h" HgfsRequestQueryVolumeV3; typedef #include "vmware_pack_begin.h" struct HgfsReplyQueryVolumeV3 { uint64 freeBytes; uint64 totalBytes; uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplyQueryVolumeV3; /* New operations for Version 2 */ typedef #include "vmware_pack_begin.h" struct HgfsRequestServerLockChange { HgfsRequest header; HgfsHandle file; HgfsLockType newServerLock; } #include "vmware_pack_end.h" HgfsRequestServerLockChange; typedef #include "vmware_pack_begin.h" struct HgfsReplyServerLockChange { HgfsReply header; HgfsLockType serverLock; } #include "vmware_pack_end.h" HgfsReplyServerLockChange; typedef #include "vmware_pack_begin.h" struct HgfsRequestSymlinkCreate { HgfsRequest header; HgfsFileName symlinkName; /* This filename is in "CPNameLite" format. See CPNameLite.c for details. */ HgfsFileName targetName; } #include "vmware_pack_end.h" HgfsRequestSymlinkCreate; typedef #include "vmware_pack_begin.h" struct HgfsReplySymlinkCreate { HgfsReply header; } #include "vmware_pack_end.h" HgfsReplySymlinkCreate; /* HgfsRequestSymlinkCreate and HgfsReplySymlinkCreate for v3. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSymlinkCreateV3 { uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 symlinkName; /* This filename is in "CPNameLite" format. See CPNameLite.c for details. */ HgfsFileNameV3 targetName; } #include "vmware_pack_end.h" HgfsRequestSymlinkCreateV3; typedef #include "vmware_pack_begin.h" struct HgfsReplySymlinkCreateV3 { uint64 reserved; /* Reserved for future use */ } #include "vmware_pack_end.h" HgfsReplySymlinkCreateV3; /* HGFS protocol version 4 definitions. */ #define HGFS_HEADER_VERSION_1 1 #define HGFS_HEADER_VERSION HGFS_HEADER_VERSION_1 /* * Flags to indicate the type of packet following the header and * the overall state of the operation. */ #define HGFS_PACKET_FLAG_REQUEST (1 << 0) // Request packet #define HGFS_PACKET_FLAG_REPLY (1 << 1) // Reply packet #define HGFS_PACKET_FLAG_INFO_EXTERROR (1 << 2) // Info has ext error #define HGFS_PACKET_FLAG_VALID_FLAGS (0x7) // Mask for valid values typedef #include "vmware_pack_begin.h" struct HgfsHeader { uint8 version; /* Header version. */ uint8 reserved1[3]; /* Reserved for future use. */ HgfsOp dummy; /* Needed to distinguish between older and newer header. */ uint32 packetSize; /* Size of the packet, including the header size. */ uint32 headerSize; /* Size of the Hgfs header. */ uint32 requestId; /* Request ID. */ HgfsOp op; /* Operation. */ uint32 status; /* Return value. */ uint32 flags; /* Flags. See above. */ uint32 information; /* Generic field, used e.g. for native error code. */ uint64 sessionId; /* Session ID. */ uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsHeader; /* * If no flags are set then the capability is not supported by the host. */ #define HGFS_REQUEST_NOT_SUPPORTED 0 /* * Flag HGFS_REQUEST_SUPPORTED is set for every requests that are supported by the host. */ #define HGFS_REQUEST_SUPPORTED (1 << 0) /* * Following flags define which optional parameters for file open * requests are supported by the host. * HGFS_OPENV4_SUPPORTS_EA - host is capable of setting EA when creating * a new file. * HGFS_OPENV4_SUPPORTS_ACL - host is capable of setting ACLs when creating * a new file. * HGFS_OPENV4_SUPPORTS_NAMED_STREAMS - opening/enumerating named streams * is supported. * HGFS_OPENV4_SUPPORTS_SHARED_ACCESS - host supports file sharing restrictions. * HGFS_OPENV4_SUPPORTS_UNIX_PERMISSIONS - host stores POSIX permissions with * file. * HGFS_OPENV4_POSIX_FILE_DELETION - host supports POSIX file deletion semantics. */ typedef uint32 HgfsOpenV4Capabilities; #define HGFS_OPENV4_SUPPORTS_EA (1 << 1) #define HGFS_OPENV4_SUPPORTS_ACL (1 << 2) #define HGFS_OPENV4_SUPPORTS_NAMED_STREAMS (1 << 3) #define HGFS_OPENV4_SUPPORTS_SHARED_ACCESS (1 << 4) #define HGFS_OPENV4_SUPPORTS_UNIX_PERMISSIONS (1 << 5) #define HGFS_OPENV4_POSIX_FILE_DELETION (1 << 6) /* * There is a significant difference in byte range locking semantics between Windows * and POSIX file systems. Windows implements mandatory locking which means that every * read or write request that conflicts with byte range locks is rejected. POSIX has * an advisory locking which means that locks are validated only when another lock is * requested and are not enforced for read/write operations. * Applications in guest OS may expect byte range locking semantics that matches guest * OS which may be different from semantics that is natively supported by host OS. In * this case either HGFS server or HGFS client should provide compensation for the host * OS semantics to maintain application compatibility. * Client must know if the server is capable to provide appropriate byte range locking * semantics to perform some compensation on behalf of server when necessary. * * Following flags define various capabilities of byte range lock implementation on * the host. * * HGFS_BYTE_RANGE_LOCKS_SUPPORTS_64 means that server is capable of locking 64 bit * length ranges. * HGFS_BYTE_RANGE_LOCKS_SUPPORTS_32 means that server is limited to 32-bit ranges. * HGFS_BYTE_RANGE_LOCKS_SUPPORTS_MANDATORY means that server is capable of enforcing * read/write restrictions for locked ranges. * HGFS_BYTE_RANGE_LOCKS_SUPPORTS_ADVISORY means that server supports advisory locking; * locks are validated only for other bytes * range locking and are not enforced * for read/write operations. */ typedef uint32 HgfsByteRangeLockingCapabilities; #define HGFS_BYTE_RANGE_LOCKS_SUPPORTS_64 (1 << 1) #define HGFS_BYTE_RANGE_LOCKS_SUPPORTS_32 (1 << 2) #define HGFS_BYTE_RANGE_LOCKS_SUPPORTS_MANDATORY (1 << 3) #define HGFS_BYTE_RANGE_LOCKS_SUPPORTS_ADVISORY (1 << 4) /* HGFS_SUPPORTS_HARD_LINKS is set when the host supports hard links. */ typedef uint32 HgfsLinkMoveCapabilities; #define HGFS_SUPPORTS_HARD_LINKS (1 << 1) /* * HGFS_SET_WATCH_SUPPORTS_FINE_GRAIN_EVENTS is set when host supports * fine grain event reporting for directory notification. */ typedef uint32 HgfsSetWatchCapabilities; #define HGFS_SET_WATCH_SUPPORTS_FINE_GRAIN_EVENTS (1 << 1) typedef #include "vmware_pack_begin.h" struct HgfsCapability { HgfsOp op; /* Op. */ uint32 flags; /* Flags. */ } #include "vmware_pack_end.h" HgfsCapability; typedef HgfsFileName HgfsUserName; typedef HgfsFileName HgfsGroupName; /* Following structures describe user identity on the host which runs HGFS service. */ typedef #include "vmware_pack_begin.h" struct HgfsIdentity { uint32 uid; /* user id. */ uint32 gid; /* Primary group id. */ HgfsUserName user; /* User name in form specified in RFC 3530. */ HgfsGroupName group; /* Group name in form specified in RFC 3530. */ } #include "vmware_pack_end.h" HgfsIdentity; #define HGFS_INVALID_SESSION_ID (~((uint64)0)) /* * The HGFS session flags. These determine the state and validity of the session * information. * It is envisaged that flags will be set for notifying the clients of file system * feature support that transcend multiple request types i.e., HGFS opcodes. */ typedef uint32 HgfsSessionFlags; #define HGFS_SESSION_MAXPACKETSIZE_VALID (1 << 0) #define HGFS_SESSION_CHANGENOTIFY_ENABLED (1 << 1) #define HGFS_SESSION_OPLOCK_ENABLED (1 << 2) typedef #include "vmware_pack_begin.h" struct HgfsRequestCreateSessionV4 { uint32 numCapabilities; /* Number of capabilities to follow. */ uint32 maxPacketSize; /* Maximum packet size supported. */ HgfsSessionFlags flags; /* Session capability flags. */ uint32 reserved; /* Reserved for future use. */ HgfsCapability capabilities[1]; /* Array of HgfsCapabilities. */ } #include "vmware_pack_end.h" HgfsRequestCreateSessionV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyCreateSessionV4 { uint64 sessionId; /* Session ID. */ uint32 numCapabilities; /* Number of capabilities to follow. */ uint32 maxPacketSize; /* Maximum packet size supported. */ uint32 identityOffset; /* Offset to HgfsIdentity or 0 if no identity. */ HgfsSessionFlags flags; /* Flags. */ uint32 reserved; /* Reserved for future use. */ HgfsCapability capabilities[1]; /* Array of HgfsCapabilities. */ } #include "vmware_pack_end.h" HgfsReplyCreateSessionV4; typedef #include "vmware_pack_begin.h" struct HgfsRequestDestroySessionV4 { uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsRequestDestroySessionV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyDestroySessionV4 { uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplyDestroySessionV4; /* Adds new error status: HGFS_STATUS_INVALID_SESSION. */ /* * If file handle is used to set watch (HGFS_FILE_NAME_USE_FILE_DESC * is set in the fileName), closing this handle implicitly removes the watch. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSetWatchV4 { uint64 events; /* What events to watch? */ uint32 flags; /* Flags. */ uint64 reserved; /* Reserved for future use. */ HgfsFileNameV3 fileName; /* Filename to watch. */ } #include "vmware_pack_end.h" HgfsRequestSetWatchV4; /* * Coarse grain notification event types. */ #define HGFS_ACTION_ADDED (1 << 0) /* File was added. */ #define HGFS_ACTION_REMOVED (1 << 1) /* File was removed. */ #define HGFS_ACTION_MODIFIED (1 << 2) /* File attributes were changed. */ #define HGFS_ACTION_RENAMED (1 << 3) /* File was renamed. */ /* * Fine grain notification event types. * HgfsRequestSetWatch events. */ #define HGFS_NOTIFY_ACCESS (1 << 0) /* File accessed (read) */ #define HGFS_NOTIFY_ATTRIB (1 << 1) /* File attributes changed. */ #define HGFS_NOTIFY_SIZE (1 << 2) /* File size changed. */ #define HGFS_NOTIFY_ATIME (1 << 3) /* Access time changed. */ #define HGFS_NOTIFY_MTIME (1 << 4) /* Modification time changed. */ #define HGFS_NOTIFY_CTIME (1 << 5) /* Attribute time changed. */ #define HGFS_NOTIFY_CRTIME (1 << 6) /* Creation time changed. */ #define HGFS_NOTIFY_NAME (1 << 7) /* File / Directory name. */ #define HGFS_NOTIFY_OPEN (1 << 8) /* File opened */ #define HGFS_NOTIFY_CLOSE_WRITE (1 << 9) /* Modified file closed. */ #define HGFS_NOTIFY_CLOSE_NOWRITE (1 << 10) /* Non-modified file closed. */ #define HGFS_NOTIFY_CREATE_FILE (1 << 11) /* File created */ #define HGFS_NOTIFY_CREATE_DIR (1 << 12) /* Directory created */ #define HGFS_NOTIFY_DELETE_FILE (1 << 13) /* File deleted */ #define HGFS_NOTIFY_DELETE_DIR (1 << 14) /* Directory deleted */ #define HGFS_NOTIFY_DELETE_SELF (1 << 15) /* Watched directory deleted */ #define HGFS_NOTIFY_MODIFY (1 << 16) /* File modified. */ #define HGFS_NOTIFY_MOVE_SELF (1 << 17) /* Watched directory moved. */ #define HGFS_NOTIFY_OLD_FILE_NAME (1 << 18) /* Rename: old file name. */ #define HGFS_NOTIFY_NEW_FILE_NAME (1 << 19) /* Rename: new file name. */ #define HGFS_NOTIFY_OLD_DIR_NAME (1 << 20) /* Rename: old dir name. */ #define HGFS_NOTIFY_NEW_DIR_NAME (1 << 21) /* Rename: new dir name. */ #define HGFS_NOTIFY_CHANGE_EA (1 << 22) /* Extended attributes. */ #define HGFS_NOTIFY_CHANGE_SECURITY (1 << 23) /* Security/permissions. */ #define HGFS_NOTIFY_ADD_STREAM (1 << 24) /* Named stream created. */ #define HGFS_NOTIFY_DELETE_STREAM (1 << 25) /* Named stream deleted. */ #define HGFS_NOTIFY_CHANGE_STREAM_SIZE (1 << 26) /* Named stream size changed. */ #define HGFS_NOTIFY_CHANGE_STREAM_LAST_WRITE (1 << 27) /* Stream timestamp changed. */ #define HGFS_NOTIFY_WATCH_DELETED (1 << 28) /* Dir with watch deleted. */ #define HGFS_NOTIFY_EVENTS_DROPPED (1 << 29) /* Notifications dropped. */ /* HgfsRequestSetWatch flags. */ #define HGFS_NOTIFY_FLAG_WATCH_TREE (1 << 0) /* Watch the entire directory tree. */ #define HGFS_NOTIFY_FLAG_DONT_FOLLOW (1 << 1) /* Don't follow symlinks. */ #define HGFS_NOTIFY_FLAG_ONE_SHOT (1 << 2) /* Generate only one notification. */ #define HGFS_NOTIFY_FLAG_POSIX_HINT (1 << 3) /* Client is POSIX and thus expects * fine grain notification. Server * may provide coarse grain * notification even if this flag is * set. */ typedef uint64 HgfsSubscriberHandle; #define HGFS_INVALID_SUBSCRIBER_HANDLE ((HgfsSubscriberHandle)~((HgfsSubscriberHandle)0)) typedef #include "vmware_pack_begin.h" struct HgfsReplySetWatchV4 { HgfsSubscriberHandle watchId; /* Watch identifier for subsequent references. */ uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplySetWatchV4; typedef #include "vmware_pack_begin.h" struct HgfsRequestRemoveWatchV4 { HgfsSubscriberHandle watchId; /* Watch identifier to remove. */ } #include "vmware_pack_end.h" HgfsRequestRemoveWatchV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyRemoveWatchV4 { uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplyRemoveWatchV4; typedef #include "vmware_pack_begin.h" struct HgfsNotifyEventV4 { uint32 nextOffset; /* Offset of next event; 0 if it i sthe last one. */ uint64 mask; /* Event occurred. */ uint64 reserved; /* Reserved for future use. */ HgfsFileName fileName; /* Filename. */ } #include "vmware_pack_end.h" HgfsNotifyEventV4; /* Too many events, some or all event were dropped by the server. */ #define HGFS_NOTIFY_FLAG_OVERFLOW (1 << 0) /* Watch had been removed either explicitly or implicitly. */ #define HGFS_NOTIFY_FLAG_REMOVED (1 << 1) /* Server generated coasrse grain events. */ #define HGFS_NOTIFY_FLAG_COARSE_GRAIN (1 << 2) typedef #include "vmware_pack_begin.h" struct HgfsRequestNotifyV4 { HgfsSubscriberHandle watchId; /* Watch identifier. */ uint32 flags; /* Various flags. */ uint32 count; /* Number of events occured. */ uint64 reserved; /* Reserved for future use. */ HgfsNotifyEventV4 events[1]; /* Events. HgfsNotifyEvent(s). */ } #include "vmware_pack_end.h" HgfsRequestNotifyV4; // Query EA flags values. #define HGFS_QUERY_EA_INDEX_SPECIFIED (1 << 0) #define HGFS_QUERY_EA_SINGLE_ENTRY (1 << 1) #define HGFS_QUERY_EA_RESTART_SCAN (1 << 2) typedef #include "vmware_pack_begin.h" struct HgfsRequestQueryEAV4 { uint32 flags; /* EA flags. */ uint32 index; uint64 reserved; /* Reserved for future use. */ uint32 eaNameLength; /* EA name length. */ uint32 eaNameOffset; /* Offset of the eaName field. */ HgfsFileNameV3 fileName; /* File to watch. */ char eaNames[1]; /* List of NULL terminated EA names. * Actual location of the data depends on * fileName length and defined by eaNameOffset. */ } #include "vmware_pack_end.h" HgfsRequestQueryEAV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyQueryEAV4 { uint32 nextOffset; /* Offset of the next structure when more then * one record is returned. */ uint32 flags; /* EA flags. */ uint32 index; /* Index needed to resume scan. */ uint64 reserved; /* Reserved for future use. */ uint32 eaDataLength; /* EA value length. */ char eaData[1]; /* NULL termianed EA name followed by EA value. */ } #include "vmware_pack_end.h" HgfsReplyQueryEAV4; typedef #include "vmware_pack_begin.h" struct HgfsEAV4 { uint32 nextOffset; /* Offset of the next structure in the chain. */ uint32 valueLength; /* EA value length. */ char data[1]; /* NULL terminated EA name followed by EA value. */ } #include "vmware_pack_end.h" HgfsEAV4; typedef #include "vmware_pack_begin.h" struct HgfsRequestSetEAV4 { uint32 flags; /* Flags, see below. */ uint64 reserved; /* Reserved for future use. */ uint32 numEAs; /* Number of EAs in this request. */ HgfsEAV4 attributes[1]; /* Array of attributes. */ } #include "vmware_pack_end.h" HgfsRequestSetEAV4; typedef #include "vmware_pack_begin.h" struct HgfsReplySetEAV4 { uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplySetEAV4; /* * EA Flags. When both flags are set EA is either created or replaced if it exists. * HGFS_EA_FLAG_CREATE - create if EA is not present, error otherwise. * HGFS_EA_FLAG_REPLACE - Replace exisitng EA. Error if EA not already present. */ #define HGFS_EA_FLAG_CREATE (1 << 0) #define HGFS_EA_FLAG_REPLACE (1 << 1) /* * Byte range lock flag values: * HGFS_RANGE_LOCK_EXCLUSIVE - Requested lock is exclusive when this flag is set, * otherwise it is a shared lock. * HGFS_RANGE_LOCK_FAIL_IMMEDIATLY - If the flag is not set server waits until the * lock becomes available. */ #define HGFS_RANGE_LOCK_EXCLUSIVE (1 << 0) #define HGFS_RANGE_LOCK_FAIL_IMMEDIATLY (1 << 1) typedef #include "vmware_pack_begin.h" struct HgfsRequestLockRangeV4 { HgfsHandle fid; /* File to take lock on. */ uint32 flags; /* Various flags. */ uint64 start; /* Starting offset in the file. */ uint64 length; /* Number of bytes to lock. */ uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsRequestLockRangeV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyLockRangeV4 { uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplyLockRangeV4; #define HGFS_RANGE_LOCK_UNLOCK_ALL (1 << 0) typedef #include "vmware_pack_begin.h" struct HgfsRequestUnlockRangeV4 { HgfsHandle fid; /* File to take lock on. */ uint32 flags; /* Various flags. */ uint64 start; /* Starting offset in the file. */ uint64 length; /* Number of bytes to lock. */ uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsRequestUnlockRangeV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyUnlockRangeV4 { uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplyUnlockRangeV4; /* * There are three types of oplocks: level 1, batch, and level 2. Both the level 1 and * batch oplocks are "exclusive access" opens. They are used slightly differently, * however, and hence have somewhat different semantics. A level 2 oplock is a "shared * access" grant on the file. * Level 1 is used by a remote client that wishes to modify the data. Once granted a * Level 1 oplock, the remote client may cache the data, modify the data in its cache * and need not write it back to the server immediately. * Batch oplocks are used by remote clients for accessing script files where the file is * opened, read or written, and then closed repeatedly. Thus, a batch oplock * corresponds not to a particular application opening the file, but rather to a remote * clients network file system caching the file because it knows something about the * semantics of the given file access. The name "batch" comes from the fact that this * behavior was observed by Microsoft with "batch files" being processed by command line * utilities. Log files especially exhibit this behavior when a script it being * processed each command is executed in turn. If the output of the script is redirected * to a log file the file fits the pattern described earlier, namely open/write/close. * With many lines in a file this pattern can be repeated hundreds of times. * Level 2 is used by a remote client that merely wishes to read the data. Once granted * a Level 2 oplock, the remote client may cache the data and need not worry that the * data on the remote file server will change without it being advised of that change. * An oplock must be broken whenever the cache consistency guarantee provided by the * oplock can no longer be provided. Thus, whenever a second network client attempts to * access data in the same file across the network, the file server is responsible for * "breaking" the oplocks and only then allowing the remote client to access the file. * This ensures that the data is guaranteed to be consistent and hence we have preserved * the consistency guarantees essential to proper operation. * * HGFS_OPLOCK_NONE: no oplock. No caching on client side. * HGFS_OPLOCK_SHARED: shared (or LEVEL II) oplock. Read caching is allowed. * HGFS_OPLOCK_EXCLUSIVE: exclusive (or LEVEL I) oplock. Read/write caching is allowed. * HGFS_OPLOCK_BATCH: batch oplock. Read/Write and Open caching is allowed. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestServerLockChangeV2 { HgfsHandle fid; /* File to take lock on. */ HgfsLockType serverLock; /* Lock type. */ uint64 reserved; } #include "vmware_pack_end.h" HgfsRequestServerLockChangeV2; typedef #include "vmware_pack_begin.h" struct HgfsReplyServerLockChangeV2 { HgfsLockType serverLock; /* Lock granted. */ uint64 reserved; } #include "vmware_pack_end.h" HgfsReplyServerLockChangeV2; /* * This request is sent from server to the client to notify that oplock * is revoked or downgraded. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestOplockBreakV4 { HgfsHandle fid; /* File handle. */ HgfsLockType serverLock; /* Lock downgraded to this type. */ uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsRequestOplockBreakV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyOplockBreakV4 { HgfsHandle fid; /* File handle. */ HgfsLockType serverLock; /* Lock type. */ uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplyOplockBreakV4; /* * Flusing of a whole volume is not supported. * Flusing of reqular files is supported on all hosts. * Flusing of directories is supproted on POSIX hosts and is * NOOP on Windows hosts. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestFsyncV4 { HgfsHandle fid; /* File to sync. */ uint64 reserved; } #include "vmware_pack_end.h" HgfsRequestFsyncV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyFsyncV4 { uint64 reserved; } #include "vmware_pack_end.h" HgfsReplyFsyncV4; /* * This request is name based only. * Server fails this request if HGFS_FILE_E_USE_FILE_DESC is set in the fileName. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestAccessCheckV4 { HgfsFileNameV3 fileName; /* File concerned. */ HgfsPermissions perms; /* Permissions to check for. */ uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsRequestAccessCheckV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyAccessCheckV4 { uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplyAccessCheckV4; /* * Additional HgfsPersmissions type: checks file existense without * requesting any particular access. * Matches F_OK mode parameter for POSIX access (2) API. */ #define HGFS_PERM_EXISTS 8 /* * HGFS_PLATFORM_ALL is a HGFS specific platform independent FSCTL * that correspond to different OS specific codes. * Other types of FSCTL are platform specific to allow better user * experience when guest and host OS are the same. HGFS does not interpret * platform specific FSCTL in any way, it just passes it through to the * host. If the host run appropriate OS it executes FSCTL on user's behalf, * otherwise it fails the request. */ typedef enum HgfsPlatformType { HGFS_PLATFORM_ALL, HGFS_PLATFORM_WINDOWS, HGFS_PLATFORM_LINUX, HGFS_PLATFORM_MAC }HgfsPlatformType; #define HGFS_FSCTL_SET_SPARSE 1 /* Platform independent FSCTL to make file sparse. */ /* Platform together with the code define exact meaning of the operation. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestFsctlV4 { HgfsHandle fid; uint32 code; HgfsPlatformType platform; uint32 dataLength; char data[1]; } #include "vmware_pack_end.h" HgfsRequestFsctlV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyFsctlV4 { uint32 dataLength; char data[1]; } #include "vmware_pack_end.h" HgfsReplyFsctlV4; /* * Creating a new file or reading file attributes involves ACL. There is a good * definition of multi-platform ACLs in RFC 3530, section 5.11. HGFS should use * ACLs defined in this document (http://tools.ietf.org/html/rfc3530#section-5.11). * ACL support is not mandatory. If a request to create file with ACL comes to a host * that does not support ACL, the request should succeed and setting ACL is ignored. * Such behavior is consistent with other file systems. */ typedef uint64 HgfsOpenCreateOptions; /* O_SYMLINK in Mac OS or FILE_FLAG_OPEN_REPARSE_POINT in Windows. */ #define HGFS_OPENCREATE_OPTION_SYMLINK (1 << 0) /* O_SHLOCK in Mac OS or obtain shared range lock for the whole file. */ #define HGFS_OPENCREATE_OPTION_SHLOCK (1 << 1) /* O_EXLOCK in Mac OS or obtain exclusive range lock for the whole file. */ #define HGFS_OPENCREATE_OPTION_EXLOCK (1 << 2) /* O_SYNC in Linux, ignored in Mac, FILE_FLAG_WRITE_THROUGH in Windows. */ #define HGFS_OPENCREATE_OPTION_WRITETHROUGH (1 << 3) /* FILE_FLAG_NO_BUFFERING in Windows, O_SYNC in Linux, ignored on Mac OS. */ #define HGFS_OPENCREATE_OPTION_NO_BUFERING (1 << 4) /* * O_NOFOLLOW in POSIX. Windows server checks for reparse point * and fails the request if file has one. */ #define HGFS_OPENCREATE_OPTION_NO_FOLLOW (1 << 5) /* FILE_FLAG_NO_RECALL in Windows. Ignored by POSIX host. */ #define HGFS_OPENCREATE_OPTION_NO_RECALL (1 << 6) /* FILE_FLAG_RANDOM_ACCESS in Windows. Ignored by POSIX host. */ #define HGFS_OPENCREATE_OPTION_RANDOM (1 << 7) /* FILE_FLAG_SEQUENTIAL_SCAN in Windows. Ignored by POSIX host. */ #define HGFS_OPENCREATE_OPTION_SEQUENTIAL (1 << 8) /* FILE_FLAG_BACKUP_SEMANTICS in Windows. Ignored by POSIX host. */ #define HGFS_OPENCREATE_OPTION_BACKUP_SEMANTICS (1 << 9) /* Fail opening if the file already exists and it is not a directory. */ #define HGFS_OPENCREATE_OPTION_DIRECTORY (1 << 10) /* Fail opening if the file already exists and it is a directory. */ #define HGFS_OPENCREATE_OPTION_NON_DIRECTORY (1 << 11) typedef #include "vmware_pack_begin.h" struct HgfsRequestOpenV4 { HgfsOpenValid mask; /* Bitmask that specified which fields are valid. */ HgfsOpenMode mode; /* Which type of access requested. See desiredAccess */ HgfsOpenFlags flags; /* Which flags to open the file with */ HgfsPermissions specialPerms; /* Desired 'special' permissions for file creation */ HgfsPermissions ownerPerms; /* Desired 'owner' permissions for file creation */ HgfsPermissions groupPerms; /* Desired 'group' permissions for file creation */ HgfsPermissions otherPerms; /* Desired 'other' permissions for file creation */ HgfsAttrFlags attr; /* Attributes, if any, for file creation */ uint64 allocationSize; /* How much space to pre-allocate during creation */ uint32 desiredAccess; /* Extended support for windows access modes */ uint32 shareAccess; /* Windows only, share access modes */ HgfsOpenCreateOptions createOptions; /* Various options. */ HgfsLockType requestedLock; /* The type of lock desired by the client */ HgfsFileNameV3 fileName; /* fid can be used only for relative open, * i.e. to open named stream. */ HgfsFileName streamName; /* Name of the alternative named stream. * All flags are the same as defined in fileName. * The name is used in conjuction with fileName * field, for example if Windows opens file * "abc.txt:stream" then fileName contains * "abc.txt" and streamName contains "stream" */ /* * EA to set if the file is created or overwritten. The parameter should be ignored * if the file already exists. * It is needed to correctly implement Windows semantics for opening files. * It should work atomically - failure to add EA should result in failure to create * the new file. * If the host file system does not support EA server should fail the request rather * then succeeding and silently dropping EA. */ HgfsRequestSetEAV4 extendedAttributes; uint32 aclLength; /* Length of the acl field. */ char acl[1]; /* Multi-platform ACL as defined in RFC 3530. */ } #include "vmware_pack_end.h" HgfsRequestOpenV4; typedef enum HgfsOpenResult { HGFS_FILE_OPENED, HGFS_FILE_CREATED, HGFS_FILE_OVERWRITTEN, HGFS_FILE_SUPERSIDED, } HgfsOpenResult; /* * Win32 API has a special value for the desired access - MAXIMUM_ALLOWED. * Such desired access means that file system must grant as much rights for the file * as it is allowed for the current user. * HGFS client must know what access rights were granted to properly communicate this * information to the IoManager; grantedAccess field is used for this purpose. */ typedef #include "vmware_pack_begin.h" struct HgfsReplyOpenV4 { HgfsHandle file; /* Opaque file ID used by the server */ HgfsLockType grantedLock; /* The type of lock acquired by the server */ HgfsOpenResult openResult; /* Opened/overwritten or a new file created? */ uint32 grantedAccess; /* Granted access rights. */ uint64 fileId; /* Persistent volume-wide unique file id. */ uint64 volumeId; /* Persistent unique volume id. */ } #include "vmware_pack_end.h" HgfsReplyOpenV4; /* * Flags that define behaviour of the move/creating hard link operation. */ typedef uint64 HgfsMoveLinkFlags; #define HGFS_LINKMOVE_FLAG_REPLACE_EXISTING (1 << 0) /* Delete existing target. */ #define HGFS_LINKMOVE_FLAG_HARD_LINK (1 << 1) /* Create hard link. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestLinkMoveV4 { HgfsFileNameV3 oldFileName; /* Path to the exisitng source file.*/ HgfsFileNameV3 newFileName; /* Path to the destinatio name.*/ HgfsMoveLinkFlags flags; /* Flags that define behaviour of the operation.*/ } #include "vmware_pack_end.h" HgfsRequestLinkMoveV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyLinkMove4 { uint64 reserved; /* Reserved for future use. */ } #include "vmware_pack_end.h" HgfsReplyLinkMove4; /* * HgfsQueryVolumeMaskV4 mask in a request defines which volume properties client needs; * mask in a reply defines which properties were actually returned by the host. * * HGFS_QUERY_VOLUME_MASK_SIZE controls totalBytes, freeBytes and availableBytes. * HGFS_QUERY_VOLUME_MASK_FS_CAPABILITIES controls capabilities. * HGFS_QUERY_VOLUME_MASK_ATTRIBUTES controls creationTime. * HGFS_QUERY_VOLUME_MASK_VOLUME_GEOMETRY controls bytesPerSector and sectorPerCluster. * HGFS_QUERY_VOLUME_MASK_VOLUME_LABEL controls volume label. * HGFS_QUERY_VOLUME_MASK_FS_NAME controls fileSystemName. */ typedef uint64 HgfsQueryVolumeMaskV4; #define HGFS_QUERY_VOLUME_MASK_SIZE (1 << 0) #define HGFS_QUERY_VOLUME_MASK_ATTRIBUTES (1 << 1) #define HGFS_QUERY_VOLUME_MASK_FS_CAPABILITIES (1 << 2) #define HGFS_QUERY_VOLUME_MASK_VOLUME_LABEL (1 << 3) #define HGFS_QUERY_VOLUME_MASK_VOLUME_GEOMETRY (1 << 4) #define HGFS_QUERY_VOLUME_MASK_FS_NAME (1 << 5) typedef uint64 HgfsFileSystemCapabilities; #define HGFS_VOLUME_CASE_SENSITIVE (1 << 0) #define HGFS_VOLUME_SUPPORTS_EA (1 << 1) #define HGFS_VOLUME_SUPPORTS_COMPRESSION (1 << 2) #define HGFS_VOLUME_SUPPORTS_SHORT_NAMES (1 << 3) #define HGFS_VOLUME_SUPPORTS_ACL (1 << 4) #define HGFS_VOLUME_READ_ONLY (1 << 5) #define HGFS_VOLUME_SUPPORTS_ENCRYPTION (1 << 6) #define HGFS_VOLUME_SUPPORTS_OBJECT_ID (1 << 7) #define HGFS_VOLUME_SUPPORTS_REMOTE_STORAGE (1 << 8) #define HGFS_VOLUME_SUPPORTS_SYMLINKS (1 << 9) #define HGFS_VOLUME_SUPPORTS_SPARSE_FILES (1 << 10) #define HGFS_VOLUME_SUPPORTS_UNICODE (1 << 11) #define HGFS_VOLUME_SUPPORTS_QUOTA (1 << 12) #define HGFS_VOLUME_SUPPORTS_NAMED_STREAMS (1 << 13) typedef #include "vmware_pack_begin.h" struct HgfsRequestQueryVolumeV4 { HgfsQueryVolumeMaskV4 mask; HgfsFileNameV3 name; } #include "vmware_pack_end.h" HgfsRequestQueryVolumeV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyQueryVolumeV4 { HgfsQueryVolumeMaskV4 mask; /* Identifies which values were set by the host. */ uint64 totalBytes; /* Total volume capacity. */ uint64 freeBytes; /* Free space on the volume. */ uint64 availableBytes; /* Free space available for the user. */ HgfsFileSystemCapabilities capabilities; /* File system capabilities. */ uint64 creationTime; /* Volume creation time. */ uint32 bytesPerSector; /* Sector size for the volume. */ uint32 sectorsPerCluster; /* Cluster size for the volume. */ HgfsFileName volumeLabel; /* Volume name or label. */ HgfsFileName fileSystemName;/* File system name. */ } #include "vmware_pack_end.h" HgfsReplyQueryVolumeV4; typedef uint32 HgfsSearchReadMask; #define HGFS_SEARCH_READ_NAME (1 << 0) #define HGFS_SEARCH_READ_SHORT_NAME (1 << 1) #define HGFS_SEARCH_READ_FILE_SIZE (1 << 2) #define HGFS_SEARCH_READ_ALLOCATION_SIZE (1 << 3) #define HGFS_SEARCH_READ_EA_SIZE (1 << 4) #define HGFS_SEARCH_READ_TIME_STAMP (1 << 5) #define HGFS_SEARCH_READ_FILE_ATTRIBUTES (1 << 6) #define HGFS_SEARCH_READ_FILE_NODE_TYPE (1 << 7) #define HGFS_SEARCH_READ_REPARSE_TAG (1 << 8) #define HGFS_SEARCH_READ_FILE_ID (1 << 9) typedef uint32 HgfsSearchReadFlags; #define HGFS_SEARCH_READ_INITIAL_QUERY (1 << 1) #define HGFS_SEARCH_READ_SINGLE_ENTRY (1 << 2) #define HGFS_SEARCH_READ_FID_OPEN_V4 (1 << 3) #define HGFS_SEARCH_READ_REPLY_FINAL_ENTRY (1 << 4) /* * Read directory request can be used to enumerate files in a directory. * File handle used in the request can be either from HgfsRequestOpenV4 or * HgfsRequestSearchOpenV3. * searchPattern parameter allows filter out file names in the server for optimization. * It is optional - host may ignore patterns and return entries that do not match * the pattern. It is client responsibility to filter out names that do not match * the pattern. * * The mask field in request allows client to specify which properties it is * interested in. It allows to implement optimization in the server by skipping * parameters which client does not need. * * The HGFS Server fills mask field in the reply buffer to specify which * of the requested properties it supports, which may be a subset of the * requested properties. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestSearchReadV4 { HgfsSearchReadMask mask; HgfsSearchReadFlags flags; HgfsHandle fid; uint32 replyDirEntryMaxSize; uint32 restartIndex; uint64 reserved; HgfsFileName searchPattern; } #include "vmware_pack_end.h" HgfsRequestSearchReadV4; typedef #include "vmware_pack_begin.h" struct HgfsDirEntryV4 { uint32 nextEntryOffset; uint32 fileIndex; HgfsSearchReadMask mask; /* Returned mask: may be a subset of requested mask. */ HgfsAttrFlags attrFlags; /* File system attributes of the entry */ HgfsFileType fileType; uint64 fileSize; uint64 allocationSize; uint64 creationTime; uint64 accessTime; uint64 writeTime; uint64 attrChangeTime; uint64 hostFileId; /* File Id of the file on host: inode_t on Linux */ uint32 eaSize; /* Byte size of any extended attributes. */ uint32 reparseTag; /* Windows only: reparse point tag. */ uint64 reserved; /* Reserved for future use. */ HgfsShortFileName shortName; /* Windows only: 8 dot 3 format name. */ HgfsFileName fileName; /* Entry file name. */ } #include "vmware_pack_end.h" HgfsDirEntryV4; typedef #include "vmware_pack_begin.h" struct HgfsReplySearchReadV4 { uint32 numberEntriesReturned; /* number of directory entries in this reply. */ uint32 offsetToContinue; /* Entry index of the directory entry. */ HgfsSearchReadFlags flags; /* Flags to indicate reply specifics */ uint64 reserved; /* Reserved for future use. */ HgfsDirEntryV4 entries[1]; /* Unused as entries transfered using shared memory. */ } #include "vmware_pack_end.h" HgfsReplySearchReadV4; /* * File handle returned by HgfsRequestOpenV4 or later. Descriptors returned by * HgfsHandle fid; earlier versions of HgfsRequestOpen are not supported. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestEnumerateStreamsV4 { uint32 restartIndex; } #include "vmware_pack_end.h" HgfsRequestEnumerateStreamsV4; typedef #include "vmware_pack_begin.h" struct HgfsRequestStreamEntryV4 { uint32 nextEntryOffset; uint32 fileIndex; HgfsFileName fileName; } #include "vmware_pack_end.h" HgfsRequestStreamEntryV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyEnumerateStreamsV4 { uint32 numberEntriesReturned; uint32 offsetToContinue; uint64 reserved; HgfsRequestStreamEntryV4 entries[1]; } #include "vmware_pack_end.h" HgfsReplyEnumerateStreamsV4; typedef #include "vmware_pack_begin.h" struct HgfsRequestGetattrV4 { uint32 mask; uint32 flags; uint64 reserved; HgfsFileNameV3 name; } #include "vmware_pack_end.h" HgfsRequestGetattrV4; /* * V4 reports different file size for symlinks then V3 or V2. * It does not return file name length as EOF - it reports actual EOF. * On POSIX the value is always 0 and on Windows it is an actual EOF of * a file with a reparse point. * Each client must adjust the value for file size according to guest OS rules. * * Mask in HgfsAttr2V2 should be extended to include short name, symlink target and ACL. * If the host does not support a requested feature it is free to clear the * correspondent bit in the mask and ignore the feature. * * Multi-platform notice: symbolic link is represented by a file with REPARSE_POINT * on Windows. Thus Windows supports swtiching a file type between * regular or directory => symlink and back. * Setting symlinkTarget attribute on Windows host results in assigning * reparse point to the host file. */ typedef #include "vmware_pack_begin.h" struct HgfsAttrV4 { HgfsAttrV2 attr; uint32 numberOfLinks; HgfsFileName shortName; HgfsFileName symlinkTarget; uint32 aclLength; uint64 reserved; char acl[1]; } #include "vmware_pack_end.h" HgfsAttrV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyGetattrV4 { HgfsAttrV4 attr; } #include "vmware_pack_end.h" HgfsReplyGetattrV4; typedef #include "vmware_pack_begin.h" struct HgfsRequestSetattrV4 { HgfsAttrHint hints; HgfsAttrV2 attr; uint64 reserved; /* Reserved for future use */ HgfsFileNameV3 fileName; /* Filename used when file handle invalid. */ } #include "vmware_pack_end.h" HgfsRequestSetattrV4; typedef #include "vmware_pack_begin.h" struct HgfsReplySetattrV4 { uint32 mask; /* Defines which attributes were set. */ } #include "vmware_pack_end.h" HgfsReplySetattrV4; /* * Unlike V3 deletion this command can be used to delete both files and directories. * Its semantics depends on whether fid or file path is specified in the fileName. * When path is used it implements/emulates POSIX semantics - name is deleted from * the directory however if the file is opened it is still accessible. When fid is used * the file name disappears from the folder only when the last handle for the file is * closed - Windows style deletion. */ typedef #include "vmware_pack_begin.h" struct HgfsRequestDeleteFileV4 { HgfsFileNameV3 fileName; } #include "vmware_pack_end.h" HgfsRequestDeleteFileV4; typedef #include "vmware_pack_begin.h" struct HgfsReplyDeleteFileV4 { uint64 reserved; } #include "vmware_pack_end.h" HgfsReplyDeleteFileV4; #endif /* _HGFS_PROTO_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsServer.h000066400000000000000000000164301321503522500247620ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _HGFS_SERVER_H_ #define _HGFS_SERVER_H_ #include "hgfs.h" /* for HGFS_PACKET_MAX */ #include "dbllnklst.h" #if defined(__cplusplus) extern "C" { #endif typedef struct HgfsVmxIov { void *va; /* Virtual addr */ uint64 pa; /* Physical address passed by the guest */ uint32 len; /* length of data; should be <= PAGE_SIZE for VMCI; arbitrary for backdoor */ void *context; /* Mapping context */ } HgfsVmxIov; typedef enum { BUF_READABLE, /* Establish readable mappings */ BUF_WRITEABLE, /* Establish writeable mappings */ BUF_READWRITEABLE, /* Establish read-writeable mappings */ } MappingType; typedef uint64 HgfsStateFlags; #define HGFS_STATE_CLIENT_REQUEST (1 << 0) #define HGFS_STATE_ASYNC_REQUEST (1 << 1) typedef struct HgfsPacket { uint64 id; HgfsStateFlags state; /* For metapacket we always establish writeable mappings */ void *metaPacket; size_t metaPacketSize; uint32 metaPacketMappedIov; size_t metaPacketDataSize; Bool metaPacketIsAllocated; MappingType metaMappingType; void *dataPacket; size_t dataPacketSize; uint32 dataPacketMappedIov; size_t dataPacketDataSize; uint32 dataPacketIovIndex; Bool dataPacketIsAllocated; /* What type of mapping was established - readable/ writeable ? */ MappingType dataMappingType; void *replyPacket; size_t replyPacketSize; size_t replyPacketDataSize; Bool replyPacketIsAllocated; /* Iov for the packet private to the channel. */ HgfsVmxIov channelIov[2]; uint32 iovCount; HgfsVmxIov iov[1]; } HgfsPacket; /* * Function used for sending replies to the client for a session. * Passed by the caller at session connect time. */ /* * Send flags. * * Contains a bitwise OR of a combination of the following flags: * HGFS_SEND_CAN_DELAY - directs the channel to try and optimize * otherwise it will send the data immediately. * HGFS_SEND_NO_COMPLETE - directs the channel to not call the * send complete callback. Caller does not call completion notification * callback, for example to free buffers. */ typedef uint32 HgfsSendFlags; #define HGFS_SEND_CAN_DELAY (1 << 0) #define HGFS_SEND_NO_COMPLETE (1 << 1) // Channel capability flags typedef uint32 HgfsChannelFlags; #define HGFS_CHANNEL_SHARED_MEM (1 << 0) #define HGFS_CHANNEL_ASYNC (1 << 1) typedef struct HgfsServerChannelData { HgfsChannelFlags flags; uint32 maxPacketSize; }HgfsServerChannelData; /* Default maximum number of open nodes. */ #define HGFS_MAX_CACHED_FILENODES 30 typedef uint32 HgfsConfigFlags; #define HGFS_CONFIG_USE_HOST_TIME (1 << 0) #define HGFS_CONFIG_NOTIFY_ENABLED (1 << 1) #define HGFS_CONFIG_VOL_INFO_MIN (1 << 2) #define HGFS_CONFIG_OPLOCK_ENABLED (1 << 3) #define HGFS_CONFIG_SHARE_ALL_HOST_DRIVES_ENABLED (1 << 4) typedef struct HgfsServerConfig { HgfsConfigFlags flags; uint32 maxCachedOpenNodes; }HgfsServerConfig; /* * Function used to notify HGFS server that a shared folder has been created or updated. * It allows HGFS server to maintain up-to-date list of shared folders and its * properties. */ typedef uint32 HgfsSharedFolderHandle; #define HGFS_INVALID_FOLDER_HANDLE ((HgfsSharedFolderHandle)~((HgfsSharedFolderHandle)0)) /* * Callback functions to enumerate the share resources. * Filled in by the HGFS server policy and passed in to the HGFS server * so that it can call out to them to enumerate the shares. */ typedef void * (*HgfsServerResEnumInitFunc)(void); typedef Bool (*HgfsServerResEnumGetFunc)(void *data, char const **name, size_t *len, Bool *done); typedef Bool (*HgfsServerResEnumExitFunc)(void *); typedef struct HgfsServerResEnumCallbacks { HgfsServerResEnumInitFunc init; HgfsServerResEnumGetFunc get; HgfsServerResEnumExitFunc exit; } HgfsServerResEnumCallbacks; /* * Server Manager callback functions to enumerate the share resources and state logging. * Passed to the HGFS server on initialization. */ typedef struct HgfsServerMgrCallbacks { HgfsServerResEnumCallbacks enumResources; } HgfsServerMgrCallbacks; typedef enum { HGFS_QUIESCE_FREEZE, HGFS_QUIESCE_THAW, } HgfsQuiesceOp; /* * Function used for invalidating nodes and searches that fall outside of a * share when the list of shares changes. */ typedef void (*HgfsInvalidateObjectsFunc)(DblLnkLst_Links *shares); typedef Bool (*HgfsChannelSendFunc)(void *opaqueSession, HgfsPacket *packet, HgfsSendFlags flags); typedef void * (*HgfsChannelMapVirtAddrFunc)(uint64 pa, uint32 size, void **context); typedef void (*HgfsChannelUnmapVirtAddrFunc)(void **context); typedef void (*HgfsChannelRegisterThreadFunc)(void); typedef void (*HgfsChannelUnregisterThreadFunc)(void); typedef struct HgfsServerChannelCallbacks { HgfsChannelRegisterThreadFunc registerThread; HgfsChannelUnregisterThreadFunc unregisterThread; HgfsChannelMapVirtAddrFunc getReadVa; HgfsChannelMapVirtAddrFunc getWriteVa; HgfsChannelUnmapVirtAddrFunc putVa; HgfsChannelSendFunc send; }HgfsServerChannelCallbacks; typedef struct HgfsServerSessionCallbacks { Bool (*connect)(void *, HgfsServerChannelCallbacks *, HgfsServerChannelData *,void **); void (*disconnect)(void *); void (*close)(void *); void (*receive)(HgfsPacket *packet, void *); void (*invalidateObjects)(void *, DblLnkLst_Links *); uint32 (*invalidateInactiveSessions)(void *); void (*sendComplete)(HgfsPacket *, void *); void (*quiesce)(void *, HgfsQuiesceOp); } HgfsServerSessionCallbacks; /* XXX: TODO delete this layer if no other non-session callbacks are required. */ typedef struct HgfsServerCallbacks { HgfsServerSessionCallbacks session; } HgfsServerCallbacks; Bool HgfsServer_InitState(const HgfsServerCallbacks **, HgfsServerConfig *, HgfsServerMgrCallbacks *); void HgfsServer_ExitState(void); Bool HgfsServer_ShareAccessCheck(HgfsOpenMode accessMode, Bool shareWriteable, Bool shareReadable); uint32 HgfsServer_GetHandleCounter(void); void HgfsServer_SetHandleCounter(uint32 newHandleCounter); #if defined(__cplusplus) } // extern "C" #endif #endif // _HGFS_SERVER_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsServerManager.h000066400000000000000000000052231321503522500262530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _HGFS_SERVER_MANAGER_H_ # define _HGFS_SERVER_MANAGER_H_ #if defined(__cplusplus) extern "C" { #endif /* * hgfsServerManager.h -- * * Common routines needed to register an HGFS server. */ #ifndef VMX86_TOOLS #include "device_shared.h" // For DeviceLock and functions Bool Hgfs_PowerOn(void); void HgfsServerManager_GetDeviceLock(DeviceLock **lock); Bool HgfsServerManager_ChangeState(Bool enable); #else /* VMX86_TOOLS */ //#include "hgfsServer.h" // For HgfsReceiveFlags typedef struct HgfsServerMgrData { const char *appName; // Application name to register void *rpc; // RpcChannel unused void *rpcCallback; // RpcChannelCallback unused void *connection; // Connection object returned on success } HgfsServerMgrData; #define HgfsServerManager_DataInit(mgr, _name, _rpc, _rpcCallback) \ do { \ (mgr)->appName = (_name); \ (mgr)->rpc = (_rpc); \ (mgr)->rpcCallback = (_rpcCallback); \ (mgr)->connection = NULL; \ } while (0) Bool HgfsServerManager_Register(HgfsServerMgrData *data); void HgfsServerManager_Unregister(HgfsServerMgrData *data); Bool HgfsServerManager_ProcessPacket(HgfsServerMgrData *mgrData, char const *packetIn, size_t packetInSize, char *packetOut, size_t *packetOutSize); uint32 HgfsServerManager_InvalidateInactiveSessions(HgfsServerMgrData *mgrData); #endif #if defined(__cplusplus) } // extern "C" #endif #endif // _HGFS_SERVER_MANAGER_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsServerPolicy.h000066400000000000000000000120031321503522500261320ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _HGFS_SERVER_POLICY_H_ #define _HGFS_SERVER_POLICY_H_ #include "vm_basic_types.h" #include "hgfs.h" #include "dbllnklst.h" #include "cpName.h" #include "hgfsServer.h" #if defined(__cplusplus) extern "C" { #endif /* * Name of share that corresponds to the root of the server's * filesystem. */ #define HGFS_SERVER_POLICY_ROOT_SHARE_NAME "root" typedef uint32 HgfsShareOptions; /* * Structure representing one shared folder. We maintain a list of * these to check accesses against. */ typedef struct HgfsSharedFolder { DblLnkLst_Links links; const char *name; /* Name of share */ const char *path; /* * Path of share in server's filesystem. Should * not include final path separator. */ const char *shareTags;/* Tags associated with this share (comma delimited). */ size_t shareTagsLen; /* Length of shareTag string */ size_t nameLen; /* Length of name string */ size_t pathLen; /* Length of path string */ Bool readAccess; /* Read permission for this share */ Bool writeAccess; /* Write permission for this share */ HgfsShareOptions configOptions; /* User-config options. */ HgfsSharedFolderHandle handle; /* Handle assigned by HGFS server * when the folder was registered with it. * Policy package keeps the context and returns * it along with other shared folder properties. * Keeping it here ensures consistent lookup all * properties of the shared folder which takes into * account such details like case sensitive/case * insensitive name lookup. */ } HgfsSharedFolder; /* Per share user configurable options. */ #define HGFS_SHARE_HOST_DEFAULT_CASE (1 << 0) #define HGFS_SHARE_FOLLOW_SYMLINKS (1 << 1) typedef struct HgfsServerPolicy_ShareList { size_t count; char **shareNames; } HgfsServerPolicy_ShareList; Bool HgfsServerPolicy_Init(HgfsInvalidateObjectsFunc invalidateObjects, HgfsServerResEnumCallbacks *enumResources); Bool HgfsServerPolicy_Cleanup(void); HgfsNameStatus HgfsServerPolicy_GetSharePath(char const *nameIn, // IN: size_t nameInLen, // IN: HgfsOpenMode mode, // IN: size_t *sharePathLen, // OUT: char const **sharePath); // OUT: HgfsNameStatus HgfsServerPolicy_GetShareMode(char const *nameIn, // IN: Share name to retrieve size_t nameInLen, // IN: Length of Share name HgfsOpenMode *mode); // OUT: Share's access mode HgfsNameStatus HgfsServerPolicy_GetShareOptions(char const *nameIn, // IN: Share name size_t nameInLen, // IN: Share name length HgfsShareOptions *configOptions); // OUT: Share config options Bool HgfsServerPolicy_IsShareOptionSet(HgfsShareOptions shareOptions, // IN: Config options uint32 option); // IN: Option to check HgfsNameStatus HgfsServerPolicy_ProcessCPName(char const *nameIn, // IN: name in CPName form size_t nameInLen, // IN: length of the name Bool *readAccess, // OUT: Read permissions Bool *writeAccess, // OUT: Write permissions HgfsSharedFolderHandle *handle,// OUT: folder handle char const **shareBaseDir); // OUT: Shared directory void HgfsServerPolicy_FreeShareList(HgfsServerPolicy_ShareList *shareList); // IN: list to free HgfsServerPolicy_ShareList * HgfsServerPolicy_GetSharesWithTag(const char *tag); // IN: tag to search for #if defined(__cplusplus) } // extern "C" #endif #endif // _HGFS_SERVER_POLICY_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsTransport.h000066400000000000000000000160131321503522500255050ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsTransport.h -- * * Transport file shared between guest drivers and host. */ #ifndef _HGFS_TRANSPORT_H_ # define _HGFS_TRANSPORT_H_ #include "vmci_defs.h" /************************************************ * VMCI specific data structures, macros * ************************************************/ /* * Limit payload to 16M. * This limit ensures that list of shared pages fits into VMCI datagram. * Client may impose a lower limit in create session request. */ #define HGFS_VMCI_PACKET_MAX (0x1000000) #define HGFS_VMCI_VERSION_1 0x1 #define HGFS_VMCI_VERSION_2 0x2 typedef enum { HGFS_TS_IO_PENDING, HGFS_TS_IO_COMPLETE, HGFS_TS_IO_FAILED, } HgfsTransportRequestState; typedef enum { HGFS_ASYNC_IOREQ_SHMEM, HGFS_ASYNC_IOREQ_GET_PAGES, HGFS_ASYNC_IOREP, } HgfsTransportReplyType; typedef enum { HGFS_TH_REP_GET_PAGES, HGFS_TH_REQUEST, HGFS_TH_TERMINATE_SESSION, } HgfsTransportRequestType; #define HGFS_VMCI_TRANSPORT_ERROR (VMCI_ERROR_CLIENT_MIN - 1) #define HGFS_VMCI_VERSION_MISMATCH (VMCI_ERROR_CLIENT_MIN - 2) #define HGFS_VMCI_TYPE_NOT_SUPPORTED (VMCI_ERROR_CLIENT_MIN - 3) /* * Used By : Guest and Host * Lives in : Inside HgfsVmciTransportHeader */ typedef #include "vmware_pack_begin.h" struct HgfsIov { uint64 pa; /* Physical addr */ uint32 len; /* length of data; should be <= PAGE_SIZE */ } #include "vmware_pack_end.h" HgfsIov; /* * Used By : Guest and Host * Lives in : Inside HgfsVmciTransportHeader */ typedef #include "vmware_pack_begin.h" struct HgfsAsyncIov { uint64 pa; /* Physical addr */ uint64 va; /* Virtual addr */ uint32 len; /* length of data; should be <= PAGE_SIZE */ uint64 index; /* Guest opaque data; should not be changed by host */ Bool chain; /* Are pages chained ? */ } #include "vmware_pack_end.h" HgfsAsyncIov; /* * Every VMCI request will have this transport Header sent over * in the datagram by the Guest OS. * * Node fields are set to be compatible for backwards compatibility * for version 1 and common for newer versions. * * Used By : Guest and Host * Lives in : Sent by Guest inside VMCI datagram */ typedef #include "vmware_pack_begin.h" struct HgfsVmciHeaderNode { uint32 version; /* Version number */ union { HgfsTransportRequestType pktType; /* Type of packet for client to server */ HgfsTransportReplyType replyType; /* Type of packet for server to client */ }; } #include "vmware_pack_end.h" HgfsVmciHeaderNode; typedef #include "vmware_pack_begin.h" struct HgfsVmciTransportHeader { HgfsVmciHeaderNode node; /* Node: version, type etc. */ uint32 iovCount; /* Number of iovs */ union { HgfsIov iov[1]; /* (PA, len) */ HgfsAsyncIov asyncIov[1]; }; } #include "vmware_pack_end.h" HgfsVmciTransportHeader; /* * Every VMCI request will have this transport Header sent over * in the datagram by the Guest or the Host. * This supersedes the above header and the HgfsVmciAsyncReply structure * below. * * Used By : Guest and Host * Lives in : Sent by Guest and Host inside VMCI datagram */ typedef #include "vmware_pack_begin.h" struct HgfsVmciTransportHeaderV2 { HgfsVmciHeaderNode node; /* Common node for all versions. */ uint32 size; /* Size of the header. */ uint64 pktId; /* Id corresponding to the request */ uint64 flags; /* flags to indicate state of the header */ uint32 pktDataSize; /* packet data size (not buffer size) */ uint64 reserved1; /* For future use, sender must zero */ uint64 reserved2; /* For future use, sender must zero */ uint32 iovCount; /* Number of iovs to follow */ union { HgfsIov iov[1]; /* (PA, len) */ HgfsAsyncIov asyncIov[1]; }; } #include "vmware_pack_end.h" HgfsVmciTransportHeaderV2; #define HGFS_VMCI_HDR_FLAGS_REQUEST (1 << 0) /* CLient to the server */ #define HGFS_VMCI_HDR_FLAGS_REPLY (1 << 1) /* Server to the client */ #define HGFS_VMCI_HDR_FLAGS_ASYNCIOV (1 << 2) /* IOV type is async */ /* * Indicates status of VMCI requests. If the requests are processed sync * by the hgfsServer then guest should see IO_COMPLETE otherwise IO_PENDING. * * Used By: Guest and Host * Lives in: Guest Memory */ typedef #include "vmware_pack_begin.h" struct HgfsVmciTransportStatus { HgfsTransportRequestState status; /* IO_PENDING, IO_COMPLETE, IO_FAILED etc */ uint32 size; /* G->H: Size of the packet,H->G: How much more space is needed */ } #include "vmware_pack_end.h" HgfsVmciTransportStatus; typedef #include "vmware_pack_begin.h" struct HgfsVmciAsyncResponse { uint64 id; /* Id corresponding to the guest request */ } #include "vmware_pack_end.h" HgfsVmciAsyncResponse; typedef #include "vmware_pack_begin.h" struct HgfsVmciAsyncShmem { uint32 count; /* Number of iovs */ HgfsAsyncIov iov[1]; } #include "vmware_pack_end.h" HgfsVmciAsyncShmem; typedef #include "vmware_pack_begin.h" struct HgfsVmciAsyncReply { HgfsVmciHeaderNode node; /* Node: version, type etc. */ union { HgfsVmciAsyncResponse response; HgfsVmciAsyncShmem shmem; }; } #include "vmware_pack_end.h" HgfsVmciAsyncReply; #endif /* _HGFS_TRANSPORT_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsUri.h000066400000000000000000000025321321503522500242510ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hgfsUri.h * * Provides a library for guest applications to convert local pathames to * x-vmware-share:// style URIs */ #ifndef _HGFS_URI_H_ #define _HGFS_URI_H_ #include "vm_basic_types.h" #include "unicode.h" #if defined(_WIN32) char *HgfsUri_ConvertFromUtf16ToHgfsUri(wchar_t *pathNameUtf16, Bool hgfsOnly); #endif // _WIN32 #if defined __linux__ || defined __APPLE__ char *HgfsUri_ConvertFromPathToHgfsUri(const char *pathName, Bool hgfsOnly); #endif // POSIX #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsUtil.h000066400000000000000000000145141321503522500244320ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsUtil.h -- * * Utility functions and macros used by hgfs. */ #ifndef _HGFSUTIL_H_ # define _HGFSUTIL_H_ # if defined __linux__ && defined __KERNEL__ # include "driver-config.h" # include // for time_t and timespec /* Include time.h in userspace code, but not in Solaris kernel code. */ # elif defined __FreeBSD__ && defined _KERNEL /* Do nothing. */ # elif defined __APPLE__ && defined KERNEL # include # else # include # endif # include "vm_basic_types.h" # if !defined _STRUCT_TIMESPEC && \ !defined _TIMESPEC_DECLARED && \ !defined __timespec_defined && \ !defined sun && \ !defined __FreeBSD__ && \ !__APPLE__ && \ !defined _WIN32 struct timespec { time_t tv_sec; long tv_nsec; }; # endif # include "hgfs.h" /* Cross-platform representation of a platform-specific error code. */ #ifndef _WIN32 # if defined __KERNEL__ || defined _KERNEL || defined KERNEL # if defined __linux__ # include # elif defined sun || defined __FreeBSD__ || defined __APPLE__ # include # endif # else # include # endif typedef int HgfsInternalStatus; /* * There is no internal error in Linux. * Define a const that is converted to HGFS_INTERNAL_STATUS_ERROR. */ # define EINTERNAL 1001 #else # include typedef DWORD HgfsInternalStatus; #endif #if defined _WIN32 #define HGFS_ERROR_SUCCESS ERROR_SUCCESS #define HGFS_ERROR_IO ERROR_IO_DEVICE #define HGFS_ERROR_ACCESS_DENIED ERROR_ACCESS_DENIED #define HGFS_ERROR_INVALID_PARAMETER ERROR_INVALID_PARAMETER #define HGFS_ERROR_INVALID_HANDLE ERROR_INVALID_HANDLE #define HGFS_ERROR_PROTOCOL RPC_S_PROTOCOL_ERROR #define HGFS_ERROR_STALE_SESSION ERROR_CONNECTION_INVALID #define HGFS_ERROR_BUSY ERROR_RETRY #define HGFS_ERROR_PATH_BUSY ERROR_RETRY #define HGFS_ERROR_FILE_NOT_FOUND ERROR_FILE_NOT_FOUND #define HGFS_ERROR_FILE_EXIST ERROR_ALREADY_EXISTS #define HGFS_ERROR_NOT_SUPPORTED ERROR_NOT_SUPPORTED #define HGFS_ERROR_NOT_ENOUGH_MEMORY ERROR_NOT_ENOUGH_MEMORY #define HGFS_ERROR_TOO_MANY_SESSIONS ERROR_MAX_SESSIONS_REACHED #define HGFS_ERROR_INTERNAL ERROR_INTERNAL_ERROR #else #define HGFS_ERROR_SUCCESS 0 #define HGFS_ERROR_IO EIO #define HGFS_ERROR_ACCESS_DENIED EACCES #define HGFS_ERROR_INVALID_PARAMETER EINVAL #define HGFS_ERROR_INVALID_HANDLE EBADF #define HGFS_ERROR_PROTOCOL EPROTO #define HGFS_ERROR_STALE_SESSION ENETRESET #define HGFS_ERROR_BUSY EBUSY #define HGFS_ERROR_PATH_BUSY EBUSY #define HGFS_ERROR_FILE_NOT_FOUND ENOENT #define HGFS_ERROR_FILE_EXIST EEXIST #define HGFS_ERROR_NOT_SUPPORTED EOPNOTSUPP #define HGFS_ERROR_NOT_ENOUGH_MEMORY ENOMEM #define HGFS_ERROR_TOO_MANY_SESSIONS ECONNREFUSED #define HGFS_ERROR_INTERNAL EINTERNAL #endif // _WIN32 /* * Unfortunately, we need a catch-all "generic error" to use with * HgfsInternalStatus, because there are times when cross-platform code needs * to return its own errors along with errors from platform specific code. * * Using -1 should be safe because we expect our platforms to use zero as * success and a positive range of numbers as error values. */ #define HGFS_INTERNAL_STATUS_ERROR (-1) #ifndef _WIN32 /* * This error code is used to notify the client that some of the parameters passed * (e.g. file handles) are not supported. Clients are expected to correct * the parameter (e.g. pass file name instead) and retry. * * Note that this error code is artificially made up and in future may conflict * with an "official" error code when added. */ #define EPARAMETERNOTSUPPORTED (MAX_INT32 - 1) #endif /* * FreeBSD (pre-6.0) does not define EPROTO, so we'll define our own error code. */ #if defined __FreeBSD__ && !defined EPROTO #define EPROTO (ELAST + 1) #endif #define HGFS_NAME_BUFFER_SIZE(packetSize, request) (packetSize - (sizeof *request - 1)) #define HGFS_NAME_BUFFER_SIZET(packetSize, sizet) (packetSize - ((sizet) - 1)) #ifndef _WIN32 /* * Routines for converting between Win NT and unix time formats. The * hgfs attributes use the NT time formats, so the linux driver and * server have to convert back and forth. [bac] */ uint64 HgfsConvertToNtTime(time_t unixTime, // IN long nsec); // IN static INLINE uint64 HgfsConvertTimeSpecToNtTime(const struct timespec *unixTime) // IN { return HgfsConvertToNtTime(unixTime->tv_sec, unixTime->tv_nsec); } int HgfsConvertFromNtTime(time_t * unixTime, // OUT uint64 ntTime); // IN int HgfsConvertFromNtTimeNsec(struct timespec *unixTime, // OUT uint64 ntTime); // IN #endif /* !def(_WIN32) */ HgfsStatus HgfsConvertFromInternalStatus(HgfsInternalStatus status); // IN #endif /* _HGFSUTIL_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hgfsVirtualDir.h000066400000000000000000000034741321503522500256050ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * hgfsVirtualDir.h -- * * Defines for virtual directory names in hgfs. */ #ifndef _HGFSVIRTUALDIR_H_ # define _HGFSVIRTUALDIR_H_ /* * These are the names of the virtual directories for accessing UNC * names and drives on the host machine. */ # define HGFS_DRIVE_DIR_NAME "drive" # define HGFS_UNC_DIR_NAME "unc" #define HGFS_STR_LEN(str) (sizeof str - 1) #endif /* _HGFSVIRTUALDIR_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hostType.h000066400000000000000000000026721321503522500244660ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hostType.h -- * * Interface to host-specific information functions * */ #ifndef _HOSTTYPE_H_ #define _HOSTTYPE_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif Bool HostType_OSIsVMK(void); Bool HostType_OSIsSimulator(void); /* Old name. TODO: remove */ static INLINE Bool HostType_OSIsPureVMK(void) { return HostType_OSIsVMK(); } #if defined(__cplusplus) } // extern "C" #endif #endif /* ifndef _HOSTTYPE_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/hostinfo.h000066400000000000000000000166411321503522500245010ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * hostinfo.h -- * * Interface to host-specific information functions * */ #if !defined(_HOSTINFO_H_) #define _HOSTINFO_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #include "vm_basic_defs.h" #include "x86cpuid.h" #include "unicodeTypes.h" #if defined(__cplusplus) extern "C" { #endif typedef enum { HOSTINFO_PROCESS_QUERY_DEAD, // Procss is dead (does not exist) HOSTINFO_PROCESS_QUERY_ALIVE, // Process is alive (does exist) HOSTINFO_PROCESS_QUERY_UNKNOWN // Process existence cannot be determined } HostinfoProcessQuery; HostinfoProcessQuery Hostinfo_QueryProcessExistence(int pid); char *Hostinfo_NameGet(void); /* don't free result */ char *Hostinfo_HostName(void); /* free result */ void Hostinfo_MachineID(uint32 *hostNameHash, uint64 *hostHardwareID); Bool Hostinfo_GetMemoryInfoInPages(unsigned int *minSize, unsigned int *maxSize, unsigned int *currentSize); #ifdef __linux__ Bool Hostinfo_GetSwapInfoInPages(unsigned int *totalSwap, unsigned int *freeSwap); #endif Bool Hostinfo_GetRatedCpuMhz(int32 cpuNumber, uint32 *mHz); char *Hostinfo_GetCpuDescription(uint32 cpuNumber); void Hostinfo_GetTimeOfDay(VmTimeType *time); VmTimeType Hostinfo_SystemUpTime(void); VmTimeType Hostinfo_SystemTimerNS(void); static INLINE VmTimeType Hostinfo_SystemTimerUS(void) { return Hostinfo_SystemTimerNS() / 1000ULL; } static INLINE VmTimeType Hostinfo_SystemTimerMS(void) { return Hostinfo_SystemTimerNS() / 1000000ULL; } /* * Apple's kernel major versions are the same as their marketed * minor versions + 4. (E.g. Marketed 10.8.0 == Kernel 12.0.0) * These constants simplify this and make code easier to read / understand. */ enum { HOSTINFO_OS_VERSION_MACOS_10_5 = 9, HOSTINFO_OS_VERSION_MACOS_10_6 = 10, HOSTINFO_OS_VERSION_MACOS_10_7 = 11, HOSTINFO_OS_VERSION_MACOS_10_8 = 12, HOSTINFO_OS_VERSION_MACOS_10_9 = 13, HOSTINFO_OS_VERSION_MACOS_10_10 = 14, HOSTINFO_OS_VERSION_MACOS_10_11 = 15, HOSTINFO_OS_VERSION_MACOS_10_12 = 16, }; int Hostinfo_OSVersion(unsigned int i); int Hostinfo_GetSystemBitness(void); const char *Hostinfo_OSVersionString(void); char *Hostinfo_GetOSName(void); char *Hostinfo_GetOSGuestString(void); #if defined(_WIN32) Bool Hostinfo_OSIsWinNT(void); Bool Hostinfo_OSIsWow64(void); Bool Hostinfo_TSCInvariant(void); DWORD Hostinfo_OpenProcessBits(void); DWORD Hostinfo_OpenThreadBits(void); int Hostinfo_EnumerateAllProcessPids(uint32 **processIds); #else void Hostinfo_ResetProcessState(const int *keepFds, size_t numKeepFds); int Hostinfo_Execute(const char *path, char * const *args, Bool wait, const int *keepFds, size_t numKeepFds); typedef enum HostinfoDaemonizeFlags { HOSTINFO_DAEMONIZE_DEFAULT = 0, HOSTINFO_DAEMONIZE_NOCHDIR = (1 << 0), HOSTINFO_DAEMONIZE_NOCLOSE = (1 << 1), HOSTINFO_DAEMONIZE_EXIT = (1 << 2), HOSTINFO_DAEMONIZE_LOCKPID = (1 << 3), } HostinfoDaemonizeFlags; Bool Hostinfo_Daemonize(const char *path, char * const *args, HostinfoDaemonizeFlags flags, const char *pidPath, const int *keepFds, size_t numKeepFds); #endif Bool Hostinfo_NestingSupported(void); Bool Hostinfo_VCPUInfoBackdoor(unsigned bit); Bool Hostinfo_SynchronizedVTSCs(void); Bool Hostinfo_NestedHVReplaySupported(void); Bool Hostinfo_TouchBackDoor(void); Bool Hostinfo_TouchVirtualPC(void); Bool Hostinfo_TouchXen(void); char *Hostinfo_HypervisorCPUIDSig(void); void Hostinfo_LogHypervisorCPUID(void); char *Hostinfo_HypervisorInterfaceSig(void); #define HGMP_PRIVILEGE 0 #define HGMP_NO_PRIVILEGE 1 char *Hostinfo_GetModulePath(uint32 priv); char *Hostinfo_GetLibraryPath(void *addr); char *Hostinfo_GetUser(void); void Hostinfo_LogMemUsage(void); /* * HostInfoCpuIdInfo -- * * Contains cpuid information for a CPU. */ typedef struct { CpuidVendor vendor; uint32 version; uint8 family; uint8 model; uint8 stepping; uint8 type; uint32 features; uint32 extfeatures; } HostinfoCpuIdInfo; uint32 Hostinfo_NumCPUs(void); char *Hostinfo_GetCpuidStr(void); Bool Hostinfo_GetCpuid(HostinfoCpuIdInfo *info); #if defined(_WIN32) typedef enum { OS_WIN95 = 1, OS_WIN98 = 2, OS_WINME = 3, OS_WINNT = 4, OS_WIN2K = 5, OS_WINXP = 6, OS_WIN2K3 = 7, OS_VISTA = 8, OS_WINSEVEN = 9, OS_WIN8 = 10, OS_WIN10 = 11, OS_UNKNOWN = 99999 // last, highest value } OS_TYPE; typedef enum { OS_DETAIL_WIN95 = 1, OS_DETAIL_WIN98 = 2, OS_DETAIL_WINME = 3, OS_DETAIL_WINNT = 4, OS_DETAIL_WIN2K = 5, OS_DETAIL_WIN2K_PRO = 6, OS_DETAIL_WIN2K_SERV = 7, OS_DETAIL_WIN2K_ADV_SERV = 8, OS_DETAIL_WINXP = 9, OS_DETAIL_WINXP_HOME = 10, OS_DETAIL_WINXP_PRO = 11, OS_DETAIL_WINXP_X64_PRO = 12, OS_DETAIL_WIN2K3 = 13, OS_DETAIL_WIN2K3_WEB = 14, OS_DETAIL_WIN2K3_ST = 15, OS_DETAIL_WIN2K3_EN = 16, OS_DETAIL_WIN2K3_BUS = 17, OS_DETAIL_VISTA = 18, OS_DETAIL_WIN2K8 = 19, OS_DETAIL_WINSEVEN = 20, OS_DETAIL_WIN2K8R2 = 21, OS_DETAIL_WIN8 = 22, OS_DETAIL_WIN8SERVER = 23, OS_DETAIL_WIN10 = 24, OS_DETAIL_WIN10SERVER = 25, OS_DETAIL_UNKNOWN = 99999 // last, highest value } OS_DETAIL_TYPE; /* generic names (to protect the future) but Windows specific for now */ OS_TYPE Hostinfo_GetOSType(void); OS_DETAIL_TYPE Hostinfo_GetOSDetailType(void); Bool Hostinfo_GetMhzOfProcessor(int32 processorNumber, uint32 *currentMhz, uint32 *maxMhz); uint64 Hostinfo_SystemIdleTime(void); Bool Hostinfo_GetAllCpuid(CPUIDQuery *query); static INLINE Bool Hostinfo_AtLeastVista(void) { return (Hostinfo_GetOSType() >= OS_VISTA); } #endif void Hostinfo_LogLoadAverage(void); Bool Hostinfo_GetLoadAverage(uint32 *l); #ifdef __APPLE__ size_t Hostinfo_GetKernelZoneElemSize(char const *name); char *Hostinfo_GetHardwareModel(void); #endif #if defined(__cplusplus) } // extern "C" #endif #endif /* ifndef _HOSTINFO_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/imgcust-common/000077500000000000000000000000001321503522500254305ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/imgcust-common/imgcust-api.h000066400000000000000000000031341321503522500300240ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * imgcust-api.h -- * * C interface to package deployment. */ #ifndef IMGCUST_API_H #define IMGCUST_API_H #ifdef WIN32 /* * We get warnings c4251 and c4275 when exporting c++ classes that * inherit from STL classes or use them as members. We can't * export these classes or the client will get duplicate symbols, * so we disable the warning. */ #pragma warning( disable : 4251 ) #pragma warning( disable : 4275 ) // if _IMGCUST_DLL is defined, we export functions/classes with this prefix #ifdef _IMGCUST_DLL #define IMGCUST_API __declspec(dllexport) #else #define IMGCUST_API __declspec(dllimport) #endif #else // linux #define IMGCUST_API __attribute__ ((visibility ("default"))) #endif // WIN32 #endif // IMGCUST_API_H open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/imgcust-common/log.h000066400000000000000000000025431321503522500263660ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * log.h -- * * Logging method that need to be provided by the client of the * library to enable logging. */ #ifndef IMGCUST_COMMON_LOG_H #define IMGCUST_COMMON_LOG_H #define GUESTCUST_LOG_DIRNAME "vmware-imc" #ifdef __cplusplus namespace ImgCustCommon { #endif enum LogLevel {log_debug, log_info, log_warning, log_error}; typedef void (*LogFunction) (int level, const char *fmtstr, ...); #ifdef __cplusplus } // namespace ImgCustCommon #endif #endif // IMGCUST_COMMON_LOG_H open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/imgcust-common/process.h000066400000000000000000000066511321503522500272670ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * process.h -- * * Functions to launch an external process. */ #ifndef IMGCUST_COMMON_PROCESS_H #define IMGCUST_COMMON_PROCESS_H #ifdef __cplusplus extern "C" { #endif typedef struct ProcessOpaque *ProcessHandle; typedef enum _ProcessError { PROCESS_SUCCESS, PROCESS_FAILED } ProcessError; /* *------------------------------------------------------------------------------ * * Process_Create -- * * Creates a process and returns result of the operation. * * Since this file can be included in a c++ file that already has the * namespaced c++ definition of LogFunction defined, we can't use the c * version of LogFunction as an input. Only choice is to make it a raw * pointer and cast it in the processXXX.c file which can use the C * definition of LogFunction. * *------------------------------------------------------------------------------ */ ProcessError Process_Create(ProcessHandle *h, char *args[], void *log); /* *------------------------------------------------------------------------------ * * Process_RunToComplete -- * * Runs the process to completion and returns its result. * *------------------------------------------------------------------------------ */ ProcessError Process_RunToComplete(ProcessHandle h, unsigned long timeout); /* *------------------------------------------------------------------------------ * * Process_GetStdout -- * * Returns process's standard output. * *------------------------------------------------------------------------------ */ const char * Process_GetStdout(ProcessHandle h); /* *------------------------------------------------------------------------------ * * Process_GetStderr -- * * Returns process's standard error output. * *------------------------------------------------------------------------------ */ const char * Process_GetStderr(ProcessHandle h); /* *------------------------------------------------------------------------------ * * Process_GetExitCode -- * * Returns process's exit code. * *------------------------------------------------------------------------------ */ int Process_GetExitCode(ProcessHandle h); /* *------------------------------------------------------------------------------ * * Process_Destroy -- * * Destroys the process and returns result of the operation. * *------------------------------------------------------------------------------ */ ProcessError Process_Destroy(ProcessHandle h); #ifdef __cplusplus } // extern "C" #endif #endif // IMGCUST_COMMON_PROCESS_H open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/imgcust-guest/000077500000000000000000000000001321503522500252675ustar00rootroot00000000000000open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/imgcust-guest/guestcust-events.h000066400000000000000000000030311321503522500307650ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * guestcust-events.h -- * * Definitions related to the GOSC events. */ #ifndef IMGCUST_COMMON_GOSC_EVENTS_H #define IMGCUST_COMMON_GOSC_EVENTS_H /* * Customization-specific events generated in the guest and handled by * hostd. They are sent via the vmx/guestTools/deployPkgState/ vmdb path. * We start these at 100 to avoid conflict with the deployPkg error * codes listed in vmx/public/toolsDeployPkg.h. */ typedef enum { GUESTCUST_EVENT_CUSTOMIZE_FAILED = 100, GUESTCUST_EVENT_NETWORK_SETUP_FAILED, GUESTCUST_EVENT_SYSPREP_FAILED, GUESTCUST_EVENT_ENABLE_NICS, GUESTCUST_EVENT_QUERY_NICS } GuestCustEvent; #endif // IMGCUST_COMMON_GOSC_EVENTS_H open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/impersonate.h000066400000000000000000000032351321503522500251710ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * impersonate.h -- * * Provides functions to assist in impersonating and unimpersonating * as a given user. */ #ifndef _IMPERSONATE_H_ #define _IMPERSONATE_H_ #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #include "auth.h" #if defined(__cplusplus) extern "C" { #endif void Impersonate_Init(void); Bool Impersonate_Owner(const char *file); Bool Impersonate_Do(const char *user, AuthToken token); Bool Impersonate_Undo(void); char *Impersonate_Who(void); Bool Impersonate_ForceRoot(void); Bool Impersonate_UnforceRoot(void); Bool Impersonate_Runas(const char *cfg, const char *caller, AuthToken callerToken); #ifdef _WIN32 Bool Impersonate_CfgRunasOnly(const char *cfg); #endif #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _IMPERSONATE_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/includeCheck.h000066400000000000000000000134021321503522500252210ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * includeCheck.h -- * * Restrict include file use. * * In every .h file, define one or more of these * * INCLUDE_ALLOW_VMX * INCLUDE_ALLOW_USERLEVEL * INCLUDE_ALLOW_VMCORE * INCLUDE_ALLOW_MODULE * INCLUDE_ALLOW_VMKERNEL * INCLUDE_ALLOW_DISTRIBUTE * INCLUDE_ALLOW_VMK_MODULE * INCLUDE_ALLOW_VMKDRIVERS * INCLUDE_ALLOW_MKS * * Then include this file. * * Any file that has INCLUDE_ALLOW_DISTRIBUTE defined will potentially * be distributed in source form along with GPLed code. Ensure * that this is acceptable. */ /* * Declare a VMCORE-only variable to help classify object * files. The variable goes in the common block and does * not create multiple definition link-time conflicts. */ #if defined VMCORE && defined VMX86_DEVEL && defined VMX86_DEBUG && \ defined linux && !defined MODULE && \ !defined COMPILED_WITH_VMCORE #define COMPILED_WITH_VMCORE compiled_with_vmcore #ifdef ASM .comm compiled_with_vmcore, 0 #else asm(".comm compiled_with_vmcore, 0"); #endif /* ASM */ #endif #if defined VMCORE && \ !(defined VMX86_VMX || defined VMM || \ defined MONITOR_APP || defined VMMON) #error "Makefile problem: VMCORE without VMX86_VMX or \ VMM or MONITOR_APP or MODULE." #endif #if defined VMCORE && !defined INCLUDE_ALLOW_VMCORE #error "The surrounding include file is not allowed in vmcore." #endif #undef INCLUDE_ALLOW_VMCORE #if defined VMX86_VMX && !defined VMCORE && \ !defined INCLUDE_ALLOW_VMX && !defined INCLUDE_ALLOW_USERLEVEL && \ !defined INCLUDE_ALLOW_MKS #error "The surrounding include file is not allowed in the VMX." #endif #undef INCLUDE_ALLOW_VMX #if defined USERLEVEL && !defined VMX86_VMX && !defined VMCORE && \ !defined INCLUDE_ALLOW_USERLEVEL && !defined INCLUDE_ALLOW_MKS #error "The surrounding include file is not allowed at userlevel." #endif #undef INCLUDE_ALLOW_USERLEVEL #if defined MODULE && !defined VMKERNEL_MODULE && \ !defined VMMON && !defined INCLUDE_ALLOW_MODULE #error "The surrounding include file is not allowed in driver modules." #endif #undef INCLUDE_ALLOW_MODULE #if defined VMMON && !defined INCLUDE_ALLOW_VMMON #error "The surrounding include file is not allowed in vmmon." #endif #undef INCLUDE_ALLOW_VMMON #if defined VMKERNEL && !defined INCLUDE_ALLOW_VMKERNEL #error "The surrounding include file is not allowed in the vmkernel." #endif #undef INCLUDE_ALLOW_VMKERNEL #if defined GPLED_CODE && !defined INCLUDE_ALLOW_DISTRIBUTE #error "The surrounding include file is not allowed in GPL code." #endif #undef INCLUDE_ALLOW_DISTRIBUTE #if defined VMKERNEL_MODULE && !defined VMKERNEL && \ !defined INCLUDE_ALLOW_VMK_MODULE && !defined INCLUDE_ALLOW_VMKDRIVERS #error "The surrounding include file is not allowed in vmkernel modules." #endif #undef INCLUDE_ALLOW_VMK_MODULE #undef INCLUDE_ALLOW_VMKDRIVERS #if defined INCLUDE_ALLOW_MKS && !(defined COREMKS) #error "The surrounding include file is not allowed outside of the MKS." #endif #undef INCLUDE_ALLOW_MKS open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/ioplGet.h000066400000000000000000000024221321503522500242430ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2012-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * ioplGet.h -- * * A utility function to retrieve the IOPL level of the current thread * Compiles on x86, x64 of Linux and Windows */ #ifndef _IOPL_GET_H_ #define _IOPL_GET_H_ #include "x86_basic_defs.h" #include "vm_basic_asm.h" #if defined(__cplusplus) extern "C" { #endif #define Iopl_Get() ((GetCallerEFlags() >> EFLAGS_IOPL_SHIFT) && 0x3) #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/iovector.h000066400000000000000000000106061321503522500244750ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * iovector.h -- * * iov management code API. */ #ifndef _IOVECTOR_H_ #define _IOVECTOR_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #if defined(__cplusplus) extern "C" { #endif /* * Ugly definition of struct iovec. */ #if defined(__linux__) || defined(sun) || defined(__APPLE__) || defined(__FreeBSD__) #include // for struct iovec #else #ifndef HAS_IOVEC struct iovec { void *iov_base; /* Starting address. */ size_t iov_len; /* Length in bytes. */ }; #endif // HAS_IOVEC #endif /* * An I/O Vector. */ typedef struct VMIOVec { SectorType startSector; SectorType numSectors; uint64 numBytes; /* Total bytes from all of the entries */ uint32 numEntries; /* Total number of entries */ Bool read; /* is it a readv operation? else it's write */ struct iovec *entries; /* Array of entries (dynamically allocated) */ struct iovec *allocEntries; /* The original array that can be passed to free(). * NULL if entries is on a stack. */ } VMIOVec; #define LAZY_ALLOC_MAGIC ((void*)0xF0F0) VMIOVec* IOV_Split(VMIOVec *regionV, SectorType numSectors, uint32 sectorSize); void IOV_Log(const VMIOVec *iov); void IOV_Zero(VMIOVec *iov); Bool IOV_IsZero(VMIOVec* iov); VMIOVec* IOV_Duplicate(VMIOVec* iovIn); VMIOVec* IOV_Allocate(int numEntries); void IOV_Free(VMIOVec* iov); void IOV_DuplicateStatic(VMIOVec *iovIn, int numStaticEntries, struct iovec *staticEntries, VMIOVec *iovOut); void IOV_MakeSingleIOV(VMIOVec* v, struct iovec* iov, SectorType startSector, SectorType dataLen, uint32 sectorSize, uint8* buffer, Bool read); void IOV_WriteIovToBuf(struct iovec const *entries, int numEntries, uint8 *bufOut, size_t bufSize); void IOV_WriteBufToIov(const uint8 *bufIn, size_t bufSize, struct iovec const *entries, int numEntries); size_t IOV_WriteIovToBufPlus(struct iovec* entries, int numEntries, uint8* bufOut, size_t bufSize, size_t iovOffset); size_t IOV_WriteBufToIovPlus(uint8* bufIn, size_t bufSize, struct iovec* entries, int numEntries, size_t iovOffset); size_t IOV_WriteIovToIov(VMIOVec *srcIov, VMIOVec *dstIov, uint32 sectorSizeShift); /* *----------------------------------------------------------------------------- * * IOV_ASSERT, IOV_Assert -- * * Checks that the 'numEntries' iovecs in 'iov' are non-null and have * nonzero lengths. * * Results: * None. * * Side effects: * Assert-fails if the iovec is invalid. * *----------------------------------------------------------------------------- */ #if VMX86_DEBUG #define IOV_ASSERT(IOVEC, NUM_ENTRIES) IOV_Assert(IOVEC, NUM_ENTRIES) void IOV_Assert(struct iovec *iov, // IN: iovector uint32 numEntries); // IN: # of entries in 'iov' #else #define IOV_ASSERT(IOVEC, NUM_ENTRIES) ((void) 0) #endif #if defined(__cplusplus) } // extern "C" #endif #endif /* #ifndef _IOVECTOR_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/libExport.hh000066400000000000000000000026671321503522500247730ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * libExport.hh -- * * Declares proper decorations for dll-export interface * for all modules in libs. */ #ifndef LIB_EXPORT_HH #define LIB_EXPORT_HH #include "vm_api.h" #ifdef LIB_EXPORT_SOURCE #define LIB_EXPORT VMW_LIB_DYNAMIC #else #define LIB_EXPORT VMW_LIB_CLIENT #endif #ifdef LIB_EXPORT_WUI_SOURCE #define LIB_EXPORT_WUI VMW_LIB_DYNAMIC #else #define LIB_EXPORT_WUI VMW_LIB_CLIENT #endif #ifdef VMSTRING_EXPORT_SOURCE #define VMSTRING_EXPORT VMW_LIB_DYNAMIC #else #define VMSTRING_EXPORT VMW_LIB_CLIENT #endif #endif // LIB_EXPORT_HH open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/localconfig.h000066400000000000000000000025711321503522500251250ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _LOCALCONFIG_H_ #define _LOCALCONFIG_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "preference.h" #if defined(__cplusplus) extern "C" { #endif #define LocalConfig_GetBool Preference_GetBool #define LocalConfig_GetTriState Preference_GetTriState #define LocalConfig_GetLong Preference_GetLong #define LocalConfig_GetString Preference_GetString #define LocalConfig_GetPathName Preference_GetPathName #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/log.h000066400000000000000000000272771321503522500234400ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef VMWARE_LOG_H #define VMWARE_LOG_H #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "productState.h" #include #if defined(__cplusplus) extern "C" { #endif /* * The bora/lib Log Facility log level model. * * Each log entry has a level associated with it. The Log Facility filters * entries as they arrive by their level; only levels equal to or below * (smaller values) the filter level will be accepted by the Log Facility for * processing. * * By default, the Log Facility will output any entry which is submitted at * level VMW_LOG_WARNING and below to the "standard error". This may be * controlled via Log_SetStderrLevel (see function header) or configuration * parameter (see comments in log.c). * * The VMW_LOG_AUDIT level is used to log something that requires an audit * at a later date. It is *ALWAYS* logged and *NEVER* outputs to the "standard * error". * * The VMW_LOG_BASE is chosen to ensure that on all platforms commonly * used system logger values will be invalid and the errant usage caught. * * Level Level value Comments *--------------------------------------------------------------------------- */ #define VMW_LOG_BASE 100 #define VMW_LOG_AUDIT (VMW_LOG_BASE + 0) // ALWAYS LOGGED; NO STDERR #define VMW_LOG_PANIC (VMW_LOG_BASE + 5) // Quietest level #define VMW_LOG_ERROR (VMW_LOG_BASE + 10) #define VMW_LOG_WARNING (VMW_LOG_BASE + 15) #define VMW_LOG_NOTICE (VMW_LOG_BASE + 20) #define VMW_LOG_INFO (VMW_LOG_BASE + 25) #define VMW_LOG_VERBOSE (VMW_LOG_BASE + 30) #define VMW_LOG_TRIVIA (VMW_LOG_BASE + 35) #define VMW_LOG_DEBUG_00 (VMW_LOG_BASE + 40) // least noisy debug level #define VMW_LOG_DEBUG_01 (VMW_LOG_DEBUG_00 + 1) #define VMW_LOG_DEBUG_02 (VMW_LOG_DEBUG_00 + 2) #define VMW_LOG_DEBUG_03 (VMW_LOG_DEBUG_00 + 3) // debug levels grow #define VMW_LOG_DEBUG_04 (VMW_LOG_DEBUG_00 + 4) // increasingly noisy #define VMW_LOG_DEBUG_05 (VMW_LOG_DEBUG_00 + 5) // as the debug number #define VMW_LOG_DEBUG_06 (VMW_LOG_DEBUG_00 + 6) // increases #define VMW_LOG_DEBUG_07 (VMW_LOG_DEBUG_00 + 7) #define VMW_LOG_DEBUG_08 (VMW_LOG_DEBUG_00 + 8) #define VMW_LOG_DEBUG_09 (VMW_LOG_DEBUG_00 + 9) #define VMW_LOG_DEBUG_10 (VMW_LOG_DEBUG_00 + 10) // Noisiest level #if defined(VMX86_DEBUG) || defined(VMX86_DEVEL) #define LOG_FILTER_DEFAULT_LEVEL VMW_LOG_VERBOSE #else #define LOG_FILTER_DEFAULT_LEVEL VMW_LOG_INFO #endif /* * The "routing" parameter may contain other information. */ #define VMW_LOG_LEVEL_MASK 0x000000FF // Log level bits are in the LOB void LogV(uint32 routing, const char *fmt, va_list args); void Log_Level(uint32 routing, const char *fmt, ...) PRINTF_DECL(2, 3); /* * Handy wrapper functions. * * Log -> VMW_LOG_INFO * Warning -> VMW_LOG_WARNING */ static INLINE void PRINTF_DECL(1, 2) Log_Panic(const char *fmt, ...) { va_list ap; va_start(ap, fmt); LogV(VMW_LOG_PANIC, fmt, ap); va_end(ap); } static INLINE void PRINTF_DECL(1, 2) Log_Audit(const char *fmt, ...) { va_list ap; va_start(ap, fmt); LogV(VMW_LOG_AUDIT, fmt, ap); va_end(ap); } static INLINE void PRINTF_DECL(1, 2) Log_Error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); LogV(VMW_LOG_ERROR, fmt, ap); va_end(ap); } static INLINE void PRINTF_DECL(1, 2) Log_Notice(const char *fmt, ...) { va_list ap; va_start(ap, fmt); LogV(VMW_LOG_NOTICE, fmt, ap); va_end(ap); } static INLINE void PRINTF_DECL(1, 2) Log_Verbose(const char *fmt, ...) { va_list ap; va_start(ap, fmt); LogV(VMW_LOG_VERBOSE, fmt, ap); va_end(ap); } static INLINE void PRINTF_DECL(1, 2) Log_Trivia(const char *fmt, ...) { va_list ap; va_start(ap, fmt); LogV(VMW_LOG_TRIVIA, fmt, ap); va_end(ap); } #if !defined(VMM) /* Forward decl */ struct Dictionary; struct CfgInterface; typedef struct LogOutput LogOutput; struct CfgInterface *Log_CfgInterface(void); int32 Log_SetStderrLevel(int32 level); int32 Log_GetStderrLevel(void); LogOutput *Log_NewStdioOutput(const char *appPrefix, struct Dictionary *params, struct CfgInterface *cfgIf); LogOutput *Log_NewSyslogOutput(const char *appPrefix, const char *instanceName, struct Dictionary *params, struct CfgInterface *cfgIf); LogOutput *Log_NewFileOutput(const char *appPrefix, const char *instanceName, struct Dictionary *params, struct CfgInterface *cfgIf); typedef void (LogCustomMsgFunc)(int level, const char *msg); LogOutput *Log_NewCustomOutput(const char *instanceName, LogCustomMsgFunc *msgFunc, int minLogLevel); Bool Log_FreeOutput(LogOutput *toOutput); Bool Log_AddOutput(LogOutput *output); Bool Log_ReplaceOutput(LogOutput *fromOutput, LogOutput *toOutput, Bool copyOver); int32 Log_SetOutputLevel(LogOutput *output, int32 level); /* * The most common Log Facility client usage is via the "InitWith" functions. * These functions - not the "Int" versions - handle informing the Log * Facility of the ProductState (product description) via inline code. This is * done to avoid making the Log Facility depend on the ProductState library - * the product should have the dependency, not an underlying library. * * In complex cases, where an "InitWith" is not sufficient and Log_AddOutput * must be used directly, the client should call Log_SetProductInfo, passing * the appropriate parameters, so the log file header information will be * correct. */ void Log_SetProductInfo(const char *appName, const char *appVersion, const char *buildNumber, const char *compilationOption); static INLINE void Log_SetProductInfoSimple(void) { Log_SetProductInfo(ProductState_GetName(), ProductState_GetVersion(), ProductState_GetBuildNumberString(), ProductState_GetCompilationOption()); } LogOutput *Log_InitWithCustomInt(struct CfgInterface *cfgIf, LogCustomMsgFunc *msgFunc, int minLogLevel); static INLINE LogOutput * Log_InitWithCustom(struct CfgInterface *cfgIf, LogCustomMsgFunc *msgFunc, int minLogLevel) { Log_SetProductInfoSimple(); return Log_InitWithCustomInt(cfgIf, msgFunc, minLogLevel); } LogOutput *Log_InitWithFileInt(const char *appPrefix, struct Dictionary *dict, struct CfgInterface *cfgIf, Bool boundNumFiles); static INLINE LogOutput * Log_InitWithFile(const char *appPrefix, struct Dictionary *dict, struct CfgInterface *cfgIf, Bool boundNumFiles) { Log_SetProductInfoSimple(); return Log_InitWithFileInt(appPrefix, dict, cfgIf, boundNumFiles); } LogOutput *Log_InitWithFileSimpleInt(const char *appPrefix, struct CfgInterface *cfgIf, const char *fileName); static INLINE LogOutput * Log_InitWithFileSimple(const char *fileName, const char *appPrefix) { Log_SetProductInfoSimple(); return Log_InitWithFileSimpleInt(appPrefix, Log_CfgInterface(), fileName); } LogOutput *Log_InitWithSyslogInt(const char *appPrefix, struct Dictionary *dict, struct CfgInterface *cfgIf); static INLINE LogOutput * Log_InitWithSyslog(const char *appPrefix, struct Dictionary *dict, struct CfgInterface *cfgIf) { Log_SetProductInfoSimple(); return Log_InitWithSyslogInt(appPrefix, dict, cfgIf); } LogOutput *Log_InitWithSyslogSimpleInt(const char *appPrefix, struct CfgInterface *cfgIf, const char *syslogID); static INLINE LogOutput * Log_InitWithSyslogSimple(const char *syslogID, const char *appPrefix) { Log_SetProductInfoSimple(); return Log_InitWithSyslogSimpleInt(appPrefix, Log_CfgInterface(), syslogID); } LogOutput *Log_InitWithStdioSimpleInt(const char *appPrefix, struct CfgInterface *cfgIf, const char *minLevel, Bool withLinePrefix); static INLINE LogOutput * Log_InitWithStdioSimple(const char *appPrefix, const char *minLevel, Bool withLinePrefix) { Log_SetProductInfoSimple(); return Log_InitWithStdioSimpleInt(appPrefix, Log_CfgInterface(), minLevel, withLinePrefix); } void Log_Exit(void); Bool Log_Outputting(void); Bool Log_IsLevelOutputting(int level); const char *Log_GetFileName(void); const char *Log_GetOutputFileName(LogOutput *output); void Log_SkipLocking(Bool skipLocking); void Log_DisableThrottling(void); uint32 Log_MaxLineLength(void); size_t Log_MakeTimeString(Bool millisec, char *buf, size_t max); typedef Bool (LogOwnerFunc)(void *userData, const char *fileName); Bool Log_BoundNumFiles(struct LogOutput *output, LogOwnerFunc *func, void *userData); #if defined(VMX86_SERVER) #define LOG_KEEPOLD 6 // Old log files to keep around; ESX value #else #define LOG_KEEPOLD 3 // Old log files to keep around; non-ESX value #endif #define LOG_NO_KEEPOLD 0 // Keep no old log files #define LOG_NO_ROTATION_SIZE 0 // Do not rotate based on file size #define LOG_NO_THROTTLE_THRESHOLD 0 // No threshold before throttling #define LOG_NO_BPS_LIMIT 0xFFFFFFFF // unlimited input rate /* * Debugging */ void Log_HexDump(const char *prefix, const void *data, size_t size); void Log_HexDumpLevel(uint32 routing, const char *prefix, const void *data, size_t size); void Log_Time(VmTimeType *time, int count, const char *message); void Log_Histogram(uint32 n, uint32 histo[], int nbuckets, const char *message, int *count, int limit); #endif /* !VMM */ #if defined(__cplusplus) } // extern "C" #endif #endif /* VMWARE_LOG_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/logFixed.h000066400000000000000000000031721321503522500244040ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _LOGFIXED_H_ #define _LOGFIXED_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #if defined(__cplusplus) extern "C" { #endif /* * LogFixed_Base2 and LogFixed_Base10 provide their values expressed * as a ration of two uint32 numbers with an accuracy of better than 1%. * * Reminder: A log, base x, of zero is undefined. These routines will assert * in development builds when a zero value is passed to them. */ void LogFixed_Base2(uint64 value, uint32 *numerator, uint32 *denominator); void LogFixed_Base10(uint64 value, uint32 *numerator, uint32 *denominator); #if defined(__cplusplus) } // extern "C" #endif #endif // _LOGFIXED_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/loglevel_defs.h000066400000000000000000000077741321503522500254710ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _LOGLEVEL_DEFS_H_ #define _LOGLEVEL_DEFS_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #ifndef LOGLEVEL_MODULE #error "loglevel_defs.h must be included with LOGLEVEL_MODULE defined" #endif #ifndef LOGLEVEL_EXTENSION #error "loglevel_defs.h must be included with LOGLEVEL_EXTENSION defined" #endif #include "vm_basic_types.h" #include "vm_basic_defs.h" #if defined __cplusplus #define LOGLEVEL_EXTERN_C_BEGIN extern "C" { #define LOGLEVEL_EXTERN_C_END } #else #define LOGLEVEL_EXTERN_C_BEGIN #define LOGLEVEL_EXTERN_C_END #endif LOGLEVEL_EXTERN_C_BEGIN /* * CPP variable name hacks */ #define LOGLEVEL_EXTOFFSET(ext) XCONC(_loglevel_offset_, ext) #define LOGLEVEL_EXTNAME(ext) XSTR(ext) #define LOGLEVEL_MODULEVAR(mod) XCONC(_loglevel_mod_, mod) /* * LogLevel declaration */ #define LOGLEVEL_EXTENSION_DECLARE(list) \ LOGLEVEL_EXTERN_C_BEGIN \ VMX86_EXTERN_DATA const int8 *logLevelPtr; \ VMX86_EXTERN_DATA int LOGLEVEL_EXTOFFSET(LOGLEVEL_EXTENSION); \ LOGLEVEL_EXTERN_C_END \ enum { list(LOGLEVEL_MODULEVAR) } #ifdef VMX86_LOG /* * Cross extension */ #define LOGLEVEL_BYEXTNAME(_ext, _mod) \ (*LogLevel_LookUpVar(XSTR(_ext), XSTR(_mod))) #define LOGLEVEL_BYEXTNAME_SET(_ext, _mod, _val) \ LogLevel_Set(XSTR(_ext), XSTR(_mod), _val) const int8 *LogLevel_LookUpVar(const char *extension, const char *module); int LogLevel_Set(const char *extension, const char *module, int val); #define DOLOG_BYEXTNAME(_ext, _mod, _min) \ UNLIKELY(LOGLEVEL_BYEXTNAME(_ext, _mod) >= (_min)) #define LOG_BYEXTNAME(_ext, _mod, _min, _log) \ (DOLOG_BYEXTNAME(_ext, _mod, _min) ? (Log _log) : (void) 0) /* * Intra extension */ #define LOGLEVEL_BYNAME(_mod) \ logLevelPtr[LOGLEVEL_EXTOFFSET(LOGLEVEL_EXTENSION) + \ LOGLEVEL_MODULEVAR(_mod)] #ifdef VMM #define LOGLEVEL_BYNAME_SET(_mod, _val) do { \ monitorLogLevels[LOGLEVEL_EXTOFFSET(LOGLEVEL_EXTENSION) + \ LOGLEVEL_MODULEVAR(_mod)] = _val; \ } while (0) #endif #define DOLOG_BYNAME(_mod, _min) \ UNLIKELY(LOGLEVEL_BYNAME(_mod) >= (_min)) #define LOG_BYNAME(_mod, _min, _log) \ (DOLOG_BYNAME(_mod, _min) ? (Log _log) : (void) 0) /* * Default */ #define LOGLEVEL() LOGLEVEL_BYNAME(LOGLEVEL_MODULE) #define DOLOG(_min) DOLOG_BYNAME(LOGLEVEL_MODULE, _min) #define LOG(_min, _log) LOG_BYNAME(LOGLEVEL_MODULE, _min, _log) #else /* VMX86_LOG */ #define LOGLEVEL_BYEXTNAME(_ext, _mod) 0 #define LOGLEVEL_BYEXTNAME_SET(_ext, _mod, _val) do {} while (0) #define DOLOG_BYEXTNAME(_ext, _mod, _min) (FALSE) #define LOG_BYEXTNAME(_ext, _mod, _min, _log) do {} while (0) #define LOGLEVEL_BYNAME(_mod) 0 #ifdef VMM #define LOGLEVEL_BYNAME_SET(_mod, _val) do {} while (0) #endif #define DOLOG_BYNAME(_mod, _min) (FALSE) #define LOG_BYNAME(_mod, _min, _log) do {} while (0) #define LOGLEVEL() 0 #define DOLOG(_min) (FALSE) #define LOG(_min, _log) #endif /* VMX86_LOG */ #ifdef VMX86_DEVEL #define LOG_DEVEL(_x) (Log _x) #else #define LOG_DEVEL(_x) #endif LOGLEVEL_EXTERN_C_END #endif /* _LOGLEVEL_DEFS_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/loglevel_user.h000066400000000000000000000232701321503522500255130ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _LOGLEVEL_USER_H_ #define _LOGLEVEL_USER_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #define LOGLEVEL_EXTENSION user #include "loglevel_defs.h" #define LOGLEVEL_USER(LOGLEVEL_VAR) \ /* user/main*/ \ /* main has to be first. */ \ LOGLEVEL_VAR(main), \ LOGLEVEL_VAR(aio), \ LOGLEVEL_VAR(passthrough), \ LOGLEVEL_VAR(tools), \ LOGLEVEL_VAR(license), \ LOGLEVEL_VAR(vui), \ LOGLEVEL_VAR(stats), \ LOGLEVEL_VAR(cpucount), \ LOGLEVEL_VAR(ovhdmem), \ LOGLEVEL_VAR(vigor), \ \ /* user/io */ \ LOGLEVEL_VAR(disk), \ LOGLEVEL_VAR(keyboard), \ LOGLEVEL_VAR(vmmouse), \ LOGLEVEL_VAR(timer), \ LOGLEVEL_VAR(vga), \ LOGLEVEL_VAR(svga), \ LOGLEVEL_VAR(svga_rect), \ LOGLEVEL_VAR(enableDetTimer), \ LOGLEVEL_VAR(dma), \ LOGLEVEL_VAR(floppy), \ LOGLEVEL_VAR(cmos), \ LOGLEVEL_VAR(vlance), \ LOGLEVEL_VAR(e1000), \ LOGLEVEL_VAR(serial), \ LOGLEVEL_VAR(parallel), \ LOGLEVEL_VAR(chipset), \ LOGLEVEL_VAR(smram), \ LOGLEVEL_VAR(txt), \ LOGLEVEL_VAR(sgx), \ LOGLEVEL_VAR(smc), \ LOGLEVEL_VAR(ich7m), \ LOGLEVEL_VAR(hpet), \ LOGLEVEL_VAR(extcfgdevice), \ LOGLEVEL_VAR(flashram), \ LOGLEVEL_VAR(efinv), \ LOGLEVEL_VAR(pvnvram), \ LOGLEVEL_VAR(pci), \ LOGLEVEL_VAR(pci_vide), \ LOGLEVEL_VAR(pci_uhci), \ LOGLEVEL_VAR(uhci), \ LOGLEVEL_VAR(pci_ehci), \ LOGLEVEL_VAR(ehci), \ LOGLEVEL_VAR(pci_xhci), \ LOGLEVEL_VAR(usb_xhci), \ LOGLEVEL_VAR(usb), \ LOGLEVEL_VAR(vusbaudio), \ LOGLEVEL_VAR(vusbccid), \ LOGLEVEL_VAR(vusbhid), \ LOGLEVEL_VAR(vusbkeyboard), \ LOGLEVEL_VAR(vusbmouse), \ LOGLEVEL_VAR(vusbtablet), \ LOGLEVEL_VAR(vusbvideo),\ LOGLEVEL_VAR(vusbrng),\ LOGLEVEL_VAR(hidQueue), \ LOGLEVEL_VAR(pci_vlance), \ LOGLEVEL_VAR(pci_svga), \ LOGLEVEL_VAR(pci_e1000), \ LOGLEVEL_VAR(pci_hyper), \ LOGLEVEL_VAR(pcibridge), \ LOGLEVEL_VAR(vide), \ LOGLEVEL_VAR(atapiCdrom), \ LOGLEVEL_VAR(hostonly), \ LOGLEVEL_VAR(oprom), \ LOGLEVEL_VAR(http), \ LOGLEVEL_VAR(vmci), \ LOGLEVEL_VAR(pci_vmci), \ LOGLEVEL_VAR(vmxnet3), \ LOGLEVEL_VAR(pci_vmxnet3), \ LOGLEVEL_VAR(vcpuhotplug), \ LOGLEVEL_VAR(vcpuNUMA), \ LOGLEVEL_VAR(heci), \ LOGLEVEL_VAR(pciplugin), \ LOGLEVEL_VAR(vsock), \ LOGLEVEL_VAR(vrdma), \ LOGLEVEL_VAR(nvdimm), \ LOGLEVEL_VAR(qat), \ LOGLEVEL_VAR(vtpm), \ LOGLEVEL_VAR(mor), \ \ /* user/disk */ \ LOGLEVEL_VAR(aioMgr), \ LOGLEVEL_VAR(aioWin32), \ LOGLEVEL_VAR(aioWin32Completion), \ LOGLEVEL_VAR(aioLinux), \ LOGLEVEL_VAR(aioHttp), \ LOGLEVEL_VAR(aioGeneric), \ LOGLEVEL_VAR(cdrom), \ LOGLEVEL_VAR(checksum), \ \ /* user/checkpoint */ \ LOGLEVEL_VAR(checkpoint), \ LOGLEVEL_VAR(dumper), \ LOGLEVEL_VAR(migrate), \ LOGLEVEL_VAR(fsresx), \ \ /* user/gui */ \ LOGLEVEL_VAR(gui), \ LOGLEVEL_VAR(guiWin32), \ LOGLEVEL_VAR(mks), \ LOGLEVEL_VAR(mksInput), \ LOGLEVEL_VAR(mksSWB), \ LOGLEVEL_VAR(mksClient), \ LOGLEVEL_VAR(mksServer), \ LOGLEVEL_VAR(mksKeyboard), \ LOGLEVEL_VAR(keymap), \ LOGLEVEL_VAR(mksMouse), \ LOGLEVEL_VAR(mksHostCursor), \ LOGLEVEL_VAR(mksCursorPosition), \ LOGLEVEL_VAR(mksBasicOps), \ LOGLEVEL_VAR(mksRenderOps), \ LOGLEVEL_VAR(mksFrame), \ LOGLEVEL_VAR(mksGLBasic), \ LOGLEVEL_VAR(mksGLManager), \ LOGLEVEL_VAR(mksGLFBO), \ LOGLEVEL_VAR(mksGLShader), \ LOGLEVEL_VAR(mksGLState), \ LOGLEVEL_VAR(mksGLWindow), \ LOGLEVEL_VAR(mksGLContextMux), \ LOGLEVEL_VAR(mksGLDraw), \ LOGLEVEL_VAR(mksGLQuery), \ LOGLEVEL_VAR(mksGLTextureView), \ LOGLEVEL_VAR(mksWinBSOD), \ LOGLEVEL_VAR(mksDX11Renderer), \ LOGLEVEL_VAR(mksDX11ResourceView), \ LOGLEVEL_VAR(mksDX11ShimOps), \ LOGLEVEL_VAR(mksMTLRenderer), \ LOGLEVEL_VAR(vaBasicOps), \ LOGLEVEL_VAR(vdpPlugin), \ LOGLEVEL_VAR(vncServer), \ \ /* user/sound */ \ LOGLEVEL_VAR(sound), \ LOGLEVEL_VAR(hdaudio), \ LOGLEVEL_VAR(pci_hdaudio), \ LOGLEVEL_VAR(hdaudio_alsa), \ \ /* user video */ \ LOGLEVEL_VAR(AVCapture), \ \ /* user/disklib */ \ LOGLEVEL_VAR(disklib), \ LOGLEVEL_VAR(dmg), \ LOGLEVEL_VAR(sparseChecker), \ LOGLEVEL_VAR(dataCache), \ /* more */ \ LOGLEVEL_VAR(dict), \ LOGLEVEL_VAR(pci_scsi), \ LOGLEVEL_VAR(scsi), \ LOGLEVEL_VAR(grm), \ LOGLEVEL_VAR(vmxnet), \ LOGLEVEL_VAR(pciPassthru), \ LOGLEVEL_VAR(vnet), \ LOGLEVEL_VAR(netPkt), \ LOGLEVEL_VAR(macfilter), \ LOGLEVEL_VAR(macbw), \ LOGLEVEL_VAR(macfi), \ LOGLEVEL_VAR(vmkcfg), \ LOGLEVEL_VAR(policy), \ LOGLEVEL_VAR(poll), \ LOGLEVEL_VAR(barrier), \ LOGLEVEL_VAR(mstat), \ LOGLEVEL_VAR(vmLock), \ LOGLEVEL_VAR(buslogic), \ LOGLEVEL_VAR(lsilogic), \ LOGLEVEL_VAR(pvscsi), \ LOGLEVEL_VAR(ahci), \ LOGLEVEL_VAR(nvme), \ LOGLEVEL_VAR(diskVmnix), \ LOGLEVEL_VAR(hbaCommon), \ LOGLEVEL_VAR(backdoor), \ LOGLEVEL_VAR(buslogicMdev), \ LOGLEVEL_VAR(hgfs), \ LOGLEVEL_VAR(hgfsServer), \ LOGLEVEL_VAR(memspace), \ LOGLEVEL_VAR(dnd), \ LOGLEVEL_VAR(appstate), \ LOGLEVEL_VAR(vthread), \ LOGLEVEL_VAR(vmhs), \ LOGLEVEL_VAR(undopoint), \ LOGLEVEL_VAR(ipc), \ LOGLEVEL_VAR(smbios), \ LOGLEVEL_VAR(acpi), \ LOGLEVEL_VAR(acpiGPE), \ LOGLEVEL_VAR(vmgenc), \ LOGLEVEL_VAR(xpmode), \ LOGLEVEL_VAR(snapshot), \ LOGLEVEL_VAR(asyncsocket), \ LOGLEVEL_VAR(mainMem), \ LOGLEVEL_VAR(mainMemReplayCheck), \ LOGLEVEL_VAR(memoryHotplug), \ LOGLEVEL_VAR(numa), \ LOGLEVEL_VAR(numaHost), \ LOGLEVEL_VAR(remoteDevice), \ LOGLEVEL_VAR(vncDecode), \ LOGLEVEL_VAR(vncEncode), \ LOGLEVEL_VAR(vncBlit), \ LOGLEVEL_VAR(libconnect), \ LOGLEVEL_VAR(state3d), \ LOGLEVEL_VAR(vmGL), \ LOGLEVEL_VAR(guest_msg), \ LOGLEVEL_VAR(guest_rpc), \ LOGLEVEL_VAR(guestVars), \ LOGLEVEL_VAR(vmkEvent), \ LOGLEVEL_VAR(authenticode), \ LOGLEVEL_VAR(tpm2Verification), \ LOGLEVEL_VAR(battery), \ LOGLEVEL_VAR(fakeDma), \ LOGLEVEL_VAR(shader), \ LOGLEVEL_VAR(machPoll), \ LOGLEVEL_VAR(replayVMX), \ LOGLEVEL_VAR(vmWindowController), \ LOGLEVEL_VAR(dui), \ LOGLEVEL_VAR(duiMKS), \ LOGLEVEL_VAR(worker), \ LOGLEVEL_VAR(duiDevices), \ LOGLEVEL_VAR(duiLocalization), \ LOGLEVEL_VAR(duiProxyApps), \ LOGLEVEL_VAR(docker), \ LOGLEVEL_VAR(vmIPC), \ LOGLEVEL_VAR(uwt), /* lib/unityWindowTracker */ \ LOGLEVEL_VAR(cui), \ LOGLEVEL_VAR(automation), \ LOGLEVEL_VAR(oemDevice), \ LOGLEVEL_VAR(cptOps), \ LOGLEVEL_VAR(vprobe), \ LOGLEVEL_VAR(VProbeClient), \ LOGLEVEL_VAR(device), \ LOGLEVEL_VAR(devicePowerOn), \ LOGLEVEL_VAR(vmxvmdbCallbacks), \ LOGLEVEL_VAR(guestInstall), \ LOGLEVEL_VAR(migrateVM), \ LOGLEVEL_VAR(vmUpsellController), \ LOGLEVEL_VAR(objc), /* lib/objc */ \ LOGLEVEL_VAR(blit), /* lib/blit */ \ LOGLEVEL_VAR(vmnetBridge), \ LOGLEVEL_VAR(wifi), /* macWireless and wpa_supplicant */ \ LOGLEVEL_VAR(brtalk), \ LOGLEVEL_VAR(button), \ LOGLEVEL_VAR(util), \ LOGLEVEL_VAR(vmcf), \ LOGLEVEL_VAR(win32util), \ LOGLEVEL_VAR(largepage), \ LOGLEVEL_VAR(guestAppMonitor), \ LOGLEVEL_VAR(syncWaitQ), \ LOGLEVEL_VAR(sg), /* lib/sg */ \ LOGLEVEL_VAR(ftcpt), \ LOGLEVEL_VAR(digestlib), \ LOGLEVEL_VAR(inputdevtap), \ LOGLEVEL_VAR(objlib), \ LOGLEVEL_VAR(vsanobj), \ LOGLEVEL_VAR(vvolbe), \ LOGLEVEL_VAR(upitbe), \ LOGLEVEL_VAR(slotfs), \ LOGLEVEL_VAR(svgadevtap), \ LOGLEVEL_VAR(masReceipt), /* lib/masReceipt */ \ LOGLEVEL_VAR(serviceImpl), /* lib/serviceImpl */ \ LOGLEVEL_VAR(serviceUser), /* lib/serviceUser */ \ LOGLEVEL_VAR(ssl), \ LOGLEVEL_VAR(namespaceDb), \ LOGLEVEL_VAR(namespaceMgr), \ LOGLEVEL_VAR(grainTrack), \ LOGLEVEL_VAR(shim3D), \ LOGLEVEL_VAR(crc32), \ LOGLEVEL_VAR(vmkmgmtlib), \ LOGLEVEL_VAR(vflash), \ LOGLEVEL_VAR(vva), /* apps/rde/vva */ \ LOGLEVEL_VAR(ftConfig), /*lib/ftConfig */ \ LOGLEVEL_VAR(vmname), /* lib/vmname */ \ LOGLEVEL_VAR(gpumgmt), \ LOGLEVEL_VAR(unityMsg), /* mks/remote/vdpUnityVmdb */ \ LOGLEVEL_VAR(sharedFolderMgr), /* mks/remote/vdpFolderSharedMgrVmdb */ \ LOGLEVEL_VAR(crtbora), /* apps/crtbora */ \ LOGLEVEL_VAR(mirror), \ LOGLEVEL_VAR(filtlib), \ LOGLEVEL_VAR(epd), \ LOGLEVEL_VAR(ddecomd), \ LOGLEVEL_VAR(vdfs), \ LOGLEVEL_VAR(vdfs_9p), \ LOGLEVEL_VAR(hostctl), \ LOGLEVEL_VAR(pmemobj), \ LOGLEVEL_VAR(secureBoot), \ LOGLEVEL_VAR(upitd), \ LOGLEVEL_VAR(promotedisk), \ LOGLEVEL_VAR(efivarstore), \ LOGLEVEL_VAR(toolsIso), \ LOGLEVEL_VAR(toolsversion), \ LOGLEVEL_VAR(vmva), \ LOGLEVEL_VAR(udpfec), /* lib/udpfec */ \ LOGLEVEL_VAR(maclatency), \ LOGLEVEL_VAR(tpm2emu), \ LOGLEVEL_VAR(tarReader),\ LOGLEVEL_VAR(nvramMgr), \ LOGLEVEL_VAR(hbr), \ LOGLEVEL_VAR(vvtd), \ LOGLEVEL_VAR(amdIommu) /* end of list */ LOGLEVEL_EXTENSION_DECLARE(LOGLEVEL_USER); #endif /* _LOGLEVEL_USER_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/memaligned.h000066400000000000000000000227531321503522500247530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * memaligned.h -- * * misc util functions */ #ifndef _MEMALIGNED_H_ #define _MEMALIGNED_H_ #ifdef __linux__ #include #else #include #ifdef __FreeBSD__ #include #endif #endif #include "vmware.h" #if defined(__cplusplus) extern "C" { #endif #if defined __APPLE__ && !vm_x86_64 /* * Bug 471584: Mac OS X 10.6's valloc() implementation for 32-bit * processes can exhaust our process's memory space. * * Work around this by using our own simple page-aligned memory * allocation implementation based on malloc() for 32-bit processes. */ #define MEMALIGNED_USE_INTERNAL_IMPL 1 #endif #ifdef MEMALIGNED_USE_INTERNAL_IMPL /* *----------------------------------------------------------------------------- * * AlignedMallocImpl -- * * Internal implementation of page-aligned memory for operating systems * that lack a working page-aligned allocation function. * * Resulting pointer needs to be freed with AlignedFreeImpl. * * Result: * A pointer. NULL on out of memory condition. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void * AlignedMallocImpl(size_t size) // IN { size_t paddedSize; void **buf; void **alignedResult; #undef PAGE_MASK #define PAGE_MASK (PAGE_SIZE - 1) #define PAGE_ROUND_DOWN(_value) ((uintptr_t)(_value) & ~PAGE_MASK) #define PAGE_ROUND_UP(_value) PAGE_ROUND_DOWN((uintptr_t)(_value) + PAGE_MASK) /* * This implementation allocates PAGE_SIZE extra bytes with * malloc() to ensure the buffer spans a page-aligned memory * address, which we return. (We could use PAGE_SIZE - 1 to save a * byte if we ensured 'size' was non-zero.) * * After padding, we allocate an extra pointer to hold the original * pointer returned by malloc() (stored immediately preceding the * page-aligned address). We free this in AlignedFreeImpl(). * * Finally, we allocate enough space to hold 'size' bytes. */ paddedSize = PAGE_SIZE + sizeof *buf + size; // Check for overflow. if (paddedSize < size) { return NULL; } buf = (void **)malloc(paddedSize); if (!buf) { return NULL; } alignedResult = (void **)PAGE_ROUND_UP(buf + 1); *(alignedResult - 1) = buf; return alignedResult; } /* *----------------------------------------------------------------------------- * * AlignedReallocImpl -- * * Internal implementation of page-aligned memory for operating systems * that lack a working page-aligned allocation function. * * Resulting pointer needs to be freed with AlignedFreeImpl. * * Result: * A pointer. NULL on out of memory condition. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void * AlignedReallocImpl(void *oldbuf, // IN size_t newsize) // IN { size_t paddedSize; void **buf; void **alignedResult; void *oldptr = NULL; if (oldbuf) { oldptr = (*((void **)oldbuf - 1)); } paddedSize = PAGE_SIZE + sizeof *buf + newsize; // Check for overflow. if (paddedSize < newsize) { return NULL; } buf = (void **)realloc(oldptr, paddedSize); if (!buf) { return NULL; } alignedResult = (void **)PAGE_ROUND_UP(buf + 1); *(alignedResult - 1) = buf; return alignedResult; } /* *----------------------------------------------------------------------------- * * AlignedFreeImpl -- * * Internal implementation to free a page-aligned buffer allocated * with AlignedMallocImpl. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void AlignedFreeImpl(void *buf) // IN { if (!buf) { return; } free(*((void **)buf - 1)); } #endif // MEMALIGNED_USE_INTERNAL_IMPL /* *--------------------------------------------------------------------------- * * Aligned_UnsafeMalloc -- * * Alloc a chunk of memory aligned on a page boundary. Resulting pointer * needs to be freed with Aligned_Free. * * Result: * A pointer. NULL on out of memory condition. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static INLINE void* Aligned_UnsafeMalloc(size_t size) // IN { void *buf; #if defined MEMALIGNED_USE_INTERNAL_IMPL buf = AlignedMallocImpl(size); #elif defined _WIN32 buf = _aligned_malloc(size, PAGE_SIZE); #elif __linux__ buf = memalign(PAGE_SIZE, size); #else // Apple, BSD, Solaris (tools) buf = valloc(size); #endif ASSERT(((uintptr_t)buf % PAGE_SIZE) == 0); return buf; } /* *--------------------------------------------------------------------------- * * Aligned_Malloc -- * * Alloc a chunk of memory aligned on a page boundary. Resulting pointer * needs to be freed with Aligned_Free. You should never use this * function. Especially if size was derived from guest provided data. * * Result: * A pointer. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static INLINE void* Aligned_Malloc(size_t size) // IN { void *buf; buf = Aligned_UnsafeMalloc(size); VERIFY(buf); return buf; } /* *--------------------------------------------------------------------------- * * Aligned_Calloc -- * * Alloc a chunk of memory aligned on a page boundary. Resulting pointer * needs to be freed with Aligned_Free. * * Result: * A pointer. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static INLINE void* Aligned_Calloc(size_t nmemb, // IN size_t size) // IN { void *buf = Aligned_Malloc(nmemb * size); VERIFY(buf); memset(buf, 0, nmemb * size); return buf; } /* *--------------------------------------------------------------------------- * * Aligned_Free -- * * Free a chunk of memory allocated using the 2 functions above. * * Result: * None. * * Side effects: * None. * *--------------------------------------------------------------------------- */ static INLINE void Aligned_Free(void *buf) // IN { #if defined MEMALIGNED_USE_INTERNAL_IMPL AlignedFreeImpl(buf); #elif defined _WIN32 _aligned_free(buf); #else free(buf); #endif } /* *--------------------------------------------------------------------------- * * Aligned_UnsafeRealloc -- * * This function is not implemented because it cannot be done safely and * portably. See https://reviewboard.eng.vmware.com/r/284303/ for * discussion. * *--------------------------------------------------------------------------- */ /* *--------------------------------------------------------------------------- * * Aligned_Realloc -- * * Realloc a chunk of memory aligned on a page boundary, potentially * copying the previous data to a new buffer if necessary. Resulting * pointer needs to be freed with Aligned_Free. You should never use this * function. Especially if size was derived from guest provided data. * * Result: * A pointer. * * Side effects: * Old buf may be freed. * *--------------------------------------------------------------------------- */ static INLINE void* Aligned_Realloc(void *buf, // IN size_t size) // IN { #if defined MEMALIGNED_USE_INTERNAL_IMPL return AlignedReallocImpl(buf, size); #elif defined _WIN32 return _aligned_realloc(buf, size, PAGE_SIZE); #else /* * Some valloc(3) manpages claim that realloc(3) on a buffer allocated by * valloc() will return an aligned buffer. If so, we have a fast path; * simply realloc, validate the alignment, and return. For realloc()s that * do not maintain the alignment (such as glibc 2.13 x64 for allocations of * 16 pages or less) then we fall back to a slowpath and copy the data. * Note that we can't avoid the realloc overhead in this case: on entry to * Aligned_Realloc we have no way to find out how big the source buffer is! * Only after the realloc do we know a safe range to copy. We may copy more * data than necessary -- consider the case of resizing from one page to * 100 pages -- but that is safe, just slow. */ buf = realloc(buf, size); if (((uintptr_t)buf % PAGE_SIZE) != 0) { void *newbuf; newbuf = Aligned_UnsafeMalloc(size); VERIFY(newbuf); memcpy(newbuf, buf, size); free(buf); return newbuf; } return buf; #endif } #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/message.h000066400000000000000000000047531321503522500242750ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1999-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * message.h -- * * Second layer of the internal communication channel between guest * applications and vmware */ #ifndef __MESSAGE_H__ # define __MESSAGE_H__ #include "vm_basic_types.h" #ifdef __cplusplus extern "C" { #endif /* The channel object */ typedef struct Message_Channel { /* Identifier */ uint16 id; /* Reception buffer */ /* Data */ unsigned char *in; /* Allocated size */ size_t inAlloc; Bool inPreallocated; /* The cookie */ uint32 cookieHigh; uint32 cookieLow; } Message_Channel; Bool Message_OpenAllocated(uint32 proto, Message_Channel *chan, char *receiveBuffer, size_t receiveBufferSize); Message_Channel* Message_Open(uint32 proto); Bool Message_Send(Message_Channel *chan, const unsigned char *buf, size_t bufSize); Bool Message_Receive(Message_Channel *chan, unsigned char **buf, size_t *bufSize); Bool Message_CloseAllocated(Message_Channel *chan); Bool Message_Close(Message_Channel *chan); #ifdef __cplusplus } #endif #endif /* __MESSAGE_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/miscSolaris.h000066400000000000000000000025311321503522500251310ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* *---------------------------------------------------------------------- * * miscSolaris -- * * Implementation of new Linux functions for Solaris. * *---------------------------------------------------------------------- */ #ifndef _MISCSOLARIS_H_ #define _MISCSOLARIS_H_ #define INCLUDE_ALLOW_USERLEVEL #if defined(__cplusplus) extern "C" { #endif int daemon(int nochdir, int noclose); #if defined(__cplusplus) } // extern "C" #endif #endif /* _MISCSOLARIS_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/mntinfo.h000066400000000000000000000165331321503522500243220ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * mntinfo.h -- * * Macros to abstract differences between structures and functions used in * accessing information about mounted file systems. * */ #ifndef __MNTINFO_H__ #define __MNTINFO_H__ #ifdef sun # include # include # include #elif defined(__linux__) # include #elif defined(__FreeBSD__) # include #endif #include "posix.h" /* *---------------------------------------------------------------------------- * * DECLARE_MNTINFO, MNTINFO * OPEN_MNTFILE, GETNEXT_MNTINFO, CLOSE_MNTFILE, * MNTINFO_NAME, MNTINFO_FSTYPE, MNTINFO_MNTPT -- * * Cross-platform macros for accessing information about the mounted file * systems. This is necessary since the interfaces for getmntent(3) are * slightly different on Linux and Solaris. * * DECLARE_MNTINFO() is used to declare the variable used when invoking * GETNEXT_MNTINFO(). MNTINFO is the type that can be used when passing * between functions. * * OPEN_MNTFILE() and CLOSE_MNTFILE() must be called before and after * a series of GETNEXT_MNTINFO() calls, respectively. GETNEXT_MNTINFO() is * called successively to retrieve information about the next mounted file * system. * * MNTINFO_NAME, MNTINFO_FSTYPE, and MNTINFO_MNTPT retrieve the name, file * system type, and mount point of the provided MNTINFO, respectively. * * MNTFILE is a string with the name of the file containing mount * information. * * Results: * OPEN_MNTFILE: MNTHANDLE on success, NULL on failure * GETNEXT_MNTINFO: on success, TRUE and mnt is filled with file system's * information; FALSE when no mounts left or on failure * CLOSE_MNTFILE: TRUE on success, FALSE on failure * * MNTINFO_NAME: mount's name on success, NULL on failure * MNTINFO_FSTYPE: mount's file system type on success, NULL on failure * MNTINFO_MNTPT: mount's mount point on success, NULL on failure * * Side effects: * None. * *---------------------------------------------------------------------------- */ #ifdef sun # define MNTFILE MNTTAB # define MNTHANDLE FILE * # define MNTINFO struct mnttab # define DECLARE_MNTINFO(name) struct mnttab __ ## name; \ struct mnttab *name = &__ ## name # define OPEN_MNTFILE(mode) Posix_Fopen(MNTFILE, mode) # define GETNEXT_MNTINFO(fp, mnt) (Posix_Getmntent(fp, mnt) == 0) # define CLOSE_MNTFILE(fp) (fclose(fp) == 0) # define MNTINFO_NAME(mnt) mnt->mnt_special # define MNTINFO_FSTYPE(mnt) mnt->mnt_fstype # define MNTINFO_MNTPT(mnt) mnt->mnt_mountp # define MNTINFO_MNT_IS_RO(mnt) (hasmntopt((mnt), "rw") == NULL) #elif defined(__linux__) # define MNTFILE MOUNTED # define MNTHANDLE FILE * # define MNTINFO struct mntent # define DECLARE_MNTINFO(name) struct mntent *name # define OPEN_MNTFILE(mode) Posix_Setmntent(MNTFILE, mode) # define GETNEXT_MNTINFO(fp, mnt) ((mnt = Posix_Getmntent(fp)) != NULL) # define CLOSE_MNTFILE(fp) (endmntent(fp) == 1) # define MNTINFO_NAME(mnt) mnt->mnt_fsname # define MNTINFO_FSTYPE(mnt) mnt->mnt_type # define MNTINFO_MNTPT(mnt) mnt->mnt_dir # define MNTINFO_MNT_IS_RO(mnt) (hasmntopt((mnt), "rw") == NULL) #elif defined(__FreeBSD__) || defined(__APPLE__) struct mntHandle { struct statfs *mountPoints; // array of mountpoints per getmntinfo(3) int numMountPoints; // number of elements in mntArray int mountIndex; // current location within mountPoints array }; # define MNTFILE _PATH_FSTAB # define MNTHANDLE struct mntHandle * # define MNTINFO struct statfs # define DECLARE_MNTINFO(name) struct statfs __ ## name; \ struct statfs *name = &__ ## name # define OPEN_MNTFILE(mode) \ ({ \ MNTHANDLE mntHandle; \ mntHandle = malloc(sizeof *mntHandle); \ if (mntHandle != NULL) { \ mntHandle->numMountPoints = getmntinfo(&mntHandle->mountPoints, \ MNT_NOWAIT); \ mntHandle->mountIndex = 0; \ } \ mntHandle; \ }) # define GETNEXT_MNTINFO(mntHandle, mnt) \ ({ \ /* Avoid multiple evaluations/expansions. */ \ MNTHANDLE thisHandle = (mntHandle); \ MNTINFO *thisMnt = (mnt); \ Bool boolVal = FALSE; \ ASSERT(thisHandle); \ if (thisHandle->mountIndex < thisHandle->numMountPoints) { \ memcpy(thisMnt, \ &thisHandle->mountPoints[thisHandle->mountIndex], \ sizeof *thisMnt); \ ++thisHandle->mountIndex; \ boolVal = TRUE; \ } \ boolVal; \ }) # define CLOSE_MNTFILE(mntHandle) \ ({ \ free(mntHandle); \ TRUE; \ }) # define MNTINFO_NAME(mnt) mnt->f_mntfromname # define MNTINFO_FSTYPE(mnt) mnt->f_fstypename # define MNTINFO_MNTPT(mnt) mnt->f_mntonname # define MNTINFO_MNT_IS_RO(mnt) ((mnt)->f_flags & MNT_RDONLY) #else # error "Define mount information macros for your OS type" #endif #endif /* __MNTINFO_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/msg.h000066400000000000000000000174121321503522500234330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * msg.h -- * * user interaction through (non-modal) messages and (modal) dialogs */ #ifndef _MSG_H_ #define _MSG_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #include #include "err.h" #include "vm_basic_types.h" #include "msgid.h" #include "msgfmt.h" #include "msgList.h" #if defined VMX86_SERVER && !defined VMCORE #include "voblib.h" #endif #if defined(__cplusplus) extern "C" { #endif #define INVALID_MSG_CODE (-1) /* * Data structures, types, and constants */ typedef struct Msg_String { const char *idFmt; } Msg_String; typedef enum MsgSeverity { MSG_INFO, MSG_INFO_TIMEOUT, MSG_WARNING, MSG_ERROR, MSG_CONFIG_EDITOR, MSG_WEB_LINK_GET_LICENSE_ERROR, MSG_WEB_LINK_EXTEND_LICENSE_ERROR, MSG_WEB_LINK_EXTEND_LICENSE_INFO, MSG_WEB_LINK_HOME_PAGE_INFO, MSG_NUM_SEVERITIES } MsgSeverity; typedef enum HintResult { HINT_CONTINUE, HINT_CANCEL, HINT_NOT_SHOWN } HintResult; typedef enum HintOptions { HINT_OK, HINT_OKCANCEL } HintOptions; typedef struct MsgCallback { void (*post)(MsgSeverity severity, const char *msgID, const char *message); int (*question)(char const * const *names, int defaultAnswer, const char *msgID, const char *message); int (*progress)(const char *msgID, const char *message, int percent, Bool cancelButton); HintResult (*hint)(HintOptions options, const char *msgID, const char *message); void *(*lazyProgressStart)(const char *msgID, const char *message, Bool allowCancel); Bool (*lazyProgress)(void *handle, const char *msgID, const char *message, Bool allowCancel, int percent); void (*lazyProgressEnd)(void *handle); void (*postList)(MsgSeverity severity, MsgList *messages); int (*questionList)(const Msg_String *buttons, int defaultAnswer, MsgList *messages); int (*progressList)(MsgList *messages, int percent, Bool cancelButton); HintResult (*hintList)(HintOptions options, MsgList *messages); void *(*lazyProgressStartList)(MsgList *messages); void (*forceUnblock)(void); void (*msgPostHook)(int severity, const MsgList *msgs); } MsgCallback; #define MSG_QUESTION_MAX_BUTTONS 10 #define MSG_PROGRESS_START (-1) #define MSG_PROGRESS_STOP 101 VMX86_EXTERN_DATA Msg_String const Msg_YesNoButtons[]; VMX86_EXTERN_DATA Msg_String const Msg_OKButtons[]; VMX86_EXTERN_DATA Msg_String const Msg_RetryCancelButtons[]; VMX86_EXTERN_DATA Msg_String const Msg_OKCancelButtons[]; VMX86_EXTERN_DATA Msg_String const Msg_RetryAbortButtons[]; VMX86_EXTERN_DATA Msg_String const Msg_Severities[]; /* * Functions */ void Msg_Append(const char *idFmt, ...) PRINTF_DECL(1, 2); void Msg_VAppend(const char *idFmt, va_list args); void Msg_AppendStr(const char *id); void Msg_AppendMsgList(const MsgList *msgs); static INLINE void Msg_AppendVobContext(void) { #if defined VMX86_SERVER && !defined VMCORE /* inline to avoid lib/vob dependency unless necessary */ MsgList *msgs = NULL; VobLib_CurrentContextMsgAppend(&msgs); Msg_AppendMsgList(msgs); MsgList_Free(msgs); #endif } void Msg_Post(MsgSeverity severity, const char *idFmt, ...) PRINTF_DECL(2, 3); void Msg_PostMsgList(MsgSeverity severity, const MsgList *msgs); char *Msg_Format(const char *idFmt, ...) PRINTF_DECL(1, 2); char *Msg_VFormat(const char *idFmt, va_list arguments); unsigned Msg_Question(Msg_String const *buttons, int defaultAnswer, const char *idFmt, ...) PRINTF_DECL(3, 4); /* * Unfortunately, gcc warns about both NULL and "" being passed as format * strings, and callers of Msg_Progress() like to do that. So I'm removing * the PRINTF_DECL() for now. --Jeremy. */ int Msg_Progress(int percentDone, Bool cancelButton, const char *idFmt, ...); int Msg_ProgressScaled(int percentDone, int opsDone, int opsTotal, Bool cancelButton); void *Msg_LazyProgressStart(Bool allowCancel, const char *idFmt, ...) PRINTF_DECL(2, 3); Bool Msg_LazyProgress(void *handle, Bool allowCancel, int percent, const char *idFmt, ...) PRINTF_DECL(4, 5); void Msg_LazyProgressEnd(void *handle); HintResult Msg_Hint(Bool defaultShow, HintOptions options, const char *idFmt, ...) PRINTF_DECL(3, 4); HintResult Msg_HintMsgList(Bool defaultShow, HintOptions options, MsgList *msg); int Msg_CompareAnswer(Msg_String const *buttons, unsigned answer, const char *string); char *Msg_GetString(const char *idString); char *Msg_GetStringSafe(const char *idString); char *Msg_GetPlainButtonText(const char *idString); char *Msg_GetLocale(void); void Msg_SetLocale(const char *locale, const char *binaryName); void Msg_SetLocaleEx(const char *locale, const char *binaryName, const char *baseDirPath); char *Msg_FormatFloat(double value, unsigned int precision); char *Msg_FormatSizeInBytes(uint64 size); Bool Msg_LoadMessageFile(const char *locale, const char *fileName); void Msg_ForceUnblock(void); /* * Message buffer management */ const char *Msg_GetMessages(void); const char *Msg_GetMessagesAndReset(void); void Msg_LogAndReset(void); MsgList *Msg_GetMsgList(void); MsgList *Msg_GetMsgListAndReset(void); char *Msg_LocalizeList(const MsgList *messages); void Msg_Reset(Bool log); Bool Msg_Present(void); void Msg_ExitThread(void); void Msg_Exit(void); /* * Don't know, don't care. -- edward */ #define MSG_POST_NOMEM() \ Msg_Post(MSG_ERROR, MSGID(msg.noMem) "Cannot allocate memory.\n") #ifndef VMX86_DEBUG #define MSG_CHECK_ORPHANED_MESSAGES(id, fmt, arg) #elif defined VMX86_DEVEL #define MSG_CHECK_ORPHANED_MESSAGES(id, fmt, arg) ( \ Msg_Present() ? \ Msg_Post(MSG_INFO, \ id fmt "THIS MESSAGE ON DEVEL BUILDS only - " \ "Please file bug about orphan Msg_Append\n", \ arg) : \ (void) 0 \ ) #else #define MSG_CHECK_ORPHANED_MESSAGES(id, fmt, arg) ( \ Msg_Present() ? \ (Log(fmt, arg), \ Msg_Reset(TRUE)) : \ (void) 0 \ ) #endif /* * To implement message dialogs */ void Msg_SetCallback(MsgCallback *cb); void Msg_SetThreadCallback(MsgCallback *cb); void Msg_GetCallback(MsgCallback *cb); void Msg_GetThreadCallback(MsgCallback *cb); /* * Conversion functions */ #define Msg_ErrString() (Err_ErrString()) #define Msg_Errno2String(errorNumber) ( \ Err_Errno2String(errorNumber) ) #ifdef _WIN32 const char *Msg_HResult2String(long hr); #endif #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _MSG_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/msgList.h000066400000000000000000000045521321503522500242700ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * msgList.h -- * * Utilities to manipulate (stateless) lists of messages. */ #ifndef _MSGLIST_H_ #define _MSGLIST_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #include #include "vm_basic_types.h" #include "msgid.h" #include "msgfmt.h" #if defined(__cplusplus) extern "C" { #endif /* * Data structures, types, and constants */ typedef struct MsgList MsgList; struct MsgList { MsgList *next; char *id; char *format; MsgFmt_Arg *args; int numArgs; }; /* * Functions */ MsgList *MsgList_Create(const char *idFmt, ...) PRINTF_DECL(1, 2); MsgList *MsgList_VCreate(const char *idFmt, va_list args); MsgList *MsgList_CreateStr(const char *id); void MsgList_Append(MsgList **tail, const char *idFmt, ...) PRINTF_DECL(2, 3); void MsgList_VAppend(MsgList **tail, const char *idFmt, va_list args); void MsgList_AppendStr(MsgList **tail, const char *id); void MsgList_AppendMsgList(MsgList **tail, MsgList *messages); void MsgList_Log(const MsgList *messages); char *MsgList_ToEnglishString(const MsgList *messages); MsgList *MsgList_Copy(const MsgList *src); void MsgList_Free(MsgList *messages); const char *MsgList_GetMsgID(const MsgList *messages); Bool MsgList_Present(const MsgList *messages); static INLINE void MsgList_LogAndFree(MsgList *messages) { MsgList_Log(messages); MsgList_Free(messages); } #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _MSGLIST_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/msgfmt.h000066400000000000000000000126071321503522500241430ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * msgfmg.h -- * * MsgFmt: format messages for the Msg module */ #ifndef _MSGFMT_H_ #define _MSGFMT_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #ifndef VMKERNEL #include "str.h" // for HAS_BSD_PRINTF #endif #if defined(__cplusplus) extern "C" { #endif /* * Format parser callback functions */ typedef int MsgFmt_LitFunc(void *clientData, // IN char const *buf, // IN int bufSize); // IN typedef int MsgFmt_SpecFunc(void *clientData, // IN char const *pos, // IN unsigned int posSize, // IN char const *type, // IN unsigned int typeSize); // IN /* * Format specifier flags from MsgFmt_ParseSpec() */ #define MSGFMT_FLAG_ALT 0x0001 #define MSGFMT_FLAG_ZERO 0x0002 #define MSGFMT_FLAG_MINUS 0x0004 #define MSGFMT_FLAG_SPACE 0x0008 #define MSGFMT_FLAG_PLUS 0x0010 #define MSGFMT_FLAG_QUOTE 0x0020 /* * A format argument * * In addition to being a internal data structure, * MsgFmt_Arg defines the Vob (vmkernel observations) protocol * between vmkernel and vmx. As such, it must be carefully aligned, * so that all the fields (except the pointers) have fixed sizes * and the same offsets in the 64-bit vmkernel, the 32-bit vmx, * and the 64-bit vmx. */ typedef enum MsgFmt_ArgType { MSGFMT_ARG_INVALID, // must be 0 MSGFMT_ARG_INT32, MSGFMT_ARG_INT64, MSGFMT_ARG_PTR32, MSGFMT_ARG_PTR64, MSGFMT_ARG_FLOAT64, MSGFMT_ARG_STRING8, MSGFMT_ARG_STRING16, MSGFMT_ARG_STRING32, MSGFMT_ARG_ERRNO, } MsgFmt_ArgType; typedef enum MsgFmt_ArgPlatform { MSGFMT_PLATFORM_UNKNOWN, MSGFMT_PLATFORM_LINUX, MSGFMT_PLATFORM_WINDOWS, MSGFMT_PLATFORM_MACOS, } MsgFmt_ArgPlatform; typedef struct MsgFmt_Arg { int32 type; int32 pad; union { int32 signed32; int64 signed64; uint32 unsigned32; uint64 unsigned64; double float64; char *string8char; // same as string8, different type int8 *string8; int16 *string16; int32 *string32; int32 offset; void *ptr; // private } v; struct { int32 platform; int32 number; } e; union { // private int32 precision; char *localString; uint64 pad; } p; } MsgFmt_Arg; #if defined __linux__ #define MSGFMT_CURRENT_PLATFORM MSGFMT_PLATFORM_LINUX #elif defined _WIN32 #define MSGFMT_CURRENT_PLATFORM MSGFMT_PLATFORM_WINDOWS #elif defined __APPLE__ #define MSGFMT_CURRENT_PLATFORM MSGFMT_PLATFORM_MACOS #else #define MSGFMT_CURRENT_PLATFORM MSGFMT_PLATFORM_UNKNOWN #endif /* * Global functions */ typedef int MsgFmt_ParseFunc(MsgFmt_LitFunc *litFunc, // IN MsgFmt_SpecFunc *specFunc, // IN void *clientData, // IN char const *in); // IN MsgFmt_ParseFunc MsgFmt_Parse; MsgFmt_ParseFunc MsgFmt_ParseWin32; int MsgFmt_ParseSpec(char const *pos, // IN: n$ location unsigned int posSize, // IN: n$ length char const *type, // IN: flags, width, etc. unsigned int typeSize, // IN: size of above int *position, // OUT: argument position int *flags, // OUT: flags, see MSGFMT_FLAG_* int *width, // OUT: width int *precision, // OUT: precision char *lengthMod, // OUT: length modifier char *conversion); // OUT: conversion specifier Bool MsgFmt_GetArgs(const char *fmt, va_list va, MsgFmt_Arg **args, int *numArgs, char **error); Bool MsgFmt_GetArgsWithBuf(const char *fmt, va_list va, MsgFmt_Arg **args, int *numArgs, char **error, void *buf, size_t *bufSize); void MsgFmt_FreeArgs(MsgFmt_Arg *args, int numArgs); void MsgFmt_SwizzleArgs(MsgFmt_Arg *args, int numArgs); int MsgFmt_GetSwizzledString(const MsgFmt_Arg *args, int numArgs, int idx, const void *bufEnd, const int8 **str); int MsgFmt_UnswizzleArgs(MsgFmt_Arg *args, int numArgs, void *bufEnd); MsgFmt_Arg* MsgFmt_CopyArgs(MsgFmt_Arg* copyArgs, int numArgs); int MsgFmt_Snprintf(char *buf, size_t size, const char *format, const MsgFmt_Arg *args, int numArgs); char *MsgFmt_Asprintf(size_t *length, const char *format, const MsgFmt_Arg *args, int numArgs); #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _MSGFMT_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/msgid.h000066400000000000000000000054671321503522500237570ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * msgid.h -- * * Message ID magic */ #ifndef _MSGID_H_ #define _MSGID_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include "msgid_defs.h" #include "vm_basic_defs.h" #ifndef VMKERNEL #include #endif #if defined(__cplusplus) extern "C" { #endif // the X hides MSG_MAGIC so it won't appear in the object file #define MSG_MAGICAL(s) \ (s != NULL && strncmp(s, MSG_MAGIC"X", MSG_MAGIC_LEN) == 0) // Start after MSG_MAGIC so it won't appear in the object file either. #define MSG_HAS_BUTTONID(s) \ (MSG_MAGICAL(s) && \ (strncmp(&(s)[MSG_MAGIC_LEN], MSG_BUTTON_ID, MSG_BUTTON_ID_LEN) == 0)) /* *----------------------------------------------------------------------------- * * Msg_HasMsgID -- * * Check that a string has a message ID. * The full "MSG_MAGIC(...)" prefix is required, not just MSG_MAGIC. * * Results: * True if string has a message ID. * * Side Effects: * None * *----------------------------------------------------------------------------- */ static INLINE Bool Msg_HasMsgID(const char *s) { return MSG_MAGICAL(s) && *(s += MSG_MAGIC_LEN) == '(' && strchr(s + 1, ')') != NULL; } /* *----------------------------------------------------------------------------- * * Msg_StripMSGID -- * * Returns the string that is inside the MSGID() or if it doesn't * have a MSGID just return the string. * * Results: * The unlocalized string. * * Side Effects: * None * *----------------------------------------------------------------------------- */ static INLINE const char * Msg_StripMSGID(const char *idString) // IN { const char *s = idString; if (MSG_MAGICAL(s) && *(s += MSG_MAGIC_LEN) == '(' && (s = strchr(s + 1, ')')) != NULL) { return s + 1; } return idString; } #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _MSGID_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/msgid_defs.h000066400000000000000000000035421321503522500247500ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2011-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * msgid_defs.h -- * * Message ID magic definitions */ #ifndef _MSGID_DEFS_H_ #define _MSGID_DEFS_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" /* * Message ID macros * * Use as in * Msg_Append(MSGID(file.openFailed) "Failed to open file %s: %s.\n" * fileName, Msg_ErrString()) * Msg_Append(MSGID(mks.powerOnFailed) "Power on failed.\n") * or * Msg_Hint(TRUE, HINT_OK, * MSGID(mks.noDGA) "No full screen mode.\n"). * * Don't make MSG_MAGIC_LEN (sizeof MSG_MAGIC - 1), since * that may cause the string to be in the object file, even * when it's not used at run time. And we are trying * to avoid littering the output with the magic string. * * -- edward */ #define MSG_MAGIC "@&!*@*@" #define MSG_MAGIC_LEN 7 #define MSGID(id) MSG_MAGIC "(msg." #id ")" #define MSG_BUTTON_ID "(button." #define MSG_BUTTON_ID_LEN 8 #define BUTTONID(id) MSG_MAGIC MSG_BUTTON_ID #id ")" #endif // ifndef _MSGID_DEFS_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/mul64.h000066400000000000000000000103461321503522500236130ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2014,2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * mul64.h * * Integer by fixed point multiplication, with rounding. * * These routines are implemented in assembly language for most * supported platforms. This file has plain C fallback versions. */ #ifndef _MUL64_H_ #define _MUL64_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_VMMON #define INCLUDE_ALLOW_VMK_MODULE #define INCLUDE_ALLOW_VMKERNEL #define INCLUDE_ALLOW_DISTRIBUTE #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_asm.h" #if defined __cplusplus extern "C" { #endif #ifdef MUL64_NO_ASM /* *----------------------------------------------------------------------------- * * Mul64x3264 -- * * Unsigned integer by fixed point multiplication, with rounding: * result = floor(multiplicand * multiplier * 2**(-shift) + 0.5) * * Unsigned 64-bit integer multiplicand. * Unsigned 32-bit fixed point multiplier, represented as * (multiplier, shift), where shift < 64. * * Result: * Unsigned 64-bit integer product. * *----------------------------------------------------------------------------- */ static INLINE uint64 Mul64x3264(uint64 multiplicand, uint32 multiplier, uint32 shift) { uint64 lo, hi, lo2, hi2; unsigned carry; // ASSERT(shift >= 0 && shift < 64); lo = (multiplicand & 0xffffffff) * multiplier; hi = (multiplicand >> 32) * multiplier; lo2 = lo + (hi << 32); carry = lo2 < lo; hi2 = (hi >> 32) + carry; if (shift == 0) { return lo2; } else { return (lo2 >> shift) + (hi2 << (64 - shift)) + ((lo2 >> (shift - 1)) & 1); } } /* *----------------------------------------------------------------------------- * * Muls64x32s64 -- * * Signed integer by fixed point multiplication, with rounding: * result = floor(multiplicand * multiplier * 2**(-shift) + 0.5) * * Signed 64-bit integer multiplicand. * Unsigned 32-bit fixed point multiplier, represented as * (multiplier, shift), where shift < 64. * * Result: * Signed 64-bit integer product. * *----------------------------------------------------------------------------- */ static INLINE int64 Muls64x32s64(int64 multiplicand, uint32 multiplier, uint32 shift) { uint64 lo, hi, lo2, hi2; unsigned carry; // ASSERT(shift >= 0 && shift < 64); hi = ((uint64)multiplicand >> 32) * multiplier; if (multiplicand < 0) { hi -= (uint64)multiplier << 32; } lo = ((uint64)multiplicand & 0xffffffff) * multiplier; lo2 = lo + (hi << 32); carry = lo2 < lo; hi2 = (((int64)hi >> 32) + carry); if (shift == 0) { return lo2; } else { return (lo2 >> shift) + (hi2 << (64 - shift)) + ((lo2 >> (shift - 1)) & 1); } } #endif #if defined __cplusplus } // extern "C" #endif #endif // _MUL64_NOASM_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/mutexRank.h000066400000000000000000000060621321503522500246220ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * mutexRank.h -- * * Base lock rank defines. See userlock.h for the related APIs. */ #ifndef _MUTEXRANK_H_ #define _MUTEXRANK_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #if defined(__cplusplus) extern "C" { #endif /* * Core rank defines. * * ANY RANK USAGE ABOVE RANK_LEAF IS RESERVED BY THE PI GROUP. */ #define RANK_UNRANKED 0 #define RANK_LEAF 0xFF000000 #define RANK_INVALID 0xFFFFFFFF /* * For situations where we need to create locks on behalf of * third-party code, but we don't know what ranking scheme, if any, * that code uses. For now, the only usage is in bora/lib/ssl. */ #define RANK_THIRDPARTY RANK_UNRANKED /* * Log lock rank. * * Very special case. Don't change it. The effect is that critical * logging code cannot call anything else which requires a lock, but * everyone else can safely Log() while holding a leaf lock. */ #define RANK_logLock (RANK_LEAF + 2) /* * overheadMem lock rank. * * Very special case. Don't change it. One must be able to enter * the overheadMem Facility at any rank (RANK_LEAF or lower) and * still be able to acquire a lock in overheadMem *AND* be able * to Log(). */ #define RANK_overheadMem (RANK_LEAF + 1) /* * bora/lib/allocTrack rank (not really). * * This is another special case. It hooks malloc/free and the like, * and thus can basically sneak in underneath anyone. To that end * allocTrack uses unranked, native locks internally to avoid any * complications. */ /* * VMX/VMM/device lock rank space. * * This rank space is at the bottom, from 1 to RANK_VMX_LEAF. See * vmx/public/mutexRankVMX.h for definitions. */ /* * Foundry lock rank space. * * This rank space is from RANK_foundryLockBase on up to * RANK_foundryLockLeaf. See apps/lib/foundry/mutexRankFoundry.h for * definitions. */ #define RANK_foundryLockBase 0x80000000 /* * bora/lib lock rank space. * * This rank space is from RANK_libLockBase on up to RANK_LEAF. See * lib/public/mutexRankLib.h for definitions. */ #define RANK_libLockBase 0xF0000000 #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _MUTEXRANK_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/mutexRankLib.h000066400000000000000000000166411321503522500252550ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _LIBMUTEXRANK_H #define _LIBMUTEXRANK_H #include "mutexRank.h" #if defined(__cplusplus) extern "C" { #endif /* * MXUser mutex ranks for bora/lib code. * * The ranks define the ordering in which locks are allowed to be acquired. * * Only locks with higher rank numbers (generally more localized) * can be acquired while a lock with a lower rank number is active. * * bora/lib lock rank space is from RANK_libLockBase on up to * RANK_LEAF (see vm_basic_defs).asdf * * (Keep all of the below offsets in hex). */ /* * hostDeviceInfo HAL lock * * Must be < vmhs locks since this is held around the RANK_vmhsHDILock * callback lock which vmhs passes into that library. */ #define RANK_hdiHALLock (RANK_libLockBase + 0x1005) /* * vmhs locks (must be < vigor) */ #define RANK_vmhsHDILock (RANK_libLockBase + 0x3002) #define RANK_vmhsThrMxLock (RANK_libLockBase + 0x3005) #define RANK_vmhsVmxMxLock (RANK_libLockBase + 0x3005) /* * hgfs locks */ #define RANK_hgfsSessionArrayLock (RANK_libLockBase + 0x4010) #define RANK_hgfsSharedFolders (RANK_libLockBase + 0x4030) #define RANK_hgfsNotifyLock (RANK_libLockBase + 0x4040) #define RANK_hgfsFileIOLock (RANK_libLockBase + 0x4050) #define RANK_hgfsSearchArrayLock (RANK_libLockBase + 0x4060) #define RANK_hgfsNodeArrayLock (RANK_libLockBase + 0x4070) /* * vigor (must be < VMDB range and < disklib, see bug 741290) */ #define RANK_vigorOnlineLock (RANK_libLockBase + 0x4400) #define RANK_vigorOfflineLock (RANK_libLockBase + 0x4410) /* * filtlib (must be > vigor and < disklib and workercmlp, PR 1340298) */ #define RANK_filtLibPollLock (RANK_vigorOfflineLock + 1) /* * filtib lock which protects a disk's allocation bitmap state. * Must be > filtLibPollLock, as it could be acquire with the poll lock held. * And as evidenced by PR1437159, it must also be lower than workerLibCmplLock. */ #define RANK_filtLibAllocBitmapLock (RANK_filtLibPollLock + 1) /* * remoteUSB (must be < workerCmpl) */ #define RANK_remoteUSBGlobalLock (RANK_filtLibAllocBitmapLock + 1) /* * workerLib default completion lock * * Used for workerLib callers who don't provide their own lock. Held * around arbitrary completion callbacks so it makes sense to be of * a low rank. * * Must be > RANK_vigorOfflineLock because we may queue work in Vigor * offline. * * Must be < RANK_nfcLibLock, because NFC uses AIO Generic to perform * async writes to the virtual disk. * * Must be > RANK_filtLibPollLock so that filtlib timers can wait * for queued work. * * Must be > RANK_filtLibAllocBitmapLock due to PR1437159. * * Must be > RANK_remoteUSBGlobalLock so that virtual CCID can wait for * queued work. */ #define RANK_workerLibCmplLock (RANK_remoteUSBGlobalLock + 1) /* * NFC lib lock */ #define RANK_nfcLibInitLock (RANK_libLockBase + 0x4505) #define RANK_nfcLibLock (RANK_libLockBase + 0x4506) /* * Policy lib lock */ #define RANK_policyLibLock (RANK_libLockBase + 0x4605) /* * disklib and I/O related locks */ #define RANK_diskLibLock (RANK_libLockBase + 0x5001) #define RANK_digestLibLock (RANK_libLockBase + 0x5004) #define RANK_nasPluginLock (RANK_libLockBase + 0x5007) #define RANK_nasPluginMappingLock (RANK_libLockBase + 0x5008) #define RANK_diskLibPluginLock (RANK_libLockBase + 0x5010) #define RANK_vmioPluginRootLock (RANK_libLockBase + 0x5020) #define RANK_vmioPluginSysLock (RANK_libLockBase + 0x5040) #define RANK_fsCmdLock (RANK_libLockBase + 0x5050) #define RANK_scsiStateLock (RANK_libLockBase + 0x5060) #define RANK_parInitLock (RANK_libLockBase + 0x5070) #define RANK_namespaceLock (RANK_libLockBase + 0x5080) #define RANK_objLibInitLock (RANK_libLockBase + 0x5085) #define RANK_vvolLibLock (RANK_libLockBase + 0x5090) /* * Persistent-memory logical and hardware management locks */ /* The nvdimm layer is the hardware layer */ #define RANK_nvdHandleLock (RANK_libLockBase + 0x5300) /* The pmem layer is the logical layer */ #define RANK_pmemHandleLock (RANK_libLockBase + 0x5310) /* * VMDB range: * (RANK_libLockBase + 0x5500, RANK_libLockBase + 0x5600) */ #define RANK_vmuSecPolicyLock (RANK_libLockBase + 0x5505) #define RANK_vmdbCnxRpcLock (RANK_libLockBase + 0x5510) #define RANK_vmdbCnxRpcBarrierLock (RANK_libLockBase + 0x5520) #define RANK_vmdbCnxLock (RANK_libLockBase + 0x5530) #define RANK_vmdbSecureLock (RANK_libLockBase + 0x5540) #define RANK_vmdbDbLock (RANK_libLockBase + 0x5550) #define RANK_vmdbW32HookLock (RANK_libLockBase + 0x5560) #define RANK_vmdbWQPoolLock (RANK_libLockBase + 0x5570) #define RANK_vmdbMemMapLock (RANK_libLockBase + 0x5580) /* * USB range: * (RANK_libLockBase + 0x6500, RANK_libLockBase + 0x6600) */ #define RANK_usbArbLibGlobalLock (RANK_libLockBase + 0x6505) #define RANK_usbEnumGlobalLock (RANK_libLockBase + 0x6506) #define RANK_usbArbLibAsockLock (RANK_libLockBase + 0x6507) #define RANK_usbEnumBackendLock (RANK_libLockBase + 0x6508) #define RANK_sensorQueueLock (RANK_libLockBase + 0x6509) /* * misc locks * * Assuming ordering is important here for the listed locks. Other * non-leaf locks are usually defined with RANK_LEAF - 1. * * At least: * impersonate < pollDefault * keyLocator < preference (for checking AESNI) * keyLocator < sslState (bug 743010) * configDb < keyLocator (for unlocking dictionaries) * battery/button < preference * workerLib < something for sure under VThread_Create * licenseCheck < preference * sslState < getSafeTmpDir */ #define RANK_vigorTransportListLock (RANK_libLockBase + 0x7010) #define RANK_batteryLock (RANK_libLockBase + 0x7030) #define RANK_buttonLock (RANK_libLockBase + 0x7040) #define RANK_impersonateLock (RANK_libLockBase + 0x7045) #define RANK_pollDefaultLock (RANK_libLockBase + 0x7050) #define RANK_workerLibLock (RANK_libLockBase + 0x7060) #define RANK_configDbLock (RANK_libLockBase + 0x7070) #define RANK_keyLocatorLock (RANK_libLockBase + 0x7080) #define RANK_sslStateLock (RANK_libLockBase + 0x7085) #define RANK_getSafeTmpDirLock (RANK_libLockBase + 0x7086) #define RANK_licenseCheckLock (RANK_libLockBase + 0x7090) #define RANK_preferenceLock (RANK_libLockBase + 0x7100) #if defined(__cplusplus) } // extern "C" #endif #endif /* _LIBMUTEXRANK_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/netutil.h000066400000000000000000000073521321503522500243330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * netutil.h -- * * Utility network functions. * */ #ifndef __NETUTIL_H__ #define __NETUTIL_H__ #ifdef _WIN32 # include # include # include "vmware/iphlpapi_packed.h" # include # include #else # include #endif #include "vm_basic_types.h" #include "guestInfo.h" /* * Interface types as assigned by IANA. * See http://www.iana.org/assignments/ianaiftype-mib for more details. */ typedef enum { IANA_IFTYPE_OTHER = 1, IANA_IFTYPE_ETHERNETCSMACD = 6, } IanaIfType; /* * Modified from iptypes.h... */ char *NetUtil_GetPrimaryIP(void); GuestNic *NetUtil_GetPrimaryNic(void); #ifdef _WIN32 /* * Brute-force this. Trying to do it "properly" with * WINVER/NTDDI_VERSION checks/manips in a way that compiles for both * VC8 and VC9 didn't work. */ #ifndef FIXED_INFO typedef FIXED_INFO_W2KSP1 FIXED_INFO; typedef FIXED_INFO_W2KSP1 *PFIXED_INFO; #endif DWORD NetUtil_LoadIpHlpApiDll(void); DWORD NetUtil_FreeIpHlpApiDll(void); /* Wrappers for functions in iphlpapi.dll */ PFIXED_INFO NetUtil_GetNetworkParams(void); PIP_ADAPTER_INFO NetUtil_GetAdaptersInfo(void); ULONG NetUtil_GetAdaptersAddresses(ULONG Family, ULONG Flags, PVOID rsvd, PIP_ADAPTER_ADDRESSES adap_addresses, PULONG SizePointer); PMIB_IPFORWARDTABLE NetUtilWin32_GetIpForwardTable(void); PMIB_IPFORWARD_TABLE2 NetUtilWin32_GetIpForwardTable2(void); void NetUtilWin32_FreeMibTable(PMIB_IPFORWARD_TABLE2); #endif #ifdef WIN32 int NetUtil_InetPToN(int af, const char *src, void *dst); const char *NetUtil_InetNToP(int af, const void *src, char *dst, socklen_t size); #else // ifdef WIN32 # define NetUtil_InetPToN inet_pton # define NetUtil_InetNToP inet_ntop #endif #if defined(__linux__) # ifdef DUMMY_NETUTIL /* * Dummy interface table to enable other tools'/libraries' unit tests. */ typedef struct { int ifIndex; const char *ifName; } NetUtilIfTableEntry; /* * {-1, NULL}-terminated array of NetUtilIfTableEntry pointers. * * (Test) applications wishing to use the dummy NetUtil_GetIf{Index,Name} * functions must define this variable somewhere. It allows said apps * to work with a priori knowledge of interface name <=> index mappings * returned by said APIs. */ EXTERN NetUtilIfTableEntry netUtilIfTable[]; int NetUtil_GetIfIndex(const char *ifName); char *NetUtil_GetIfName(int ifIndex); # endif // ifdef DUMMY_NETUTIL #endif // if defined(__linux__) size_t NetUtil_GetHardwareAddress(int ifIndex, // IN char *hwAddr, // OUT size_t hwAddrSize, // IN IanaIfType *ifType); // OUT #endif // ifndef _NETUTIL_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/nicInfo.h000066400000000000000000000054071321503522500242330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2014-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * nicInfo.h -- * * Functions used to communicate guest networking information to the host. * */ #ifndef NICINFO_H #define NICINFO_H #include #include "guestInfo.h" typedef enum { NICINFO_PRIORITY_PRIMARY, NICINFO_PRIORITY_NORMAL, NICINFO_PRIORITY_LOW, NICINFO_PRIORITY_MAX } NicInfoPriority; Bool GuestInfo_GetFqdn(int outBufLen, char fqdn[]); Bool GuestInfo_GetNicInfo(NicInfoV3 **nicInfo); void GuestInfo_FreeNicInfo(NicInfoV3 *nicInfo); char *GuestInfo_GetPrimaryIP(void); /* * Comparison routines -- handy for caching, unit testing. */ Bool GuestInfo_IsEqual_DhcpConfigInfo(const DhcpConfigInfo *a, const DhcpConfigInfo *b); Bool GuestInfo_IsEqual_DnsConfigInfo(const DnsConfigInfo *a, const DnsConfigInfo *b); Bool GuestInfo_IsEqual_DnsHostname(const DnsHostname *a, const DnsHostname *b); Bool GuestInfo_IsEqual_InetCidrRouteEntry(const InetCidrRouteEntry *a, const InetCidrRouteEntry *b, const NicInfoV3 *aInfo, const NicInfoV3 *bInfo); Bool GuestInfo_IsEqual_IpAddressEntry(const IpAddressEntry *a, const IpAddressEntry *b); Bool GuestInfo_IsEqual_NicInfoV3(const NicInfoV3 *a, const NicInfoV3 *b); Bool GuestInfo_IsEqual_TypedIpAddress(const TypedIpAddress *a, const TypedIpAddress *b); Bool GuestInfo_IsEqual_WinsConfigInfo(const WinsConfigInfo *a, const WinsConfigInfo *b); void GuestInfo_SetIfaceExcludeList(char **list); void GuestInfo_SetIfacePrimaryList(char **list); void GuestInfo_SetIfaceLowPriorityList(char **list); Bool GuestInfo_IfaceIsExcluded(const char *name); NicInfoPriority GuestInfo_IfaceGetPriority(const char *name); #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/panic.h000066400000000000000000000065461321503522500237450ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * panic.h -- * * Module to encapsulate common Panic behavior. */ #ifndef _PANIC_H_ #define _PANIC_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif /* * Initialize module to read custom behavior from config files. */ void Panic_Init(void); /* * If you want the Panic module to just handle everything: implement Panic() * as a call to Panic_Panic(). If you want to implement your own Panic(), * you can still use functions below to query whether certain features are * desired and get the default implementation of each feature. */ NORETURN void Panic_Panic(const char *format, va_list args); /* * On panic, post a UI dialog about the panic and how to diagnose it: */ void Panic_SetPanicMsgPost(Bool postMsg); Bool Panic_GetPanicMsgPost(void); void Panic_PostPanicMsg(const char *format, ...); /* * On panic, break into a debugger or enter an infinite loop until a * debugger stops it: */ typedef enum { PanicBreakAction_Never, PanicBreakAction_IfDebuggerAttached, PanicBreakAction_Always } PanicBreakAction; void Panic_SetBreakAction(PanicBreakAction action); PanicBreakAction Panic_GetBreakAction(void); Bool Panic_GetBreakOnPanic(void); void Panic_BreakOnPanic(void); void Panic_LoopOnPanic(void); /* *----------------------------------------------------------------------------- * * Panic_SetBreakOnPanic -- * * Allow the debug breakpoint on panic to be suppressed. If passed FALSE, * then any subsequent Panics will not attempt to attract a debugger. * * Results: * void. * * Side effects: * Enables/Disables break into debugger on Panic(). * *----------------------------------------------------------------------------- */ static INLINE void Panic_SetBreakOnPanic(Bool breakOnPanic) // IN: { Panic_SetBreakAction(breakOnPanic ? PanicBreakAction_Always : PanicBreakAction_Never); } /* * On panic, dump core; Panic is also the place where various pieces of * back end stash information about the core dump. */ void Panic_SetCoreDumpOnPanic(Bool dumpCore); Bool Panic_GetCoreDumpOnPanic(void); void Panic_SetCoreDumpFileName(const char *fileName); int Panic_GetCoreDumpFlags(void); void Panic_SetCoreDumpFlags(int flags); /* * Extra debugging information that Panic module knows how to dump. */ void Panic_DumpGuiResources(void); #if defined(__cplusplus) } // extern "C" #endif #endif // _PANIC_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/poll.h000066400000000000000000000240361321503522500236130ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ #ifndef _POLL_H_ #define _POLL_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #include "vm_basic_defs.h" #include "vmware.h" #include "userlock.h" #if defined(__cplusplus) extern "C" { #endif #ifdef _WIN32 #define HZ 100 #elif defined linux #include #elif __APPLE__ #include /* * Old SDKs don't define TARGET_OS_IPHONE at all. * New ones define it to 0 on Mac OS X, 1 on iOS. */ #if !defined(TARGET_OS_IPHONE) || TARGET_OS_IPHONE == 0 #include #endif #include #define HZ 100 #endif #ifdef __ANDROID__ /* * of android should be included, but its name is same * with this file. So its content is put here to avoid conflict. */ #include #define HZ 100 typedef unsigned int nfds_t; int poll(struct pollfd *, nfds_t, long); #endif /* * Poll event types: each type has a different reason for firing, * or condition that must be met before firing. */ typedef enum { /* * Actual Poll queue types against which you can register callbacks. */ POLL_VIRTUALREALTIME = -1, /* Negative because it doesn't have its own Q */ POLL_VTIME = 0, POLL_REALTIME, POLL_DEVICE, POLL_MAIN_LOOP, POLL_NUM_QUEUES } PollEventType; /* * Classes of events * * These are the predefined classes. More can be declared * with Poll_AllocClass(). */ typedef enum PollClass { POLL_CLASS_MAIN, POLL_CLASS_PAUSE, POLL_CLASS_IPC, POLL_CLASS_CPT, POLL_CLASS_MKS, POLL_FIXED_CLASSES, /* Size enum to maximum */ POLL_MAX_CLASSES = 31, } PollClass; /* * Each callback is registered in a set of classes */ typedef struct PollClassSet { uintptr_t bits; } PollClassSet; /* An empty PollClassSet. */ static INLINE PollClassSet PollClassSet_Empty(void) { PollClassSet set = { 0 }; return set; } /* A PollClassSet with the single member. */ static INLINE PollClassSet PollClassSet_Singleton(PollClass c) { PollClassSet s = PollClassSet_Empty(); ASSERT_ON_COMPILE(POLL_MAX_CLASSES < sizeof s.bits * 8); ASSERT(c < POLL_MAX_CLASSES); s.bits = CONST3264U(1) << c; return s; } /* Combine two PollClassSets. */ static INLINE PollClassSet PollClassSet_Union(PollClassSet lhs, PollClassSet rhs) { PollClassSet set; set.bits = lhs.bits | rhs.bits; return set; } /* Add single class to PollClassSet. */ static INLINE PollClassSet PollClassSet_Include(PollClassSet set, PollClass c) { return PollClassSet_Union(set, PollClassSet_Singleton(c)); } #define POLL_CS_MAIN PollClassSet_Singleton(POLL_CLASS_MAIN) #define POLL_CS_PAUSE PollClassSet_Union(POLL_CS_MAIN, \ PollClassSet_Singleton(POLL_CLASS_PAUSE)) #define POLL_CS_CPT PollClassSet_Union(POLL_CS_PAUSE, \ PollClassSet_Singleton(POLL_CLASS_CPT)) #define POLL_CS_IPC PollClassSet_Union(POLL_CS_CPT, \ PollClassSet_Singleton(POLL_CLASS_IPC)) #define POLL_CS_VMDB POLL_CS_PAUSE /* POLL_CLASS_VMDB is retired */ #define POLL_CS_MKS PollClassSet_Singleton(POLL_CLASS_MKS) /* * DANGER. You don't need POLL_CS_ALWAYS. Really. So don't use it. */ #define POLL_CS_ALWAYS PollClassSet_Union(POLL_CS_CPT, POLL_CS_IPC) /* * Poll class-set taxonomy: * POLL_CS_MAIN * - Unless you NEED another class, use POLL_CS_MAIN. * POLL_CS_PAUSE * - For callbacks that must occur even if the guest is paused. * Most VMDB or Foundry commands are in this category. * POLL_CS_CPT * - Only for callbacks which can trigger intermediate Checkpoint * transitions. * The ONLY such callback is Migrate. * POLL_CS_IPC * - Only for callbacks which can contain Msg_(Post|Hint|Question) * responses, and for signal handlers (why)? * Vigor, VMDB, and Foundry can contain Msg_* responses. * POLL_CS_MKS * - Callback runs in MKS thread. * POLL_CS_ALWAYS * - Only for events that must be processed immediately. * The ONLY such callback is OvhdMemVmxSizeCheck. */ /* * Poll_Callback flags */ #define POLL_FLAG_PERIODIC 0x01 // keep after firing #define POLL_FLAG_REMOVE_AT_POWEROFF 0x02 // self-explanatory #define POLL_FLAG_READ 0x04 // device is ready for reading #define POLL_FLAG_WRITE 0x08 // device is ready for writing #define POLL_FLAG_SOCKET 0x10 // device is a Windows socket #define POLL_FLAG_NO_BULL 0x20 // callback does its own locking #define POLL_FLAG_WINSOCK 0x40 // Winsock style write events #define POLL_FLAG_FD 0x80 // device is a Windows file descriptor. #define POLL_FLAG_ACCEPT_INVALID_FDS 0x100 // For broken 3rd party libs, e.g. curl #define POLL_FLAG_THUNK_TO_WND 0x200 // thunk callback to window message loop typedef void (*PollerFunction)(void *clientData); typedef void (*PollerFireWrapper)(PollerFunction func, void *funcData, void *wrapperData); typedef Bool (*PollerErrorFn)(const char *errorStr); /* * Initialisers: * * For the sake of convenience, we declare the initialisers * for custom implmentations here, even though the actual * implementations are distinct from the core poll code. */ typedef struct PollOptions { Bool locked; // Use internal MXUser for locking Bool allowFullQueue; // Don't assert when device event queue is full. VThreadID windowsMsgThread; // thread that processes Windows messages PollerFireWrapper fireWrapperFn; // optional; may be useful for stats void *fireWrapperData; // optional PollerErrorFn errorFn; // optional; called upon unrecoverable error } PollOptions; void Poll_InitDefault(void); void Poll_InitDefaultEx(const PollOptions *opts); void Poll_InitGtk(void); // On top of glib for Linux void Poll_InitCF(void); // On top of CoreFoundation for OSX /* * Functions */ int Poll_SocketPair(Bool vmci, Bool stream, int fds[2]); void Poll_Loop(Bool loop, Bool *exit, PollClass c); void Poll_LoopTimeout(Bool loop, Bool *exit, PollClass c, int timeout); Bool Poll_LockingEnabled(void); void Poll_Exit(void); /* * Poll_Callback adds a callback regardless of whether an identical one exists. * The exception to this rule is POLL_DEVICE callbacks: there is a maximum of * one read and one write callback per fd. * * Poll_CallbackRemove removes one callback. If there are multiple identical * callbacks, which one is removed is an implementation detail. Note that in * the case of POLL_DEVICE and POLL_REALTIME callbacks, the fd/delay used to * create the callback is not specified when removing, so all callbacks * of those types with the same flags, function, and clientData are considered * "identical" even if their fd/delay differed. */ VMwareStatus Poll_Callback(PollClassSet classSet, int flags, PollerFunction f, void *clientData, PollEventType type, PollDevHandle info, // fd/microsec delay MXUserRecLock *lck); Bool Poll_CallbackRemove(PollClassSet classSet, int flags, PollerFunction f, void *clientData, PollEventType type); Bool Poll_CallbackRemoveOneByCB(PollClassSet classSet, int flags, PollerFunction f, PollEventType type, void **clientData); void Poll_NotifyChange(PollClassSet classSet); /* * Wrappers for Poll_Callback and Poll_CallbackRemove that present * simpler subsets of those interfaces. */ VMwareStatus Poll_CB_Device(PollerFunction f, void *clientData, PollDevHandle device, Bool periodic); Bool Poll_CB_DeviceRemove(PollerFunction f, void *clientData, Bool periodic); VMwareStatus Poll_CB_RTime(PollerFunction f, void *clientData, int64 delay, // microseconds Bool periodic, MXUserRecLock *lock); Bool Poll_CB_RTimeRemove(PollerFunction f, void *clientData, Bool periodic); #ifdef _WIN32 void Poll_SetPumpsWindowsMessages(Bool pumps); void Poll_SetWindowMessageRecipient(HWND hWnd, UINT msg, Bool alwaysThunk); Bool Poll_FireWndCallback(void *lparam); #endif #if defined(__cplusplus) } // extern "C" #endif #endif // _POLL_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/pollImpl.h000066400000000000000000000107341321503522500244350ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * pollImpl.h -- * * Header file for poll implementations. Poll consumers should not * include is file. */ #ifndef _POLLIMPL_H_ #define _POLLIMPL_H_ #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #include "poll.h" #include "vm_basic_asm.h" #if defined(__cplusplus) extern "C" { #endif /* * PollImpl: * * A Poll implementation should provide a filled in PollImpl * to pass to Poll_Init. */ typedef struct PollImpl { void (*Init) (void); void (*Exit) (void); void (*LoopTimeout) (Bool loop, Bool *exit, PollClass c, int timeout); VMwareStatus (*Callback) (PollClassSet classSet, int flags, PollerFunction f, void *clientData, PollEventType type, PollDevHandle info, MXUserRecLock *lock); Bool (*CallbackRemove) (PollClassSet classSet, int flags, PollerFunction f, void *clientData, PollEventType type); Bool (*CallbackRemoveOneByCB)(PollClassSet classSet, int flags, PollerFunction f, PollEventType type, void **clientData); Bool (*LockingEnabled) (void); void (*NotifyChange) (PollClassSet classSet); } PollImpl; void Poll_InitWithImpl(const PollImpl *impl); /* Check if a PollClass is part of the set. */ static INLINE Bool PollClassSet_IsMember(PollClassSet set, PollClass c) { return (set.bits & PollClassSet_Singleton(c).bits) != 0; } /* Compare two PollClassSets. */ static INLINE Bool PollClassSet_Equals(PollClassSet lhs, PollClassSet rhs) { return lhs.bits == rhs.bits; } /* Verifies if the class set is empty. */ static INLINE Bool PollClassSet_IsEmpty(PollClassSet cs) { return PollClassSet_Equals(cs, PollClassSet_Empty()); } /* Remove from a PollClassSet. */ static INLINE void PollClassSet_Remove(PollClassSet *set, PollClass c) { set->bits &= ~PollClassSet_Singleton(c).bits; } /* Find first set. POLL_MAX_CLASSES for none set. */ static INLINE PollClass PollClassSet_FFS(PollClassSet *set) { if (set->bits != 0) { return (PollClass)lssbPtr_0(set->bits); } return POLL_MAX_CLASSES; } /* *---------------------------------------------------------------------------- * * PollLockingAlwaysEnabled -- * PollLockingNotAvailable -- * * Simple LockingEnabled() functions for poll implementation that does * not dynamically enable locking. * * Results: * Bool. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static INLINE Bool PollLockingAlwaysEnabled(void) { return TRUE; } static INLINE Bool PollLockingNotAvailable(void) { return FALSE; } #if defined(__cplusplus) } // extern "C" #endif #endif /* _POLLIMPL_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/posix.h000066400000000000000000000510201321503522500240000ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef VMWARE_POSIX_H #define VMWARE_POSIX_H #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #include #if !defined(_WIN32) #include #include #include #endif #include "vm_basic_types.h" #include "unicodeTypes.h" #include "unicodeBase.h" #include "codeset.h" #if defined(__cplusplus) extern "C" { #endif /* * Require the _FILE_OFFSET_BITS=64 interface, where all Posix file * structures and functions are transparently 64-bit. * * Some OSes (FreeBSD, OS X) natively use 64-bit file offsets and * will never be a problem. Other OSes (Linux, Solaris) default * to 32-bit offsets in 32-bit mode. Android ... does its own thing. * Windows only offers the Posix APIs as 32-bit. * * There are two ways of getting 64-bit offsets, defined by the LFS standard: * _LARGEFILE64_SOURCE, which defines xxx64 types and functions * _FILE_OFFSET_BITS=64, which replaces all types and functions * The _LARGEFILE64_SOURCE strategy was transitional (late 90s) and is now * deprecated. All modern code should use _FILE_OFFSET_BITS=64. * * Instead of checking for the exact details, check for what matters * for the purposes of this file: types (e.g. off_t) must be 64-bit. */ #if !defined(_WIN32) && !defined(__ANDROID__) MY_ASSERTS(_file_offset_bits64, ASSERT_ON_COMPILE(sizeof(off_t) == 8);) #endif struct stat; #if defined(_WIN32) typedef int mode_t; #else struct statfs; struct utimbuf; struct timeval; struct passwd; #if !defined(sun) struct mntent; #else struct mnttab; #endif #endif int Posix_Creat(const char *pathName, mode_t mode); int Posix_Open(const char *pathName, int flags, ...); FILE *Posix_Fopen(const char *pathName, const char *mode); FILE *Posix_Popen(const char *pathName, const char *mode); int Posix_Rename(const char *fromPathName, const char *toPathName); int Posix_Rmdir(const char *pathName); int Posix_Unlink(const char *pathName); FILE *Posix_Freopen(const char *pathName, const char *mode, FILE *stream); int Posix_Access(const char *pathName, int mode); int Posix_EuidAccess(const char *pathName, int mode); int Posix_Stat(const char *pathName, struct stat *statbuf); int Posix_Chmod(const char *pathName, mode_t mode); void Posix_Perror(const char *str); int Posix_Printf(const char *format, ...); int Posix_Fprintf(FILE *stream, const char *format, ...); int Posix_Mkdir(const char *pathName, mode_t mode); int Posix_Chdir(const char *pathName); char *Posix_Getenv(const char *name); long Posix_Pathconf(const char *pathName, int name); int Posix_Lstat(const char *pathName, struct stat *statbuf); char *Posix_MkTemp(const char *pathName); /* *----------------------------------------------------------------------------- * * Posix_Free -- * * Wrapper around free() that preserves errno. * * C11 (and earlier) does not prohibit free() implementations from * modifying errno. That is undesirable since it can clobber errno along * cleanup paths, and it is expected to be prohibited by a future (as of * January 2017) version of the POSIX standard. See: * * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE void Posix_Free(void *p) // IN { int err = errno; free(p); errno = err; } #if !defined(_WIN32) /* * These Windows APIs actually work with non-ASCII (MBCS) strings. * Make them NULL wrappers for all other platforms. */ #define Posix_GetHostName gethostname #if defined(__APPLE__) #define Posix_GetHostByName gethostbyname #endif #define Posix_GetAddrInfo getaddrinfo #define Posix_FreeAddrInfo freeaddrinfo #define Posix_GetNameInfo getnameinfo void *Posix_Dlopen(const char *pathName, int flags); int Posix_Utime(const char *pathName, const struct utimbuf *times); int Posix_Mknod(const char *pathName, mode_t mode, dev_t dev); int Posix_Chown(const char *pathName, uid_t owner, gid_t group); int Posix_Lchown(const char *pathName, uid_t owner, gid_t group); int Posix_Link(const char *oldPath, const char *newPath); int Posix_Symlink(const char *oldPath, const char *newPath); int Posix_Mkfifo(const char *pathName, mode_t mode); int Posix_Truncate(const char *pathName, off_t length); int Posix_Utimes(const char *pathName, const struct timeval *time); int Posix_Execl(const char *pathName, const char *arg0, ...); int Posix_Execlp(const char *fileName, const char *arg0, ...); int Posix_Execv(const char *pathName, char *const argVal[]); int Posix_Execve(const char *pathName, char *const argVal[], char *const envPtr[]); int Posix_Execvp(const char *fileName, char *const argVal[]); DIR *Posix_OpenDir(const char *pathName); int Posix_System(const char *command); int Posix_Putenv(char *name); int Posix_Unsetenv(const char *name); /* * These functions return dynamically allocated stings that have to be * freed by the caller so they must be used in the ESX environment. They * are different than their POSIX "base" functions. */ char *Posix_RealPath(const char *pathName); char *Posix_ReadLink(const char *pathName); struct passwd *Posix_Getpwnam(const char *name); struct passwd *Posix_Getpwuid(uid_t uid); int Posix_Setenv(const char *name, const char *value, int overWrite); int Posix_Getpwnam_r(const char *name, struct passwd *pw, char *buf, size_t size, struct passwd **ppw); int Posix_Getpwuid_r(uid_t uid, struct passwd *pw, char *buf, size_t size, struct passwd **ppw); struct passwd *Posix_Getpwent(void); struct group *Posix_Getgrnam(const char *name); int Posix_Getgrnam_r(const char *name, struct group *gr, char *buf, size_t size, struct group **pgr); #if !defined(sun) int Posix_Statfs(const char *pathName, struct statfs *statfsbuf); int Posix_GetGroupList(const char *user, gid_t group, gid_t *groups, int *ngroups); #if !defined(__APPLE__) && !defined(__FreeBSD__) int Posix_Mount(const char *source, const char *target, const char *filesystemtype, unsigned long mountflags, const void *data); int Posix_Umount(const char *target); FILE *Posix_Setmntent(const char *pathName, const char *mode); struct mntent *Posix_Getmntent(FILE *fp); struct mntent *Posix_Getmntent_r(FILE *fp, struct mntent *m, char *buf, int size); #endif // !defined(__APPLE__) && !defined(__FreeBSD__) #else // !defined(sun) int Posix_Getmntent(FILE *fp, struct mnttab *mp); #endif // !defined(sun) #if !defined(__APPLE__) /* *---------------------------------------------------------------------- * * Posix_GetHostByName -- * * Wrapper for gethostbyname(). Caller should release memory * allocated for the hostent structure returned by calling * Posix_FreeHostent(). * * Results: * NULL Error * !NULL Pointer to hostent structure * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE struct hostent* Posix_GetHostByName(const char *name) // IN { struct hostent *newhostent; int error; struct hostent he; char buffer[1024]; struct hostent *phe = &he; char **p; int i; int naddrs; ASSERT(name); if ((gethostbyname_r(name, &he, buffer, sizeof buffer, #if !defined(sun) && !defined(SOLARIS) && !defined(SOL10) &phe, #endif &error) == 0) && phe) { newhostent = (struct hostent *)Util_SafeMalloc(sizeof *newhostent); newhostent->h_name = Unicode_Alloc(phe->h_name, STRING_ENCODING_DEFAULT); if (phe->h_aliases) { newhostent->h_aliases = Unicode_AllocList(phe->h_aliases, -1, STRING_ENCODING_DEFAULT); } else { newhostent->h_aliases = NULL; } newhostent->h_addrtype = phe->h_addrtype; newhostent->h_length = phe->h_length; naddrs = 1; for (p = phe->h_addr_list; *p; p++) { naddrs++; } newhostent->h_addr_list = (char **)Util_SafeMalloc(naddrs * sizeof(*(phe->h_addr_list))); for (i = 0; i < naddrs - 1; i++) { newhostent->h_addr_list[i] = (char *)Util_SafeMalloc(phe->h_length); memcpy(newhostent->h_addr_list[i], phe->h_addr_list[i], phe->h_length); } newhostent->h_addr_list[naddrs - 1] = NULL; return newhostent; } /* There has been an error */ return NULL; } #endif // !define(__APPLE__) /* *---------------------------------------------------------------------- * * Posix_FreeHostent -- * * Free the memory allocated for an hostent structure returned * by Posix_GetHostByName. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE void Posix_FreeHostent(struct hostent *he) { #if !defined(__APPLE__) char **p; if (he) { // See Posix_Free. int err = errno; free(he->h_name); if (he->h_aliases) { Util_FreeStringList(he->h_aliases, -1); } p = he->h_addr_list; while (*p) { free(*p++); } free(he->h_addr_list); free(he); errno = err; } #else (void) he; #endif } #else // !define(_WIN32) #if defined(_WINSOCKAPI_) || defined(_WINSOCK2API_) #include #include "vm_atomic.h" #if defined(VM_WIN_UWP) /* UWP use the network definition in winsock2.h */ #include #endif /* *---------------------------------------------------------------------- * * Posix_GetHostName -- * * Wrapper for gethostname(). * * Results: * 0 Success * -1 Error * * Side effects: * On error, error code returned by WSAGetLastError() is updated. * *---------------------------------------------------------------------- */ static INLINE int Posix_GetHostName(char *name, // OUT int namelen) // IN { char *nameMBCS = (char *)Util_SafeMalloc(namelen); char *nameUTF8; int retval; ASSERT(name); retval = gethostname(nameMBCS, namelen); if (retval == 0) { nameUTF8 = Unicode_Alloc(nameMBCS, STRING_ENCODING_DEFAULT); if (!Unicode_CopyBytes(name, nameUTF8, namelen, NULL, STRING_ENCODING_UTF8)) { retval = -1; WSASetLastError(WSAEFAULT); } Posix_Free(nameUTF8); } Posix_Free(nameMBCS); return retval; } /* *---------------------------------------------------------------------- * * Posix_GetHostByName -- * * Wrapper for gethostbyname(). Caller should release memory * allocated for the hostent structure returned by calling * Posix_FreeHostent(). * * Results: * NULL Error * !NULL Pointer to hostent structure * * Side effects: * On error, error code returned by WSAGetLastError() is updated. * *---------------------------------------------------------------------- */ static INLINE struct hostent* Posix_GetHostByName(const char *name) // IN { struct hostent *newhostent; char *nameMBCS; struct hostent *hostentMBCS; struct hostent *ret = NULL; ASSERT(name); nameMBCS = (char *)Unicode_GetAllocBytes(name, STRING_ENCODING_DEFAULT); if (nameMBCS != NULL) { hostentMBCS = gethostbyname(nameMBCS); Posix_Free(nameMBCS); if (hostentMBCS != NULL) { newhostent = (struct hostent *)Util_SafeMalloc(sizeof *newhostent); newhostent->h_name = Unicode_Alloc(hostentMBCS->h_name, STRING_ENCODING_DEFAULT); if (hostentMBCS->h_aliases) { newhostent->h_aliases = Unicode_AllocList(hostentMBCS->h_aliases, -1, STRING_ENCODING_DEFAULT); } else { newhostent->h_aliases = NULL; } newhostent->h_addrtype = hostentMBCS->h_addrtype; newhostent->h_length = hostentMBCS->h_length; newhostent->h_addr_list = hostentMBCS->h_addr_list; ret = newhostent; } } else { /* There has been an error converting from UTF-8 to local encoding. */ WSASetLastError(WSANO_RECOVERY); } return ret; } /* *---------------------------------------------------------------------- * * Posix_FreeHostent -- * * Free the memory allocated for an hostent structure returned * by Posix_GetHostByName. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INLINE void Posix_FreeHostent(struct hostent *he) { if (he) { Posix_Free(he->h_name); if (he->h_aliases) { Util_FreeStringList(he->h_aliases, -1); } Posix_Free(he); } } #endif // defined(_WINSOCKAPI_) || defined(_WINSOCK2API_) #ifdef _WS2TCPIP_H_ /* *---------------------------------------------------------------------- * * Posix_GetAddrInfo -- * * Wrapper for getaddrinfo(). * * Inlined to match Ws2tcpip.h inclusion. * * Results: * 0 Success * != 0 Error * * Side effects: * On error, error code returned by WSAGetLastError() is updated. * *---------------------------------------------------------------------- */ static INLINE int Posix_GetAddrInfo(const char *nodename, // IN const char *servname, // IN const struct addrinfo *hints, // IN struct addrinfo **res) // OUT { int retval; struct addrinfoW *resW; utf16_t *nodenameW = Unicode_GetAllocUTF16(nodename); utf16_t *servnameW = Unicode_GetAllocUTF16(servname); ASSERT(nodename || servname); ASSERT(res); /* * The string conversion required is between UTF-8 and UTF-16 encodings. * Note that struct addrinfo and ADDRINFOW are identical except for the * fields ai_canonname (char * vs. PWSTR) and ai_next (obviously), * and those fields must be NULL, so hints can be cast to UTF-16. */ retval = GetAddrInfoW(nodenameW, servnameW, (struct addrinfoW *)hints, &resW); if (retval == 0) { struct addrinfoW *cur; struct addrinfo **pres = res; for (cur = resW; cur != NULL; cur = cur->ai_next) { *pres = (struct addrinfo *)Util_SafeMalloc(sizeof **pres); (*pres)->ai_flags = cur->ai_flags; (*pres)->ai_family = cur->ai_family; (*pres)->ai_socktype = cur->ai_socktype; (*pres)->ai_protocol = cur->ai_protocol; (*pres)->ai_addrlen = cur->ai_addrlen; if (cur->ai_canonname) { (*pres)->ai_canonname = Unicode_AllocWithUTF16(cur->ai_canonname); } else { (*pres)->ai_canonname = NULL; } (*pres)->ai_addr = (struct sockaddr *) Util_SafeMalloc((*pres)->ai_addrlen); memcpy((*pres)->ai_addr, cur->ai_addr, (*pres)->ai_addrlen); pres = &((*pres)->ai_next); } *pres = NULL; FreeAddrInfoW(resW); } Posix_Free(nodenameW); Posix_Free(servnameW); return retval; } /* *---------------------------------------------------------------------------- * * Posix_FreeAddrInfo -- * * Free the addrinfo structure allocated by Posix_GetAddrInfo. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------------- */ static INLINE void Posix_FreeAddrInfo(struct addrinfo *ai) { struct addrinfo *temp; // See Posix_Free. int err = errno; while (ai) { temp = ai; ai = ai->ai_next; free(temp->ai_canonname); free(temp->ai_addr); free(temp); } errno = err; } /* *---------------------------------------------------------------------- * * Posix_GetNameInfo -- * * Wrapper for getnameinfo(). * * Inlined to match Ws2tcpip.h inclusion. * * Results: * 0 Success * != 0 Error * * Side effects: * On error, error code returned by WSAGetLastError() is updated. * *---------------------------------------------------------------------- */ static INLINE int Posix_GetNameInfo(const struct sockaddr *sa, // IN socklen_t salen, // IN char *host, // OUT DWORD hostlen, // IN char *serv, // OUT DWORD servlen, // IN int flags) // IN { int retval; utf16_t *hostW = NULL; utf16_t *servW = NULL; char *hostUTF8 = NULL; char *servUTF8 = NULL; if (host) { hostW = (utf16_t *)Util_SafeMalloc(hostlen * sizeof *hostW); } if (serv) { servW = (utf16_t *)Util_SafeMalloc(servlen * sizeof *servW); } retval = GetNameInfoW(sa, salen, hostW, hostlen, servW, servlen, flags); if (retval == 0) { if (host) { hostUTF8 = Unicode_AllocWithUTF16(hostW); if (!Unicode_CopyBytes(host, hostUTF8, hostlen, NULL, STRING_ENCODING_UTF8)) { retval = EAI_MEMORY; WSASetLastError(WSA_NOT_ENOUGH_MEMORY); goto exit; } } if (serv) { servUTF8 = Unicode_AllocWithUTF16(servW); if (!Unicode_CopyBytes(serv, servUTF8, servlen, NULL, STRING_ENCODING_UTF8)) { retval = EAI_MEMORY; WSASetLastError(WSA_NOT_ENOUGH_MEMORY); goto exit; } } } exit: Posix_Free(hostW); Posix_Free(servW); Posix_Free(hostUTF8); Posix_Free(servUTF8); return retval; } #endif // ifdef _WS2TCPIP_H_ #endif // !define(_WIN32) #if (defined(VMX86_SERVER) || defined(__APPLE__)) && \ !defined(UNICODE_BUILDING_POSIX_WRAPPERS) /* * ESX and Mac OS are UTF-8 environments so these functions can be * "defined away" - the POSIX wrapper call can be directly mapped to the * POSIX function avoiding unneccesary (call and handling) overhead. * * NOTE: PLEASE KEEP THESE IN SORTED ORDER */ #define Posix_Access access #define Posix_Chdir chdir #define Posix_Chmod chmod #define Posix_Chown chown #define Posix_Creat creat #define Posix_Dlopen dlopen #define Posix_Execl execl #define Posix_Execlp execlp #define Posix_Execv execv #define Posix_Execve execve #define Posix_Execvp execvp #define Posix_Fopen fopen #define Posix_Fprintf fprintf #define Posix_Freopen freopen #define Posix_Getenv getenv #define Posix_GetGroupList getgrouplist #define Posix_Getmntent getmntent #define Posix_Getmntent_r getmntent_r #define Posix_Getpwnam getpwnam #define Posix_Getpwnam_r getpwnam_r #define Posix_Getpwuid getpwuid #define Posix_Getpwuid_r getpwuid_r #define Posix_Getgrnam getgrnam #define Posix_Getgrnam_r getgrnam_r #define Posix_Lchown lchown #define Posix_Link link #define Posix_Lstat lstat #define Posix_Mkdir mkdir #define Posix_Mkfifo mkfifo #define Posix_Mknod mknod #define Posix_Mount mount #define Posix_Open open #define Posix_OpenDir opendir #define Posix_Pathconf pathconf #define Posix_Perror perror #define Posix_Popen popen #define Posix_Printf printf #define Posix_Putenv putenv #define Posix_Rename rename #define Posix_Rmdir rmdir #define Posix_Setenv setenv #define Posix_Setmntent setmntent #define Posix_Stat stat #define Posix_Statfs statfs #define Posix_Symlink symlink #define Posix_System system #define Posix_Truncate truncate #define Posix_Umount umount #define Posix_Unlink unlink #define Posix_Unsetenv unsetenv #define Posix_Utime utime #define Posix_Utimes utimes #endif #if defined(__cplusplus) } // extern "C" #endif #endif // VMWARE_POSIX_H open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/preference.h000066400000000000000000000034741321503522500247660ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _PREFERENCE_H_ #define _PREFERENCE_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif void Preference_DisableUserPreferences(void); Bool Preference_Init(void); void Preference_Exit(void); Bool Preference_GetBool(Bool defaultValue, const char *fmt); int32 Preference_GetTriState(int32 defaultValue, const char *fmt); int32 Preference_GetLong(int32 defaultValue, const char *fmt); int64 Preference_GetInt64(int64 defaultvalue, const char *fmt); double Preference_GetDouble(double defaultValue, const char *fmt); char *Preference_GetString(const char *defaultValue, const char *fmt); void Preference_Log(void); char *Preference_GetPathName(const char *defaultValue, const char *fmt); void Preference_SetFromString(const char *string, Bool overwrite); Bool Preference_NotSet(const char *fmt); #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/procMgr.h000066400000000000000000000123011321503522500242460ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2002-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * procMgr.h -- * * Process management library. * */ #ifndef __PROCMGR_H__ # define __PROCMGR_H__ #include "vm_basic_types.h" #include "auth.h" #include "dynarray.h" #if !defined(_WIN32) # include #endif #include /* * Keeps track of the platform-specific handle(s) to an asynchronous process. */ typedef struct ProcMgr_AsyncProc ProcMgr_AsyncProc; #if defined(_WIN32) typedef DWORD ProcMgr_Pid; #else /* POSIX */ typedef pid_t ProcMgr_Pid; #endif /* * Process information structure. * This holds basic information we return per process * when listing process information inside the guest. */ typedef struct ProcMgrProcInfo { ProcMgr_Pid procId; char *procCmdName; // UTF-8 char *procCmdLine; // UTF-8 char *procOwner; // UTF-8 #if defined(_WIN32) Bool procDebugged; #endif time_t procStartTime; } ProcMgrProcInfo; DEFINE_DYNARRAY_TYPE(ProcMgrProcInfo); typedef struct ProcMgr_ProcArgs { #if defined(_WIN32) /* * If a caller needs to use a non-default set of arguments for * CreateProcess[AsUser] in ProcMgr_Exec[A]sync, this structure should be used. * * - If 'userArgs' is NULL, defaults are used: * - bInheritHandles defaults to TRUE * - lpStartupInfo is instantiated and initialized with: * - cb initialized to size of the object * - dwFlags initialized to STARTF_USESHOWWINDOW * - wShowWindow initialized to SW_MINIMIZE. * - defaults for all other parameters are NULL/FALSE * * - If 'userArgs' is not NULL, the values in the 'userArgs' object are used * according to the following rules: * - If lpStartupInfo is NULL, it is instantiated and initialized with: * - cb initialized to size of the object * - dwFlags initialized to STARTF_USESHOWWINDOW * - wShowWindow initialized to SW_MINIMIZE. * - The caller would need to do some of this initialization if they set * lpStartupInfo. * - If hToken is set: * - if lpStartupInfo->lpDesktop is not NULL, then it is used directly. Otherwise, * lpStartupInfo->lpDesktop is initialized appropriately. * * XXX: Make it more convenient for callers(like ToolsDaemonTcloRunProgramImpl) * to set just wShowWindow without needing to instantiate and initialize a * STARTUPINFO object. */ HANDLE hToken; LPCWSTR lpApplicationName; LPSECURITY_ATTRIBUTES lpProcessAttributes; LPSECURITY_ATTRIBUTES lpThreadAttributes; BOOL bInheritHandles; DWORD dwCreationFlags; LPVOID lpEnvironment; LPCWSTR lpCurrentDirectory; LPSTARTUPINFO lpStartupInfo; #else /* * The environment variables to run the program with. If NULL, use the current * environment. */ char **envp; /* * If non-NULL, the directory to be changed to before the process is * started. */ char *workingDirectory; #endif } ProcMgr_ProcArgs; typedef void ProcMgr_Callback(Bool status, void *clientData); #if defined(_WIN32) typedef HANDLE Selectable; #else typedef int Selectable; #endif ProcMgrProcInfoArray *ProcMgr_ListProcesses(void); void ProcMgr_FreeProcList(ProcMgrProcInfoArray *procList); Bool ProcMgr_KillByPid(ProcMgr_Pid procId); Bool ProcMgr_ExecSync(char const *cmd, // UTF-8 ProcMgr_ProcArgs *userArgs); ProcMgr_AsyncProc *ProcMgr_ExecAsync(char const *cmd, // UTF-8 ProcMgr_ProcArgs *userArgs); #if defined(__linux__) Bool ProcMgr_ExecSyncWithExitCode(char const *cmd, ProcMgr_ProcArgs *userArgs, Bool *validExitCode, int *exitCode); #endif void ProcMgr_Kill(ProcMgr_AsyncProc *asyncProc); Selectable ProcMgr_GetAsyncProcSelectable(ProcMgr_AsyncProc *asyncProc); ProcMgr_Pid ProcMgr_GetPid(ProcMgr_AsyncProc *asyncProc); Bool ProcMgr_IsAsyncProcRunning(ProcMgr_AsyncProc *asyncProc); int ProcMgr_GetExitCode(ProcMgr_AsyncProc *asyncProc, int *result); void ProcMgr_Free(ProcMgr_AsyncProc *asyncProc); #if !defined(_WIN32) Bool ProcMgr_ImpersonateUserStart(const char *user, // UTF-8 AuthToken token); Bool ProcMgr_ImpersonateUserStop(void); #endif Bool ProcMgr_GetImpersonatedUserInfo(char **username, char **homeDir); #endif /* __PROCMGR_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/product.h000066400000000000000000000033641321503522500243260ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * product.h -- * * This file contains the Product enum. * * Products that don't want to include productState and vm_basic_types.h * and want to know about the magic values for various products should * include this file. */ #ifndef _PRODUCT_H_ #define _PRODUCT_H_ #if defined(__cplusplus) extern "C" { #endif /* * Public types. */ typedef enum { PRODUCT_GENERIC = 0, PRODUCT_WORKSTATION = 1 << 0, PRODUCT_ESX = 1 << 1, PRODUCT_PLAYER = 1 << 2, PRODUCT_TOOLS = 1 << 3, PRODUCT_VDM_CLIENT = 1 << 4, PRODUCT_CVP = 1 << 5, PRODUCT_FUSION = 1 << 6, PRODUCT_VIEW = 1 << 7, PRODUCT_VMRC = 1 << 8, PRODUCT_GANTRY = 1 << 9, PRODUCT_VMACORETESTS = 1 << 10, PRODUCT_SRM = 1 << 11, /* etc */ } Product; #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/productState.h000066400000000000000000000077331321503522500253330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * productState.h -- * * ProductState is a runtime encapsulation of the identity of a product * and product dependent characteristics. */ #ifndef _PRODUCT_STATE_H_ #define _PRODUCT_STATE_H_ #include "vm_basic_types.h" #include "product.h" #if defined(__cplusplus) extern "C" { #endif typedef uint64 ProductMask; #define PRODUCTMASK_HOSTED (PRODUCT_WORKSTATION |\ PRODUCT_PLAYER |\ PRODUCT_CVP |\ PRODUCT_FUSION |\ PRODUCT_VMRC |\ PRODUCT_GANTRY) typedef uint64 ProductCaps; /* * Define as needed. * * #define PRODUCT_CAP_FOO (1 << 0) */ typedef enum { PRODUCTSTATE_FLAG_NONE = 0, PRODUCTSTATE_FLAG_PRODUCT = 1 << 0, PRODUCTSTATE_FLAG_NAME = 1 << 1, PRODUCTSTATE_FLAG_VERSION = 1 << 2, PRODUCTSTATE_FLAG_BUILDNUMBER = 1 << 3, PRODUCTSTATE_FLAG_CAPABILITIES = 1 << 4, PRODUCTSTATE_FLAG_LICENSENAME = 1 << 5, PRODUCTSTATE_FLAG_LICENSEVERSION = 1 << 6, PRODUCTSTATE_FLAG_BUNDLEIDENTIFIER = 1 << 7, } ProductStateSerializationFlags; /* * Public functions. * * PR 567850 * ProductState_Set should only be called once. Subsequent calls will be * ignored. */ void ProductState_Set(Product product, const char *name, const char *version, unsigned int buildNumber, ProductCaps capabilities, const char *licenseName, const char *licenseVersion, const char *bundleIdentifier); unsigned int ProductState_GetBuildNumber(void); const char *ProductState_GetBuildNumberString(void); const char *ProductState_GetBundleIdentifier(void); ProductCaps ProductState_GetCapabilities(void); const char *ProductState_GetCompilationOption(void); const char *ProductState_GetConfigName(void); const char *ProductState_GetFullVersion(void); void ProductState_GetHelp(Product *helpProduct, const char **helpVersion); const char *ProductState_GetLicenseName(void); const char *ProductState_GetLicenseVersion(void); const char *ProductState_GetName(void); Product ProductState_GetProduct(void); const char *ProductState_GetRegistryPath(void); char *ProductState_GetRegistryPathForProduct(const char *productName); const char *ProductState_GetVersion(void); void ProductState_GetVersionNumber(unsigned int *major, unsigned int *minor, unsigned int *patchLevel); Bool ProductState_IsProduct(ProductMask product); Bool ProductState_AllowUnlicensedVMX(void); void ProductState_SetConfigName(const char *configName); /* etc */ void ProductState_SetHelp(Product helpProduct, const char *helpVersion); char *ProductState_Serialize(ProductStateSerializationFlags flags); ProductStateSerializationFlags ProductState_Deserialize(const char *state); #if defined(__cplusplus) } // extern "C" #endif #endif /* _PRODUCT_STATE_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/random.h000066400000000000000000000061001321503522500241150ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * random.h -- * * Random bits generation. Please use CryptoRandom_GetBytes if * you require a FIPS-compliant source of random data. */ #ifndef __RANDOM_H__ # define __RANDOM_H__ #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif /* * OS-native random number generator based on one-way hashes. * * Good enough for any non-cryptographic use, but slower than * alternative algorithms. Recommended for generating seeds. * * Period: infinite * Speed: slow */ Bool Random_Crypto(size_t size, void *buffer); /* * High quality - research grade - random number generator. * * Period: 2^800 * Speed: ~23 cycles */ typedef struct rqContext rqContext; rqContext *Random_QuickSeed(uint32 seed); uint32 Random_Quick(rqContext *context); /* * Good quality non-deterministic random number generator. * * This generator uses &(*state) as the seed to go beyond 64-bits without * additional storage space; the low-grade entropy makes seeding * non-deterministic. Multiple generators in the same address space * with the same seed will produce unique streams, but using the same * seed will NOT produce the same sequence (due to ASLR). See * Raondom_FastStream for a deterministic generator. * * Initialize by setting *state to any seed (including zero) and calling * Random_Fast TWICE. (Unless the seed is very good, the first two values * are not very random). * * Period: 2^64 * Speed: ~10 cycles */ uint32 Random_Fast(uint64 *state); static INLINE void Random_FastSeed(uint64 *state, // OUT: uint64 seed) // IN: { *state = seed; (void) Random_Fast(state); (void) Random_Fast(state); } /* * Good quality deterministic random number generator. * * Period: 2^64 * Speed: ~10 cycles */ typedef struct { uint64 state; uint64 sequence; } RandomFastContext; uint32 Random_FastStream(RandomFastContext *rfc); void Random_FastStreamSeed(RandomFastContext *rfc, uint64 seed, uint64 seq); /* * Simple multiplicative congruential RNG. * * Deprecated; prefer Random_Fast for better quality. * Period: 2^31-1 * Speed: ~9 cycles */ int Random_Simple(int seed); #if defined(__cplusplus) } // extern "C" #endif #endif /* __RANDOM_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/removable_device.h000066400000000000000000000022171321503522500261350ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _REMOVABLE_DEVICE_H_ #define _REMOVABLE_DEVICE_H_ #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #define REMOVABLE_DEVICE_PRETTY_NAME_LENGTH 32 typedef struct { char name[REMOVABLE_DEVICE_PRETTY_NAME_LENGTH]; uint32 uid; Bool enabled; } RD_Info; #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/rpcin.h000066400000000000000000000053641321503522500237630ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * rpcin.h -- * * Remote Procedure Call between VMware and guest applications * C declarations */ #ifndef __RPCIN_H__ # define __RPCIN_H__ #ifdef __cplusplus extern "C" { #endif typedef void RpcIn_ErrorFunc(void *clientData, char const *status); typedef struct RpcIn RpcIn; #if defined(VMTOOLS_USE_GLIB) /* { */ #include "vmware/tools/guestrpc.h" RpcIn *RpcIn_Construct(GMainContext *mainCtx, RpcIn_Callback dispatch, gpointer clientData); Bool RpcIn_start(RpcIn *in, unsigned int delay, RpcIn_ErrorFunc *errorFunc, void *errorData); #else /* } { */ #include "dbllnklst.h" /* * Type for old RpcIn callbacks. Don't use this anymore - this is here * for backwards compatibility. */ typedef Bool (*RpcIn_Callback)(char const **result, // OUT size_t *resultLen, // OUT const char *name, // IN const char *args, // IN size_t argsSize, // IN void *clientData); // IN RpcIn *RpcIn_Construct(DblLnkLst_Links *eventQueue); Bool RpcIn_start(RpcIn *in, unsigned int delay, RpcIn_Callback resetCallback, void *resetClientData, RpcIn_ErrorFunc *errorFunc, void *errorData); /* * Don't use this function anymore - it's here only for backwards compatibility. * Use RpcIn_RegisterCallbackEx() instead. */ void RpcIn_RegisterCallback(RpcIn *in, const char *name, RpcIn_Callback callback, void *clientData); void RpcIn_UnregisterCallback(RpcIn *in, const char *name); unsigned int RpcIn_SetRetVals(char const **result, size_t *resultLen, const char *resultVal, Bool retVal); #endif /* } */ void RpcIn_Destruct(RpcIn *in); void RpcIn_stop(RpcIn *in); #ifdef __cplusplus } // extern "C" #endif #endif /* __RPCIN_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/rpcout.h000066400000000000000000000060441321503522500241600ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * rpcout.h -- * * Remote Procedure Call between VMware and guest applications * C declarations */ #ifndef __RPCOUT_H__ # define __RPCOUT_H__ #include "vm_basic_types.h" #define RPCI_PROTOCOL_NUM 0x49435052 /* 'RPCI' ;-) */ typedef struct RpcOut RpcOut; RpcOut *RpcOut_Construct(void); void RpcOut_Destruct(RpcOut *out); Bool RpcOut_start(RpcOut *out); Bool RpcOut_send(RpcOut *out, char const *request, size_t reqLen, Bool *rpcStatus, char const **reply, size_t *repLen); Bool RpcOut_stop(RpcOut *out); /* * This is the only method needed to send a message to vmware for * 99% of uses. I'm leaving the others defined here so people know * they can be exported again if the need arises. [greg] */ Bool RpcOut_sendOne(char **reply, size_t *repLen, char const *reqFmt, ...); /* * A version of the RpcOut_sendOne function that works with UTF-8 * strings and other data that would be corrupted by Win32's * FormatMessage function (which is used by RpcOut_sendOne()). */ Bool RpcOut_SendOneRaw(void *request, size_t reqLen, char **reply, size_t *repLen); /* * A variant of the RpcOut_SendOneRaw in which the caller supplies the * receive buffer so as to avoid the need to call malloc internally. * Useful in situations where calling malloc is not allowed. */ Bool RpcOut_SendOneRawPreallocated(void *request, size_t reqLen, char *reply, size_t repLen); /* * As the above but must be run by admin/root to make the privileged * RPC call successfully. */ Bool RpcOut_SendOneRawPriv(void *request, size_t reqLen, char **reply, size_t *repLen); #endif /* __RPCOUT_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/rpcvmx.h000066400000000000000000000052311321503522500241600ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * rpcvmx.h -- * * Simple utility library (usable by guest drivers as well as userlevel * Tools code) that provides some useful VMX interaction capability, e.g. * logging to the VM's VMX log, querying config variables, etc. * * NB: This library is *NOT* threadsafe, so if you want to avoid * corrupting your log statements or other screwups, add your own * locking around calls to RpcVMX_Log. */ #ifndef _RPCVMX_H_ #define _RPCVMX_H_ #include #include "vm_basic_types.h" #define RPCVMX_MAX_LOG_LEN (2048) /* 2kb max - make it dynamic? */ /* * Set a prefix to prepend to any future log statements. */ void RpcVMX_LogSetPrefix(const char *prefix); /* * Get the currently set prefix (returns empty string if no prefix set) */ const char *RpcVMX_LogGetPrefix(const char *prefix); /* * Format the provided string with the provided arguments, and post it to the * VMX logfile via RPC. */ void RpcVMX_Log(const char *fmt, ...) PRINTF_DECL(1, 2); /* * Save as RpcVMX_Log but takes a va_list instead of inline arguments. */ void RpcVMX_LogV(const char *fmt, va_list args); /* * Get the value of "guestinfo.$key" in the host VMX dictionary and return it. * Returns the default if the key is not set. */ char *RpcVMX_ConfigGetString(const char *defval, const char *key); /* * Same as _ConfigGetString, but convert the value to a 32-bit quantity. * XXX Returns 0, *NOT* the default, if the key was set but the value could * not be converted to an int32. */ int32 RpcVMX_ConfigGetLong(int32 defval, const char *key); /* * Same as _ConfigGetString, but convert the value to a Bool. Returns the * default value if the key was set but could not be converted. */ Bool RpcVMX_ConfigGetBool(Bool defval, const char *key); #endif /* _VMXRPC_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/safetime.h000066400000000000000000000115011321503522500244330ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * safetime.h -- * * This header file defines wrappers so that we use the * 64-bit versions of the C time calls. This file is * temporary until we switch to a newer version of * Visual Studio that uses the 64-bit verisions by default. * * In Windows, the user is allowed to set the time past the * 32-bit overflow date (in 2038), which can cause crashes * and security problems. In Linux, the time can't be set * to overflow, so we do nothing. * * NB: We do not know if one can set the time past 2038 in * 64-bit versions of Linux, and, if so, what happens when * one does. This requires further investigation sometime * in the future. * * The stat types and functions must be defined manually, * since they contain time_ts, and we can't use the macro * trick, since the struct stat and the function stat have * the same 32 bit name (but different 64 bit names). * */ #ifndef _SAFETIME_H_ #define _SAFETIME_H_ #ifdef _WIN32 #undef FMTTIME #define FMTTIME FMT64"d" #if (_MSC_VER < 1400) #if (defined(_STAT_DEFINED) || defined(_INC_TIME) || defined(_INC_TYPES)) #error Use safetime.h instead of time.h, stat.h, and types.h #endif #define _STAT_DEFINED #include #include #include #define time_t __time64_t #define time(a) _time64(a) #define localtime(a) _localtime64((a)) #define _ctime(a) _ctime64((a)) #define ctime(a) _ctime64((a)) #define _ftime(a) _ftime64((a)) #define ftime(a) _ftime64((a)) #define _timeb __timeb64 #define _gmtime(a) _gmtime64((a)) #define gmtime(a) _gmtime64((a)) #define _mktime(a) _mktime64((a)) #define mktime(a) _mktime64((a)) #define _utime(a,b) _utime64((a),(b)) #define utime(a,b) _utime64((a),(b)) #define _utimbuf __utimbuf64 #define utimbuf __utimbuf64 #define _wctime(a) _wctime64((a),(b)) #define wctime(a) _wctime64((a),(b)) #define _futime(a,b) _futime64((a),(b)) #define futime(a,b) _futime64((a),(b)) #define _wutime(a,b) _wutime64((a),(b)) #define wutime(a,b) _wutime64((a),(b)) #include #ifdef _MSC_VER #pragma pack(push,8) #endif struct _stat { _dev_t st_dev; _ino_t st_ino; unsigned short st_mode; short st_nlink; short st_uid; short st_gid; _dev_t st_rdev; __int64 st_size; __time64_t st_atime; __time64_t st_mtime; __time64_t st_ctime; }; struct stat { _dev_t st_dev; _ino_t st_ino; unsigned short st_mode; short st_nlink; short st_uid; short st_gid; _dev_t st_rdev; __int64 st_size; __time64_t st_atime; __time64_t st_mtime; __time64_t st_ctime; }; struct __stat64 { _dev_t st_dev; _ino_t st_ino; unsigned short st_mode; short st_nlink; short st_uid; short st_gid; _dev_t st_rdev; __int64 st_size; __time64_t st_atime; __time64_t st_mtime; __time64_t st_ctime; }; #ifdef _MSC_VER #pragma pack(pop) #endif #include #define stat(a,b) _stat64((a),(struct __stat64*)(b)) #define _stat(a,b) _stat64((a),(struct __stat64*)(b)) #define fstat(a,b) _fstat64((a),(struct __stat64*)(b)) #define _fstat(a,b) _fstat64((a),(struct __stat64*)(b)) #define wstat(a,b) _wstat64((a),(struct __stat64*)(b)) #define _wstat(a,b) _wstat64((a),(struct __stat64*)(b)) #else /* (_MSC_VER < 1400) */ /* * Starting with VC80, we can pick between 32-bit and 64-bit time_t * by defining or not defining _USE_32BIT_TIME_T. Don't define it. */ #include #include #include #include #include /* Make sure that the headers didn't revert to 32-bit. */ #ifdef _USE_32BIT_TIME_T #error Refusing to use 32-bit time_t in safetime.h #endif #endif /* (_MSC_VER < 1400) */ #else #include #include #include #include #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/sha1.h000066400000000000000000000077241321503522500235060ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * sha1.h -- * * SHA1 encryption */ #ifndef _SHA1_H_ #define _SHA1_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMKERNEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" /* for uint32 */ #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif #if defined __APPLE__ && defined USERLEVEL /* * Apple provides basic crypto functions in its system runtime that are * maintained for both speed and security. Use those instead. */ #include #define SHA1_HASH_LEN CC_SHA1_DIGEST_LENGTH #define SHA1_CTX CC_SHA1_CTX #define SHA1Init CC_SHA1_Init #define SHA1Update CC_SHA1_Update #define SHA1Final CC_SHA1_Final #else #ifndef VMKERNEL /* * Prevent linkage conflicts with the SHA1 APIs brought in from * OpenSSL. (Pro tip: If you're doing anything security-related, you * _must_ be using lib/crypto hash routines to preserve FIPS * compatibility.) */ #define SHA1Init VMW_SHA1Init #define SHA1Update VMW_SHA1Update #define SHA1Final VMW_SHA1Final #define SHA1RawBufferHash VMW_SHA1RawBufferHash #endif /* !VMKERNEL */ /* SHA-1 in C By Steve Reid 100% Public Domain Test Vectors (from FIPS PUB 180-1) "abc" A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 A million repetitions of "a" 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F */ /* 12/15/98: JEB: Removed main and moved prototypes to sha1.h Made SHA1Transform a static function */ #define SHA1_HASH_LEN 20 typedef struct SHA1_CTX { uint32 state[5]; uint32 count[2]; unsigned char buffer[64]; } SHA1_CTX; void SHA1Init(SHA1_CTX* context); void SHA1Update(SHA1_CTX* context, const unsigned char *data, size_t len); void SHA1Final(unsigned char digest[SHA1_HASH_LEN], SHA1_CTX* context); void SHA1RawBufferHash(const void *data, uint32 size, uint32 result[5]); void SHA1RawTransformBlocks(uint32 state[5], const unsigned char *buffer, uint32 numBlocks); void SHA1RawInit(uint32 state[5]); #define SHA1_MULTI_MAX_BUFFERS 8 void SHA1MultiBuffer(uint32 numBuffers, uint32 len, const void *data[], unsigned char *digests[]); #endif // defined __APPLE__ && defined USERLEVEL #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _SHA1_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/sigPosixRegs.h000066400000000000000000000340511321503522500252710ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * sigPosixRegs.h -- * * Platform-specific definitions for saved CPU registers inside * ucontext_t. These aren't part of sigPosix.h since few source * files need them, and this header is a bit invasive, and it must * be defined before system headers. */ #ifndef _SIGPOSIXREGS_H_ #define _SIGPOSIXREGS_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #if defined(__cplusplus) extern "C" { #endif #if __linux__ // We need the REG_foo offsets in the gregset_t; # define _GNU_SOURCE // _GNU_SOURCE maps to __USE_GNU /* And, the REG_foo definitions conflict with our own in x86.h */ # if defined(__x86_64__) # define REG_RAX GNU_REG_RAX # define REG_RBX GNU_REG_RBX # define REG_RCX GNU_REG_RCX # define REG_RDX GNU_REG_RDX # define REG_RSI GNU_REG_RSI # define REG_RDI GNU_REG_RDI # define REG_RSP GNU_REG_RSP # define REG_RBP GNU_REG_RBP # define REG_RIP GNU_REG_RIP # define REG_R8 GNU_REG_R8 # define REG_R9 GNU_REG_R9 # define REG_R10 GNU_REG_R10 # define REG_R11 GNU_REG_R11 # define REG_R12 GNU_REG_R12 # define REG_R13 GNU_REG_R13 # define REG_R14 GNU_REG_R14 # define REG_R15 GNU_REG_R15 # elif defined(__i386__) # define REG_EAX GNU_REG_EAX # define REG_EBX GNU_REG_EBX # define REG_ECX GNU_REG_ECX # define REG_EDX GNU_REG_EDX # define REG_ESI GNU_REG_ESI # define REG_EDI GNU_REG_EDI # define REG_ESP GNU_REG_ESP # define REG_EBP GNU_REG_EBP # define REG_EIP GNU_REG_EIP # endif #endif #include #include #if __linux__ && !defined __ANDROID__ # if defined(__x86_64__) # undef REG_RAX # undef REG_RBX # undef REG_RCX # undef REG_RDX # undef REG_RSI # undef REG_RDI # undef REG_RSP # undef REG_RBP # undef REG_RIP # undef REG_R8 # undef REG_R9 # undef REG_R10 # undef REG_R11 # undef REG_R12 # undef REG_R13 # undef REG_R14 # undef REG_R15 # elif defined(__i386__) # undef REG_EAX # undef REG_EBX # undef REG_ECX # undef REG_EDX # undef REG_ESI # undef REG_EDI # undef REG_ESP # undef REG_EBP # undef REG_EIP # endif #endif #if defined(__APPLE__) #if __DARWIN_UNIX03 #ifdef __x86_64__ #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rax) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rbx) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rcx) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rdx) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rdi) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rsi) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rbp) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rsp) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__rip) #define SC_R8(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r8) #define SC_R9(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r9) #define SC_R10(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r10) #define SC_R11(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r11) #define SC_R12(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r12) #define SC_R13(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r13) #define SC_R14(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r14) #define SC_R15(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r15) #elif defined(__arm__) #define SC_R0(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[0]) #define SC_R1(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[1]) #define SC_R2(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[2]) #define SC_R3(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[3]) #define SC_R4(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[4]) #define SC_R5(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[5]) #define SC_R6(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[6]) #define SC_R7(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[7]) #define SC_R8(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[8]) #define SC_R9(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[9]) #define SC_R10(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[10]) #define SC_FP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[11]) #define SC_IP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__r[12]) #define SC_SP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__sp) #define SC_LR(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__lr) #define SC_PC(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__pc) #elif defined(__aarch64__) #define SC_X(uc,n) ((unsigned long) (uc)->uc_mcontext->__ss.__x[n]) #define SC_SP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__sp) #define SC_PC(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__pc) #define SC_PSR(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__cpsr) #else #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__eax) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__ebx) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__ecx) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__edx) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__edi) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__esi) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__ebp) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__esp) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext->__ss.__eip) #endif #else #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext->ss.eax) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext->ss.ebx) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext->ss.ecx) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext->ss.edx) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext->ss.edi) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext->ss.esi) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext->ss.ebp) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext->ss.esp) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext->ss.eip) #endif #elif defined(__FreeBSD__) #ifdef __x86_64__ #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext.mc_rax) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext.mc_rbx) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext.mc_rcx) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext.mc_rdx) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext.mc_rdi) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext.mc_rsi) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext.mc_rbp) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext.mc_rsp) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext.mc_rip) #define SC_R8(uc) ((unsigned long) (uc)->uc_mcontext.mc_r8) #define SC_R9(uc) ((unsigned long) (uc)->uc_mcontext.mc_r9) #define SC_R10(uc) ((unsigned long) (uc)->uc_mcontext.mc_r10) #define SC_R11(uc) ((unsigned long) (uc)->uc_mcontext.mc_r11) #define SC_R12(uc) ((unsigned long) (uc)->uc_mcontext.mc_r12) #define SC_R13(uc) ((unsigned long) (uc)->uc_mcontext.mc_r13) #define SC_R14(uc) ((unsigned long) (uc)->uc_mcontext.mc_r14) #define SC_R15(uc) ((unsigned long) (uc)->uc_mcontext.mc_r15) #else #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext.mc_eax) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext.mc_ebx) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext.mc_ecx) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext.mc_edx) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext.mc_edi) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext.mc_esi) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext.mc_ebp) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext.mc_esp) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext.mc_eip) #endif #elif defined (sun) #ifdef __x86_64__ #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RAX]) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RBX]) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RCX]) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RDX]) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RDI]) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RSI]) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RBP]) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RSP]) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_RIP]) #define SC_R8(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_R8]) #define SC_R9(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_R9]) #define SC_R10(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_R10]) #define SC_R11(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_R11]) #define SC_R12(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_R12]) #define SC_R13(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_R13]) #define SC_R14(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_R14]) #define SC_R15(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_R15]) #else #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[EAX]) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[EBX]) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[ECX]) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[EDX]) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[EDI]) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[ESI]) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[EBP]) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[ESP]) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[EIP]) #endif #elif defined(ANDROID_X86) #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_EAX]) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_EBX]) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_ECX]) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_EDX]) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_EDI]) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_ESI]) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_EBP]) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_ESP]) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[REG_EIP]) #else #ifdef __x86_64__ #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RAX]) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RBX]) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RCX]) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RDX]) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RDI]) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RSI]) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RBP]) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RSP]) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_RIP]) #define SC_R8(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_R8]) #define SC_R9(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_R9]) #define SC_R10(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_R10]) #define SC_R11(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_R11]) #define SC_R12(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_R12]) #define SC_R13(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_R13]) #define SC_R14(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_R14]) #define SC_R15(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_R15]) #elif defined(__arm__) #define SC_R0(uc) ((unsigned long) (uc)->uc_mcontext.arm_r0) #define SC_R1(uc) ((unsigned long) (uc)->uc_mcontext.arm_r1) #define SC_R2(uc) ((unsigned long) (uc)->uc_mcontext.arm_r2) #define SC_R3(uc) ((unsigned long) (uc)->uc_mcontext.arm_r3) #define SC_R4(uc) ((unsigned long) (uc)->uc_mcontext.arm_r4) #define SC_R5(uc) ((unsigned long) (uc)->uc_mcontext.arm_r5) #define SC_R6(uc) ((unsigned long) (uc)->uc_mcontext.arm_r6) #define SC_R7(uc) ((unsigned long) (uc)->uc_mcontext.arm_r7) #define SC_R8(uc) ((unsigned long) (uc)->uc_mcontext.arm_r8) #define SC_R9(uc) ((unsigned long) (uc)->uc_mcontext.arm_r9) #define SC_R10(uc) ((unsigned long) (uc)->uc_mcontext.arm_r10) #define SC_FP(uc) ((unsigned long) (uc)->uc_mcontext.arm_fp) #define SC_IP(uc) ((unsigned long) (uc)->uc_mcontext.arm_ip) #define SC_SP(uc) ((unsigned long) (uc)->uc_mcontext.arm_sp) #define SC_LR(uc) ((unsigned long) (uc)->uc_mcontext.arm_lr) #define SC_PC(uc) ((unsigned long) (uc)->uc_mcontext.arm_pc) #elif defined(__aarch64__) #define SC_X(uc,n) ((unsigned long) (uc)->uc_mcontext.regs[n]) #define SC_SP(uc) ((unsigned long) (uc)->uc_mcontext.sp) #define SC_PC(uc) ((unsigned long) (uc)->uc_mcontext.pc) #define SC_PSR(uc) ((unsigned long) (uc)->uc_mcontext.pstate) #else #define SC_EAX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_EAX]) #define SC_EBX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_EBX]) #define SC_ECX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_ECX]) #define SC_EDX(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_EDX]) #define SC_EDI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_EDI]) #define SC_ESI(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_ESI]) #define SC_EBP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_EBP]) #define SC_ESP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_ESP]) #define SC_EIP(uc) ((unsigned long) (uc)->uc_mcontext.gregs[GNU_REG_EIP]) #endif #endif #if defined(__cplusplus) } // extern "C" #endif #endif // ifndef _SIGPOSIXREGS_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/slashProc.h000066400000000000000000000025261321503522500246030ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /** * @file slashProc.h */ #ifndef _SLASHPROC_H_ #define _SLASHPROC_H_ #include #include /* * Global functions */ EXTERN GHashTable *SlashProcNet_GetSnmp(void); EXTERN GHashTable *SlashProcNet_GetSnmp6(void); EXTERN GPtrArray *SlashProcNet_GetRoute(void); EXTERN void SlashProcNet_FreeRoute(GPtrArray *); EXTERN GPtrArray *SlashProcNet_GetRoute6(void); EXTERN void SlashProcNet_FreeRoute6(GPtrArray *); #endif // ifndef _SLASHPROC_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/sslDirect.h000066400000000000000000000044651321503522500246050ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2014-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * sslDirect.h -- * * declarations in ssl.h that are required by AsyncSocket. * */ #ifndef _SSLDIRECT_H_ #define _SSLDIRECT_H_ #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" typedef struct _SSLVerifyParam SSLVerifyParam; typedef struct SSLSockStruct *SSLSock; typedef char* (SSLLibFn)(const char*, const char*); void SSL_Init(SSLLibFn *getLibFn, const char *defaultLib, const char *name); SSLSock SSL_New(int fd,Bool closeFdOnShutdown); void SSL_SetCloseOnShutdownFlag(SSLSock ssl); Bool SSL_SetupAcceptWithContext(SSLSock sSock, void *ctx); int SSL_TryCompleteAccept(SSLSock sSock); ssize_t SSL_Read(SSLSock ssl, char *buf, size_t num); ssize_t SSL_RecvDataAndFd(SSLSock ssl, char *buf, size_t num, int *fd); ssize_t SSL_Write(SSLSock ssl, const char *buf, size_t num); int SSL_Shutdown(SSLSock ssl); int SSL_GetFd(SSLSock sSock); int SSL_Pending(SSLSock ssl); int SSL_WantRead(const SSLSock ssl); #ifdef _WIN32 #define SSLGeneric_read(sock,buf,num) recv(sock,buf,num,0) #define SSLGeneric_write(sock,buf,num) send(sock,buf,num,0) #define SSLGeneric_recvmsg(sock,msg,flags) recvmsg(sock,msg,flags) #define SSLGeneric_close(sock) closesocket(sock) #else #define SSLGeneric_read(sock,buf,num) read(sock, buf, num) #define SSLGeneric_write(sock,buf,num) write(sock, buf,num) #define SSLGeneric_recvmsg(sock,msg,flags) recvmsg(sock,msg,flags) #define SSLGeneric_close(sock) close(sock) #endif void *SSL_NewContext(void); #endif // ifndef _SSLDIRECT_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/str.h000066400000000000000000000226211321503522500234530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * str.h -- * * string wrapping functions */ #ifndef _STR_H_ #define _STR_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #if defined(__linux__) #include #elif defined(_WIN32) #include #elif __APPLE__ #include #endif #include "compat/compat_stdarg.h" // Provides stdarg.h plus va_copy #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif /* * These platforms use bsd_vsnprintf(). * This does not mean it has bsd_vsnwprintf(). */ #if !defined(OPEN_VM_TOOLS) #if (defined _WIN32 && !defined STR_NO_WIN32_LIBS) || \ (defined __linux__ && !defined __UCLIBC__) || \ defined __APPLE__ #define HAS_BSD_PRINTF 1 #endif #endif /* * And these platforms/setups use bsd_vsnwprintf() */ #if !defined(OPEN_VM_TOOLS) #if (defined _WIN32 && !defined STR_NO_WIN32_LIBS) || \ (defined __GNUC__ && (__GNUC__ < 2 \ || (__GNUC__ == 2 \ && __GNUC_MINOR__ < 96))) #define HAS_BSD_WPRINTF 1 #endif #endif /* * ASCII/UTF-8 versions * * NOTE: All size_t arguments and integer returns values are in bytes. * * NOTE: Str_Asprintf/Str_Vasprintf return NULL on failure, while * Str_SafeAsprintf/Str_SafeVasprintf VERIFY. * * NOTE: "%s" refers to strings of "char" units, while "%S" refers to * strings of "wchar_t" units, regardless of platform. */ #ifdef HAS_BSD_PRINTF int Str_Sprintf_C_Locale(char *buf, // OUT: size_t max, // IN: const char *fmt, // IN: ...) PRINTF_DECL(3, 4); // IN: #endif int Str_Sprintf(char *buf, // OUT: size_t max, // IN: const char *fmt, // IN: ...) PRINTF_DECL(3, 4); // IN: int Str_Snprintf(char *buf, // OUT: size_t len, // IN: const char *fmt, // IN: ...) PRINTF_DECL(3, 4); // IN: int Str_Vsnprintf(char *buf, // OUT: size_t len, // IN: const char *fmt, // IN: va_list args); // IN: size_t Str_Strlen(const char *src, // IN: size_t maxLen); // IN: char *Str_Strnstr(const char *src, // IN: const char *sub, // IN: size_t n); // IN: char *Str_Strcpy(char *dst, // OUT: const char *src, // IN: size_t maxLen); // IN: char *Str_Strncpy(char *dest, // OUT: size_t destSize, // IN: const char *src, // IN: size_t n); // IN: char *Str_Strcat(char *dst, // IN/OUT: const char *src, // IN: size_t maxLen); // IN: char *Str_Strncat(char *buf, // IN/OUT: size_t bufSize, // IN: const char *src, // IN: size_t n); // IN: char *Str_Asprintf(size_t *length, // OUT/OPT: const char *format, // IN: ...) PRINTF_DECL(2, 3); // IN: char *Str_Vasprintf(size_t *length, // OUT/OPT: const char *format, // IN: va_list arguments); // IN: char *Str_SafeAsprintf(size_t *length, // OUT/OPT: const char *format, // IN: ...) PRINTF_DECL(2, 3); // IN: char *Str_SafeVasprintf(size_t *length, // OUT/OPT: const char *format, // IN: va_list arguments); // IN: #if defined(_WIN32) || defined(__linux__) // { /* * wchar_t versions * * NOTE: All size_t arguments and integer return values are in * wchar_ts, not bytes. * * NOTE: Str_Aswprintf/Str_Vaswprintf return NULL on failure, while * Str_SafeAswprintf/Str_SafeVaswprintf VERIFY. * * NOTE: "%s" refers to strings of "char" units, while "%S" refers to * strings of "wchar_t" units, regardless of platform. */ int Str_Swprintf(wchar_t *buf, // OUT: size_t max, // IN: const wchar_t *fmt, // IN: ...); int Str_Snwprintf(wchar_t *buf, // OUT: size_t len, // IN: const wchar_t *fmt, // IN: ...); int Str_Vsnwprintf(wchar_t *buf, // OUT: size_t len, // IN: const wchar_t *fmt, // IN: va_list args); wchar_t *Str_Wcscpy(wchar_t *dst, // OUT: const wchar_t *src, // IN: size_t maxLen); // IN: wchar_t *Str_Wcscat(wchar_t *dst, // IN/OUT: const wchar_t *src, // IN: size_t maxLen); // IN: wchar_t *Str_Wcsncat(wchar_t *buf, // IN/OUT: size_t bufSize, // IN: const wchar_t *src, // IN: size_t n); // IN: wchar_t *Str_Aswprintf(size_t *length, // OUT/OPT: const wchar_t *format, // IN: ...); // IN: wchar_t *Str_Vaswprintf(size_t *length, // OUT/OPT: const wchar_t *format, // IN: va_list arguments); // IN: wchar_t *Str_SafeAswprintf(size_t *length, // OUT/OPT: const wchar_t *format, // IN: ...); // IN: wchar_t *Str_SafeVaswprintf(size_t *length, // OUT/OPT: const wchar_t *format, // IN: va_list arguments); // IN: unsigned char *Str_Mbscpy(char *buf, // OUT: const char *src, // IN: size_t maxSize); // IN: unsigned char *Str_Mbscat(char *buf, // IN/OUT: const char *src, // IN: size_t maxSize); // IN: /* * These are handly for Windows programmers. They are like * the _tcs functions, but with Str_Strcpy-style bounds checking. * * We don't have Str_Mbsncat() because it has some odd semantic * ambiguity (whether to truncate in the middle of a multibyte * sequence) that I want to stay away from. -- edward */ #ifdef _WIN32 #ifdef UNICODE #define Str_Tcscpy(s1, s2, n) Str_Wcscpy(s1, s2, n) #define Str_Tcscat(s1, s2, n) Str_Wcscat(s1, s2, n) #else #define Str_Tcscpy(s1, s2, n) Str_Mbscpy(s1, s2, n) #define Str_Tcscat(s1, s2, n) Str_Mbscat(s1, s2, n) #endif #endif #endif // } defined(_WIN32) || defined(__linux__) /* * Wrappers for standard string functions * * These are either for Windows-Posix compatibility, * or just gratuitous wrapping for consistency. */ #define Str_Strcmp(s1, s2) strcmp(s1, s2) #define Str_Strncmp(s1, s2, n) strncmp(s1, s2, n) #define Str_Strchr(s, c) strchr(s, c) #define Str_Strrchr(s, c) strrchr(s, c) #define Str_Strspn(s1, s2) strspn(s1, s2) #define Str_Strcspn(s1, s2) strcspn(s1, s2) #if defined(_WIN32) #define Str_Strcasecmp(s1, s2) _stricmp(s1, s2) #define Str_Strncasecmp(s1, s2, n) _strnicmp(s1, s2, n) #define Str_ToUpper(s) _strupr(s) #define Str_ToLower(s) _strlwr(s) #else #define Str_Strcasecmp(s1, s2) strcasecmp(s1, s2) #define Str_Strncasecmp(s1, s2, n) strncasecmp(s1, s2, n) char *Str_ToUpper(char *string); char *Str_ToLower(char *string); #endif #ifdef _WIN32 #define Str_Tcscmp(s1, s2) _tcscmp(s1, s2) #define Str_Tcsncmp(s1, s2, n) _tcsncmp(s1, s2, n) #define Str_Tcsicmp(s1, s2) _tcsicmp(s1, s2) #define Str_Tcsnicmp(s1, s2, n) _tcsnicmp(s1, s2, n) #define Str_Tcschr(s, c) _tcschr(s, c) #define Str_Tcsrchr(s, c) _tcsrchr(s, c) #define Str_Tcsspn(s1, s2) _tcsspn(s1, s2) #define Str_Tcscspn(s1, s2) _tcscspn(s1, s2) #define Str_Tcsupr(s) _tcsupr(s) #define Str_Tcslwr(s) _tcslwr(s) #endif #if defined(__cplusplus) } // extern "C" #endif #endif /* _STR_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/strutil.h000066400000000000000000000073231321503522500243530ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * strutil.h -- * * String utility functions. */ #ifndef STRUTIL_H #define STRUTIL_H #include #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif struct DynBuf; char *StrUtil_GetNextToken(unsigned int *index, const char *str, const char *delimiters); Bool StrUtil_GetNextIntToken(int32 *out, unsigned int *index, const char *str, const char *delimiters); Bool StrUtil_GetNextUintToken(uint32 *out, unsigned int *index, const char *str, const char *delimiters); Bool StrUtil_GetNextInt64Token(int64 *out, unsigned int *index, const char *str, const char *delimiters); Bool StrUtil_DecimalStrToUint(unsigned int *out, const char **str); Bool StrUtil_StrToInt(int32 *out, const char *str); Bool StrUtil_StrToUint(uint32 *out, const char *str); Bool StrUtil_StrToInt64(int64 *out, const char *str); Bool StrUtil_StrToUint64(uint64 *out, const char *str); Bool StrUtil_StrToSizet(size_t *out, const char *str); Bool StrUtil_StrToDouble(double *out, const char *str); Bool StrUtil_CapacityToBytes(SectorType *out, const char *str, unsigned int bytes); Bool StrUtil_CapacityToSectorType(SectorType *out, const char *str, unsigned int bytes); char *StrUtil_FormatSizeInBytesUnlocalized(uint64 size); size_t StrUtil_GetLongestLineLength(const char *buf, size_t bufLength); Bool StrUtil_StartsWith(const char *s, const char *prefix); Bool StrUtil_CaselessStartsWith(const char *s, const char *prefix); Bool StrUtil_EndsWith(const char *s, const char *suffix); Bool StrUtil_IsASCII(const char *s); Bool StrUtil_VDynBufPrintf(struct DynBuf *b, const char *fmt, va_list args); Bool StrUtil_DynBufPrintf(struct DynBuf *b, const char *fmt, ...) PRINTF_DECL(2, 3); void StrUtil_SafeDynBufPrintf(struct DynBuf *b, const char *fmt, ...) PRINTF_DECL(2, 3); void StrUtil_SafeStrcat(char **prefix, const char *str); void StrUtil_SafeStrcatFV(char **prefix, const char *fmt, va_list args); void StrUtil_SafeStrcatF(char **prefix, const char *fmt, ...) PRINTF_DECL(2, 3); char *StrUtil_TrimWhitespace(const char *str); char *StrUtil_ReplaceAll(const char *orig, const char *what, const char *with); char *StrUtil_GetNextItem(char **list, char delim); char *StrUtil_GetLastItem(char **list, char delim); Bool StrUtil_HasListItem(char const *list, char delim, char const *item); Bool StrUtil_HasListItemCase(char const *list, char delim, char const *item); char *StrUtil_AppendListItem(char const *list, char delim, char const *item); void StrUtil_RemoveListItem(char * const list, char delim, char const *item); void StrUtil_RemoveListItemCase(char * const list, char delim, char const *item); #if defined(__cplusplus) } // extern "C" #endif #endif /* STRUTIL_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/su.h000066400000000000000000000070651321503522500232770ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * su.h -- * * Manage super-user priviledges * */ #ifndef USER_SU_H #define USER_SU_H #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #include "vm_assert.h" #if defined(__cplusplus) extern "C" { #endif #if defined(__APPLE__) #include #include int Id_SetGid(gid_t egid); int Id_SetREUid(uid_t ruid, uid_t euid); int Id_SetRESUid(uid_t ruid, uid_t euid, uid_t suid); #define Id_GetEUid() geteuid() void *Id_AuthGetLocal(); void *Id_AuthGetExternal(size_t *size); Bool Id_AuthSet(void const *buf, size_t size); Bool Id_AuthCheck(char const *right, char const *localizedDescription, Bool showDialogIfNeeded); #elif (defined(__linux__) || defined(sun) || defined(__FreeBSD__)) #include #include /* Our set of set*id functions which affect current thread only */ int Id_SetUid(uid_t euid); int Id_SetGid(gid_t egid); int Id_SetREUid(uid_t ruid, uid_t euid); int Id_SetREGid(gid_t rgid, gid_t egid); int Id_SetRESUid(uid_t ruid, uid_t euid, uid_t suid); int Id_SetRESGid(gid_t rgid, gid_t egid, gid_t sgid); /* For symmetry */ #define Id_GetEUid() geteuid() /* *---------------------------------------------------------------------------- * * Id_SetEUid -- * * Set specified effective uid for current thread. Does not affect * real uid or saved uid. * * Results: * 0 on success, -1 on failure, errno set * * Side effects: * errno may be modified on success * *---------------------------------------------------------------------------- */ static INLINE int Id_SetEUid(uid_t euid) { return Id_SetRESUid((uid_t)-1, euid, (uid_t)-1); } /* *---------------------------------------------------------------------------- * * Id_SetEGid -- * * Set specified effective gid for current thread. Does not affect * real gid or saved gid. * * Results: * 0 on success, -1 on failure, errno set * * Side effects: * errno may be modified on success * *---------------------------------------------------------------------------- */ static INLINE int Id_SetEGid(gid_t egid) { return Id_SetRESGid((gid_t)-1, egid, (gid_t)-1); } #endif /* linux */ #if defined(_WIN32) static INLINE int Id_BeginSuperUser(void) { return -1; } static INLINE void Id_EndSuperUser(int id) { } static INLINE Bool Id_IsSuperUser(void) { return TRUE; } static INLINE Bool Id_IsSetUGid(void) { return FALSE; } #else static INLINE Bool Id_IsSuperUser(void) { return 0 == geteuid(); } uid_t Id_BeginSuperUser(void); void Id_EndSuperUser(uid_t uid); Bool Id_IsSetUGid(void); #endif #if defined(__cplusplus) } // extern "C" #endif #endif /* USER_SU_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/syncDriver.h000066400000000000000000000036251321503522500247760ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2005-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * syncDriver.h -- * * Interface to the Sync Driver. */ #ifndef _SYNC_DRIVER_H_ #define _SYNC_DRIVER_H_ #include "vm_basic_types.h" #if defined(_WIN32) /* { */ # include # define SYNCDRIVER_INVALID_HANDLE INVALID_HANDLE_VALUE typedef HANDLE SyncDriverHandle; #else /* }{ POSIX */ # define INFINITE -1 # define SYNCDRIVER_INVALID_HANDLE NULL typedef struct SyncHandle * SyncDriverHandle; #endif /* } */ typedef enum { SYNCDRIVER_IDLE, SYNCDRIVER_BUSY, SYNCDRIVER_ERROR } SyncDriverStatus; Bool SyncDriver_Init(void); Bool SyncDriver_Freeze(const char *drives, Bool enableNullDriver, SyncDriverHandle *handle); Bool SyncDriver_Thaw(const SyncDriverHandle handle); SyncDriverStatus SyncDriver_QueryStatus(const SyncDriverHandle handle, int32 timeout); void SyncDriver_CloseHandle(SyncDriverHandle *handle); #if defined(__linux__) void SyncDriver_GetAttr(const SyncDriverHandle handle, const char **name, Bool *quiesces); #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/syncDriverIoc.h000066400000000000000000000030411321503522500254210ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * syncDriverIoc.h -- * * ioctl commands used by the sync driver on Unix systems. * * SYNC_IOC_FREEZE: Freezes the provided paths. * SYNC_IOC_THAW: Thaws frozen block devices after a FREEZE ioctl. * SYNC_IOC_QUERY: Returns the total number of frozen devices (not * specific to the fd used). */ #ifndef _SYNCDRIVERIOC_H_ #define _SYNCDRIVERIOC_H_ #ifdef linux # include # define SYNC_IOC_FREEZE _IOW(0xF5,0x01,const char *) # define SYNC_IOC_THAW _IO(0xF5,0x02) # define SYNC_IOC_QUERY _IOR(0xF5,0x03,int) #else # error "Driver not yet implemented for this OS." #endif #endif /* _SYNCDRIVERIOC_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/syncEvent.h000066400000000000000000000044561321503522500246270ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * syncEvent.h -- * * Implements a platform independent condition event that * you can either wait on or pass to Poll() or your event loop. * * WARNING! * This is an auto-reset event. So, you cannot use it for devices * in Poll that may be holding a device lock. It works fine for Poll if * you don't specify a lock when you register the handle with Poll(). */ #ifndef _SYNC_EVENT_H_ #define _SYNC_EVENT_H_ //#include "syncWaitQ.h" #include "vm_atomic.h" #if defined(__cplusplus) extern "C" { #endif #ifndef _WIN32 typedef enum { READ_FD_INDEX = 0, WRITE_FD_INDEX = 1, NUM_SYNC_EVENT_FDS = 2 } SyncEventFDTypes; #endif // _WIN32 /* * SyncEvent -- */ typedef struct SyncEvent { /* * Whether the waitqueue has been initialized; */ Bool initialized; #ifdef _WIN32 HANDLE event; #else Atomic_uint32 signalled; int fdList[NUM_SYNC_EVENT_FDS]; #endif // #ifdef _WIN32 } SyncEvent; /* * Be careful, on win64, handles are 64 bits, but Poll takes an int32. */ typedef int32 SyncEventSelectableHandle; Bool SyncEvent_Init(SyncEvent *that); void SyncEvent_Destroy(SyncEvent *that); void SyncEvent_Signal(SyncEvent *that); Bool SyncEvent_TryWait(SyncEvent *that); void SyncEvent_Wait(SyncEvent *that); SyncEventSelectableHandle SyncEvent_GetHandle(SyncEvent *that); #if defined(__cplusplus) } // extern "C" #endif #endif // #ifndef _SYNC_EVENT_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/system.h000066400000000000000000000060761321503522500241750ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * system.h -- * * System-specific routines used by the tools daemon. * */ #ifndef __SYSTEM_H__ # define __SYSTEM_H__ #include "vm_basic_types.h" #ifdef _WIN32 #include "dbllnklst.h" #endif #include "unicode.h" uint64 System_GetTimeMonotonic(void); uint64 System_Uptime(void); char *System_GetTimeAsString(void); void System_Shutdown(Bool reboot); Bool System_GetNodeName(size_t outBufSize, char *outBuf); char *System_GetEnv(Bool global, const char *valueName); int System_SetEnv(Bool global, const char *valueName, const char *value); Bool System_IsUserAdmin(void); #ifdef _WIN32 /* * Representation of monitors gathered by System_GetMonitors. */ typedef struct MonListNode { RECT rect; RECT work; BOOL isPrimary; DWORD bpp; BOOL isActive; uint32 srcId; DblLnkLst_Links l; } MonListNode; /* * The value returned by System_GetServiceState if the current state of the * vmtools service can't be determined. We need to use a value that is not * already used for a real state. The current values run from 0x1 to 0x7, so * 0xffffffff should be fairly safe (cf. winsvc.h). */ #define VM_SERVICE_STATE_UNKNOWN 0xffffffff BOOL System_SetProcessPrivilege(wchar_t *privName, Bool enable); int32 System_GetSPVersion(void); Bool System_IsLoginScreenActive(void); Bool System_IsScreenSaverActive(void); Bool System_IsScreenSaverRunning(void); Bool System_IsSecureDesktopActive(void); Bool System_DisableAndKillScreenSaver(void); DWORD System_GetServiceState(LPCWSTR szServiceName); DblLnkLst_Links *System_GetMonitors(); void System_SetFocusedWindow(HWND windowToFocus, Bool force); Bool System_EnableDesktopComposition(BOOL enabled); LPWSTR System_GetImageFilePathForWindow(HWND hwnd); HANDLE System_OpenProcessForHWND(DWORD mask, BOOL inherit, HWND hwnd); #endif /* * TODO: Targets' make/SCons files, or perhaps the entire build infrastructure * as a whole, should define a POSIX_LIKE_ENVIRONMENT variable which is * then acted upon and translates to a -DPOSIX_LIKE_ENVIRONMENT * preprocessor option. */ #if !defined(_WIN32) const char **System_GetNativeEnviron(const char **compatEnviron); void System_FreeNativeEnviron(const char **nativeEnviron); #endif #endif /* __SYSTEM_H__ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/timeutil.h000066400000000000000000000102031321503522500244700ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * timeutil.h -- * * Miscellaneous time related utility functions. * */ #ifndef _TIMEUTIL_H_ #define _TIMEUTIL_H_ #include #define INCLUDE_ALLOW_USERLEVEL #include "includeCheck.h" #include "vm_basic_types.h" #include "vm_basic_defs.h" #include "vm_assert.h" #if defined(__cplusplus) extern "C" { #endif #define MAX_DAYSLEFT 4096 struct timeval; /*struct timespec is not supported on UWP*/ #if defined(_WIN32) && !defined(VM_WIN_UWP) && _MSC_VER < 1900 struct timespec { time_t tv_sec; long tv_nsec; }; #endif /* Similar to a struct tm but with slightly less weird semantics. */ typedef struct TimeUtil_Date { unsigned int year; /* e.g. 1970 */ unsigned int month; /* [1, 12] */ unsigned int day; /* [1, 31] */ unsigned int hour; /* [0, 23] */ unsigned int minute; /* [0, 59] */ unsigned int second; /* [0, 61] (for leap seconds) */ } TimeUtil_Date; typedef struct TimeUtil_TimeOfDay { unsigned long seconds; unsigned long useconds; } TimeUtil_TimeOfDay; typedef struct TimeUtil_Expiration { /* * Does it expire? */ Bool expires; /* * When does it expire? (valid only if 'expires' == TRUE) * * Note: TimeUtil_Expiration only uses the 'year', 'month' * and 'day' fields of 'when'. */ TimeUtil_Date when; /* * Compute this once for all, to avoid problems when the current day changes * (valid only if 'expires' == TRUE). */ unsigned int daysLeft; } TimeUtil_Expiration; time_t TimeUtil_MakeTime(const TimeUtil_Date *d); // IN Bool TimeUtil_StringToDate(TimeUtil_Date *d, // IN/OUT char const *date); // IN: 'YYYYMMDD' or 'YYYY/MM/DD' or 'YYYY-MM-DD' Bool TimeUtil_DaysSubtract(TimeUtil_Date *d, // IN/OUT unsigned int nr); // IN int TimeUtil_DeltaDays(TimeUtil_Date const *left, // IN TimeUtil_Date const *right); // IN void TimeUtil_DaysAdd(TimeUtil_Date *d, // IN/OUT unsigned int nr); // IN void TimeUtil_PopulateWithCurrent(Bool local, // IN TimeUtil_Date *d); // OUT void TimeUtil_GetTimeOfDay(TimeUtil_TimeOfDay *d); // OUT unsigned int TimeUtil_DaysLeft(TimeUtil_Date const *d); // IN Bool TimeUtil_ExpirationLowerThan(TimeUtil_Expiration const *left, // IN TimeUtil_Expiration const *right); // IN Bool TimeUtil_DateLowerThan(TimeUtil_Date const *left, // IN TimeUtil_Date const *right); // IN void TimeUtil_ProductExpiration(TimeUtil_Expiration *e); // OUT char * TimeUtil_GetTimeFormat(int64 utcTime, // IN Bool showDate, // IN Bool showTime); // IN int TimeUtil_NtTimeToUnixTime(struct timespec *unixTime, // OUT VmTimeType ntTime); // IN VmTimeType TimeUtil_UnixTimeToNtTime(struct timespec unixTime); // IN #ifdef _WIN32 Bool TimeUtil_UTCTimeToSystemTime(const __time64_t utcTime, // IN SYSTEMTIME *systemTime); // OUT #endif int TimeUtil_GetLocalWindowsTimeZoneIndexAndName(char **ptzName); time_t TimeUtil_SecondsSinceEpoch(TimeUtil_Date *d); // IN #if defined(__cplusplus) } // extern "C" #endif #endif // _TIMEUTIL_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/tracer.hh000066400000000000000000000027771321503522500243050ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2013-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * tracer.hh -- * * A dumb object to trace function enter/exit. (Devel-only.) */ #ifndef TRACER_HH #define TRACER_HH #include "vm_basic_defs.h" extern "C" { #include "glib.h" } #ifdef VMX86_DEVEL # define TRACE_CALL() Tracer _fn_tracer (__FUNCTION__) class Tracer { public: Tracer(const char* fnName) : mFnName(fnName) { g_debug("> %s: enter\n", mFnName); } ~Tracer() { g_debug("< %s: exit\n", mFnName); } private: Tracer(); // = delete Tracer(const Tracer&); // = delete const char* mFnName; }; #else # define TRACE_CALL() #endif #endif // ifndef TRACER_HH open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/unicode.h000066400000000000000000000030201321503522500242610ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * unicode.h -- * * Unicode-aware string library. */ #ifndef _UNICODE_H_ #define _UNICODE_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" // Start here: string creation, destruction, and encoding conversion. #include "unicodeBase.h" // Basic string operations: length, append, find, insert, replace. #include "unicodeOperations.h" // Character transformations: upper/lower/title case, case folding, etc. #include "unicodeTransforms.h" #ifdef USE_ICU // Unicode functionality depending on the third-party ICU library. #include "unicodeICU.h" #endif // USE_ICU #endif // _UNICODE_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/unicodeBase.h000066400000000000000000000234621321503522500250700ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * unicodeBase.h -- * * Basic Unicode string creation and encoding conversion. */ #ifndef _UNICODE_BASE_H_ #define _UNICODE_BASE_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include #include #include "util.h" #include "unicodeTypes.h" #if defined(__cplusplus) extern "C" { #endif #define UNICODE_SUBSTITUTION_CHAR "\xEF\xBF\xBD" /* * Unescapes \\uABCD in string literals to Unicode code point * U+ABCD, and \\U001FABCD to Unicode code point U+1FABCD. * * The resulting string is never freed, so this is not to be used for * general runtime Unicode string creation. * * Use to replace: * * const char *utf8Copyright = "Copyright \302\251 COMPANY_NAME"; * * with: * * const char *copyright = U_UNESCAPE("Copyright \\u00A9 COMPANY_NAME"); */ #define U_UNESCAPE(x) Unicode_GetStatic(x, TRUE) /* * In contexts where an errno makes sense, use this * to report conversion failure. */ #ifndef _WIN32 #define UNICODE_CONVERSION_ERRNO EINVAL #endif /* * Allocates a Unicode string given a buffer of the specified length * (not necessarily NUL-terminated) in the specified encoding. * * Returns NULL if the buffer was invalid or memory could not be * allocated. */ char *Unicode_AllocWithLength(const void *buffer, ssize_t lengthInBytes, StringEncoding encoding); /* *----------------------------------------------------------------------------- * * Unicode_Alloc -- * * Allocates a new Unicode string given a NUL-terminated buffer * of bytes in the specified string encoding. * * If buffer is NULL, then NULL is returned. * * Note that regardless of the encoding of the buffer passed to this * function, the returned string can hold any Unicode characters. * * Results: * An allocated Unicode string containing the decoded characters * in buffer, or NULL if input is NULL. Caller must pass to * free to free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_Alloc(const void *buffer, // IN StringEncoding encoding) // IN { return Unicode_AllocWithLength(buffer, -1, encoding); } /* *----------------------------------------------------------------------------- * * Unicode_AllocWithUTF8 -- * * Allocates a new Unicode string given a NUL-terminated UTF-8 string. * * If utf8String is NULL, then NULL is returned. * * Results: * An allocated Unicode string containing the characters in * utf8String, or NULL if utf8String is NULL. Caller must pass to * free to free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_AllocWithUTF8(const char *utf8String) // IN { return Unicode_AllocWithLength(utf8String, -1, STRING_ENCODING_UTF8); } /* *----------------------------------------------------------------------------- * * Unicode_AllocWithUTF16 -- * * Allocates a new Unicode string given a NUL-terminated UTF-16 * string in host-endian order. * * If utf16String is NULL, then NULL is returned. * * Results: * An allocated Unicode string containing the characters in * utf16String, or NULL if utf16String is NULL. Caller must pass to * free to free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_AllocWithUTF16(const utf16_t *utf16String) // IN { return Unicode_AllocWithLength(utf16String, -1, STRING_ENCODING_UTF16); } char *Unicode_Duplicate(const char *str); char **Unicode_AllocList(char **srcList, ssize_t length, StringEncoding encoding); char **Unicode_GetAllocList(char *const srcList[], ssize_t length, StringEncoding encoding); /* *----------------------------------------------------------------------------- * * Unicode_AllocListWithUTF16 -- * * Allocates a list (actually a vector) of Unicode strings from a list * (vector) of UTF-16 strings. The input list has a specified length or * can be an argv-style NULL-terminated list (if length is negative). * * Results: * An allocated list (vector) of Unicode strings. * The result must be freed with Util_FreeStringList. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char ** Unicode_AllocListWithUTF16(utf16_t **utf16list, // IN: ssize_t length) // IN: { return Unicode_AllocList((char **) utf16list, length, STRING_ENCODING_UTF16); } /* * Compute the number of bytes in a string. */ ssize_t Unicode_LengthInBytes(const void *buffer, StringEncoding encoding); /* * Gets the number of UTF-16 code units in the NUL-terminated UTF-16 array. */ ssize_t Unicode_UTF16Strlen(const utf16_t *utf16); /* * Duplicates a UTF-16 string. */ utf16_t *Unicode_UTF16Strdup(const utf16_t *utf16); /* * Tests if the buffer's bytes are valid in the specified encoding. */ Bool Unicode_IsBufferValid(const void *buffer, ssize_t lengthInBytes, StringEncoding encoding); Bool Unicode_IsStringValidUTF8(const char *str); /* * Tests if the buffer's unicode contents can be converted to the * specified encoding. */ Bool Unicode_CanGetBytesWithEncoding(const char *ustr, StringEncoding encoding); /* * Escape non-printable bytes of the buffer with \xAB, where 0xAB * is the non-printable byte value. */ char *Unicode_EscapeBuffer(const void *buffer, ssize_t lengthInBytes, StringEncoding encoding); /* * Returns the length in number of native code units (UTF-8 bytes or * UTF-16 words) of the string. */ UnicodeIndex Unicode_LengthInCodeUnits(const char *str); /* *----------------------------------------------------------------------------- * * Unicode_IsEmpty -- * * Test if the Unicode string is empty. * * Results: * TRUE if the string has length 0, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE Bool Unicode_IsEmpty(const char *str) // IN: { ASSERT(str != NULL); return str[0] == '\0'; } /* * Efficiently returns the upper bound on the number of bytes required * to encode the Unicode string in the specified encoding, including * NUL termination. */ size_t Unicode_BytesRequired(const char *str, StringEncoding encoding); /* * Extracts the contents of the Unicode string into a NUL-terminated * buffer using the specified encoding. Copies at most * maxLengthInBytes including NUL termination. Returns FALSE if * truncation occurred, TRUE otherwise. If retLength is not NULL, * *retLength holds the number of bytes actually copied, not including * the NUL termination, upon return. */ Bool Unicode_CopyBytes(void *destBuffer, const char *srcBuffer, size_t maxLengthInBytes, size_t *retLength, StringEncoding encoding); void *Unicode_GetAllocBytes(const char *str, StringEncoding encoding); void *Unicode_GetAllocBytesWithLength(const char *str, StringEncoding encoding, ssize_t lengthInBytes); /* *----------------------------------------------------------------------------- * * Unicode_GetAllocUTF16 -- * * Allocates and returns a NUL terminated buffer into which the contents * of the unicode string are extracted using the (host native) UTF-16 * encoding. (Note that UTF-16 NUL is two bytes: "\0\0".) * * NULL is returned for NULL argument. * * Results: * Pointer to the dynamically allocated memory, * or NULL on NULL argument. * * Caller is responsible to free the memory allocated by this routine. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE utf16_t * Unicode_GetAllocUTF16(const char *str) // IN: { /* Cast for compatibility with C++ compilers. */ return (utf16_t *) Unicode_GetAllocBytes(str, STRING_ENCODING_UTF16); } /* * Helper function for Unicode string literal macros. */ const char *Unicode_GetStatic(const char *asciiBytes, Bool unescape); /* * Helper macros for Win32 Unicode string transition. */ #if defined(_WIN32) #define UNICODE_GET_UTF16(s) Unicode_GetAllocUTF16(s) #define UNICODE_RELEASE_UTF16(s) free((utf16_t *)s) #endif #if defined(__cplusplus) } // extern "C" #endif #endif // _UNICODE_BASE_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/unicodeICU.h000066400000000000000000000056621321503522500246400ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2008-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * unicodeICU.h -- * * Unicode operations that depend on the third-party ICU support * library. */ #ifndef _UNICODE_ICU_H_ #define _UNICODE_ICU_H_ #define INCLUDE_ALLOW_USERLEVEL #ifndef USE_ICU #error These interfaces require the ICU library (define USE_ICU). #endif #include "includeCheck.h" #include "unicodeBase.h" #if defined(__cplusplus) extern "C" { #endif typedef enum { UNICODE_COMPARE_DEFAULT = 0, UNICODE_COMPARE_IGNORE_ACCENTS, UNICODE_COMPARE_IGNORE_CASE, UNICODE_COMPARE_IGNORE_PUNCTUATION } UnicodeCompareOption; /* * Different languages and cultures have unique rules for how strings * are compared and sorted. For example: * * Swedish: z < "o with umlaut" * German: "o with umlaut" < z * * When producing a result visible to the user (like a sorted list of * virtual machine names) string comparsion must obey the rules set by * the user's language and culture, collectively called the "locale". */ int Unicode_CompareWithLocale(const char *str1, const char *str2, const char *locale, UnicodeCompareOption compareOption); /* * Transforms the case of the string using the given locale's rules. * * Pass in a NULL locale to use the process's default locale. * * Changing the case of a string can change its length, so don't * assume the string is the same length after calling these functions. */ char *Unicode_ToLower(const char *str, const char *locale); char *Unicode_ToUpper(const char *str, const char *locale); #ifdef HAVE_ICU_38 char *Unicode_ToTitle(const char *str, const char *locale); #endif typedef enum { UNICODE_NORMAL_FORM_C, // "e with acute accent" -> U+00E9 UNICODE_NORMAL_FORM_D // "e with acute accent" -> U+0065 U+0302 } UnicodeNormalizationForm; /* * Normalizes Unicode characters composed of multiple parts into a * standard form. */ char *Unicode_Normalize(const char *str, UnicodeNormalizationForm form); #if defined(__cplusplus) } // extern "C" #endif #endif // _UNICODE_ICU_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/unicodeOperations.h000066400000000000000000000526631321503522500263460ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * unicodeOperations.h -- * * Basic Unicode string operations. * * UnicodeIndex index and length arguments are in terms of code * units, not characters. The size of a code unit depends on the * implementation (one byte for UTF-8, one 16-bit word for * UTF-16). Do not store these values on disk, modify them, or * do arithmetic operations on them. * * Instead of iterating over the code units in a string to do * character operations, use the library functions provided to * search and transform strings. * * If the functionality you need is not present, email the * i18n-dev mailing list. */ #ifndef _UNICODE_OPERATIONS_H_ #define _UNICODE_OPERATIONS_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include #include "unicodeBase.h" #include "vm_assert.h" #if defined(__cplusplus) extern "C" { #endif /* * Primitive operations. All other Unicode operations are implemented * in terms of these. * * Pass -1 for any length parameter to indicate "from start until end * of string". */ int Unicode_CompareRange(const char *str1, UnicodeIndex str1Start, UnicodeIndex str1Length, const char *str2, UnicodeIndex str2Start, UnicodeIndex str2Length, Bool ignoreCase); UnicodeIndex Unicode_FindSubstrInRange(const char *str, UnicodeIndex strStart, UnicodeIndex strLength, const char *strToFind, UnicodeIndex strToFindStart, UnicodeIndex strToFindLength); UnicodeIndex Unicode_FindLastSubstrInRange(const char *str, UnicodeIndex strStart, UnicodeIndex strLength, const char *strToFind, UnicodeIndex strToFindStart, UnicodeIndex strToFindLength); char *Unicode_Substr(const char *str, UnicodeIndex start, UnicodeIndex length); char *Unicode_ReplaceRange(const char *destination, UnicodeIndex destinationStart, UnicodeIndex destinationLength, const char *source, UnicodeIndex sourceStart, UnicodeIndex sourceLength); char *Unicode_Join(const char *first, ...); char *Unicode_Format(const char *fmt, ...); UnicodeIndex Unicode_LengthInCodePoints(const char *str); /* * Simple in-line functions that may be used below. */ /* *----------------------------------------------------------------------------- * * Unicode_IsIndexAtCodePointBoundary -- * * Check a string index (in bytes) for code point boundary. * * The index must be valid (>= 0 and <= string length). * The end of the string is considered a valid boundary. * * Results: * TRUE if index is at a code point boundary. * * Side effects: * Panic if index is not valid. * *----------------------------------------------------------------------------- */ static INLINE Bool Unicode_IsIndexAtCodePointBoundary(const char *str, // IN: UnicodeIndex index) // IN: { ASSERT(index >= 0 && index <= Unicode_LengthInCodeUnits(str)); return (str[index] & 0xc0) != 0x80; } /* * Other operations, each based upon calls to primitives. */ /* *----------------------------------------------------------------------------- * * Unicode_Append -- * * Allocates and returns a new string containing 'destination' * followed by 'source'. * * Results: * The newly-allocated string. Caller must free with free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_Append(const char *destination, // IN const char *source) // IN { return Unicode_ReplaceRange(destination, -1, 0, source, 0, -1); } /* *----------------------------------------------------------------------------- * * Unicode_AppendRange -- * * Allocates and returns a new string containing 'destination' * followed by the specified range of 'source'. * * Results: * The newly-allocated string. Caller must free with free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_AppendRange(const char *dest, // IN: const char *src, // IN: UnicodeIndex srcStart, // IN: UnicodeIndex srcLength) // IN: { return Unicode_ReplaceRange(dest, Unicode_LengthInCodePoints(dest), 0, src, srcStart, srcLength); } /* *----------------------------------------------------------------------------- * * Unicode_Compare -- * * Compares two Unicode strings for canonical equivalence in code * point order. * * If the result is to be visible in a user interface, use * Unicode_CompareWithLocale to support language and * culture-specific comparison and sorting rules. * * Results: * -1 if str1 < str2, 0 if str1 == str2, 1 if str1 > str2. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE int Unicode_Compare(const char *str1, // IN const char *str2) // IN { return Unicode_CompareRange(str1, 0, -1, str2, 0, -1, FALSE); } /* *----------------------------------------------------------------------------- * * Unicode_CompareIgnoreCase -- * * Compares two Unicode strings for case-insensitive canonical * equivalence in code point order. * * If the result is to be visible in a user interface, use * Unicode_CompareWithLocale to support language and * culture-specific comparison and sorting rules. * * Results: * -1 if str1 < str2, 0 if str1 == str2, 1 if str1 > str2. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE int Unicode_CompareIgnoreCase(const char *str1, // IN const char *str2) // IN { return Unicode_CompareRange(str1, 0, -1, str2, 0, -1, TRUE); } /* *----------------------------------------------------------------------------- * * UnicodeEndsWith -- * Unicode_EndsWith -- * Unicode_EndsWithIgnoreCase -- * * Tests if 'str' ends with 'suffix'. * * Results: * TRUE if 'str' ends with 'suffix', FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE Bool UnicodeEndsWith(const char *str, // IN: const char *suffix, // IN: Bool ignoreCase) // IN: { UnicodeIndex strLength = Unicode_LengthInCodePoints(str); UnicodeIndex suffixLength = Unicode_LengthInCodePoints(suffix); UnicodeIndex offset = strLength - suffixLength; if (suffixLength > strLength) { return FALSE; } return Unicode_CompareRange(str, offset, suffixLength, suffix, 0, suffixLength, ignoreCase) == 0; } static INLINE Bool Unicode_EndsWith(const char *str, // IN const char *suffix) // IN { return UnicodeEndsWith(str, suffix, FALSE); } static INLINE Bool Unicode_EndsWithIgnoreCase(const char *str, // IN const char *suffix) // IN { return UnicodeEndsWith(str, suffix, TRUE); } /* *----------------------------------------------------------------------------- * * Unicode_Find -- * * Finds the first occurrence of 'strToFind' inside 'str'. * * Results: * If 'strToFind' exists inside 'str', returns the first starting * index of 'strToFind' in that range. * * Otherwise, returns UNICODE_INDEX_NOT_FOUND. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE UnicodeIndex Unicode_Find(const char *str, // IN const char *strToFind) // IN { return Unicode_FindSubstrInRange(str, 0, -1, strToFind, 0, -1); } /* *----------------------------------------------------------------------------- * * Unicode_FindFromIndex -- * * Finds the first occurrence of 'strToFind' inside 'str' in the range * [fromIndex, lengthOfStr). * * Results: * If 'strToFind' exists inside 'str' in the specified range, * returns the first starting index of 'strToFind' in that range. * * Otherwise, returns UNICODE_INDEX_NOT_FOUND. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE UnicodeIndex Unicode_FindFromIndex(const char *str, // IN const char *strToFind, // IN UnicodeIndex fromIndex) // IN { return Unicode_FindSubstrInRange(str, fromIndex, -1, strToFind, 0, -1); } /* *----------------------------------------------------------------------------- * * Unicode_FindInRange -- * * Finds the first occurrence of 'strToFind' inside 'str' in the range * [start, start+length). * * Results: * If 'strToFind' exists inside 'str' in the specified range, * returns the first starting index of 'strToFind' in that range. * * Otherwise, returns UNICODE_INDEX_NOT_FOUND. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE UnicodeIndex Unicode_FindInRange(const char *str, // IN const char *strToFind, // IN UnicodeIndex start, // IN UnicodeIndex length) // IN { return Unicode_FindSubstrInRange(str, start, length, strToFind, 0, -1); } /* *----------------------------------------------------------------------------- * * Unicode_FindLast -- * * Finds the last occurrence of 'strToFind' inside 'str'. * * Results: * If 'strToFind' exists inside 'str', returns the last starting * index of 'strToFind' in that range. * * Otherwise, returns UNICODE_INDEX_NOT_FOUND. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE UnicodeIndex Unicode_FindLast(const char *str, // IN const char *strToFind) // IN { return Unicode_FindLastSubstrInRange(str, 0, -1, strToFind, 0, -1); } /* *----------------------------------------------------------------------------- * * Unicode_FindLastFromIndex -- * * Finds the last occurrence of 'strToFind' inside 'str' in the range * [fromIndex, lengthOfStr). * * Results: * If 'strToFind' exists inside 'str' in the specified range, * returns the last starting index of 'strToFind' in that range. * * Otherwise, returns UNICODE_INDEX_NOT_FOUND. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE UnicodeIndex Unicode_FindLastFromIndex(const char *str, // IN const char *strToFind, // IN UnicodeIndex fromIndex) // IN { return Unicode_FindLastSubstrInRange(str, fromIndex, -1, strToFind, 0, -1); } /* *----------------------------------------------------------------------------- * * Unicode_FindLastInRange -- * * Finds the last occurrence of 'strToFind' inside 'str' in the range * [start, start+length). * * Results: * If 'strToFind' exists inside 'str' in the specified range, * returns the last starting index of 'strToFind' in that range. * * Otherwise, returns UNICODE_INDEX_NOT_FOUND. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE UnicodeIndex Unicode_FindLastInRange(const char *str, // IN const char *strToFind, // IN UnicodeIndex start, // IN UnicodeIndex length) // IN { return Unicode_FindLastSubstrInRange(str, start, length, strToFind, 0, -1); } /* *----------------------------------------------------------------------------- * * Unicode_Insert -- * * Allocates and returns a new copy of 'destination', with the * string 'source' inserted at the index 'destinationStart'. * * Results: * The newly-allocated string. Caller must free with free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_Insert(const char *destination, // IN UnicodeIndex destinationStart, // IN const char *source) // IN { return Unicode_ReplaceRange(destination, destinationStart, 0, source, 0, -1); } /* *----------------------------------------------------------------------------- * * Unicode_InsertRange -- * * Allocates and returns a new copy of 'destination', with the * specified range of the string 'source' inserted at the index * 'destinationStart'. * * Results: * The newly-allocated string. Caller must free with free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_InsertRange(const char *destination, UnicodeIndex destinationStart, const char *source, UnicodeIndex sourceStart, UnicodeIndex sourceLength) { return Unicode_ReplaceRange(destination, destinationStart, 0, source, sourceStart, sourceLength); } /* *----------------------------------------------------------------------------- * * Unicode_IsEqual -- * * Tests two strings for canonical equivalence. * * Results: * TRUE if the two strings are canonically equivalent, FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE Bool Unicode_IsEqual(const char *str1, // IN const char *str2) // IN { return Unicode_CompareRange(str1, 0, -1, str2, 0, -1, FALSE) == 0; } /* *----------------------------------------------------------------------------- * * Unicode_RemoveRange -- * * Allocates and returns a new string that contains a copy of * 'destination' with the code units in the range [start, start + length) * removed. * * Results: * The newly-allocated string. Caller must free with free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_RemoveRange(const char *destination, UnicodeIndex start, UnicodeIndex length) { return Unicode_ReplaceRange(destination, start, length, "", 0, 0); } /* *----------------------------------------------------------------------------- * * Unicode_Replace -- * * Allocates and returns a new string that contains a copy of * 'destination' with the code units in the range * [destinationStart, destinarionStart + destinationLength) replaced * with 'source'. * * Results: * The newly-allocated string. Caller must free with free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_Replace(const char *destination, UnicodeIndex destinationStart, UnicodeIndex destinationLength, const char *source) { return Unicode_ReplaceRange(destination, destinationStart, destinationLength, source, 0, -1); } /* *----------------------------------------------------------------------------- * * UnicodeStartsWith -- * Unicode_StartsWith -- * Unicode_StartsWithIgnoreCase -- * * Tests if 'str' starts with 'prefix'. * * Results: * TRUE if 'str' starts with 'prefix', FALSE otherwise. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE Bool UnicodeStartsWith(const char *str, // IN: const char *prefix, // IN: Bool ignoreCase) // IN: { UnicodeIndex strLength = Unicode_LengthInCodePoints(str); UnicodeIndex prefixLength = Unicode_LengthInCodePoints(prefix); if (prefixLength > strLength) { return FALSE; } return Unicode_CompareRange(str, 0, prefixLength, prefix, 0, prefixLength, ignoreCase) == 0; } static INLINE Bool Unicode_StartsWith(const char *str, // IN const char *prefix) // IN { return UnicodeStartsWith(str, prefix, FALSE); } static INLINE Bool Unicode_StartsWithIgnoreCase(const char *str, // IN const char *prefix) // IN { return UnicodeStartsWith(str, prefix, TRUE); } /* *----------------------------------------------------------------------------- * * Unicode_Truncate -- * * Allocates and returns a new copy of 'str' truncated to the * specified length in code units. * * Results: * The newly-allocated truncated copy of 'str'. Caller must free * with free. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE char * Unicode_Truncate(const char *str, // IN UnicodeIndex length) // IN { return Unicode_Substr(str, 0, length); } #if defined(__cplusplus) } // extern "C" #endif #endif // _UNICODE_OPERATIONS_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/unicodeTransforms.h000066400000000000000000000034621321503522500263520ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * unicodeTransforms.h -- * * Operations that transform all the characters in a string. * * Transform operations like uppercase and lowercase are * locale-sensitive (depending on the user's country and language * preferences). */ #ifndef _UNICODE_TRANSFORMS_H_ #define _UNICODE_TRANSFORMS_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include "unicodeTypes.h" #if defined(__cplusplus) extern "C" { #endif /* * Standardizes the case of the string by doing a locale-agnostic * uppercase operation, then a locale-agnostic lowercase operation. */ char *Unicode_FoldCase(const char *str); /* * Trims whitespace from either side of the string. */ char *Unicode_Trim(const char *str); char *Unicode_TrimLeft(const char *str); char *Unicode_TrimRight(const char *str); #if defined(__cplusplus) } // extern "C" #endif #endif // _UNICODE_TRANSFORMS_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/unicodeTypes.h000066400000000000000000000330651321503522500253220ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * unicodeTypes.h -- * * Types used throughout the Unicode library. */ #ifndef _UNICODE_TYPES_H_ #define _UNICODE_TYPES_H_ #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #define INCLUDE_ALLOW_VMKERNEL #include "includeCheck.h" #include "vm_basic_types.h" #include "vm_assert.h" #if defined(__cplusplus) extern "C" { #endif typedef ssize_t UnicodeIndex; /* * Special UnicodeIndex value returned when a string is not found. */ enum { UNICODE_INDEX_NOT_FOUND = -1 }; /* * Encodings passed to convert encoded byte strings to and from * Unicode. * * Keep this enum synchronized with ICU_ENCODING_LIST in unicodeICU.cc! */ typedef enum { STRING_ENCODING_FIRST, /* * Byte string encodings that support all characters in Unicode. * * If you don't know what to use for bytes in a new system, use * STRING_ENCODING_UTF8. */ STRING_ENCODING_UTF8 = STRING_ENCODING_FIRST, STRING_ENCODING_UTF16_LE, // Little-endian UTF-16. STRING_ENCODING_UTF16_BE, // Big-endian UTF-16. STRING_ENCODING_UTF16_XE, // UTF-16 with BOM. STRING_ENCODING_UTF32_LE, // Little-endian UTF-32. STRING_ENCODING_UTF32_BE, // Big-endian UTF-32. STRING_ENCODING_UTF32_XE, // UTF-32 with BOM. /* * Legacy byte string encodings that only support a subset of Unicode. */ /* * Latin encodings */ STRING_ENCODING_US_ASCII, STRING_ENCODING_ISO_8859_1, STRING_ENCODING_ISO_8859_2, STRING_ENCODING_ISO_8859_3, STRING_ENCODING_ISO_8859_4, STRING_ENCODING_ISO_8859_5, STRING_ENCODING_ISO_8859_6, STRING_ENCODING_ISO_8859_7, STRING_ENCODING_ISO_8859_8, STRING_ENCODING_ISO_8859_9, STRING_ENCODING_ISO_8859_10, // ISO-8859-11 is unused. // Oddly, there is no ISO-8859-12. STRING_ENCODING_ISO_8859_13, STRING_ENCODING_ISO_8859_14, STRING_ENCODING_ISO_8859_15, /* * Chinese encodings */ STRING_ENCODING_GB_18030, STRING_ENCODING_BIG_5, STRING_ENCODING_BIG_5_HK, STRING_ENCODING_GBK, STRING_ENCODING_GB_2312, STRING_ENCODING_ISO_2022_CN, /* * Japanese encodings */ STRING_ENCODING_SHIFT_JIS, STRING_ENCODING_EUC_JP, STRING_ENCODING_ISO_2022_JP, STRING_ENCODING_ISO_2022_JP_1, STRING_ENCODING_ISO_2022_JP_2, /* * Korean encodings */ STRING_ENCODING_ISO_2022_KR, /* * Windows encodings */ STRING_ENCODING_WINDOWS_1250, STRING_ENCODING_WINDOWS_1251, STRING_ENCODING_WINDOWS_1252, STRING_ENCODING_WINDOWS_1253, STRING_ENCODING_WINDOWS_1254, STRING_ENCODING_WINDOWS_1255, STRING_ENCODING_WINDOWS_1256, STRING_ENCODING_WINDOWS_1257, STRING_ENCODING_WINDOWS_1258, STRING_ENCODING_ISO_6937_2_ADD, STRING_ENCODING_JIS_X0201, STRING_ENCODING_JIS_ENCODING, STRING_ENCODING_EXTENDED_UNIX_CODE_FIXED_WIDTH_FOR_JAPANESE, STRING_ENCODING_BS_4730, STRING_ENCODING_SEN_850200_C, STRING_ENCODING_IT, STRING_ENCODING_ES, STRING_ENCODING_DIN_66003, STRING_ENCODING_NS_4551_1, STRING_ENCODING_NF_Z_62_010, STRING_ENCODING_ISO_10646_UTF_1, STRING_ENCODING_ISO_646_BASIC_1983, STRING_ENCODING_INVARIANT, STRING_ENCODING_ISO_646_IRV_1983, STRING_ENCODING_NATS_SEFI, STRING_ENCODING_NATS_SEFI_ADD, STRING_ENCODING_NATS_DANO, STRING_ENCODING_NATS_DANO_ADD, STRING_ENCODING_SEN_850200_B, STRING_ENCODING_KS_C_5601_1987, STRING_ENCODING_JIS_C6220_1969_JP, STRING_ENCODING_JIS_C6220_1969_RO, STRING_ENCODING_PT, STRING_ENCODING_GREEK7_OLD, STRING_ENCODING_LATIN_GREEK, STRING_ENCODING_NF_Z_62_010__1973_, STRING_ENCODING_LATIN_GREEK_1, STRING_ENCODING_ISO_5427, STRING_ENCODING_JIS_C6226_1978, STRING_ENCODING_BS_VIEWDATA, STRING_ENCODING_INIS, STRING_ENCODING_INIS_8, STRING_ENCODING_INIS_CYRILLIC, STRING_ENCODING_ISO_5427_1981, STRING_ENCODING_ISO_5428_1980, STRING_ENCODING_GB_1988_80, STRING_ENCODING_GB_2312_80, STRING_ENCODING_NS_4551_2, STRING_ENCODING_VIDEOTEX_SUPPL, STRING_ENCODING_PT2, STRING_ENCODING_ES2, STRING_ENCODING_MSZ_7795_3, STRING_ENCODING_JIS_C6226_1983, STRING_ENCODING_GREEK7, STRING_ENCODING_ASMO_449, STRING_ENCODING_ISO_IR_90, STRING_ENCODING_JIS_C6229_1984_A, STRING_ENCODING_JIS_C6229_1984_B, STRING_ENCODING_JIS_C6229_1984_B_ADD, STRING_ENCODING_JIS_C6229_1984_HAND, STRING_ENCODING_JIS_C6229_1984_HAND_ADD, STRING_ENCODING_JIS_C6229_1984_KANA, STRING_ENCODING_ISO_2033_1983, STRING_ENCODING_ANSI_X3_110_1983, STRING_ENCODING_T_61_7BIT, STRING_ENCODING_T_61_8BIT, STRING_ENCODING_ECMA_CYRILLIC, STRING_ENCODING_CSA_Z243_4_1985_1, STRING_ENCODING_CSA_Z243_4_1985_2, STRING_ENCODING_CSA_Z243_4_1985_GR, STRING_ENCODING_ISO_8859_6_E, STRING_ENCODING_ISO_8859_6_I, STRING_ENCODING_T_101_G2, STRING_ENCODING_ISO_8859_8_E, STRING_ENCODING_ISO_8859_8_I, STRING_ENCODING_CSN_369103, STRING_ENCODING_JUS_I_B1_002, STRING_ENCODING_IEC_P27_1, STRING_ENCODING_JUS_I_B1_003_SERB, STRING_ENCODING_JUS_I_B1_003_MAC, STRING_ENCODING_GREEK_CCITT, STRING_ENCODING_NC_NC00_10_81, STRING_ENCODING_ISO_6937_2_25, STRING_ENCODING_GOST_19768_74, STRING_ENCODING_ISO_8859_SUPP, STRING_ENCODING_ISO_10367_BOX, STRING_ENCODING_LATIN_LAP, STRING_ENCODING_JIS_X0212_1990, STRING_ENCODING_DS_2089, STRING_ENCODING_US_DK, STRING_ENCODING_DK_US, STRING_ENCODING_KSC5636, STRING_ENCODING_UNICODE_1_1_UTF_7, STRING_ENCODING_ISO_2022_CN_EXT, STRING_ENCODING_ISO_8859_16, STRING_ENCODING_OSD_EBCDIC_DF04_15, STRING_ENCODING_OSD_EBCDIC_DF03_IRV, STRING_ENCODING_OSD_EBCDIC_DF04_1, STRING_ENCODING_ISO_11548_1, STRING_ENCODING_KZ_1048, STRING_ENCODING_ISO_10646_UCS_2, STRING_ENCODING_ISO_10646_UCS_4, STRING_ENCODING_ISO_10646_UCS_BASIC, STRING_ENCODING_ISO_10646_UNICODE_LATIN1, STRING_ENCODING_ISO_10646_J_1, STRING_ENCODING_ISO_UNICODE_IBM_1261, STRING_ENCODING_ISO_UNICODE_IBM_1268, STRING_ENCODING_ISO_UNICODE_IBM_1276, STRING_ENCODING_ISO_UNICODE_IBM_1264, STRING_ENCODING_ISO_UNICODE_IBM_1265, STRING_ENCODING_UNICODE_1_1, STRING_ENCODING_SCSU, STRING_ENCODING_UTF_7, STRING_ENCODING_CESU_8, STRING_ENCODING_BOCU_1, STRING_ENCODING_ISO_8859_1_WINDOWS_3_0_LATIN_1, STRING_ENCODING_ISO_8859_1_WINDOWS_3_1_LATIN_1, STRING_ENCODING_ISO_8859_2_WINDOWS_LATIN_2, STRING_ENCODING_ISO_8859_9_WINDOWS_LATIN_5, STRING_ENCODING_HP_ROMAN8, STRING_ENCODING_ADOBE_STANDARD_ENCODING, STRING_ENCODING_VENTURA_US, STRING_ENCODING_VENTURA_INTERNATIONAL, STRING_ENCODING_DEC_MCS, STRING_ENCODING_IBM_850, STRING_ENCODING_PC8_DANISH_NORWEGIAN, STRING_ENCODING_IBM_862, STRING_ENCODING_PC8_TURKISH, STRING_ENCODING_IBM_SYMBOLS, STRING_ENCODING_IBM_THAI, STRING_ENCODING_HP_LEGAL, STRING_ENCODING_HP_PI_FONT, STRING_ENCODING_HP_MATH8, STRING_ENCODING_ADOBE_SYMBOL_ENCODING, STRING_ENCODING_HP_DESKTOP, STRING_ENCODING_VENTURA_MATH, STRING_ENCODING_MICROSOFT_PUBLISHING, STRING_ENCODING_WINDOWS_31J, STRING_ENCODING_MACINTOSH, STRING_ENCODING_IBM_037, STRING_ENCODING_IBM_038, STRING_ENCODING_IBM_273, STRING_ENCODING_IBM_274, STRING_ENCODING_IBM_275, STRING_ENCODING_IBM_277, STRING_ENCODING_IBM_278, STRING_ENCODING_IBM_280, STRING_ENCODING_IBM_281, STRING_ENCODING_IBM_284, STRING_ENCODING_IBM_285, STRING_ENCODING_IBM_290, STRING_ENCODING_IBM_297, STRING_ENCODING_IBM_420, STRING_ENCODING_IBM_423, STRING_ENCODING_IBM_424, STRING_ENCODING_IBM_437, STRING_ENCODING_IBM_500, STRING_ENCODING_IBM_851, STRING_ENCODING_IBM_852, STRING_ENCODING_IBM_855, STRING_ENCODING_IBM_857, STRING_ENCODING_IBM_860, STRING_ENCODING_IBM_861, STRING_ENCODING_IBM_863, STRING_ENCODING_IBM_864, STRING_ENCODING_IBM_865, STRING_ENCODING_IBM_868, STRING_ENCODING_IBM_869, STRING_ENCODING_IBM_870, STRING_ENCODING_IBM_871, STRING_ENCODING_IBM_880, STRING_ENCODING_IBM_891, STRING_ENCODING_IBM_903, STRING_ENCODING_IBM_904, STRING_ENCODING_IBM_905, STRING_ENCODING_IBM_918, STRING_ENCODING_IBM_1026, STRING_ENCODING_EBCDIC_AT_DE, STRING_ENCODING_EBCDIC_AT_DE_A, STRING_ENCODING_EBCDIC_CA_FR, STRING_ENCODING_EBCDIC_DK_NO, STRING_ENCODING_EBCDIC_DK_NO_A, STRING_ENCODING_EBCDIC_FI_SE, STRING_ENCODING_EBCDIC_FI_SE_A, STRING_ENCODING_EBCDIC_FR, STRING_ENCODING_EBCDIC_IT, STRING_ENCODING_EBCDIC_PT, STRING_ENCODING_EBCDIC_ES, STRING_ENCODING_EBCDIC_ES_A, STRING_ENCODING_EBCDIC_ES_S, STRING_ENCODING_EBCDIC_UK, STRING_ENCODING_EBCDIC_US, STRING_ENCODING_UNKNOWN_8BIT, STRING_ENCODING_MNEMONIC, STRING_ENCODING_MNEM, STRING_ENCODING_VISCII, STRING_ENCODING_VIQR, STRING_ENCODING_KOI8_R, STRING_ENCODING_HZ_GB_2312, STRING_ENCODING_IBM_866, STRING_ENCODING_IBM_775, STRING_ENCODING_KOI8_U, STRING_ENCODING_IBM_00858, STRING_ENCODING_IBM_00924, STRING_ENCODING_IBM_01140, STRING_ENCODING_IBM_01141, STRING_ENCODING_IBM_01142, STRING_ENCODING_IBM_01143, STRING_ENCODING_IBM_01144, STRING_ENCODING_IBM_01145, STRING_ENCODING_IBM_01146, STRING_ENCODING_IBM_01147, STRING_ENCODING_IBM_01148, STRING_ENCODING_IBM_01149, STRING_ENCODING_IBM_1047, STRING_ENCODING_PTCP154, STRING_ENCODING_AMIGA_1251, STRING_ENCODING_KOI7_SWITCHED, STRING_ENCODING_BRF, STRING_ENCODING_TSCII, STRING_ENCODING_TIS_620, STRING_ENCODING_WINDOWS_709, STRING_ENCODING_WINDOWS_710, STRING_ENCODING_WINDOWS_720, STRING_ENCODING_WINDOWS_737, STRING_ENCODING_WINDOWS_875, STRING_ENCODING_WINDOWS_1361, STRING_ENCODING_WINDOWS_10000, STRING_ENCODING_WINDOWS_10001, STRING_ENCODING_WINDOWS_10002, STRING_ENCODING_WINDOWS_10003, STRING_ENCODING_WINDOWS_10004, STRING_ENCODING_WINDOWS_10005, STRING_ENCODING_WINDOWS_10006, STRING_ENCODING_WINDOWS_10007, STRING_ENCODING_WINDOWS_10008, STRING_ENCODING_WINDOWS_10010, STRING_ENCODING_WINDOWS_10017, STRING_ENCODING_WINDOWS_10021, STRING_ENCODING_WINDOWS_10029, STRING_ENCODING_WINDOWS_10079, STRING_ENCODING_WINDOWS_10081, STRING_ENCODING_WINDOWS_10082, STRING_ENCODING_WINDOWS_20000, STRING_ENCODING_WINDOWS_20001, STRING_ENCODING_WINDOWS_20002, STRING_ENCODING_WINDOWS_20003, STRING_ENCODING_WINDOWS_20004, STRING_ENCODING_WINDOWS_20005, STRING_ENCODING_WINDOWS_20105, STRING_ENCODING_WINDOWS_20106, STRING_ENCODING_WINDOWS_20107, STRING_ENCODING_WINDOWS_20108, STRING_ENCODING_WINDOWS_20269, STRING_ENCODING_WINDOWS_20833, STRING_ENCODING_WINDOWS_20949, STRING_ENCODING_WINDOWS_21025, STRING_ENCODING_WINDOWS_21027, STRING_ENCODING_WINDOWS_29001, STRING_ENCODING_WINDOWS_38598, STRING_ENCODING_WINDOWS_50221, STRING_ENCODING_WINDOWS_50222, STRING_ENCODING_WINDOWS_50229, STRING_ENCODING_WINDOWS_50930, STRING_ENCODING_WINDOWS_50931, STRING_ENCODING_WINDOWS_50933, STRING_ENCODING_WINDOWS_50935, STRING_ENCODING_WINDOWS_50936, STRING_ENCODING_WINDOWS_50937, STRING_ENCODING_WINDOWS_50939, STRING_ENCODING_WINDOWS_51936, STRING_ENCODING_WINDOWS_51950, STRING_ENCODING_WINDOWS_57002, STRING_ENCODING_WINDOWS_57003, STRING_ENCODING_WINDOWS_57004, STRING_ENCODING_WINDOWS_57005, STRING_ENCODING_WINDOWS_57006, STRING_ENCODING_WINDOWS_57007, STRING_ENCODING_WINDOWS_57008, STRING_ENCODING_WINDOWS_57009, STRING_ENCODING_WINDOWS_57010, STRING_ENCODING_WINDOWS_57011, STRING_ENCODING_IBM_813, STRING_ENCODING_IBM_943_P130_1999, STRING_ENCODING_IBM_33722, STRING_ENCODING_WINDOWS_949, STRING_ENCODING_IBM_1363, STRING_ENCODING_IBM_1386, STRING_ENCODING_IBM_1373, STRING_ENCODING_IBM_5471, STRING_ENCODING_IBM_874, // Add more encodings here. // Sentinel value after the last explicitly specified encoding. STRING_ENCODING_MAX_SPECIFIED, /* * The environment-specified "default" encoding for this process. */ STRING_ENCODING_DEFAULT = -1, STRING_ENCODING_UNKNOWN = -2, /* * UTF-16 and UTF-32 in native byte order. */ STRING_ENCODING_UTF16 = STRING_ENCODING_UTF16_LE, STRING_ENCODING_UTF32 = STRING_ENCODING_UTF32_LE, } StringEncoding; const char *Unicode_EncodingEnumToName(StringEncoding encoding); StringEncoding Unicode_EncodingNameToEnum(const char *encodingName); Bool Unicode_IsEncodingValid(StringEncoding encoding); void Unicode_Init(int argc, char ***argv, char ***envp); void Unicode_InitEx(int argc, char ***argv, char ***envp, const char *icuDataDir); #if defined (_WIN32) void Unicode_InitW(int argc, utf16_t **wargv, utf16_t **wenvp, char ***argv, char ***envp); #endif StringEncoding Unicode_GetCurrentEncoding(void); StringEncoding Unicode_ResolveEncoding(StringEncoding encoding); #if defined(__cplusplus) } // extern "C" #endif #endif // _UNICODE_TYPES_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/userlock.h000066400000000000000000000253411321503522500244740ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2009-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _USERLOCK_H_ #define _USERLOCK_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #include "vm_atomic.h" #include "vm_basic_types.h" #include "vm_basic_defs.h" #include "mutexRank.h" #include "vthreadBase.h" #if defined(__cplusplus) extern "C" { #endif typedef struct MXUserExclLock MXUserExclLock; typedef struct MXUserRecLock MXUserRecLock; typedef struct MXUserRWLock MXUserRWLock; typedef struct MXUserRankLock MXUserRankLock; typedef struct MXUserCondVar MXUserCondVar; typedef struct MXUserSemaphore MXUserSemaphore; typedef struct MXUserEvent MXUserEvent; typedef struct MXUserBarrier MXUserBarrier; /* * Exclusive ownership lock */ MXUserExclLock *MXUser_CreateExclLock(const char *name, MX_Rank rank); void MXUser_AcquireExclLock(MXUserExclLock *lock); Bool MXUser_TryAcquireExclLock(MXUserExclLock *lock); void MXUser_ReleaseExclLock(MXUserExclLock *lock); void MXUser_DestroyExclLock(MXUserExclLock *lock); Bool MXUser_IsCurThreadHoldingExclLock(MXUserExclLock *lock); /* Use only when necessary */ MXUserExclLock *MXUser_CreateSingletonExclLockInt(Atomic_Ptr *lockStorage, const char *name, MX_Rank rank); /* This is the public interface */ static INLINE MXUserExclLock * MXUser_CreateSingletonExclLock(Atomic_Ptr *lockStorage, const char *name, MX_Rank rank) { MXUserExclLock *lock; ASSERT(lockStorage); lock = (MXUserExclLock *) Atomic_ReadPtr(lockStorage); if (UNLIKELY(lock == NULL)) { lock = MXUser_CreateSingletonExclLockInt(lockStorage, name, rank); } return lock; } MXUserCondVar *MXUser_CreateCondVarExclLock(MXUserExclLock *lock); void MXUser_WaitCondVarExclLock(MXUserExclLock *lock, MXUserCondVar *condVar); void MXUser_TimedWaitCondVarExclLock(MXUserExclLock *lock, MXUserCondVar *condVar, uint32 waitTimeMsec); Bool MXUser_EnableStatsExclLock(MXUserExclLock *lock, Bool trackAcquisitionTime, Bool trackHeldTime); Bool MXUser_DisableStatsExclLock(MXUserExclLock *lock); Bool MXUser_SetContentionRatioFloorExclLock(MXUserExclLock *lock, double ratio); Bool MXUser_SetContentionCountFloorExclLock(MXUserExclLock *lock, uint64 count); Bool MXUser_SetContentionDurationFloorExclLock(MXUserExclLock *lock, uint64 count); /* * Recursive lock. */ MXUserRecLock *MXUser_CreateRecLock(const char *name, MX_Rank rank); void MXUser_AcquireRecLock(MXUserRecLock *lock); Bool MXUser_TryAcquireRecLock(MXUserRecLock *lock); void MXUser_ReleaseRecLock(MXUserRecLock *lock); void MXUser_DestroyRecLock(MXUserRecLock *lock); Bool MXUser_IsCurThreadHoldingRecLock(MXUserRecLock *lock); /* Use only when necessary */ MXUserRecLock *MXUser_CreateSingletonRecLockInt(Atomic_Ptr *lockStorage, const char *name, MX_Rank rank); /* This is the public interface */ static INLINE MXUserRecLock * MXUser_CreateSingletonRecLock(Atomic_Ptr *lockStorage, const char *name, MX_Rank rank) { MXUserRecLock *lock; ASSERT(lockStorage); lock = (MXUserRecLock *) Atomic_ReadPtr(lockStorage); if (UNLIKELY(lock == NULL)) { lock = MXUser_CreateSingletonRecLockInt(lockStorage, name, rank); } return lock; } void MXUser_DumpRecLock(MXUserRecLock *lock); MXUserCondVar *MXUser_CreateCondVarRecLock(MXUserRecLock *lock); void MXUser_WaitCondVarRecLock(MXUserRecLock *lock, MXUserCondVar *condVar); void MXUser_TimedWaitCondVarRecLock(MXUserRecLock *lock, MXUserCondVar *condVar, uint32 waitTimeMsec); void MXUser_IncRefRecLock(MXUserRecLock *lock); void MXUser_DecRefRecLock(MXUserRecLock *lock); Bool MXUser_EnableStatsRecLock(MXUserRecLock *lock, Bool trackAcquisitionTime, Bool trackHeldTime); Bool MXUser_DisableStatsRecLock(MXUserRecLock *lock); Bool MXUser_SetContentionRatioFloorRecLock(MXUserRecLock *lock, double ratio); Bool MXUser_SetContentionCountFloorRecLock(MXUserRecLock *lock, uint64 count); Bool MXUser_SetContentionDurationFloorRecLock(MXUserRecLock *lock, uint64 count); /* * Read-write lock */ MXUserRWLock *MXUser_CreateRWLock(const char *name, MX_Rank rank); void MXUser_AcquireForRead(MXUserRWLock *lock); void MXUser_AcquireForWrite(MXUserRWLock *lock); void MXUser_ReleaseRWLock(MXUserRWLock *lock); void MXUser_DestroyRWLock(MXUserRWLock *lock); #define MXUSER_RW_FOR_READ 0 #define MXUSER_RW_FOR_WRITE 1 #define MXUSER_RW_LOCKED 2 Bool MXUser_IsCurThreadHoldingRWLock(MXUserRWLock *lock, uint32 queryType); /* Use only when necessary */ MXUserRWLock *MXUser_CreateSingletonRWLockInt(Atomic_Ptr *lockStorage, const char *name, MX_Rank rank); /* This is the public interface */ static INLINE MXUserRWLock * MXUser_CreateSingletonRWLock(Atomic_Ptr *lockStorage, const char *name, MX_Rank rank) { MXUserRWLock *lock; ASSERT(lockStorage); lock = (MXUserRWLock *) Atomic_ReadPtr(lockStorage); if (UNLIKELY(lock == NULL)) { lock = MXUser_CreateSingletonRWLockInt(lockStorage, name, rank); } return lock; } /* * Stateful auto-reset event */ MXUserEvent *MXUser_CreateEvent(const char *name, MX_Rank rank); void MXUser_SignalEvent(MXUserEvent *event); void MXUser_WaitEvent(MXUserEvent *event); Bool MXUser_TryWaitEvent(MXUserEvent *event); PollDevHandle MXUser_GetHandleForEvent(MXUserEvent *event); void MXUser_DestroyEvent(MXUserEvent *event); MXUserEvent *MXUser_CreateSingletonEvent(Atomic_Ptr *eventStorage, const char *name, MX_Rank rank); /* * Computational barrier */ MXUserBarrier *MXUser_CreateBarrier(const char *name, MX_Rank rank, uint32 count); void MXUser_DestroyBarrier(MXUserBarrier *barrier); void MXUser_EnterBarrier(MXUserBarrier *barrier); MXUserBarrier *MXUser_CreateSingletonBarrier(Atomic_Ptr *barrierStorage, const char *name, MX_Rank rank, uint32 count); /* * Counting semaphore */ MXUserSemaphore *MXUser_CreateSemaphore(const char *name, MX_Rank rank); void MXUser_DestroySemaphore(MXUserSemaphore *sema); void MXUser_UpSemaphore(MXUserSemaphore *sema); void MXUser_DownSemaphore(MXUserSemaphore *sema); Bool MXUser_TryDownSemaphore(MXUserSemaphore *sema); Bool MXUser_TimedDownSemaphore(MXUserSemaphore *sema, uint32 waitTimeMsec); MXUserSemaphore *MXUser_CreateSingletonSemaphore(Atomic_Ptr *semaStorage, const char *name, MX_Rank rank); /* * Rank lock * * Rank "locks" are entities that perform rank checking but do not provide * any form of mutual exclusion. Their main use is for protecting certain * situations involving Poll and friends/enemies. */ MXUserRankLock *MXUser_CreateRankLock(const char *name, MX_Rank rank); void MXUser_AcquireRankLock(MXUserRankLock *lock); void MXUser_ReleaseRankLock(MXUserRankLock *lock); void MXUser_DestroyRankLock(MXUserRankLock *lock); /* * Generic conditional variable functions. */ #define MXUSER_WAIT_INFINITE 0xFFFFFFFF void MXUser_SignalCondVar(MXUserCondVar *condVar); void MXUser_BroadcastCondVar(MXUserCondVar *condVar); void MXUser_DestroyCondVar(MXUserCondVar *condVar); void MXUser_LockingTreeCollection(Bool enabled); Bool MXUser_IsLockingTreeAvailable(void); void MXUser_DumpLockTree(const char *fileName, const char *timeStamp); void MXUser_EmptyLockTree(void); #if defined(VMX86_DEBUG) && !defined(DISABLE_MXUSER_DEBUG) #define MXUSER_DEBUG // debugging "everywhere" when requested #endif #if defined(MXUSER_DEBUG) void MXUser_TryAcquireFailureControl(Bool (*func)(const char *lockName)); Bool MXUser_IsCurThreadHoldingLocks(void); #endif void MXUser_StatisticsControl(double contentionRatioFloor, uint64 minAccessCountFloor, uint64 contentionDurationFloor); void MXUser_PerLockData(void); void MXUser_SetStatsFunc(void *context, uint32 maxLineLength, Bool trackHeldTime, void (*statsFunc)(void *context, const char *fmt, va_list ap)); void MXUser_SetInPanic(void); Bool MXUser_InPanic(void); struct MX_MutexRec; MXUserRecLock *MXUser_BindMXMutexRec(struct MX_MutexRec *mutex, MX_Rank rank); struct MX_MutexRec *MXUser_GetRecLockVmm(MXUserRecLock *lock); MX_Rank MXUser_GetRecLockRank(MXUserRecLock *lock); #if defined(__cplusplus) } // extern "C" #endif #endif // _USERLOCK_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/util.h000066400000000000000000000303641321503522500236230ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * util.h -- * * misc util functions */ #ifndef UTIL_H #define UTIL_H #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #include #ifndef VMKBOOT #include #endif #ifdef _WIN32 #ifdef USERLEVEL #include /* Needed for MBCS string functions */ #include /* for definition of HANDLE */ #endif #else #include #include #include "errno.h" #endif #include "vm_assert.h" #include "vm_basic_defs.h" #include "unicodeTypes.h" #include "utilZero.h" #if defined(__cplusplus) extern "C" { #endif uint32 CRC_Compute(const uint8 *buf, int len); uint32 Util_Checksum32(const uint32 *buf, int len); uint32 Util_Checksum(const uint8 *buf, int len); uint32 Util_Checksumv(void *iov, int numEntries); uint32 Util_HashString(const char *str); char *Util_ExpandString(const char *fileName); void Util_ExitThread(int); NORETURN void Util_ExitProcessAbruptly(int); int Util_HasAdminPriv(void); #if defined _WIN32 && defined USERLEVEL int Util_TokenHasAdminPriv(HANDLE token); #endif Bool Util_Data2Buffer(char *buf, size_t bufSize, const void *data0, size_t dataSize); char *Util_GetCanonicalPath(const char *path); #ifdef _WIN32 char *Util_CompatGetCanonicalPath(const char *path); char *Util_GetCanonicalPathForHash(const char *path); char *Util_CompatGetLowerCaseCanonicalPath(const char* path); #endif int Util_BumpNoFds(uint32 *cur, uint32 *wanted); Bool Util_CanonicalPathsIdentical(const char *path1, const char *path2); Bool Util_IsAbsolutePath(const char *path); char *Util_DeriveFileName(const char *source, const char *name, const char *ext); typedef struct UtilSingleUseResource UtilSingleUseResource; UtilSingleUseResource *Util_SingleUseAcquire(const char *name); void Util_SingleUseRelease(UtilSingleUseResource *res); #ifndef _WIN32 Bool Util_IPv4AddrValid(const char *addr); Bool Util_IPv6AddrValid(const char *addr); Bool Util_IPAddrValid(const char *addr); #endif #if defined(__linux__) || defined(__FreeBSD__) || defined(sun) Bool Util_GetProcessName(pid_t pid, char *bufOut, size_t bufOutSize); #endif #if defined __linux__ && !defined VMX86_SERVER Bool Util_IsPhysicalSSD(const char* device); #endif // backtrace functions and utilities #define UTIL_BACKTRACE_LINE_LEN (511) typedef void (*Util_OutputFunc)(void *data, const char *fmt, ...); void Util_Backtrace(int bugNr); void Util_BacktraceFromPointer(uintptr_t *basePtr); void Util_BacktraceFromPointerWithFunc(uintptr_t *basePtr, Util_OutputFunc outFunc, void *outFuncData); void Util_BacktraceWithFunc(int bugNr, Util_OutputFunc outFunc, void *outFuncData); void Util_BacktraceToBuffer(uintptr_t *basePtr, uintptr_t *buffer, int len); // sleep functions void Util_Usleep(long usec); void Util_Sleep(unsigned int sec); int Util_CompareDotted(const char *s1, const char *s2); /* * This enum defines how Util_GetOpt should handle non-option arguments: * * UTIL_NONOPT_PERMUTE: Permute argv so that all non-options are at the end. * UTIL_NONOPT_STOP: Stop when first non-option argument is seen. (This is * the standard POSIX behavior.) * UTIL_NONOPT_ALL: Return each non-option argument as if it were * an option with character code 1. */ typedef enum { UTIL_NONOPT_PERMUTE, UTIL_NONOPT_STOP, UTIL_NONOPT_ALL } Util_NonOptMode; struct option; int Util_GetOpt(int argc, char * const *argv, const struct option *opts, Util_NonOptMode mode, Bool manualErrorHandling); #if defined(VMX86_STATS) Bool Util_QueryCStResidency(uint32 *numCpus, uint32 *numCStates, uint64 **transitns, uint64 **residency, uint64 **transTime, uint64 **residTime); #endif #define UTIL_FASTRAND_SEED_MAX (0x7fffffff) Bool Util_Throttle(uint32 count); uint32 Util_FastRand(uint32 seed); // Not thread safe! void Util_OverrideHomeDir(const char *path); Bool Util_MakeSureDirExistsAndAccessible(char const *path, unsigned int mode); #if _WIN32 # define DIRSEPS "\\" # define DIRSEPS_W L"\\" # define DIRSEPC '\\' # define DIRSEPC_W L'\\' # define VALID_DIRSEPS "\\/" # define VALID_DIRSEPS_W L"\\/" # define CUR_DIRS_W L"." # define CUR_DIRC_W L'.' #else # define DIRSEPS "/" # define DIRSEPC '/' # define VALID_DIRSEPS DIRSEPS #endif #define CURR_DIRS "." #define CURR_DIRC '.' /* *----------------------------------------------------------------------- * * Util_Safe[Malloc, Realloc, Calloc, Strdup] and * Util_Safe[Malloc, Realloc, Calloc, Strdup]Bug -- * * These functions work just like the standard C library functions * (except Util_SafeStrdup[,Bug]() accept NULL, see below), * but will not fail. Instead they Panic(), printing the file and * line number of the caller, if the underlying library function * fails. The Util_SafeFnBug functions print bugNumber in the * Panic() message. * * These functions should only be used when there is no way to * gracefully recover from the error condition. * * The internal versions of these functions expect a bug number * as the first argument. If that bug number is something other * than -1, the panic message will include the bug number. * * Since Util_SafeStrdup[,Bug]() do not need to return NULL * on error, they have been extended to accept the null pointer * (and return it). The competing view is that they should * panic on NULL. This is a convenience vs. strictness argument. * Convenience wins. -- edward * * Results: * The freshly allocated memory. * * Side effects: * Panic() if the library function fails. * *-------------------------------------------------------------------------- */ void *UtilSafeMalloc0(size_t size); void *UtilSafeMalloc1(size_t size, int bugNumber, const char *file, int lineno); void *UtilSafeRealloc0(void *ptr, size_t size); void *UtilSafeRealloc1(void *ptr, size_t size, int bugNumber, const char *file, int lineno); void *UtilSafeCalloc0(size_t nmemb, size_t size); void *UtilSafeCalloc1(size_t nmemb, size_t size, int bugNumber, const char *file, int lineno); char *UtilSafeStrdup0(const char *s); char *UtilSafeStrdup1(const char *s, int bugNumber, const char *file, int lineno); char *UtilSafeStrndup0(const char *s, size_t n); char *UtilSafeStrndup1(const char *s, size_t n, int bugNumber, const char *file, int lineno); /* * Debug builds carry extra arguments into the allocation functions for * better error reporting. Non-debug builds don't pay this extra overhead. */ #ifdef VMX86_DEBUG #define Util_SafeMalloc(_size) \ UtilSafeMalloc1((_size), -1, __FILE__, __LINE__) #define Util_SafeMallocBug(_bugNr, _size) \ UtilSafeMalloc1((_size),(_bugNr), __FILE__, __LINE__) #define Util_SafeRealloc(_ptr, _size) \ UtilSafeRealloc1((_ptr), (_size), -1, __FILE__, __LINE__) #define Util_SafeReallocBug(_bugNr, _ptr, _size) \ UtilSafeRealloc1((_ptr), (_size), (_bugNr), __FILE__, __LINE__) #define Util_SafeCalloc(_nmemb, _size) \ UtilSafeCalloc1((_nmemb), (_size), -1, __FILE__, __LINE__) #define Util_SafeCallocBug(_bugNr, _nmemb, _size) \ UtilSafeCalloc1((_nmemb), (_size), (_bugNr), __FILE__, __LINE__) #define Util_SafeStrndup(_str, _size) \ UtilSafeStrndup1((_str), (_size), -1, __FILE__, __LINE__) #define Util_SafeStrndupBug(_bugNr, _str, _size) \ UtilSafeStrndup1((_str), (_size), (_bugNr), __FILE__, __LINE__) #define Util_SafeStrdup(_str) \ UtilSafeStrdup1((_str), -1, __FILE__, __LINE__) #define Util_SafeStrdupBug(_bugNr, _str) \ UtilSafeStrdup1((_str), (_bugNr), __FILE__, __LINE__) #else /* VMX86_DEBUG */ #define Util_SafeMalloc(_size) \ UtilSafeMalloc0((_size)) #define Util_SafeMallocBug(_bugNr, _size) \ UtilSafeMalloc0((_size)) #define Util_SafeRealloc(_ptr, _size) \ UtilSafeRealloc0((_ptr), (_size)) #define Util_SafeReallocBug(_ptr, _size) \ UtilSafeRealloc0((_ptr), (_size)) #define Util_SafeCalloc(_nmemb, _size) \ UtilSafeCalloc0((_nmemb), (_size)) #define Util_SafeCallocBug(_bugNr, _nmemb, _size) \ UtilSafeCalloc0((_nmemb), (_size)) #define Util_SafeStrndup(_str, _size) \ UtilSafeStrndup0((_str), (_size)) #define Util_SafeStrndupBug(_bugNr, _str, _size) \ UtilSafeStrndup0((_str), (_size)) #define Util_SafeStrdup(_str) \ UtilSafeStrdup0((_str)) #define Util_SafeStrdupBug(_bugNr, _str) \ UtilSafeStrdup0((_str)) #endif /* VMX86_DEBUG */ void *Util_Memdup(const void *src, size_t size); void *Util_Memcpy(void *dest, const void *src, size_t count); #ifndef VMKBOOT /* *----------------------------------------------------------------------------- * * Util_FreeList -- * Util_FreeStringList -- * * Free a list (actually a vector) of allocated objects. * The list (vector) itself is also freed. * * The list either has a specified length or is * argv-style NULL terminated (if length is negative). * * The list can be NULL, in which case no operation is performed. * * Results: * None * * Side effects: * errno or Windows last error is preserved. * *----------------------------------------------------------------------------- */ static INLINE void Util_FreeList(void **list, // IN/OUT/OPT: the list to free ssize_t length) // IN: the length { // See Posix_Free. int err; if (list == NULL) { ASSERT(length <= 0); return; } err = errno; if (length >= 0) { ssize_t i; for (i = 0; i < length; i++) { free(list[i]); DEBUG_ONLY(list[i] = NULL); } } else { void **s; for (s = list; *s != NULL; s++) { free(*s); DEBUG_ONLY(*s = NULL); } } free(list); errno = err; } static INLINE void Util_FreeStringList(char **list, // IN/OUT/OPT: the list to free ssize_t length) // IN: the length { Util_FreeList((void **) list, length); } #endif /* VMKBOOT */ /* *----------------------------------------------------------------------------- * * Util_Memcpy32 -- * * Special purpose version of memcpy that requires nbytes be a * multiple of 4. This assumption lets us have a very small, * inlineable implementation. * * Results: * dst * * Side effects: * See above. * *----------------------------------------------------------------------------- */ static INLINE void * Util_Memcpy32(void *dst, const void *src, size_t nbytes) { ASSERT((nbytes % 4) == 0); #if defined __GNUC__ && (defined(__i386__) || defined(__x86_64__)) do { int dummy0, dummy1, dummy2; __asm__ __volatile__( "cld \n\t" "rep ; movsl" "\n\t" : "=&c" (dummy0), "=&D" (dummy1), "=&S" (dummy2) : "0" (nbytes / 4), "1" ((long) dst), "2" ((long) src) : "memory", "cc" ); return dst; } while (0); #else return memcpy(dst, src, nbytes); #endif } #if defined(__cplusplus) } // extern "C" #endif #endif /* UTIL_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/utilZero.h000066400000000000000000000152411321503522500244600ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * utilZero.h -- * * Utility functions for zeroing memory, and verifying memory is * zeroed. */ #ifndef UTIL_ZERO_H #define UTIL_ZERO_H #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include #ifndef VMKBOOT #include #endif #ifndef _WIN32 #include #include #include #endif #include "vm_assert.h" #include "vm_basic_defs.h" #include "unicodeTypes.h" #if defined(__cplusplus) extern "C" { #endif /* *----------------------------------------------------------------------------- * * Util_ValidateBytes -- * * Check that memory is filled with the specified value. * * Results: * NULL No error * !NULL First address that doesn't have the proper value * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE void * Util_ValidateBytes(const void *ptr, // IN: ptr to check size_t size, // IN: size of ptr uint8 byteValue) // IN: memory must be filled with this { uint8 *p; uint8 *end; uint64 bigValue; ASSERT(ptr); if (size == 0) { return NULL; } p = (uint8 *) ptr; end = p + size; /* Compare bytes until a "nice" boundary is achieved. */ while ((uintptr_t) p % sizeof bigValue) { if (*p != byteValue) { return p; } p++; if (p == end) { return NULL; } } /* Compare using a "nice sized" chunk for a long as possible. */ memset(&bigValue, (int) byteValue, sizeof bigValue); while (p + sizeof bigValue <= end) { if (*((uint64 *) p) != bigValue) { /* That's not right... let the loop below report the exact address. */ break; } size -= sizeof bigValue; p += sizeof bigValue; } /* Handle any trailing bytes. */ while (p < end) { if (*p != byteValue) { return p; } p++; } return NULL; } /* *---------------------------------------------------------------------- * * Util_BufferIsEmpty -- * * Determine if the specified buffer of 'len' bytes starting at 'base' * is empty (i.e. full of zeroes). * * Results: * TRUE Yes * FALSE No * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE Bool Util_BufferIsEmpty(void const *base, // IN: size_t len) // IN: { return Util_ValidateBytes(base, len, '\0') == NULL; } /* *----------------------------------------------------------------------------- * * Util_Zero -- * * Zeros out bufSize bytes of buf. NULL is legal. * * Results: * None. * * Side effects: * See above. * *----------------------------------------------------------------------------- */ static INLINE void Util_Zero(void *buf, // OUT size_t bufSize) // IN { if (buf != NULL) { #if defined _WIN32 && defined USERLEVEL /* * Simple memset calls might be optimized out. See CERT advisory * MSC06-C. */ SecureZeroMemory(buf, bufSize); #else memset(buf, 0, bufSize); #if !defined _WIN32 /* * Memset calls before free might be optimized out. See PR1248269. */ __asm__ __volatile__("" : : "r"(&buf) : "memory"); #endif #endif } } /* *----------------------------------------------------------------------------- * * Util_ZeroString -- * * Zeros out a NULL-terminated string. NULL is legal. * * Results: * None. * * Side effects: * See above. * *----------------------------------------------------------------------------- */ static INLINE void Util_ZeroString(char *str) // IN/OUT/OPT { if (str != NULL) { Util_Zero(str, strlen(str)); } } #ifndef VMKBOOT /* *----------------------------------------------------------------------------- * * Util_ZeroFree -- * * Zeros out bufSize bytes of buf, and then frees it. NULL is * legal. * * Results: * None. * * Side effects: * buf is zeroed, and then free() is called on it. * *----------------------------------------------------------------------------- */ static INLINE void Util_ZeroFree(void *buf, // OUT/OPT size_t bufSize) // IN { if (buf != NULL) { // See Posix_Free. int err = errno; Util_Zero(buf, bufSize); free(buf); errno = err; } } /* *----------------------------------------------------------------------------- * * Util_ZeroFreeString -- * * Zeros out a NULL-terminated string, and then frees it. NULL is * legal. * * Results: * None. * * Side effects: * str is zeroed, and then free() is called on it. * *----------------------------------------------------------------------------- */ static INLINE void Util_ZeroFreeString(char *str) // IN/OUT/OPT { if (str != NULL) { // See Posix_Free. int err = errno; Util_ZeroString(str); free(str); errno = err; } } #endif /* VMKBOOT */ #ifdef _WIN32 /* *----------------------------------------------------------------------------- * * Util_ZeroFreeStringW -- * * Zeros out a NUL-terminated wide-character string, and then frees it. * NULL is legal. * * Results: * None. * * Side effects: * str is zeroed, and then free() is called on it. * *----------------------------------------------------------------------------- */ static INLINE void Util_ZeroFreeStringW(wchar_t *str) // IN/OUT/OPT { if (str != NULL) { // See Posix_Free. int err = errno; Util_Zero(str, wcslen(str) * sizeof *str); free(str); errno = err; } } #endif /* _WIN32 */ #if defined(__cplusplus) } // extern "C" #endif #endif /* UTIL_ZERO_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/uuid.h000066400000000000000000000122551321503522500236130ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * uuid.h -- * * UUID generation */ #ifndef _UUID_H_ #define _UUID_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #if defined(__cplusplus) extern "C" { #endif #define UUID_SIZE 16 #define UUID_STRSIZE (2*UUID_SIZE + 1) #define UUID_MAXLEN 48 /* * ISO 11578 (now X.667 section 6.4) defines the canonical text format of a * UUID, which looks like this example: * * "f81d4fae-7dec-11d0-a765-00a0c91e6bf6" * * It is always precisely 36 characters long (excluding terminating NUL). */ #define UUID_ISO_11578_LEN 36 typedef enum { UUID_WITH_PATH = 0, UUID_RANDOM, UUID_VPX_BIOS, UUID_VPX_INSTANCE, UUID_UNKNOWN } UUIDStyle; /* Scheme control */ #define UUID_CREATE_WS4 0 /* the "original", WS4 and earlier scheme */ #define UUID_CREATE_WS5 1 /* the WS5 scheme */ #define UUID_CREATE_WS6 2 /* the WS6 scheme - "native" path */ #define UUID_CREATE_ESX50 3 /* the scheme to allow location generated using host UUID with wrong endianness as reported by pre-ESX 5.0 U2. See PR 861271 for details. */ #define UUID_CREATE_WS65 4 /* the WS65 scheme - UTF-8 path */ #define UUID_CREATE_CURRENT 4 /* the current scheme - always the latest */ /* * An RFC 4122-compliant UUID. * * See RFC 4122 section 4.1.2 (Layout and Byte Order). All multi-byte types are * stored in big-endian (most significant byte first) order. * * The UUID packed text string * 00112233-4455-6677-8899-AABBCCDDEEFF * represents * timeLow = 0x00112233 * timeMid = 0x4455 * timeHiAndVersion = 0x6677 * clockSeqHiAndReserved = 0x88 * clockSeqLow = 0x99 * node[0] = 0xAA * node[1] = 0xBB * node[2] = 0xCC * node[3] = 0xDD * node[4] = 0xEE * node[5] = 0xFF * and the structure is stored as the sequence of bytes * 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF */ typedef #include "vmware_pack_begin.h" struct { uint32 timeLow; uint16 timeMid; uint16 timeHiAndVersion; uint8 clockSeqHiAndReserved; uint8 clockSeqLow; uint8 node[6]; } #include "vmware_pack_end.h" UUIDRFC4122; /* * An EFI/UEFI/Microsoft-compliant GUID. * * See MdeModulePkg/Universal/DevicePathDxe/DevicePathFromText.c::StrToGuid(), * BaseTools/Source/C/Common/ParseInf.c::StringToGuid(), * http://en.wikipedia.org/wiki/GUID . All multi-byte types are stored in CPU * (a.k.a. native) byte order. * * The GUID packed text string * 00112233-4455-6677-8899-AABBCCDDEEFF * represents * data1 = 0x00112233 * data2 = 0x4455 * data3 = 0x6677 * data4[0] = 0x88 * data4[1] = 0x99 * data4[2] = 0xAA * data4[3] = 0xBB * data4[4] = 0xCC * data4[5] = 0xDD * data4[6] = 0xEE * data4[7] = 0xFF * and the structure is stored as the sequence of bytes * big-endian CPU: 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF * little-endian CPU: 33 22 11 00 55 44 77 66 88 99 AA BB CC DD EE FF */ typedef #include "vmware_pack_begin.h" struct { uint32 data1; uint16 data2; uint16 data3; uint8 data4[8]; } #include "vmware_pack_end.h" EFIGUID; Bool UUID_ConvertPackedToBin(EFIGUID *destID, const char *text); Bool UUID_ConvertToBin(uint8 dest_id[UUID_SIZE], const char *text); char *UUID_ConvertToText(const uint8 id[UUID_SIZE]); void UUID_ConvertToTextBuf(const uint8 id[UUID_SIZE], char *buffer, size_t len); char *UUID_Create(const char *configFileFullPath, int schemeControl); char *UUID_CreateRandom(void); Bool UUID_CreateRandomRFC4122V4(UUIDRFC4122 *id); Bool UUID_CreateRandomEFI(EFIGUID *id); char *UUID_CreateRandomVpxStyle(uint8 vpxdId, UUIDStyle); Bool UUID_IsUUIDGeneratedByThatVpxd(const uint8 *id, int vpxdInstanceId); char *UUID_PackText(const char *text, char *pack, int packLen); char *UUID_ProperHostUUID(void); char *UUID_GetHostUUID(void); UUIDStyle UUID_GetStyle(const uint8 *id); /* like UUID_GetHostUUID, except gets actual host UUID */ char *UUID_GetRealHostUUID(void); Bool UUID_Equal(const uint8 id1[UUID_SIZE], const uint8 id2[UUID_SIZE]); #if defined(__cplusplus) } // extern "C" #endif #endif open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vix.h000066400000000000000000001324251321503522500234550ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2004-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * This is the C interface to the VIX API. * This is platform-independent. */ #ifndef _VIX_H_ #define _VIX_H_ #ifdef __cplusplus extern "C" { #endif /* *----------------------------------------------------------------------------- * * Basic Types -- * *----------------------------------------------------------------------------- */ #include "vm_basic_types.h" typedef int VixHandle; enum { VIX_INVALID_HANDLE = 0, }; /* * These are the types of handles. */ typedef int VixHandleType; enum { VIX_HANDLETYPE_NONE = 0, VIX_HANDLETYPE_HOST = 2, VIX_HANDLETYPE_VM = 3, VIX_HANDLETYPE_NETWORK = 5, VIX_HANDLETYPE_JOB = 6, VIX_HANDLETYPE_SNAPSHOT = 7, VIX_HANDLETYPE_PROPERTY_LIST = 9, VIX_HANDLETYPE_METADATA_CONTAINER = 11 }; /* * The "//{{ Begin VIX_ERROR }}" and "//{{ End VIX_ERROR }}" lines are * to bracket the error code definitions that will be copied over * to vixDiskLib.h during build time. If you modify these two lines, please * make sure you also change bora/lib/distribute/vixDiskLib.h and * bora/support/scripts/replaceVixErrors.py */ // {{ Begin VIX_ERROR }} /* * An error is a 64-bit value. If there is no error, then the value is * set to VIX_OK. If there is an error, then the least significant bits * will be set to one of the integer error codes defined below. The more * significant bits may or may not be set to various values, depending on * the errors. */ typedef uint64 VixError; #define VIX_ERROR_CODE(err) ((err) & 0xFFFF) #define VIX_SUCCEEDED(err) (VIX_OK == (err)) #define VIX_FAILED(err) (VIX_OK != (err)) /* * The error codes are returned by all public VIX routines. */ enum { VIX_OK = 0, /* General errors */ VIX_E_FAIL = 1, VIX_E_OUT_OF_MEMORY = 2, VIX_E_INVALID_ARG = 3, VIX_E_FILE_NOT_FOUND = 4, VIX_E_OBJECT_IS_BUSY = 5, VIX_E_NOT_SUPPORTED = 6, VIX_E_FILE_ERROR = 7, VIX_E_DISK_FULL = 8, VIX_E_INCORRECT_FILE_TYPE = 9, VIX_E_CANCELLED = 10, VIX_E_FILE_READ_ONLY = 11, VIX_E_FILE_ALREADY_EXISTS = 12, VIX_E_FILE_ACCESS_ERROR = 13, VIX_E_REQUIRES_LARGE_FILES = 14, VIX_E_FILE_ALREADY_LOCKED = 15, VIX_E_VMDB = 16, VIX_E_NOT_SUPPORTED_ON_REMOTE_OBJECT = 20, VIX_E_FILE_TOO_BIG = 21, VIX_E_FILE_NAME_INVALID = 22, VIX_E_ALREADY_EXISTS = 23, VIX_E_BUFFER_TOOSMALL = 24, VIX_E_OBJECT_NOT_FOUND = 25, VIX_E_HOST_NOT_CONNECTED = 26, VIX_E_INVALID_UTF8_STRING = 27, VIX_E_OPERATION_ALREADY_IN_PROGRESS = 31, VIX_E_UNFINISHED_JOB = 29, VIX_E_NEED_KEY = 30, VIX_E_LICENSE = 32, VIX_E_VM_HOST_DISCONNECTED = 34, VIX_E_AUTHENTICATION_FAIL = 35, VIX_E_HOST_CONNECTION_LOST = 36, VIX_E_DUPLICATE_NAME = 41, VIX_E_ARGUMENT_TOO_BIG = 44, /* Handle Errors */ VIX_E_INVALID_HANDLE = 1000, VIX_E_NOT_SUPPORTED_ON_HANDLE_TYPE = 1001, VIX_E_TOO_MANY_HANDLES = 1002, /* XML errors */ VIX_E_NOT_FOUND = 2000, VIX_E_TYPE_MISMATCH = 2001, VIX_E_INVALID_XML = 2002, /* VM Control Errors */ VIX_E_TIMEOUT_WAITING_FOR_TOOLS = 3000, VIX_E_UNRECOGNIZED_COMMAND = 3001, VIX_E_OP_NOT_SUPPORTED_ON_GUEST = 3003, VIX_E_PROGRAM_NOT_STARTED = 3004, VIX_E_CANNOT_START_READ_ONLY_VM = 3005, VIX_E_VM_NOT_RUNNING = 3006, VIX_E_VM_IS_RUNNING = 3007, VIX_E_CANNOT_CONNECT_TO_VM = 3008, VIX_E_POWEROP_SCRIPTS_NOT_AVAILABLE = 3009, VIX_E_NO_GUEST_OS_INSTALLED = 3010, VIX_E_VM_INSUFFICIENT_HOST_MEMORY = 3011, VIX_E_SUSPEND_ERROR = 3012, VIX_E_VM_NOT_ENOUGH_CPUS = 3013, VIX_E_HOST_USER_PERMISSIONS = 3014, VIX_E_GUEST_USER_PERMISSIONS = 3015, VIX_E_TOOLS_NOT_RUNNING = 3016, VIX_E_GUEST_OPERATIONS_PROHIBITED = 3017, VIX_E_ANON_GUEST_OPERATIONS_PROHIBITED = 3018, VIX_E_ROOT_GUEST_OPERATIONS_PROHIBITED = 3019, VIX_E_MISSING_ANON_GUEST_ACCOUNT = 3023, VIX_E_CANNOT_AUTHENTICATE_WITH_GUEST = 3024, VIX_E_UNRECOGNIZED_COMMAND_IN_GUEST = 3025, VIX_E_CONSOLE_GUEST_OPERATIONS_PROHIBITED = 3026, VIX_E_MUST_BE_CONSOLE_USER = 3027, VIX_E_VMX_MSG_DIALOG_AND_NO_UI = 3028, /* VIX_E_NOT_ALLOWED_DURING_VM_RECORDING = 3029, Removed in version 1.11 */ /* VIX_E_NOT_ALLOWED_DURING_VM_REPLAY = 3030, Removed in version 1.11 */ VIX_E_OPERATION_NOT_ALLOWED_FOR_LOGIN_TYPE = 3031, VIX_E_LOGIN_TYPE_NOT_SUPPORTED = 3032, VIX_E_EMPTY_PASSWORD_NOT_ALLOWED_IN_GUEST = 3033, VIX_E_INTERACTIVE_SESSION_NOT_PRESENT = 3034, VIX_E_INTERACTIVE_SESSION_USER_MISMATCH = 3035, /* VIX_E_UNABLE_TO_REPLAY_VM = 3039, Removed in version 1.11 */ VIX_E_CANNOT_POWER_ON_VM = 3041, VIX_E_NO_DISPLAY_SERVER = 3043, /* VIX_E_VM_NOT_RECORDING = 3044, Removed in version 1.11 */ /* VIX_E_VM_NOT_REPLAYING = 3045, Removed in version 1.11 */ VIX_E_TOO_MANY_LOGONS = 3046, VIX_E_INVALID_AUTHENTICATION_SESSION = 3047, /* VM Errors */ VIX_E_VM_NOT_FOUND = 4000, VIX_E_NOT_SUPPORTED_FOR_VM_VERSION = 4001, VIX_E_CANNOT_READ_VM_CONFIG = 4002, VIX_E_TEMPLATE_VM = 4003, VIX_E_VM_ALREADY_LOADED = 4004, VIX_E_VM_ALREADY_UP_TO_DATE = 4006, VIX_E_VM_UNSUPPORTED_GUEST = 4011, /* Property Errors */ VIX_E_UNRECOGNIZED_PROPERTY = 6000, VIX_E_INVALID_PROPERTY_VALUE = 6001, VIX_E_READ_ONLY_PROPERTY = 6002, VIX_E_MISSING_REQUIRED_PROPERTY = 6003, VIX_E_INVALID_SERIALIZED_DATA = 6004, VIX_E_PROPERTY_TYPE_MISMATCH = 6005, /* Completion Errors */ VIX_E_BAD_VM_INDEX = 8000, /* Message errors */ VIX_E_INVALID_MESSAGE_HEADER = 10000, VIX_E_INVALID_MESSAGE_BODY = 10001, /* Snapshot errors */ VIX_E_SNAPSHOT_INVAL = 13000, VIX_E_SNAPSHOT_DUMPER = 13001, VIX_E_SNAPSHOT_DISKLIB = 13002, VIX_E_SNAPSHOT_NOTFOUND = 13003, VIX_E_SNAPSHOT_EXISTS = 13004, VIX_E_SNAPSHOT_VERSION = 13005, VIX_E_SNAPSHOT_NOPERM = 13006, VIX_E_SNAPSHOT_CONFIG = 13007, VIX_E_SNAPSHOT_NOCHANGE = 13008, VIX_E_SNAPSHOT_CHECKPOINT = 13009, VIX_E_SNAPSHOT_LOCKED = 13010, VIX_E_SNAPSHOT_INCONSISTENT = 13011, VIX_E_SNAPSHOT_NAMETOOLONG = 13012, VIX_E_SNAPSHOT_VIXFILE = 13013, VIX_E_SNAPSHOT_DISKLOCKED = 13014, VIX_E_SNAPSHOT_DUPLICATEDDISK = 13015, VIX_E_SNAPSHOT_INDEPENDENTDISK = 13016, VIX_E_SNAPSHOT_NONUNIQUE_NAME = 13017, VIX_E_SNAPSHOT_MEMORY_ON_INDEPENDENT_DISK = 13018, VIX_E_SNAPSHOT_MAXSNAPSHOTS = 13019, VIX_E_SNAPSHOT_MIN_FREE_SPACE = 13020, VIX_E_SNAPSHOT_HIERARCHY_TOODEEP = 13021, // DEPRECRATED VIX_E_SNAPSHOT_RRSUSPEND = 13022, VIX_E_SNAPSHOT_NOT_REVERTABLE = 13024, /* Host Errors */ VIX_E_HOST_DISK_INVALID_VALUE = 14003, VIX_E_HOST_DISK_SECTORSIZE = 14004, VIX_E_HOST_FILE_ERROR_EOF = 14005, VIX_E_HOST_NETBLKDEV_HANDSHAKE = 14006, VIX_E_HOST_SOCKET_CREATION_ERROR = 14007, VIX_E_HOST_SERVER_NOT_FOUND = 14008, VIX_E_HOST_NETWORK_CONN_REFUSED = 14009, VIX_E_HOST_TCP_SOCKET_ERROR = 14010, VIX_E_HOST_TCP_CONN_LOST = 14011, VIX_E_HOST_NBD_HASHFILE_VOLUME = 14012, VIX_E_HOST_NBD_HASHFILE_INIT = 14013, /* Disklib errors */ VIX_E_DISK_INVAL = 16000, VIX_E_DISK_NOINIT = 16001, VIX_E_DISK_NOIO = 16002, VIX_E_DISK_PARTIALCHAIN = 16003, VIX_E_DISK_NEEDSREPAIR = 16006, VIX_E_DISK_OUTOFRANGE = 16007, VIX_E_DISK_CID_MISMATCH = 16008, VIX_E_DISK_CANTSHRINK = 16009, VIX_E_DISK_PARTMISMATCH = 16010, VIX_E_DISK_UNSUPPORTEDDISKVERSION = 16011, VIX_E_DISK_OPENPARENT = 16012, VIX_E_DISK_NOTSUPPORTED = 16013, VIX_E_DISK_NEEDKEY = 16014, VIX_E_DISK_NOKEYOVERRIDE = 16015, VIX_E_DISK_NOTENCRYPTED = 16016, VIX_E_DISK_NOKEY = 16017, VIX_E_DISK_INVALIDPARTITIONTABLE = 16018, VIX_E_DISK_NOTNORMAL = 16019, VIX_E_DISK_NOTENCDESC = 16020, VIX_E_DISK_NEEDVMFS = 16022, VIX_E_DISK_RAWTOOBIG = 16024, VIX_E_DISK_TOOMANYOPENFILES = 16027, VIX_E_DISK_TOOMANYREDO = 16028, VIX_E_DISK_RAWTOOSMALL = 16029, VIX_E_DISK_INVALIDCHAIN = 16030, VIX_E_DISK_KEY_NOTFOUND = 16052, // metadata key is not found VIX_E_DISK_SUBSYSTEM_INIT_FAIL = 16053, VIX_E_DISK_INVALID_CONNECTION = 16054, VIX_E_DISK_ENCODING = 16061, VIX_E_DISK_CANTREPAIR = 16062, VIX_E_DISK_INVALIDDISK = 16063, VIX_E_DISK_NOLICENSE = 16064, VIX_E_DISK_NODEVICE = 16065, VIX_E_DISK_UNSUPPORTEDDEVICE = 16066, VIX_E_DISK_CAPACITY_MISMATCH = 16067, VIX_E_DISK_PARENT_NOTALLOWED = 16068, VIX_E_DISK_ATTACH_ROOTLINK = 16069, /* Crypto Library Errors */ VIX_E_CRYPTO_UNKNOWN_ALGORITHM = 17000, VIX_E_CRYPTO_BAD_BUFFER_SIZE = 17001, VIX_E_CRYPTO_INVALID_OPERATION = 17002, VIX_E_CRYPTO_RANDOM_DEVICE = 17003, VIX_E_CRYPTO_NEED_PASSWORD = 17004, VIX_E_CRYPTO_BAD_PASSWORD = 17005, VIX_E_CRYPTO_NOT_IN_DICTIONARY = 17006, VIX_E_CRYPTO_NO_CRYPTO = 17007, VIX_E_CRYPTO_ERROR = 17008, VIX_E_CRYPTO_BAD_FORMAT = 17009, VIX_E_CRYPTO_LOCKED = 17010, VIX_E_CRYPTO_EMPTY = 17011, VIX_E_CRYPTO_KEYSAFE_LOCATOR = 17012, /* Remoting Errors. */ VIX_E_CANNOT_CONNECT_TO_HOST = 18000, VIX_E_NOT_FOR_REMOTE_HOST = 18001, VIX_E_INVALID_HOSTNAME_SPECIFICATION = 18002, /* Screen Capture Errors. */ VIX_E_SCREEN_CAPTURE_ERROR = 19000, VIX_E_SCREEN_CAPTURE_BAD_FORMAT = 19001, VIX_E_SCREEN_CAPTURE_COMPRESSION_FAIL = 19002, VIX_E_SCREEN_CAPTURE_LARGE_DATA = 19003, /* Guest Errors */ VIX_E_GUEST_VOLUMES_NOT_FROZEN = 20000, VIX_E_NOT_A_FILE = 20001, VIX_E_NOT_A_DIRECTORY = 20002, VIX_E_NO_SUCH_PROCESS = 20003, VIX_E_FILE_NAME_TOO_LONG = 20004, VIX_E_OPERATION_DISABLED = 20005, /* Tools install errors */ VIX_E_TOOLS_INSTALL_NO_IMAGE = 21000, VIX_E_TOOLS_INSTALL_IMAGE_INACCESIBLE = 21001, VIX_E_TOOLS_INSTALL_NO_DEVICE = 21002, VIX_E_TOOLS_INSTALL_DEVICE_NOT_CONNECTED = 21003, VIX_E_TOOLS_INSTALL_CANCELLED = 21004, VIX_E_TOOLS_INSTALL_INIT_FAILED = 21005, VIX_E_TOOLS_INSTALL_AUTO_NOT_SUPPORTED = 21006, VIX_E_TOOLS_INSTALL_GUEST_NOT_READY = 21007, VIX_E_TOOLS_INSTALL_SIG_CHECK_FAILED = 21008, VIX_E_TOOLS_INSTALL_ERROR = 21009, VIX_E_TOOLS_INSTALL_ALREADY_UP_TO_DATE = 21010, VIX_E_TOOLS_INSTALL_IN_PROGRESS = 21011, VIX_E_TOOLS_INSTALL_IMAGE_COPY_FAILED = 21012, /* Wrapper Errors */ VIX_E_WRAPPER_WORKSTATION_NOT_INSTALLED = 22001, VIX_E_WRAPPER_VERSION_NOT_FOUND = 22002, VIX_E_WRAPPER_SERVICEPROVIDER_NOT_FOUND = 22003, VIX_E_WRAPPER_PLAYER_NOT_INSTALLED = 22004, VIX_E_WRAPPER_RUNTIME_NOT_INSTALLED = 22005, VIX_E_WRAPPER_MULTIPLE_SERVICEPROVIDERS = 22006, /* FuseMnt errors*/ VIX_E_MNTAPI_MOUNTPT_NOT_FOUND = 24000, VIX_E_MNTAPI_MOUNTPT_IN_USE = 24001, VIX_E_MNTAPI_DISK_NOT_FOUND = 24002, VIX_E_MNTAPI_DISK_NOT_MOUNTED = 24003, VIX_E_MNTAPI_DISK_IS_MOUNTED = 24004, VIX_E_MNTAPI_DISK_NOT_SAFE = 24005, VIX_E_MNTAPI_DISK_CANT_OPEN = 24006, VIX_E_MNTAPI_CANT_READ_PARTS = 24007, VIX_E_MNTAPI_UMOUNT_APP_NOT_FOUND = 24008, VIX_E_MNTAPI_UMOUNT = 24009, VIX_E_MNTAPI_NO_MOUNTABLE_PARTITONS = 24010, VIX_E_MNTAPI_PARTITION_RANGE = 24011, VIX_E_MNTAPI_PERM = 24012, VIX_E_MNTAPI_DICT = 24013, VIX_E_MNTAPI_DICT_LOCKED = 24014, VIX_E_MNTAPI_OPEN_HANDLES = 24015, VIX_E_MNTAPI_CANT_MAKE_VAR_DIR = 24016, VIX_E_MNTAPI_NO_ROOT = 24017, VIX_E_MNTAPI_LOOP_FAILED = 24018, VIX_E_MNTAPI_DAEMON = 24019, VIX_E_MNTAPI_INTERNAL = 24020, VIX_E_MNTAPI_SYSTEM = 24021, VIX_E_MNTAPI_NO_CONNECTION_DETAILS = 24022, /* FuseMnt errors: Do not exceed 24299 */ /* VixMntapi errors*/ VIX_E_MNTAPI_INCOMPATIBLE_VERSION = 24300, VIX_E_MNTAPI_OS_ERROR = 24301, VIX_E_MNTAPI_DRIVE_LETTER_IN_USE = 24302, VIX_E_MNTAPI_DRIVE_LETTER_ALREADY_ASSIGNED = 24303, VIX_E_MNTAPI_VOLUME_NOT_MOUNTED = 24304, VIX_E_MNTAPI_VOLUME_ALREADY_MOUNTED = 24305, VIX_E_MNTAPI_FORMAT_FAILURE = 24306, VIX_E_MNTAPI_NO_DRIVER = 24307, VIX_E_MNTAPI_ALREADY_OPENED = 24308, VIX_E_MNTAPI_ITEM_NOT_FOUND = 24309, VIX_E_MNTAPI_UNSUPPROTED_BOOT_LOADER = 24310, VIX_E_MNTAPI_UNSUPPROTED_OS = 24311, VIX_E_MNTAPI_CODECONVERSION = 24312, VIX_E_MNTAPI_REGWRITE_ERROR = 24313, VIX_E_MNTAPI_UNSUPPORTED_FT_VOLUME = 24314, VIX_E_MNTAPI_PARTITION_NOT_FOUND = 24315, VIX_E_MNTAPI_PUTFILE_ERROR = 24316, VIX_E_MNTAPI_GETFILE_ERROR = 24317, VIX_E_MNTAPI_REG_NOT_OPENED = 24318, VIX_E_MNTAPI_REGDELKEY_ERROR = 24319, VIX_E_MNTAPI_CREATE_PARTITIONTABLE_ERROR = 24320, VIX_E_MNTAPI_OPEN_FAILURE = 24321, VIX_E_MNTAPI_VOLUME_NOT_WRITABLE = 24322, /* Success on operation that completes asynchronously */ VIX_ASYNC = 25000, /* Async errors */ VIX_E_ASYNC_MIXEDMODE_UNSUPPORTED = 26000, /* Network Errors */ VIX_E_NET_HTTP_UNSUPPORTED_PROTOCOL = 30001, VIX_E_NET_HTTP_URL_MALFORMAT = 30003, VIX_E_NET_HTTP_COULDNT_RESOLVE_PROXY = 30005, VIX_E_NET_HTTP_COULDNT_RESOLVE_HOST = 30006, VIX_E_NET_HTTP_COULDNT_CONNECT = 30007, VIX_E_NET_HTTP_HTTP_RETURNED_ERROR = 30022, VIX_E_NET_HTTP_OPERATION_TIMEDOUT = 30028, VIX_E_NET_HTTP_SSL_CONNECT_ERROR = 30035, VIX_E_NET_HTTP_TOO_MANY_REDIRECTS = 30047, VIX_E_NET_HTTP_TRANSFER = 30200, VIX_E_NET_HTTP_SSL_SECURITY = 30201, VIX_E_NET_HTTP_GENERIC = 30202, }; // {{ End VIX_ERROR }} const char *Vix_GetErrorText(VixError err, const char *locale); /* *----------------------------------------------------------------------------- * * VIX Handles -- * * These are common functions that apply to handles of several types. *----------------------------------------------------------------------------- */ /* * VIX Property Type */ typedef int VixPropertyType; enum { VIX_PROPERTYTYPE_ANY = 0, VIX_PROPERTYTYPE_INTEGER = 1, VIX_PROPERTYTYPE_STRING = 2, VIX_PROPERTYTYPE_BOOL = 3, VIX_PROPERTYTYPE_HANDLE = 4, VIX_PROPERTYTYPE_INT64 = 5, VIX_PROPERTYTYPE_BLOB = 6 }; /* * VIX Property ID's */ typedef int VixPropertyID; enum { VIX_PROPERTY_NONE = 0, /* Properties used by several handle types. */ VIX_PROPERTY_META_DATA_CONTAINER = 2, /* VIX_HANDLETYPE_HOST properties */ VIX_PROPERTY_HOST_HOSTTYPE = 50, VIX_PROPERTY_HOST_API_VERSION = 51, VIX_PROPERTY_HOST_SOFTWARE_VERSION = 52, /* VIX_HANDLETYPE_VM properties */ VIX_PROPERTY_VM_NUM_VCPUS = 101, VIX_PROPERTY_VM_VMX_PATHNAME = 103, VIX_PROPERTY_VM_VMTEAM_PATHNAME = 105, VIX_PROPERTY_VM_MEMORY_SIZE = 106, VIX_PROPERTY_VM_READ_ONLY = 107, VIX_PROPERTY_VM_NAME = 108, VIX_PROPERTY_VM_GUESTOS = 109, VIX_PROPERTY_VM_IN_VMTEAM = 128, VIX_PROPERTY_VM_POWER_STATE = 129, VIX_PROPERTY_VM_TOOLS_STATE = 152, VIX_PROPERTY_VM_IS_RUNNING = 196, VIX_PROPERTY_VM_SUPPORTED_FEATURES = 197, /* VIX_PROPERTY_VM_IS_RECORDING = 236, Removed in version 1.11 */ /* VIX_PROPERTY_VM_IS_REPLAYING = 237, Removed in version 1.11 */ VIX_PROPERTY_VM_SSL_ERROR = 293, /* Result properties; these are returned by various procedures */ VIX_PROPERTY_JOB_RESULT_ERROR_CODE = 3000, VIX_PROPERTY_JOB_RESULT_VM_IN_GROUP = 3001, VIX_PROPERTY_JOB_RESULT_USER_MESSAGE = 3002, VIX_PROPERTY_JOB_RESULT_EXIT_CODE = 3004, VIX_PROPERTY_JOB_RESULT_COMMAND_OUTPUT = 3005, VIX_PROPERTY_JOB_RESULT_HANDLE = 3010, VIX_PROPERTY_JOB_RESULT_GUEST_OBJECT_EXISTS = 3011, VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_ELAPSED_TIME = 3017, VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_EXIT_CODE = 3018, VIX_PROPERTY_JOB_RESULT_ITEM_NAME = 3035, VIX_PROPERTY_JOB_RESULT_FOUND_ITEM_DESCRIPTION = 3036, VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_COUNT = 3046, VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_HOST = 3048, VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_FLAGS = 3049, VIX_PROPERTY_JOB_RESULT_PROCESS_ID = 3051, VIX_PROPERTY_JOB_RESULT_PROCESS_OWNER = 3052, VIX_PROPERTY_JOB_RESULT_PROCESS_COMMAND = 3053, VIX_PROPERTY_JOB_RESULT_FILE_FLAGS = 3054, VIX_PROPERTY_JOB_RESULT_PROCESS_START_TIME = 3055, VIX_PROPERTY_JOB_RESULT_VM_VARIABLE_STRING = 3056, VIX_PROPERTY_JOB_RESULT_PROCESS_BEING_DEBUGGED = 3057, VIX_PROPERTY_JOB_RESULT_SCREEN_IMAGE_SIZE = 3058, VIX_PROPERTY_JOB_RESULT_SCREEN_IMAGE_DATA = 3059, VIX_PROPERTY_JOB_RESULT_FILE_SIZE = 3061, VIX_PROPERTY_JOB_RESULT_FILE_MOD_TIME = 3062, VIX_PROPERTY_JOB_RESULT_EXTRA_ERROR_INFO = 3084, /* Event properties; these are sent in the moreEventInfo for some events. */ VIX_PROPERTY_FOUND_ITEM_LOCATION = 4010, /* VIX_HANDLETYPE_SNAPSHOT properties */ VIX_PROPERTY_SNAPSHOT_DISPLAYNAME = 4200, VIX_PROPERTY_SNAPSHOT_DESCRIPTION = 4201, VIX_PROPERTY_SNAPSHOT_POWERSTATE = 4205, /* VIX_PROPERTY_SNAPSHOT_IS_REPLAYABLE = 4207, Removed in version 1.11 */ VIX_PROPERTY_GUEST_SHAREDFOLDERS_SHARES_PATH = 4525, /* Virtual machine encryption properties */ VIX_PROPERTY_VM_ENCRYPTION_PASSWORD = 7001, }; /* * These are events that may be signalled by calling a procedure * of type VixEventProc. */ typedef int VixEventType; enum { VIX_EVENTTYPE_JOB_COMPLETED = 2, VIX_EVENTTYPE_JOB_PROGRESS = 3, VIX_EVENTTYPE_FIND_ITEM = 8, VIX_EVENTTYPE_CALLBACK_SIGNALLED = 2, // Deprecated - Use VIX_EVENTTYPE_JOB_COMPLETED instead. }; /* * These are the property flags for each file. */ enum { VIX_FILE_ATTRIBUTES_DIRECTORY = 0x0001, VIX_FILE_ATTRIBUTES_SYMLINK = 0x0002, }; /* * Procedures of this type are called when an event happens on a handle. */ typedef void VixEventProc(VixHandle handle, VixEventType eventType, VixHandle moreEventInfo, void *clientData); /* * Handle Property functions */ void Vix_ReleaseHandle(VixHandle handle); void Vix_AddRefHandle(VixHandle handle); VixHandleType Vix_GetHandleType(VixHandle handle); VixError Vix_GetProperties(VixHandle handle, VixPropertyID firstPropertyID, ...); VixError Vix_GetPropertyType(VixHandle handle, VixPropertyID propertyID, VixPropertyType *propertyType); void Vix_FreeBuffer(void *p); /* *----------------------------------------------------------------------------- * * VIX Host -- * *----------------------------------------------------------------------------- */ typedef int VixHostOptions; enum { /* * The following option was removed in version 1.11. VIX_HOSTOPTION_USE_EVENT_PUMP = 0x0008, */ VIX_HOSTOPTION_VERIFY_SSL_CERT = 0x4000, }; typedef int VixServiceProvider; enum { VIX_SERVICEPROVIDER_DEFAULT = 1, VIX_SERVICEPROVIDER_VMWARE_SERVER = 2, VIX_SERVICEPROVIDER_VMWARE_WORKSTATION = 3, VIX_SERVICEPROVIDER_VMWARE_PLAYER = 4, VIX_SERVICEPROVIDER_VMWARE_VI_SERVER = 10, VIX_SERVICEPROVIDER_VMWARE_WORKSTATION_SHARED = 11, }; /* * VIX_API_VERSION tells VixHost_Connect to use the latest API version * that is available for the product specified in the VixServiceProvider * parameter. */ enum { VIX_API_VERSION = -1 }; VixHandle VixHost_Connect(int apiVersion, VixServiceProvider hostType, const char *hostName, int hostPort, const char *userName, const char *password, VixHostOptions options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); void VixHost_Disconnect(VixHandle hostHandle); /* * VM Registration */ VixHandle VixHost_RegisterVM(VixHandle hostHandle, const char *vmxFilePath, VixEventProc *callbackProc, void *clientData); VixHandle VixHost_UnregisterVM(VixHandle hostHandle, const char *vmxFilePath, VixEventProc *callbackProc, void *clientData); /* * VM Search */ typedef int VixFindItemType; enum { VIX_FIND_RUNNING_VMS = 1, VIX_FIND_REGISTERED_VMS = 4, }; VixHandle VixHost_FindItems(VixHandle hostHandle, VixFindItemType searchType, VixHandle searchCriteria, int32 timeout, VixEventProc *callbackProc, void *clientData); /* * VixHost_OpenVM() supercedes VixVM_Open() since it allows for * the passing of option flags and extra data in the form of a * property list. * It is recommended to use VixHost_OpenVM() instead of VixVM_Open(). */ typedef int VixVMOpenOptions; enum { VIX_VMOPEN_NORMAL = 0x0, }; VixHandle VixHost_OpenVM(VixHandle hostHandle, const char *vmxFilePathName, VixVMOpenOptions options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); /* * Following functions were removed in version 1.11. * typedef int VixPumpEventsOptions; enum { VIX_PUMPEVENTOPTION_NONE = 0, }; void Vix_PumpEvents(VixHandle hostHandle, VixPumpEventsOptions options); VixHandle VixVM_OpenUrlInGuest(VixHandle vmHandle, const char *url, int windowState, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); */ /* *----------------------------------------------------------------------------- * * PropertyList -- * *----------------------------------------------------------------------------- */ #ifndef VIX_HIDE_FROM_JAVA VixError VixPropertyList_AllocPropertyList(VixHandle hostHandle, VixHandle *resultHandle, int firstPropertyID, ...); #endif /* *----------------------------------------------------------------------------- * * VIX VM -- * * This describes the persistent configuration state of a single VM. The * VM may or may not be running. * *----------------------------------------------------------------------------- */ VixHandle VixVM_Open(VixHandle hostHandle, const char *vmxFilePathName, VixEventProc *callbackProc, void *clientData); typedef int VixVMPowerOpOptions; enum { VIX_VMPOWEROP_NORMAL = 0, VIX_VMPOWEROP_FROM_GUEST = 0x0004, VIX_VMPOWEROP_SUPPRESS_SNAPSHOT_POWERON = 0x0080, VIX_VMPOWEROP_LAUNCH_GUI = 0x0200, VIX_VMPOWEROP_START_VM_PAUSED = 0x1000, }; /* * Power operations */ VixHandle VixVM_PowerOn(VixHandle vmHandle, VixVMPowerOpOptions powerOnOptions, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_PowerOff(VixHandle vmHandle, VixVMPowerOpOptions powerOffOptions, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_Reset(VixHandle vmHandle, VixVMPowerOpOptions resetOptions, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_Suspend(VixHandle vmHandle, VixVMPowerOpOptions suspendOptions, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_Pause(VixHandle vmHandle, int options, VixHandle propertyList, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_Unpause(VixHandle vmHandle, int options, VixHandle propertyList, VixEventProc *callbackProc, void *clientData); typedef int VixVMDeleteOptions; enum { VIX_VMDELETE_DISK_FILES = 0x0002, }; VixHandle VixVM_Delete(VixHandle vmHandle, VixVMDeleteOptions deleteOptions, VixEventProc *callbackProc, void *clientData); /* * This is the state of an individual VM. These values are bitwise flags. * The actual value returned for may be a bitwise OR of one more of these * flags, along with other reserved values not documented here. */ typedef int VixPowerState; enum { VIX_POWERSTATE_POWERING_OFF = 0x0001, VIX_POWERSTATE_POWERED_OFF = 0x0002, VIX_POWERSTATE_POWERING_ON = 0x0004, VIX_POWERSTATE_POWERED_ON = 0x0008, VIX_POWERSTATE_SUSPENDING = 0x0010, VIX_POWERSTATE_SUSPENDED = 0x0020, VIX_POWERSTATE_TOOLS_RUNNING = 0x0040, VIX_POWERSTATE_RESETTING = 0x0080, VIX_POWERSTATE_BLOCKED_ON_MSG = 0x0100, VIX_POWERSTATE_PAUSED = 0x0200, VIX_POWERSTATE_RESUMING = 0x0800, }; typedef int VixToolsState; enum { VIX_TOOLSSTATE_UNKNOWN = 0x0001, VIX_TOOLSSTATE_RUNNING = 0x0002, VIX_TOOLSSTATE_NOT_INSTALLED = 0x0004, }; /* * These flags describe optional functions supported by different * types of VM. */ enum { VIX_VM_SUPPORT_SHARED_FOLDERS = 0x0001, VIX_VM_SUPPORT_MULTIPLE_SNAPSHOTS = 0x0002, VIX_VM_SUPPORT_TOOLS_INSTALL = 0x0004, VIX_VM_SUPPORT_HARDWARE_UPGRADE = 0x0008, }; /* * VIX_ADMINISTRATOR_USER_NAME and VIX_CONSOLE_USER_NAME are no longer * supported. If your code includes references to these constants please * update your code to use a valid guest username and password when calling * VixVM_LoginInGuest(). */ //#define VIX_ADMINISTRATOR_USER_NAME "__VMware_Vix_Guest_User_Admin__" //#define VIX_CONSOLE_USER_NAME "__VMware_Vix_Guest_Console_User__" /* * Guest operations */ VixHandle VixVM_WaitForToolsInGuest(VixHandle vmHandle, int timeoutInSeconds, VixEventProc *callbackProc, void *clientData); /* * VixVM_LoginInGuest option flags. */ enum { VIX_LOGIN_IN_GUEST_REQUIRE_INTERACTIVE_ENVIRONMENT = 0x08, }; VixHandle VixVM_LoginInGuest(VixHandle vmHandle, const char *userName, const char *password, int options, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_LogoutFromGuest(VixHandle vmHandle, VixEventProc *callbackProc, void *clientData); /* * Guest Process functions */ typedef int VixRunProgramOptions; enum { VIX_RUNPROGRAM_RETURN_IMMEDIATELY = 0x0001, VIX_RUNPROGRAM_ACTIVATE_WINDOW = 0x0002, }; VixHandle VixVM_RunProgramInGuest(VixHandle vmHandle, const char *guestProgramName, const char *commandLineArgs, VixRunProgramOptions options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_ListProcessesInGuest(VixHandle vmHandle, int options, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_KillProcessInGuest(VixHandle vmHandle, uint64 pid, int options, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_RunScriptInGuest(VixHandle vmHandle, const char *interpreter, const char *scriptText, VixRunProgramOptions options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); /* * Guest File functions */ VixHandle VixVM_CopyFileFromHostToGuest(VixHandle vmHandle, const char *hostPathName, const char *guestPathName, int options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_CopyFileFromGuestToHost(VixHandle vmHandle, const char *guestPathName, const char *hostPathName, int options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_DeleteFileInGuest(VixHandle vmHandle, const char *guestPathName, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_FileExistsInGuest(VixHandle vmHandle, const char *guestPathName, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_RenameFileInGuest(VixHandle vmHandle, const char *oldName, const char *newName, int options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_CreateTempFileInGuest(VixHandle vmHandle, int options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_GetFileInfoInGuest(VixHandle vmHandle, const char *pathName, VixEventProc *callbackProc, void *clientData); /* * Guest Directory functions */ VixHandle VixVM_ListDirectoryInGuest(VixHandle vmHandle, const char *pathName, int options, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_CreateDirectoryInGuest(VixHandle vmHandle, const char *pathName, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_DeleteDirectoryInGuest(VixHandle vmHandle, const char *pathName, int options, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_DirectoryExistsInGuest(VixHandle vmHandle, const char *pathName, VixEventProc *callbackProc, void *clientData); /* * Guest Variable Functions */ enum { VIX_VM_GUEST_VARIABLE = 1, VIX_VM_CONFIG_RUNTIME_ONLY = 2, VIX_GUEST_ENVIRONMENT_VARIABLE = 3, }; VixHandle VixVM_ReadVariable(VixHandle vmHandle, int variableType, const char *name, int options, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_WriteVariable(VixHandle vmHandle, int variableType, const char *valueName, const char *value, int options, VixEventProc *callbackProc, void *clientData); /* * Snapshot functions that operate on a VM */ VixError VixVM_GetNumRootSnapshots(VixHandle vmHandle, int *result); VixError VixVM_GetRootSnapshot(VixHandle vmHandle, int index, VixHandle *snapshotHandle); VixError VixVM_GetCurrentSnapshot(VixHandle vmHandle, VixHandle *snapshotHandle); VixError VixVM_GetNamedSnapshot(VixHandle vmHandle, const char *name, VixHandle *snapshotHandle); typedef int VixRemoveSnapshotOptions; enum { VIX_SNAPSHOT_REMOVE_CHILDREN = 0x0001, }; VixHandle VixVM_RemoveSnapshot(VixHandle vmHandle, VixHandle snapshotHandle, VixRemoveSnapshotOptions options, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_RevertToSnapshot(VixHandle vmHandle, VixHandle snapshotHandle, VixVMPowerOpOptions options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); typedef int VixCreateSnapshotOptions; enum { VIX_SNAPSHOT_INCLUDE_MEMORY = 0x0002, }; VixHandle VixVM_CreateSnapshot(VixHandle vmHandle, const char *name, const char *description, VixCreateSnapshotOptions options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); /* * Shared Folders Functions */ /* * These are the flags describing each shared folder. */ typedef int VixMsgSharedFolderOptions; enum { VIX_SHAREDFOLDER_WRITE_ACCESS = 0x04, }; VixHandle VixVM_EnableSharedFolders(VixHandle vmHandle, Bool enabled, int options, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_GetNumSharedFolders(VixHandle vmHandle, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_GetSharedFolderState(VixHandle vmHandle, int index, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_SetSharedFolderState(VixHandle vmHandle, const char *shareName, const char *hostPathName, VixMsgSharedFolderOptions flags, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_AddSharedFolder(VixHandle vmHandle, const char *shareName, const char *hostPathName, VixMsgSharedFolderOptions flags, VixEventProc *callbackProc, void *clientData); VixHandle VixVM_RemoveSharedFolder(VixHandle vmHandle, const char *shareName, int flags, VixEventProc *callbackProc, void *clientData); /* * Screen Capture */ #ifndef VIX_HIDE_FROM_JAVA enum { VIX_CAPTURESCREENFORMAT_PNG = 0x01, VIX_CAPTURESCREENFORMAT_PNG_NOCOMPRESS = 0x02, }; VixHandle VixVM_CaptureScreenImage(VixHandle vmHandle, int captureType, VixHandle additionalProperties, VixEventProc *callbackProc, void *clientdata); #endif // VIX_HIDE_FROM_JAVA /* * VM Cloning -- */ typedef int VixCloneType; enum { VIX_CLONETYPE_FULL = 0, VIX_CLONETYPE_LINKED = 1, }; VixHandle VixVM_Clone(VixHandle vmHandle, VixHandle snapshotHandle, VixCloneType cloneType, const char *destConfigPathName, int options, VixHandle propertyListHandle, VixEventProc *callbackProc, void *clientData); /* * Misc Functions */ VixHandle VixVM_UpgradeVirtualHardware(VixHandle vmHandle, int options, VixEventProc *callbackProc, void *clientData); enum { VIX_INSTALLTOOLS_MOUNT_TOOLS_INSTALLER = 0x00, VIX_INSTALLTOOLS_AUTO_UPGRADE = 0x01, VIX_INSTALLTOOLS_RETURN_IMMEDIATELY = 0x02 }; VixHandle VixVM_InstallTools(VixHandle vmHandle, int options, const char *commandLineArgs, VixEventProc *callbackProc, void *clientData); /* *----------------------------------------------------------------------------- * * VIX Job -- * *----------------------------------------------------------------------------- */ /* * Synchronization functions * (used to detect when an asynch operation completes). */ VixError VixJob_Wait(VixHandle jobHandle, VixPropertyID firstPropertyID, ...); VixError VixJob_CheckCompletion(VixHandle jobHandle, Bool *complete); /* * Accessor functions * (used to get results of a completed asynch operation). */ VixError VixJob_GetError(VixHandle jobHandle); int VixJob_GetNumProperties(VixHandle jobHandle, int resultPropertyID); VixError VixJob_GetNthProperties(VixHandle jobHandle, int index, int propertyID, ...); /* *----------------------------------------------------------------------------- * * VIX Snapshot -- * *----------------------------------------------------------------------------- */ VixError VixSnapshot_GetNumChildren(VixHandle parentSnapshotHandle, int *numChildSnapshots); VixError VixSnapshot_GetChild(VixHandle parentSnapshotHandle, int index, VixHandle *childSnapshotHandle); VixError VixSnapshot_GetParent(VixHandle snapshotHandle, VixHandle *parentSnapshotHandle); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* _VIX_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vixCommands.h000066400000000000000000002304741321503522500251420ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * vixCommands.h -- * * Defines used when Vix crosses various IPC boundaries. */ #ifndef _VIX_COMMANDS_H_ #define _VIX_COMMANDS_H_ #include "vixOpenSource.h" #if defined(__cplusplus) extern "C" { #endif /* * These describe the format of the message objects. * This will change when the client/vmx support different * structures for the message header. Hopefully, that won't * happen. */ #define VIX_COMMAND_MAGIC_WORD 0xd00d0001 #define VIX_COMMAND_MESSAGE_VERSION 5 /* * These give upper bounds for how big any VIX IPC meesage * should be. There are for sanity checks and to ignore maliciously * large messages that may be part of an DoS attack. The may need to * be revised if large messages are added to the protocol. */ #define VIX_COMMAND_MAX_SIZE (16 * 1024 * 1024) #define VIX_COMMAND_MAX_REQUEST_SIZE 65536 /* * We don't want to allow guest ops commands with input size too large. * Limit it to the max request size with enough room for the credentials. * Check bugs 824773, 926819 for more details. */ #define VIX_COMMAND_MAX_USER_INPUT_SIZE (VIX_COMMAND_MAX_REQUEST_SIZE - 5000) /* * The types of credential we can pass with any request. */ #define VIX_USER_CREDENTIAL_NONE 0 #define VIX_USER_CREDENTIAL_NAME_PASSWORD 1 #define VIX_USER_CREDENTIAL_ANONYMOUS 2 #define VIX_USER_CREDENTIAL_ROOT 3 #define VIX_USER_CREDENTIAL_NAME_PASSWORD_OBFUSCATED 4 #define VIX_USER_CREDENTIAL_CONSOLE_USER 5 #define VIX_USER_CREDENTIAL_HOST_CONFIG_SECRET 6 #define VIX_USER_CREDENTIAL_HOST_CONFIG_HASHED_SECRET 7 #define VIX_USER_CREDENTIAL_NAMED_INTERACTIVE_USER 8 #define VIX_USER_CREDENTIAL_TICKETED_SESSION 9 #define VIX_USER_CREDENTIAL_SSPI 10 #define VIX_USER_CREDENTIAL_SAML_BEARER_TOKEN 11 #define VIX_SHARED_SECRET_CONFIG_USER_NAME "__VMware_Vix_Shared_Secret_1__" /* * This is the port for the server side remote Vix component */ #define VIX_SERVER_PORT 61525 #define VIX_TOOLS_SOCKET_PORT 61526 /* * These are the flags set in the commonFlags field. */ enum VixCommonCommandOptionValues { VIX_COMMAND_REQUEST = 0x01, VIX_COMMAND_REPORT_EVENT = 0x02, VIX_COMMAND_FORWARD_TO_GUEST = 0x04, VIX_COMMAND_GUEST_RETURNS_STRING = 0x08, VIX_COMMAND_GUEST_RETURNS_INTEGER_STRING = 0x10, /* DEPRECATED VIX_COMMAND_GUEST_RETURNS_ENCODED_STRING = 0x20, */ VIX_COMMAND_GUEST_RETURNS_PROPERTY_LIST = 0x40, VIX_COMMAND_GUEST_RETURNS_BINARY = 0x80, // We cannot add more constants here. This is stored in a uint8, // so it is full. Use requestFlags or responseFlags. }; /* * These are the flags set in the request Flags field. */ enum { VIX_REQUESTMSG_ONLY_RELOAD_NETWORKS = 0x001, VIX_REQUESTMSG_RETURN_ON_INITIATING_TOOLS_UPGRADE = 0x002, VIX_REQUESTMSG_RUN_IN_ANY_VMX_STATE = 0x004, VIX_REQUESTMSG_REQUIRES_INTERACTIVE_ENVIRONMENT = 0x008, VIX_REQUESTMSG_INCLUDES_AUTH_DATA_V1 = 0x010, VIX_REQUESTMSG_REQUIRES_VMDB_NOTIFICATION = 0x020, VIX_REQUESTMSG_ESCAPE_XML_DATA = 0x040, VIX_REQUESTMSG_HAS_HASHED_SHARED_SECRET = 0x080, VIX_REQUESTMSG_VIGOR_COMMAND = 0x100, }; /* * These are the flags set in responseFlags. */ enum VixResponseFlagsValues { VIX_RESPONSE_SOFT_POWER_OP = 0x0001, VIX_RESPONSE_EXTENDED_RESULT_V1 = 0x0002, VIX_RESPONSE_TRUNCATED = 0x0004, VIX_RESPONSE_FSR = 0x0008, VIX_RESPONSE_VMDB_NOTIFICATION_POSTED = 0x0010, VIX_RESPONSE_VIGOR_COMMAND = 0x0020, }; /* * This is the header for one message, either a request or a * response, and sent either to or from the VMX. * * Every message has 3 regions: * * ------------------------------------- * | Header | Body | Credential | * ------------------------------------- * * The credential and the body may either or both be empty. * The 3 regions always appear in this order. First the header, then a body * if there is one, then a credential if there is one. * There should be no gaps between these regions. New regions are added * to the end. This means the lengths can also be used to compute * offsets to the regions. * * The length of the headers, the credential, and the body are all stored in * the common header. This should allow parsing code to receive complete * messages even if it does not understand them. * * Currently that the credential is only used for a Request. It is * currently empty for a response. * */ typedef #include "vmware_pack_begin.h" struct VixMsgHeader { uint32 magic; uint16 messageVersion; uint32 totalMessageLength; uint32 headerLength; uint32 bodyLength; uint32 credentialLength; uint8 commonFlags; } #include "vmware_pack_end.h" VixMsgHeader; /* * These are the headers for a single request, response, or event. * In theory, either the VMX or the client may issue a request * to the other. In practice, legacy foundry clients can only * accept response messages from the VMX, not requests. Because of * this, an event message is a special kind of response message. */ typedef #include "vmware_pack_begin.h" struct VixCommandRequestHeader { VixMsgHeader commonHeader; uint32 opCode; uint32 requestFlags; uint32 timeOut; uint64 cookie; uint32 clientHandleId; // for remote case uint32 userCredentialType; } #include "vmware_pack_end.h" VixCommandRequestHeader; typedef #include "vmware_pack_begin.h" struct VixCommandResponseHeader { VixMsgHeader commonHeader; uint64 requestCookie; uint32 responseFlags; uint32 duration; uint32 error; uint32 additionalError; uint32 errorDataLength; } #include "vmware_pack_end.h" VixCommandResponseHeader; typedef #include "vmware_pack_begin.h" struct VixMsgEventHeader { VixCommandResponseHeader responseHeader; int32 eventType; } #include "vmware_pack_end.h" VixMsgEventHeader; /* * A trivial request that is just a generic * response header (it has no body). */ typedef #include "vmware_pack_begin.h" struct VixMsgTrivialRequest { VixCommandRequestHeader header; } #include "vmware_pack_end.h" VixMsgTrivialRequest; /* * A trivial event that is just a generic * event header (it has no body). */ typedef #include "vmware_pack_begin.h" struct VixMsgTrivialEvent { VixMsgEventHeader eventHeader; } #include "vmware_pack_end.h" VixMsgTrivialEvent; /* * ********************************************************** * This is a generic progress update from the VMX. * The VMX may send several of these before sending a final response * message. These only report progress, they do not mean the job * has completed. These messages are identified by the * VIX_COMMAND_REPORT_EVENT flag in the commonFlags field and * VIX_EVENTTYPE_JOB_PROGRESS as the eventType. */ typedef #include "vmware_pack_begin.h" struct VixMsgProgressEvent { VixMsgEventHeader eventHeader; int64 workToDo; int64 workDone; } #include "vmware_pack_end.h" VixMsgProgressEvent; /* * This is an event sent from the VMX to all clients when some property changes. * It may be used for any runtime property. */ typedef #include "vmware_pack_begin.h" struct VixMsgPropertyChangedEvent { VixMsgEventHeader eventHeader; int options; uint32 propertyListSize; } #include "vmware_pack_end.h" VixMsgPropertyChangedEvent; /* * ********************************************************** * This is a userName and password pair. */ typedef #include "vmware_pack_begin.h" struct VixCommandNamePassword { uint32 nameLength; uint32 passwordLength; } #include "vmware_pack_end.h" VixCommandNamePassword; /* * ********************************************************** * This is a ticketed session for authentication. */ typedef #include "vmware_pack_begin.h" struct VixCommandTicketedSession { uint32 ticketLength; } #include "vmware_pack_end.h" VixCommandTicketedSession; /* * ********************************************************** * This is a SSPI token for acquiring credentials */ typedef #include "vmware_pack_begin.h" struct VixCommandSSPI { uint32 tokenLength; } #include "vmware_pack_end.h" VixCommandSSPI; /* * ********************************************************** * This is a SAML bearer token with optional userName to specify * an IdProvider store. */ typedef #include "vmware_pack_begin.h" struct VixCommandSAMLToken { uint32 tokenLength; uint32 nameLength; } #include "vmware_pack_end.h" VixCommandSAMLToken; /* * ********************************************************** * Basic power op request. The response is just a generic * response header (it has no body). */ typedef #include "vmware_pack_begin.h" struct VixMsgPowerOpRequest { VixCommandRequestHeader header; VixVMPowerOpOptions powerOpOptions; /* * Starting in Workstation 7.0, a serialized property list buffer * can be appended here. This was originally used for augmenting * poweroff to support revert to snapshot upon poweroff functionality. */ } #include "vmware_pack_end.h" VixMsgPowerOpRequest; /* * ********************************************************** * Get/Set Properties Request */ typedef #include "vmware_pack_begin.h" struct VixMsgGetVMStateResponse { VixCommandResponseHeader header; uint32 bufferSize; // This is followed by the buffer of serialized properties } #include "vmware_pack_end.h" VixMsgGetVMStateResponse; typedef #include "vmware_pack_begin.h" struct VixMsgSetVMStateRequest { VixCommandRequestHeader header; uint32 bufferSize; // This is followed by the buffer of serialized properties } #include "vmware_pack_end.h" VixMsgSetVMStateRequest; typedef #include "vmware_pack_begin.h" struct VixMsgAuthDataV1 { int64 nonce; uint32 sequenceNumber; uint8 hashValue[32]; } #include "vmware_pack_end.h" VixMsgAuthDataV1; /* * ********************************************************** * Basic reload state request. The response is just a generic * response header (it has no body). */ typedef #include "vmware_pack_begin.h" struct VixMsgReloadVMStateRequest { VixCommandRequestHeader header; // This is followed by an array of VixMsgConfigurationObjectType objects } #include "vmware_pack_end.h" VixMsgReloadVMStateRequest; /* * This is a prefix to a configuration object. The current supported * types are defined below in the VixCommonConfigObjectType enum. * Following each object type struct is the specific object. Currently, * we support: * * VIX_NETWORK_SETTING_CONFIG - VixMsgNICBandwidth */ typedef #include "vmware_pack_begin.h" struct VixMsgConfigurationObjectType { int32 configurationType; uint32 objectSize; } #include "vmware_pack_end.h" VixMsgConfigurationObjectType; typedef #include "vmware_pack_begin.h" struct VixMsgNICBandwidth { Bool validNICNum; int32 nicNum; char pvnGUID[64]; uint32 totalBandwidth; uint32 maxSendBandwidth; uint32 maxReceiveBandwidth; uint32 packetLossPattern; uint32 packetLossRate; uint32 packetLossMinBurstDuration; uint32 packetLossMaxBurstDuration; uint32 minLatency; uint32 maxLatency; uint32 options; } #include "vmware_pack_end.h" VixMsgNICBandwidth; typedef #include "vmware_pack_begin.h" struct VixMsgLANSegmentConfiguration { VixMsgConfigurationObjectType configHeader; VixMsgNICBandwidth lanSegment; } #include "vmware_pack_end.h" VixMsgLANSegmentConfiguration; /* * These are options to the bandwidth commands. */ enum VixMsgPacketLossType { // packetLossPattern values VIX_PACKETLOSS_RANDOM = 1, }; /* * These are the types of configuration objects we can send * to a VIX_COMMAND_RELOAD_VM command. */ enum VixMsgConfigObjectType { VIX_LAN_SEGMENT_SETTING_CONFIG = 1, }; /* * ********************************************************** * Wait for tools request. The response is just a generic * response header (it has no body). */ typedef #include "vmware_pack_begin.h" struct VixMsgWaitForToolsRequest { VixCommandRequestHeader header; int32 timeoutInSeconds; int32 minVersion; } #include "vmware_pack_end.h" VixMsgWaitForToolsRequest; /* * ********************************************************** * Run a program on the guest. */ typedef #include "vmware_pack_begin.h" struct VixMsgRunProgramRequest { VixCommandRequestHeader header; int32 runProgramOptions; uint32 programNameLength; uint32 commandLineArgsLength; } #include "vmware_pack_end.h" VixMsgRunProgramRequest; typedef #include "vmware_pack_begin.h" struct VixMsgOldRunProgramResponse { VixCommandResponseHeader header; int32 exitCode; VmTimeType deltaTime; } #include "vmware_pack_end.h" VixMsgOldRunProgramResponse; typedef #include "vmware_pack_begin.h" struct VixMsgRunProgramResponse { VixCommandResponseHeader header; int32 exitCode; VmTimeType deltaTime; int64 pid; uint32 stdOutLength; uint32 stdErrLength; } #include "vmware_pack_end.h" VixMsgRunProgramResponse; /* * ********************************************************** * Install VMware tools. */ typedef #include "vmware_pack_begin.h" struct VixMsgInstallToolsRequest { VixCommandRequestHeader header; int32 installOptions; uint32 commandLineArgsLength; } #include "vmware_pack_end.h" VixMsgInstallToolsRequest; /* * ********************************************************** * Send keystrokes to the guest. */ enum VixKeyStrokeCharType { VIX_KEYSTROKE_SCANCODE = 1, VIX_KEYSTROKE_TEXT_CHAR = 2, }; enum VixKeyStrokeModifiers { VIX_KEYSTROKE_MODIFIER_KEY_DOWN = 0x01, VIX_KEYSTROKE_MODIFIER_KEY_UP = 0x02, VIX_KEYSTROKE_MODIFIER_CONTROL = 0x04, VIX_KEYSTROKE_MODIFIER_SHIFT = 0x08, VIX_KEYSTROKE_MODIFIER_ALT = 0x10, VIX_KEYSTROKE_MODIFIER_KEY_DOWN_ONLY = 0x80, VIX_KEYSTROKE_MODIFIER_KEY_UP_ONLY = 0x100, }; typedef #include "vmware_pack_begin.h" struct VixMsgKeyStroke { int32 modifier; int32 scanCode; int32 duration; int32 delayAfterKeyUp; int32 repeat; } #include "vmware_pack_end.h" VixMsgKeyStroke; typedef #include "vmware_pack_begin.h" struct VixMsgSendKeyStrokesRequest { VixCommandRequestHeader header; int32 keyStrokeType; int32 options; int64 targetPid; int32 numKeyStrokes; uint32 windowNameLength; } #include "vmware_pack_end.h" VixMsgSendKeyStrokesRequest; /* * send a mouse event to the guest */ typedef #include "vmware_pack_begin.h" struct VixMsgSendMouseEventRequest { VixCommandRequestHeader header; int16 x; int16 y; int16 buttons; int32 options; } #include "vmware_pack_end.h" VixMsgSendMouseEventRequest; /* * ********************************************************** * Read or write the registry on the guest. */ typedef #include "vmware_pack_begin.h" struct VixMsgRegistryRequest { VixCommandRequestHeader header; uint32 registryKeyLength; int32 expectedRegistryKeyType; uint32 dataToWriteSize; } #include "vmware_pack_end.h" VixMsgRegistryRequest; /* * ********************************************************** * Copy files between the host and the guest. */ typedef #include "vmware_pack_begin.h" struct VixCommandRenameFileRequest { VixCommandRequestHeader header; int32 copyFileOptions; uint32 oldPathNameLength; uint32 newPathNameLength; uint32 filePropertiesLength; } #include "vmware_pack_end.h" VixCommandRenameFileRequest; typedef #include "vmware_pack_begin.h" struct VixCommandRenameFileRequestEx { VixCommandRequestHeader header; int32 copyFileOptions; uint32 oldPathNameLength; uint32 newPathNameLength; uint32 filePropertiesLength; Bool overwrite; } #include "vmware_pack_end.h" VixCommandRenameFileRequestEx; typedef #include "vmware_pack_begin.h" struct VixCommandHgfsSendPacket { VixCommandRequestHeader header; uint32 hgfsPacketSize; int32 timeout; } #include "vmware_pack_end.h" VixCommandHgfsSendPacket; typedef #include "vmware_pack_begin.h" struct VixMsgSetGuestFileAttributesRequest { VixCommandRequestHeader header; int32 fileOptions; int64 accessTime; int64 modificationTime; int32 ownerId; int32 groupId; int32 permissions; Bool hidden; Bool readOnly; uint32 guestPathNameLength; } #include "vmware_pack_end.h" VixMsgSetGuestFileAttributesRequest; /* * ********************************************************** * Perform a simple operation (like delete or check for existence) * on a file or registry key on the guest. */ typedef #include "vmware_pack_begin.h" struct VixMsgSimpleFileRequest { VixCommandRequestHeader header; int32 fileOptions; uint32 guestPathNameLength; } #include "vmware_pack_end.h" VixMsgSimpleFileRequest; typedef #include "vmware_pack_begin.h" struct VixMsgListDirectoryRequest { VixCommandRequestHeader header; int32 fileOptions; uint32 guestPathNameLength; int64 offset; } #include "vmware_pack_end.h" VixMsgListDirectoryRequest; enum VixListDirectoryOptions { VIX_LIST_DIRECTORY_USE_OFFSET = 0x01 }; typedef #include "vmware_pack_begin.h" struct VixMsgListFilesRequest { VixCommandRequestHeader header; int32 fileOptions; uint32 guestPathNameLength; uint32 patternLength; int32 index; int32 maxResults; uint64 offset; } #include "vmware_pack_end.h" VixMsgListFilesRequest; typedef #include "vmware_pack_begin.h" struct VixCommandInitiateFileTransferToGuestRequest { VixCommandRequestHeader header; int32 options; uint32 guestPathNameLength; Bool overwrite; } #include "vmware_pack_end.h" VixCommandInitiateFileTransferToGuestRequest; /* * This is used to reply to several operations, like testing whether * a file or registry key exists on the client. */ typedef #include "vmware_pack_begin.h" struct VixMsgCheckExistsResponse { VixCommandResponseHeader header; Bool exists; } #include "vmware_pack_end.h" VixMsgCheckExistsResponse; /* * ********************************************************** * Perform a create file operation (like createDir or moveFile) * on a file in the guest. This lets you pass in things like the initial file * properties. */ typedef #include "vmware_pack_begin.h" struct VixMsgCreateFileRequest { VixCommandRequestHeader header; int32 fileOptions; uint32 guestPathNameLength; uint32 filePropertiesLength; } #include "vmware_pack_end.h" VixMsgCreateFileRequest; typedef #include "vmware_pack_begin.h" struct VixMsgCreateFileRequestEx { VixCommandRequestHeader header; int32 fileOptions; uint32 guestPathNameLength; uint32 filePropertiesLength; Bool createParentDirectories; } #include "vmware_pack_end.h" VixMsgCreateFileRequestEx; /* * ********************************************************** * Hot extend a disk in a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgHotExtendDiskRequest { VixCommandRequestHeader header; int32 hotDiskOptions; uint32 typeLength; int32 adapterNum; int32 targetNum; uint64 newNumSectors; } #include "vmware_pack_end.h" VixMsgHotExtendDiskRequest; /* * ********************************************************** * Hot plug CPU in a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgHotPlugCPURequest { VixCommandRequestHeader header; uint32 newNumCPU; } #include "vmware_pack_end.h" VixMsgHotPlugCPURequest; /* * ********************************************************** * Hot plug memory in a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgHotPlugMemoryRequest { VixCommandRequestHeader header; uint32 newSizeMb; } #include "vmware_pack_end.h" VixMsgHotPlugMemoryRequest; /* * ********************************************************** * Hot add device in a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgHotAddDeviceRequest { VixCommandRequestHeader header; int32 deviceType; uint32 devicePropsBufferSize; int32 backingType; uint32 backingPropsBufferSize; } #include "vmware_pack_end.h" VixMsgHotAddDeviceRequest; typedef #include "vmware_pack_begin.h" struct VixMsgHotAddDeviceResponse { VixCommandResponseHeader header; int32 adapterNum; int32 targetNum; } #include "vmware_pack_end.h" VixMsgHotAddDeviceResponse; /* * ********************************************************** * Hot remove device in a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgHotRemoveDeviceRequest { VixCommandRequestHeader header; int32 deviceType; uint32 devicePropsBufferSize; } #include "vmware_pack_end.h" VixMsgHotRemoveDeviceRequest; /* * ********************************************************** * Change monitor type of a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgHotChangeMonitorTypeRequest { VixCommandRequestHeader header; int32 monitorType; } #include "vmware_pack_end.h" VixMsgHotChangeMonitorTypeRequest; /* * ********************************************************** * Hot plug begin batch. */ typedef #include "vmware_pack_begin.h" struct VixMsgHotPlugBeginBatchRequest { VixCommandRequestHeader header; int32 flags; } #include "vmware_pack_end.h" VixMsgHotPlugBeginBatchRequest; /* * ********************************************************** * Hot plug commit batch. */ typedef #include "vmware_pack_begin.h" struct VixMsgHotPlugCommitBatchRequest { VixCommandRequestHeader header; int32 status; } #include "vmware_pack_end.h" VixMsgHotPlugCommitBatchRequest; /* * ********************************************************** * Transfer connection. Besides fields here you are supposed to * receive file descriptor OOB. */ typedef #include "vmware_pack_begin.h" struct VixMsgTransferConnectionRequest { VixCommandRequestHeader header; Bool isPrivileged; uint32 cryptoLength; uint32 fdLength; /* uint8 cryptoData[]; */ /* uint8 fdData[]; */ } #include "vmware_pack_end.h" VixMsgTransferConnectionRequest; /* * ********************************************************** * Pass data. Besides fields here you may receive also * file descriptor. Data is just command which was pending * on original connection already transferred via * TransferConnectionRequest. */ typedef #include "vmware_pack_begin.h" struct VixMsgTransferRequestRequest { VixCommandRequestHeader header; uint32 dataLength; uint32 fdLength; /* uint8 data[]; */ /* uint8 fdData[]; */ } #include "vmware_pack_end.h" VixMsgTransferRequestRequest; /* * ********************************************************** * Pass final data. Besides fields here you may receive also * file descriptor. Data is just what was already received * on the socket passed by TransferConnectionRequest. */ typedef #include "vmware_pack_begin.h" struct VixMsgTransferFinalDataRequest { VixCommandRequestHeader header; uint32 dataLength; uint32 fdLength; /* uint8 data[]; */ /* uint8 fdData[]; */ } #include "vmware_pack_end.h" VixMsgTransferFinalDataRequest; /* * ********************************************************** * Create a snapshot of a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgCreateSnapshotRequest { VixCommandRequestHeader header; int32 options; Bool powerOff; Bool saveDeviceState; uint32 nameLength; uint32 descriptionLength; } #include "vmware_pack_end.h" VixMsgCreateSnapshotRequest; typedef #include "vmware_pack_begin.h" struct VixMsgCreateSnapshotResponse { VixCommandResponseHeader header; int32 snapshotUID; } #include "vmware_pack_end.h" VixMsgCreateSnapshotResponse; /* * Several snapshot operations for a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgSnapshotRequest { VixCommandRequestHeader header; int32 options; int32 snapshotId; } #include "vmware_pack_end.h" VixMsgSnapshotRequest; typedef #include "vmware_pack_begin.h" struct VixMsgSnapshotUpdateEvent { VixMsgEventHeader eventHeader; int32 options; uint32 propertyListLength; /* * This is followed by a serialized property list. */ } #include "vmware_pack_end.h" VixMsgSnapshotUpdateEvent; typedef #include "vmware_pack_begin.h" struct VixMsgSnapshotMRURequest { VixCommandRequestHeader header; int32 snapshotId; int32 maxMRU; } #include "vmware_pack_end.h" VixMsgSnapshotMRURequest; typedef #include "vmware_pack_begin.h" struct VixMsgSetSnapshotInfoRequest { VixCommandRequestHeader header; int32 snapshotId; int32 clientFlags; int32 numTierUIDs; uint32 displayNameLength; uint32 descriptionLength; uint32 propertyListLength; uint32 tierUIDListLength; /* * Followed by: * displayName string * description string * serialized property list. */ } #include "vmware_pack_end.h" VixMsgSetSnapshotInfoRequest; typedef #include "vmware_pack_begin.h" struct VixMsgSetSnapshotInfoResponse { VixCommandResponseHeader header; uint32 propertyListLength; } #include "vmware_pack_end.h" VixMsgSetSnapshotInfoResponse; typedef #include "vmware_pack_begin.h" struct VixMsgRemoveBulkSnapshotRequest { VixCommandRequestHeader header; int32 options; int32 numSnapshots; /* * This is followed by numSnapshots snapshotIDs. */ } #include "vmware_pack_end.h" VixMsgRemoveBulkSnapshotRequest; /* * Stop recording or playback of a snapshot event log. */ typedef #include "vmware_pack_begin.h" struct VixMsgVMSnapshotPauseRequest { VixCommandRequestHeader header; int32 options; } #include "vmware_pack_end.h" VixMsgVMSnapshotPauseRequest; typedef #include "vmware_pack_begin.h" struct VixMsgDebuggerEvent { VixMsgEventHeader eventHeader; int32 blobLength; /* * This is followed by the blob buffer. */ } #include "vmware_pack_end.h" VixMsgDebuggerEvent; /* * ********************************************************** * Shared folder operations. */ typedef #include "vmware_pack_begin.h" struct VixMsgSharedFolderRequest { VixCommandRequestHeader header; int32 options; int32 index; uint32 shareNameLength; uint32 hostPathNameLength; } #include "vmware_pack_end.h" VixMsgSharedFolderRequest; typedef #include "vmware_pack_begin.h" struct VixMsgSharedFolderResponse { VixCommandResponseHeader header; int32 numSharedFolders; } #include "vmware_pack_end.h" VixMsgSharedFolderResponse; typedef #include "vmware_pack_begin.h" struct VixMsgGetSharedFolderInfoResponse { VixCommandResponseHeader header; uint32 shareNameLength; uint32 hostPathNameLength; int32 sharedFolderFlags; } #include "vmware_pack_end.h" VixMsgGetSharedFolderInfoResponse; /* * Add or change a shared folder request. */ typedef #include "vmware_pack_begin.h" struct VixMsgSetSharedFolderRequest { VixCommandRequestHeader header; int32 options; uint32 shareNameLength; uint32 hostPathNameLength; } #include "vmware_pack_end.h" VixMsgSetSharedFolderRequest; /* * ********************************************************** * Capture the screen of a VM */ typedef #include "vmware_pack_begin.h" struct VixMsgCaptureScreenRequest { VixCommandRequestHeader header; int32 format; // Identifies the requested data format. int32 maxSize; // Max data response size in bytes // (-1 is any size) int32 captureScreenOptions; } #include "vmware_pack_end.h" VixMsgCaptureScreenRequest; typedef #include "vmware_pack_begin.h" struct VixMsgCaptureScreenResponse { VixCommandResponseHeader header; int32 format; // Format of the data in the response. uint32 dataOffset; // Relative to the address of this struct. } #include "vmware_pack_end.h" VixMsgCaptureScreenResponse; /* * ********************************************************** * Run a script in the guest. */ typedef #include "vmware_pack_begin.h" struct VixMsgRunScriptRequest { VixCommandRequestHeader header; int32 scriptOptions; uint32 interpreterNameLength; uint32 scriptLength; uint32 propertiesLength; } #include "vmware_pack_end.h" VixMsgRunScriptRequest; /* * ********************************************************** * An unsupported command. This is used to test future versions * of the API sending us commands we don't recognize. */ typedef #include "vmware_pack_begin.h" struct VixUnsupportedCommandRequest { VixCommandRequestHeader header; char junk[2053]; } #include "vmware_pack_end.h" VixUnsupportedCommandRequest; /* * ********************************************************** * Create a session key between the client and the VMX. */ typedef #include "vmware_pack_begin.h" struct VixCommandMakeSessionKeyRequest { VixCommandRequestHeader header; int32 keyOptions; int32 timeout; uint32 responseKeyLength; int32 responseKeyCypherType; int32 cypherType; } #include "vmware_pack_end.h" VixCommandMakeSessionKeyRequest; typedef #include "vmware_pack_begin.h" struct VixCommandMakeSessionKeyResponse { VixCommandResponseHeader header; int32 keyOptions; int32 timeout; uint32 keyLength; int32 cypherType; } #include "vmware_pack_end.h" VixCommandMakeSessionKeyResponse; typedef #include "vmware_pack_begin.h" struct VixCommandGenerateNonceResponse { VixCommandResponseHeader header; int64 nonce; } #include "vmware_pack_end.h" VixCommandGenerateNonceResponse; enum { VIX_CYPHERTYPE_NONE = 0, VIX_CYPHERTYPE_DEFAULT = 1, }; /* * ********************************************************** * Kill a guest process. */ typedef #include "vmware_pack_begin.h" struct VixCommandKillProcessRequest { VixCommandRequestHeader header; uint64 pid; uint32 options; } #include "vmware_pack_end.h" VixCommandKillProcessRequest; /* * ********************************************************** * Read and write variables like guest variables and config values. */ typedef #include "vmware_pack_begin.h" struct VixMsgReadVariableRequest { VixCommandRequestHeader header; int32 variableType; int32 options; uint32 nameLength; } #include "vmware_pack_end.h" VixMsgReadVariableRequest; typedef #include "vmware_pack_begin.h" struct VixMsgReadVariableResponse { VixCommandResponseHeader header; int32 valueType; int32 valueProperties; uint32 valueLength; } #include "vmware_pack_end.h" VixMsgReadVariableResponse; /* * Several snapshot operations for a running VM. */ typedef #include "vmware_pack_begin.h" struct VixMsgWriteVariableRequest { VixCommandRequestHeader header; int32 variableType; int32 options; uint32 nameLength; uint32 valueLength; } #include "vmware_pack_end.h" VixMsgWriteVariableRequest; /* * ********************************************************** * Perform a create file operation (like createDir or moveFile) * on a file in the guest. This lets you pass in things like the initial file * properties. */ typedef #include "vmware_pack_begin.h" struct VixMsgCreateTempFileRequest { VixCommandRequestHeader header; int32 options; uint32 propertyNameLength; uint32 filePrefixLength; uint32 fileSuffixLength; } #include "vmware_pack_end.h" VixMsgCreateTempFileRequest; typedef #include "vmware_pack_begin.h" struct VixMsgCreateTempFileRequestEx { VixCommandRequestHeader header; int32 options; uint32 filePrefixLength; uint32 fileSuffixLength; uint32 directoryPathLength; uint32 propertyListLength; } #include "vmware_pack_end.h" VixMsgCreateTempFileRequestEx; typedef #include "vmware_pack_begin.h" struct { VixCommandRequestHeader header; int32 fileOptions; uint32 guestPathNameLength; uint32 filePropertiesLength; Bool recursive; } #include "vmware_pack_end.h" VixMsgDeleteDirectoryRequest; /* * ********************************************************** * Connect/Disconnect device request. The response is just a generic * response header (it has no body). */ typedef #include "vmware_pack_begin.h" struct VixMsgConnectDeviceRequest { VixCommandRequestHeader header; int32 options; Bool connected; uint32 nameLength; } #include "vmware_pack_end.h" VixMsgConnectDeviceRequest; /* * ********************************************************** * Get the state of a virtual device. */ typedef #include "vmware_pack_begin.h" struct VixMsgGetDeviceStateRequest { VixCommandRequestHeader header; int32 options; uint32 nameLength; } #include "vmware_pack_end.h" VixMsgGetDeviceStateRequest; /* * This is used to reply to IsDeviceConnected operations. */ typedef #include "vmware_pack_begin.h" struct VixMsgGetDeviceStateResponse { VixCommandResponseHeader header; Bool connected; int32 stateFlags; // Maybe capacity and percent allocated? } #include "vmware_pack_end.h" VixMsgGetDeviceStateResponse; /* * ********************************************************** * Enable/disable all shared folders on this VM. The response * is just a generic response header (it has no body). */ typedef #include "vmware_pack_begin.h" struct VixMsgEnableSharedFoldersRequest { VixCommandRequestHeader header; Bool enabled; int32 sharedFolderOptions; } #include "vmware_pack_end.h" VixMsgEnableSharedFoldersRequest; /* * ********************************************************** * Mount volumes in the guest. */ enum VixMountOptions { VIX_MOUNT_ALL = 0x0001, VIX_MOUNT_REMOUNT_FIRST = 0x0002, }; typedef #include "vmware_pack_begin.h" struct VixMsgMountHGFSRequest { VixCommandRequestHeader header; int32 mountOptions; int32 mountType; /* The str path list has the form "host1\0dest1\0host2\0dest2\0host3\0dest3\0\0" */ uint32 pathListLength; } #include "vmware_pack_end.h" VixMsgMountHGFSRequest; /* * Get guest networking config */ typedef #include "vmware_pack_begin.h" struct VixMsgGetGuestNetworkingConfigRequest { VixCommandRequestHeader header; int32 options; } #include "vmware_pack_end.h" VixMsgGetGuestNetworkingConfigRequest; /* * Set guest networking config */ typedef #include "vmware_pack_begin.h" struct VixMsgSetGuestNetworkingConfigRequest { VixCommandRequestHeader header; int32 options; uint32 bufferSize; } #include "vmware_pack_end.h" VixMsgSetGuestNetworkingConfigRequest; /* * Query VMX performance data */ typedef #include "vmware_pack_begin.h" struct VixMsgGetPerformanceDataRequest { VixCommandRequestHeader header; // unused for now, but left for future expansion in case we // get such a large list that we want to pass the desired properties. int32 options; uint32 sizeOfPropertyList; // This is followed by the buffer of properties we wish to fetch } #include "vmware_pack_end.h" VixMsgGetPerformanceDataRequest; typedef #include "vmware_pack_begin.h" struct VixMsgGetPerformanceDataResponse { VixCommandResponseHeader header; uint32 bufferSize; // This is followed by the buffer of serialized properties } #include "vmware_pack_end.h" VixMsgGetPerformanceDataResponse; /* * Run a program in guest with (VI version with more args) */ typedef #include "vmware_pack_begin.h" struct VixMsgStartProgramRequest { VixCommandRequestHeader header; Bool startMinimized; uint32 programPathLength; uint32 argumentsLength; uint32 workingDirLength; uint32 numEnvVars; uint32 envVarLength; // This is followed by the buffer of the args } #include "vmware_pack_end.h" VixMsgStartProgramRequest; typedef #include "vmware_pack_begin.h" struct VixMsgListProcessesExRequest { VixCommandRequestHeader header; // if we need to make multiple trips, this is the key used to identify // the result being processed uint32 key; // if we need to make multiple trips, this is the offset in the reply // from which to send the next chunk uint32 offset; uint32 numPids; // This is followed by the list of uint64s } #include "vmware_pack_end.h" VixMsgListProcessesExRequest; typedef #include "vmware_pack_begin.h" struct VixMsgReadEnvironmentVariablesRequest { VixCommandRequestHeader header; uint32 numNames; uint32 namesLength; // This is followed by the list of NUL-terminated names } #include "vmware_pack_end.h" VixMsgReadEnvironmentVariablesRequest; /* IdProvider support */ typedef #include "vmware_pack_begin.h" struct VixMsgAddAliasRequest { VixCommandRequestHeader header; uint32 options; uint32 userNameLen; uint32 pemCertLen; Bool addMapping; int32 subjectType; // one of VixGuestAuthSubjectType uint32 subjectNameLen; uint32 aliasCommentLen; /* Followed by the NUL-terminated string arguments. */ /* char[] userName; */ /* char[] pemCert; */ /* char[] subjectName; */ /* char[] aliasComment; */ } #include "vmware_pack_end.h" VixMsgAddAuthAliasRequest; typedef #include "vmware_pack_begin.h" struct VixMsgRemoveAuthAliasRequest { VixCommandRequestHeader header; uint32 options; uint32 userNameLen; uint32 pemCertLen; // special case for RemoveAliasByCert: // if subjectType is NONE, then all aliases will be removed. int32 subjectType; // one of VixGuestAuthSubjectType uint32 subjectNameLen; /* Followed by the NUL-terminated string arguments. */ /* char[] userName; */ /* char[] pemCert; */ /* char[] subjectName; */ } #include "vmware_pack_end.h" VixMsgRemoveAuthAliasRequest; typedef #include "vmware_pack_begin.h" struct VixMsgListAuthAliasesRequest { VixCommandRequestHeader header; uint32 options; uint32 userNameLen; /* char[] userName; */ } #include "vmware_pack_end.h" VixMsgListAuthAliasesRequest; typedef #include "vmware_pack_begin.h" struct VixMsgListMappedAliasesRequest { VixCommandRequestHeader header; uint32 options; } #include "vmware_pack_end.h" VixMsgListMappedAliasesRequest; /* * Windows Registry Management Support. */ typedef #include "vmware_pack_begin.h" struct VixMsgCreateRegKeyRequest { VixCommandRequestHeader header; uint32 options; uint32 pathLength; uint32 wowBitness; Bool isVolatile; uint32 classTypeLength; /* * Followed by NUL-terminated string arguments. * char[] path; * char[] classType; */ } #include "vmware_pack_end.h" VixMsgCreateRegKeyRequest; typedef #include "vmware_pack_begin.h" struct VixMsgListRegKeysRequest { VixCommandRequestHeader header; uint32 options; /* * If we need multiple roundtrips, this is the index * used to identify the result being processed. */ uint32 index; /* * If we need multiple roundtrips, this is the offset * in the reply from which to send the next chunk. */ uint32 offset; uint32 pathLength; uint32 wowBitness; Bool recursive; uint32 matchPatternLength; /* * Followed by NUL-terminated string arguments. * char[] path; * char[] matchPattern; */ } #include "vmware_pack_end.h" VixMsgListRegKeysRequest; typedef #include "vmware_pack_begin.h" struct VixMsgDeleteRegKeyRequest { VixCommandRequestHeader header; uint32 options; uint32 pathLength; uint32 wowBitness; Bool recursive; /* * Followed by NUL-terminated string arguments. * char[] path; */ } #include "vmware_pack_end.h" VixMsgDeleteRegKeyRequest; typedef #include "vmware_pack_begin.h" struct VixMsgSetRegValueRequest { VixCommandRequestHeader header; uint32 options; uint32 pathLength; uint32 wowBitness; uint32 nameLength; uint32 dataBlobType; uint32 dataBlobLength; /* * Followed by NUL-terminated string arguments. * char[] path; * char[] name; * * Followed by a data blob of specified length * containing information of specified type. * void *dataBlob; */ } #include "vmware_pack_end.h" VixMsgSetRegValueRequest; typedef #include "vmware_pack_begin.h" struct VixMsgListRegValuesRequest { VixCommandRequestHeader header; uint32 options; /* * If we need multiple roundtrips, this is the index * used to identify the result being processed. */ uint32 index; /* * If we need multiple roundtrips, this is the offset * in the reply from which to send the next chunk. */ uint32 offset; uint32 pathLength; uint32 wowBitness; Bool expandStrings; uint32 matchPatternLength; /* * Followed by NUL-terminated string arguments. * char[] path; * char[] matchPattern; */ } #include "vmware_pack_end.h" VixMsgListRegValuesRequest; typedef #include "vmware_pack_begin.h" struct VixMsgDeleteRegValueRequest { VixCommandRequestHeader header; uint32 options; uint32 pathLength; uint32 wowBitness; uint32 nameLength; /* * Followed by NUL-terminated string arguments. * char[] path; * char[] name; */ } #include "vmware_pack_end.h" VixMsgDeleteRegValueRequest; /* * HOWTO: Adding a new Vix Command. Step 3. * * Add a new struct to pass over the control socket into the VMX. * You only need to do this if your command is manipulating a running * VM, but that is a common situation. If your command only manipulates * non-running VMs, then you can skip this. * * This particular command passes strings as both a param and a * result. This is the most general case, because it means that both * the request and response have a variable-length string on the end. * You can make a simpler request or response if it only passes integers * and so is fixed size. */ /* * ********************************************************** * Sample Command. */ typedef #include "vmware_pack_begin.h" struct VixMsgSampleCommandRequest { VixCommandRequestHeader header; int32 intArg; uint32 strArgLength; } #include "vmware_pack_end.h" VixMsgSampleCommandRequest; typedef #include "vmware_pack_begin.h" struct VixMsgSampleCommandResponse { VixCommandResponseHeader header; int32 intResult; uint32 strResultLength; } #include "vmware_pack_end.h" VixMsgSampleCommandResponse; // End of "HOWTO: Adding a new Vix Command. Step 3." /* * ********************************************************** * Debugger related commands. */ typedef #include "vmware_pack_begin.h" struct VixMsgAttachDebuggerRequest { VixCommandRequestHeader header; int32 options; uint32 propertyListBufferSize; } #include "vmware_pack_end.h" VixMsgAttachDebuggerRequest; typedef #include "vmware_pack_begin.h" struct VixMsgAttachDebuggerResponse { VixCommandResponseHeader header; uint32 propertyListBufferSize; } #include "vmware_pack_end.h" VixMsgAttachDebuggerResponse; typedef #include "vmware_pack_begin.h" struct VixMsgIssueDebuggerCommandRequest { VixCommandRequestHeader header; int32 options; uint32 propertyListBufferSize; uint32 debuggerBlobBufferSize; } #include "vmware_pack_end.h" VixMsgIssueDebuggerCommandRequest; typedef #include "vmware_pack_begin.h" struct VixMsgIssueDebuggerCommandResponse { VixCommandResponseHeader header; uint32 propertyListBufferSize; uint32 debuggerBlobBufferSize; } #include "vmware_pack_end.h" VixMsgIssueDebuggerCommandResponse; typedef #include "vmware_pack_begin.h" struct VixMsgDetachDebuggerRequest { VixCommandRequestHeader header; int32 options; uint32 propertyListBufferSize; } #include "vmware_pack_end.h" VixMsgDetachDebuggerRequest; typedef #include "vmware_pack_begin.h" struct VixMsgDetachDebuggerResponse { VixCommandResponseHeader header; uint32 propertyListBufferSize; } #include "vmware_pack_end.h" VixMsgDetachDebuggerResponse; /* * ********************************************************** * VM Pause state change event format */ typedef #include "vmware_pack_begin.h" struct VixMsgPauseStateChangedEvent { VixMsgEventHeader eventHeader; Bool paused; } #include "vmware_pack_end.h" VixMsgPauseStateChangedEvent; /* * ********************************************************** * Wait for a user action, such as a user logging into the guest. */ /* * Vix_WaitForUserActionInGuest Request * VIX_COMMAND_WAIT_FOR_USER_ACTION_IN_GUEST */ typedef #include "vmware_pack_begin.h" struct VixMsgWaitForUserActionRequest { VixCommandRequestHeader header; int32 userType; int32 userAction; int32 timeoutInSeconds; int32 options; uint32 userNameLength; uint32 propertyBufferSize; // This is followed by: // userName // buffer of serialized properties } #include "vmware_pack_end.h" VixMsgWaitForUserActionRequest; typedef #include "vmware_pack_begin.h" struct VixMsgWaitForUserActionResponse { VixCommandRequestHeader header; Bool actionHappened; uint32 bufferSize; // This is followed by the buffer of serialized properties } #include "vmware_pack_end.h" VixMsgWaitForUserActionResponse; /* * ********************************************************** * List filesystems */ typedef #include "vmware_pack_begin.h" struct VixCommandListFileSystemsRequest { VixCommandRequestHeader header; uint32 options; uint32 propertyListSize; } #include "vmware_pack_end.h" VixCommandListFileSystemsRequest; /* * ********************************************************** * Acquire Credentials. */ typedef #include "vmware_pack_begin.h" struct VixCommandAcquireCredentialsRequest { VixCommandRequestHeader header; int64 sessionID; } #include "vmware_pack_end.h" VixCommandAcquireCredentialsRequest; /* * ********************************************************** * A simple request packet that contains an options field and a * property list. */ typedef #include "vmware_pack_begin.h" struct VixCommandGenericRequest { VixCommandRequestHeader header; uint32 options; uint32 propertyListSize; // This is followed by the buffer of serialized properties } #include "vmware_pack_end.h" VixCommandGenericRequest; /* * The security classifications for async op types/op code. Each op code * is given a security category, and the VMX uses that category to determine * whether a client is allowed to perform the given command. */ typedef enum VixCommandSecurityCategory { /* The default for unknown commands */ VIX_COMMAND_CATEGORY_UNKNOWN, /* * A command that should be executed in the guest OS by the VIX Tools. * component. These are allowed for all connection types. */ VIX_COMMAND_CATEGORY_ALWAYS_ALLOWED, /* * A command that only allowed by privileged connections; in the VI * world this is means that only Hostd is allowed to perform these * commands. */ VIX_COMMAND_CATEGORY_PRIVILEGED, /* * A command that may or may not be privileged. Usually, extra inspection * of the payload is required to make the determination. This should be * used sparingly, since must always be accompanied by "deep packet * inspection" code in the VMX (mainDispatch.c). */ VIX_COMMAND_CATEGORY_MIXED, } VixCommandSecurityCategory; /* * This is the list of all Vix commands * * Be really careful with these. These values are passed over the socket * between clients and the VMX process. One client may connect to newer or * older versions of the VMX, so we cannot ever change or recycle values if * if we add or remove command ids. This is why the values are explicitly * assigned, and there may be gaps in the numeric sequence as some commands * are no longer supported. */ typedef int VixAsyncOpType; enum { VIX_COMMAND_UNKNOWN = -1, VIX_COMMAND_VM_POWERON = 0, VIX_COMMAND_VM_POWEROFF = 1, VIX_COMMAND_VM_RESET = 2, VIX_COMMAND_VM_SUSPEND = 3, VIX_COMMAND_RUN_PROGRAM = 4, /* DEPRECATED VIX_COMMAND_GET_PROPERTY = 5, */ /* DEPRECATED VIX_COMMAND_SET_PROPERTY = 6, */ VIX_COMMAND_KEYSTROKES = 7, VIX_COMMAND_READ_REGISTRY = 8, VIX_COMMAND_WRITE_REGISTRY = 10, VIX_COMMAND_COPY_FILE_FROM_GUEST_TO_HOST = 12, VIX_COMMAND_COPY_FILE_FROM_HOST_TO_GUEST = 13, VIX_COMMAND_CREATE_SNAPSHOT = 14, VIX_COMMAND_REMOVE_SNAPSHOT = 15, VIX_COMMAND_REVERT_TO_SNAPSHOT = 16, VIX_COMMAND_VM_CLONE = 17, VIX_COMMAND_DELETE_GUEST_FILE = 18, VIX_COMMAND_GUEST_FILE_EXISTS = 19, VIX_COMMAND_FIND_VM = 20, VIX_COMMAND_CALL_PROCEDURE = 21, VIX_COMMAND_REGISTRY_KEY_EXISTS = 22, VIX_COMMAND_WIN32_WINDOW_MESSAGE = 23, VIX_COMMAND_CONSOLIDATE_SNAPSHOTS = 24, VIX_COMMAND_INSTALL_TOOLS = 25, VIX_COMMAND_CANCEL_INSTALL_TOOLS = 26, VIX_COMMAND_UPGRADE_VIRTUAL_HARDWARE = 27, VIX_COMMAND_SET_NIC_BANDWIDTH = 28, /* DEPRECATED VIX_COMMAND_CREATE_DISK = 29, */ /* DEPRECATED VIX_COMMAND_CREATE_FLOPPY = 30, */ VIX_COMMAND_RELOAD_VM = 31, VIX_COMMAND_DELETE_VM = 32, /* DEPRECATED VIX_COMMAND_SYNCDRIVER_FREEZE = 33, */ /* DEPRECATED VIX_COMMAND_SYNCDRIVER_THAW = 34, */ /* DEPRECATED VIX_COMMAND_HOT_ADD_DISK = 35, */ /* DEPRECATED VIX_COMMAND_HOT_REMOVE_DISK = 36, */ /* DEPRECATED VIX_COMMAND_SET_GUEST_PRINTER = 37, */ VIX_COMMAND_WAIT_FOR_TOOLS = 38, VIX_COMMAND_CREATE_RUNNING_VM_SNAPSHOT = 39, VIX_COMMAND_CONSOLIDATE_RUNNING_VM_SNAPSHOT = 40, VIX_COMMAND_GET_NUM_SHARED_FOLDERS = 41, VIX_COMMAND_GET_SHARED_FOLDER_STATE = 42, VIX_COMMAND_EDIT_SHARED_FOLDER_STATE = 43, VIX_COMMAND_REMOVE_SHARED_FOLDER = 44, VIX_COMMAND_ADD_SHARED_FOLDER = 45, VIX_COMMAND_RUN_SCRIPT_IN_GUEST = 46, VIX_COMMAND_OPEN_VM = 47, /* DEPRECATED VIX_COMMAND_GET_DISK_PROPERTIES = 48, */ /* DEPRECATED VIX_COMMAND_OPEN_URL = 49, */ VIX_COMMAND_GET_HANDLE_STATE = 50, /* DEPRECATED VIX_COMMAND_SET_HANDLE_STATE = 51, */ VIX_COMMAND_CREATE_WORKING_COPY = 55, // DELETE this when we switch remote foundry to VIM VIX_COMMAND_DISCARD_WORKING_COPY = 56, // DELETE this when we switch remote foundry to VIM VIX_COMMAND_SAVE_WORKING_COPY = 57, // DELETE this when we switch remote foundry to VIM VIX_COMMAND_CAPTURE_SCREEN = 58, /* DEPRECATED VIX_COMMAND_GET_VMDB_VALUES = 59, */ /* DEPRECATED VIX_COMMAND_SET_VMDB_VALUES = 60, */ /* DEPRECATED VIX_COMMAND_READ_XML_FILE = 61, */ VIX_COMMAND_GET_TOOLS_STATE = 62, VIX_COMMAND_CHANGE_SCREEN_RESOLUTION = 69, VIX_COMMAND_DIRECTORY_EXISTS = 70, VIX_COMMAND_DELETE_GUEST_REGISTRY_KEY = 71, VIX_COMMAND_DELETE_GUEST_DIRECTORY = 72, VIX_COMMAND_DELETE_GUEST_EMPTY_DIRECTORY = 73, VIX_COMMAND_CREATE_TEMPORARY_FILE = 74, VIX_COMMAND_LIST_PROCESSES = 75, VIX_COMMAND_MOVE_GUEST_FILE = 76, VIX_COMMAND_CREATE_DIRECTORY = 77, VIX_COMMAND_CHECK_USER_ACCOUNT = 78, VIX_COMMAND_LIST_DIRECTORY = 79, VIX_COMMAND_REGISTER_VM = 80, VIX_COMMAND_UNREGISTER_VM = 81, VIX_CREATE_SESSION_KEY_COMMAND = 83, VMXI_HGFS_SEND_PACKET_COMMAND = 84, VIX_COMMAND_KILL_PROCESS = 85, /* DEPRECATED VIX_VM_FORK_COMMAND = 86, */ VIX_COMMAND_LOGOUT_IN_GUEST = 87, VIX_COMMAND_READ_VARIABLE = 88, VIX_COMMAND_WRITE_VARIABLE = 89, VIX_COMMAND_CONNECT_DEVICE = 92, VIX_COMMAND_IS_DEVICE_CONNECTED = 93, VIX_COMMAND_GET_FILE_INFO = 94, VIX_COMMAND_SET_FILE_INFO = 95, VIX_COMMAND_MOUSE_EVENTS = 96, VIX_COMMAND_OPEN_TEAM = 97, /* DEPRECATED VIX_COMMAND_FIND_HOST_DEVICES = 98, */ VIX_COMMAND_ANSWER_MESSAGE = 99, VIX_COMMAND_ENABLE_SHARED_FOLDERS = 100, VIX_COMMAND_MOUNT_HGFS_FOLDERS = 101, VIX_COMMAND_HOT_EXTEND_DISK = 102, /* DEPRECATED VIX_COMMAND_GET_VPROBES_VERSION = 104, */ /* DEPRECATED VIX_COMMAND_GET_VPROBES = 105, */ /* DEPRECATED VIX_COMMAND_VPROBE_GET_GLOBALS = 106, */ /* DEPRECATED VIX_COMMAND_VPROBE_LOAD = 107, */ /* DEPRECATED VIX_COMMAND_VPROBE_RESET = 108, */ /* DEPRECATED VIX_COMMAND_LIST_USB_DEVICES = 109, */ VIX_COMMAND_CONNECT_HOST = 110, VIX_COMMAND_CREATE_LINKED_CLONE = 112, /* DEPRECATED VIX_COMMAND_STOP_SNAPSHOT_LOG_RECORDING = 113, */ /* DEPRECATED VIX_COMMAND_STOP_SNAPSHOT_LOG_PLAYBACK = 114, */ VIX_COMMAND_SAMPLE_COMMAND = 115, VIX_COMMAND_GET_GUEST_NETWORKING_CONFIG = 116, VIX_COMMAND_SET_GUEST_NETWORKING_CONFIG = 117, /* DEPRECATED VIX_COMMAND_FAULT_TOLERANCE_REGISTER = 118, */ /* DEPRECATED VIX_COMMAND_FAULT_TOLERANCE_UNREGISTER = 119, */ /* DEPRECATED VIX_COMMAND_FAULT_TOLERANCE_CONTROL = 120, */ /* DEPRECATED VIX_COMMAND_FAULT_TOLERANCE_QUERY_SECONDARY = 121, */ VIX_COMMAND_VM_PAUSE = 122, VIX_COMMAND_VM_UNPAUSE = 123, /* DEPRECATED VIX_COMMAND_GET_SNAPSHOT_LOG_INFO = 124, */ /* DEPRECATED VIX_COMMAND_SET_REPLAY_SPEED = 125, */ /* DEPRECATED VIX_COMMAND_ANSWER_USER_MESSAGE = 126, */ /* DEPRECATED VIX_COMMAND_SET_CLIENT_LOCALE = 127, */ VIX_COMMAND_GET_PERFORMANCE_DATA = 128, /* DEPRECATED VIX_COMMAND_REFRESH_RUNTIME_PROPERTIES = 129, */ VIX_COMMAND_GET_SNAPSHOT_SCREENSHOT = 130, /* DEPRECATED VIX_COMMAND_ADD_TIMEMARKER = 131, */ VIX_COMMAND_WAIT_FOR_USER_ACTION_IN_GUEST = 132, /* DEPRECATED VIX_COMMAND_VMDB_END_TRANSACTION = 133, */ /* DEPRECATED VIX_COMMAND_VMDB_SET = 134, */ VIX_COMMAND_CHANGE_VIRTUAL_HARDWARE = 135, VIX_COMMAND_HOT_PLUG_CPU = 136, VIX_COMMAND_HOT_PLUG_MEMORY = 137, VIX_COMMAND_HOT_ADD_DEVICE = 138, VIX_COMMAND_HOT_REMOVE_DEVICE = 139, /* DEPRECATED VIX_COMMAND_DEBUGGER_ATTACH = 140, */ /* DEPRECATED VIX_COMMAND_DEBUGGER_DETACH = 141, */ /* DEPRECATED VIX_COMMAND_DEBUGGER_SEND_COMMAND = 142, */ /* DEPRECATED VIX_COMMAND_GET_RECORD_STATE = 143, */ /* DEPRECATED VIX_COMMAND_SET_RECORD_STATE = 144, */ /* DEPRECATED VIX_COMMAND_REMOVE_RECORD_STATE = 145, */ /* DEPRECATED VIX_COMMAND_GET_REPLAY_STATE = 146, */ /* DEPRECATED VIX_COMMAND_SET_REPLAY_STATE = 147, */ /* DEPRECATED VIX_COMMAND_REMOVE_REPLAY_STATE = 148, */ /* DEPRECATED VIX_COMMAND_CANCEL_USER_PROGRESS_MESSAGE = 150, */ VIX_COMMAND_GET_VMX_DEVICE_STATE = 151, /* DEPRECATED VIX_COMMAND_GET_NUM_TIMEMARKERS = 152, */ /* DEPRECATED VIX_COMMAND_GET_TIMEMARKER = 153, */ /* DEPRECATED VIX_COMMAND_REMOVE_TIMEMARKER = 154, */ VIX_COMMAND_SET_SNAPSHOT_INFO = 155, VIX_COMMAND_SNAPSHOT_SET_MRU = 156, VIX_COMMAND_LOGOUT_HOST = 157, VIX_COMMAND_HOT_PLUG_BEGIN_BATCH = 158, VIX_COMMAND_HOT_PLUG_COMMIT_BATCH = 159, VIX_COMMAND_TRANSFER_CONNECTION = 160, VIX_COMMAND_TRANSFER_REQUEST = 161, VIX_COMMAND_TRANSFER_FINAL_DATA = 162, /* DEPRECATED VIX_COMMAND_ADD_ROLLING_SNAPSHOT_TIER = 163, */ /* DEPRECATED VIX_COMMAND_REMOVE_ROLLING_SNAPSHOT_TIER = 164, */ /* DEPRECATED VIX_COMMAND_LIST_ROLLING_SNAPSHOT_TIER = 165, */ /* DEPRECATED VIX_COMMAND_ADD_ROLLING_SNAPSHOT_TIER_VMX = 166, */ /* DEPRECATED VIX_COMMAND_REMOVE_ROLLING_SNAPSHOT_TIER_VMX = 167, */ /* DEPRECATED VIX_COMMAND_LIST_ROLLING_SNAPSHOT_TIER_VMX = 168, */ VIX_COMMAND_LIST_FILESYSTEMS = 169, VIX_COMMAND_CHANGE_DISPLAY_TOPOLOGY = 170, VIX_COMMAND_SUSPEND_AND_RESUME = 171, VIX_COMMAND_REMOVE_BULK_SNAPSHOT = 172, VIX_COMMAND_COPY_FILE_FROM_READER_TO_GUEST = 173, VIX_COMMAND_GENERATE_NONCE = 174, VIX_COMMAND_CHANGE_DISPLAY_TOPOLOGY_MODES = 175, VIX_COMMAND_QUERY_CHILDREN = 176, VIX_COMMAND_LIST_FILES = 177, VIX_COMMAND_CREATE_DIRECTORY_EX = 178, VIX_COMMAND_MOVE_GUEST_FILE_EX = 179, VIX_COMMAND_MOVE_GUEST_DIRECTORY = 180, VIX_COMMAND_CREATE_TEMPORARY_FILE_EX = 181, VIX_COMMAND_CREATE_TEMPORARY_DIRECTORY = 182, VIX_COMMAND_SET_GUEST_FILE_ATTRIBUTES = 183, VIX_COMMAND_COPY_FILE_FROM_GUEST_TO_READER = 184, VIX_COMMAND_START_PROGRAM = 185, VIX_COMMAND_LIST_PROCESSES_EX = 186, VIX_COMMAND_READ_ENV_VARIABLES = 187, VIX_COMMAND_INITIATE_FILE_TRANSFER_FROM_GUEST = 188, VIX_COMMAND_INITIATE_FILE_TRANSFER_TO_GUEST = 189, VIX_COMMAND_ACQUIRE_CREDENTIALS = 190, VIX_COMMAND_RELEASE_CREDENTIALS = 191, VIX_COMMAND_VALIDATE_CREDENTIALS = 192, VIX_COMMAND_TERMINATE_PROCESS = 193, VIX_COMMAND_DELETE_GUEST_FILE_EX = 194, VIX_COMMAND_DELETE_GUEST_DIRECTORY_EX = 195, VIX_COMMAND_HOT_CHANGE_MONITOR_TYPE = 196, VIX_COMMAND_ADD_AUTH_ALIAS = 197, VIX_COMMAND_REMOVE_AUTH_ALIAS = 198, VIX_COMMAND_LIST_AUTH_PROVIDER_ALIASES = 199, VIX_COMMAND_LIST_AUTH_MAPPED_ALIASES = 200, VIX_COMMAND_CREATE_REGISTRY_KEY = 201, VIX_COMMAND_LIST_REGISTRY_KEYS = 202, VIX_COMMAND_DELETE_REGISTRY_KEY = 203, VIX_COMMAND_SET_REGISTRY_VALUE = 204, VIX_COMMAND_LIST_REGISTRY_VALUES = 205, VIX_COMMAND_DELETE_REGISTRY_VALUE = 206, VIX_COMMAND_REMOVE_AUTH_ALIAS_BY_CERT = 207, /* * HOWTO: Adding a new Vix Command. Step 2a. * * Add a new ID for your new function prototype here. BE CAREFUL. The * OFFICIAL list of id's is in the bfg-main tree, in bora/lib/public/vixCommands.h. * When people add new command id's in different tree, they may collide and use * the same ID values. This can merge without conflicts, and cause runtime bugs. * Once a new command is added here, a command info field needs to be added * in bora/lib/foundryMsg/foundryMsg.c as well. */ VIX_COMMAND_LAST_NORMAL_COMMAND = 208, VIX_TEST_UNSUPPORTED_TOOLS_OPCODE_COMMAND = 998, VIX_TEST_UNSUPPORTED_VMX_OPCODE_COMMAND = 999, }; /* * These are the command names that are passed through the backdoor from the * VMX to the tools. */ #define VIX_BACKDOOR_COMMAND_VERSION "Vix_1_" #define VIX_BACKDOORCOMMAND_RUN_PROGRAM VIX_BACKDOOR_COMMAND_VERSION"Run_Program" #define VIX_BACKDOORCOMMAND_SYNCDRIVER_FREEZE VIX_BACKDOOR_COMMAND_VERSION"SyncDriver_Freeze" #define VIX_BACKDOORCOMMAND_SYNCDRIVER_THAW VIX_BACKDOOR_COMMAND_VERSION"SyncDriver_Thaw" #define VIX_BACKDOORCOMMAND_GET_PROPERTIES VIX_BACKDOOR_COMMAND_VERSION"Get_ToolsProperties" #define VIX_BACKDOORCOMMAND_SEND_HGFS_PACKET VIX_BACKDOOR_COMMAND_VERSION"Send_Hgfs_Packet" #define VIX_BACKDOORCOMMAND_UNRECOGNIZED_COMMAND VIX_BACKDOOR_COMMAND_VERSION"Unrecognized_Command" #define VIX_BACKDOORCOMMAND_COMMAND VIX_BACKDOOR_COMMAND_VERSION"Relayed_Command" #define VIX_BACKDOORCOMMAND_MOUNT_VOLUME_LIST VIX_BACKDOOR_COMMAND_VERSION"Mount_Volumes" /* * This is the set of features that may be supported by different * versions of the VMX or Vix Tools. */ enum VixToolsFeatures { VIX_TOOLSFEATURE_SUPPORT_GET_HANDLE_STATE = 0x0001, /* VIX_TOOLSFEATURE_SUPPORT_OPEN_URL = 0x0002, Removed in version 1.11*/ }; enum { VIX_TOOLS_READ_FILE_ACCESS = 0x01, VIX_TOOLS_WRITE_FILE_ACCESS = 0x02, }; /* * These are the command names that are passed through the backdoor from the tools * to the VMX. */ #define VIX_BACKDOORCOMMAND_RUN_PROGRAM_DONE "Run_Program_Done" #define VIX_FEATURE_UNKNOWN_VALUE "Unknown" /* * VIX_COMMAND_RUN_PROGRAM returns 2 integer values as an array. These * are the indexes * TODO: Delete this enum */ enum VixRunProgramResultValues { VIX_COMMAND_RUN_PROGRAM_ELAPSED_TIME_RESULT = 0, VIX_COMMAND_RUN_PROGRAM_EXIT_CODE_RESULT = 1, }; /* These are the values of Vix objects. */ #define VIX_VM_OBJECT_TYPE "VixVM" /* VM enumeration */ #ifdef _WIN32 #define VIX_WINDOWSREGISTRY_VMWARE_KEY "Software\\" COMPANY_NAME #define VIX_WINDOWSREGISTRY_RUNNING_VM_LIST "Running VM List" #define VIX_WINDOWSREGISTRY_VMWARE_KEY_RUNNING_VM_LIST VIX_WINDOWSREGISTRY_VMWARE_KEY "\\" VIX_WINDOWSREGISTRY_RUNNING_VM_LIST #endif /* * This is used to denote that the contents of a VIX XML-like response * string has been escaped. Old Tools did not escape the contents. * This tag is only used for existing commands that did not originally perform * escaping. Any new command must always escape any strings passed in XML. * See ListProcessesInGuest as an example. * The protocol works as follows: * 1) A client library that internally knows how to handle escaped XML opts in * by including the VIX_REQUESTMSG_ESCAPE_XML_DATA in relevent requests. * 2) Tools that understands the VIX_REQUESTMSG_ESCAPE_XML_DATA flag sees that * it is set in the request, and then escapes all string data within the * XML response. To indicate to the client that it has understood the * request, it include the VIX_XML_ESCAPED_TAG in the response (at the * begining of the response). * 3) When the client library receives the response, it searches for the * VIX_XML_ESCAPED_TAG. If it is present, it then unescapes all string * data in the response. If the tag is not present, the client library * assumes that the Tools did not understand VIX_REQUESTMSG_ESCAPE_XML_DATA * and that the string data is not escaped. * The following characters are escaped: '<', '>', and '%'. * For new commands (starting with those released in M/N for the vSphere * guest ops project), the escaping is exactly the same, but the * VIX_REQUESTMSG_ESCAPE_XML_DATA flag and the VIX_XML_ESCAPED_TAG are not * used, since both ends expect escaping. */ #define VIX_XML_ESCAPED_TAG "" #define VIX_XML_ESCAPE_CHARACTER '%' /* *----------------------------------------------------------------------------- * * VixMsg -- * * These are the formatting and parsing utilities provided by the VixMsg * library. * *----------------------------------------------------------------------------- */ #ifndef VIX_HIDE_FROM_JAVA struct VixCommandRequestHeader * VixMsg_AllocRequestMsg(size_t msgHeaderAndBodyLength, int opCode, uint64 cookie, int credentialType, const char *userNamePassword); struct VixCommandResponseHeader * VixMsg_AllocResponseMsg(const struct VixCommandRequestHeader *requestHeader, VixError error, uint32 additionalError, size_t responseBodyLength, const void *responseBody, size_t *responseMsgLength); void VixMsg_InitResponseMsg(struct VixCommandResponseHeader *responseHeader, const struct VixCommandRequestHeader *requestHeader, VixError error, uint32 additionalError, size_t totalMessageLength); VixError VixMsg_ValidateMessage(const void *vMsg, size_t msgLength); VixError VixMsg_ValidateRequestMsg(const void *vMsg, size_t msgLength); VixError VixMsg_ValidateResponseMsg(const void *vMsg, size_t msgLength); VixError VixMsg_ParseWriteVariableRequest(VixMsgWriteVariableRequest *msg, char **valueName, char **value); VixError VixMsg_ObfuscateNamePassword(const char *userName, const char *password, char **result); VixError VixMsg_DeObfuscateNamePassword(const char *packagedName, char **userNameResult, char **passwordResult); VixError VixMsg_EncodeString(const char *str, char **result); VixError VixMsg_DecodeString(const char *str, char **result); Bool VixMsg_ValidateCommandInfoTable(void); const char *VixAsyncOp_GetDebugStrForOpCode(int opCode); VixCommandSecurityCategory VixMsg_GetCommandSecurityCategory(int opCode); /* * Vix private internal properties shared between the Vix client * and the VMX. */ enum { VIX_PROPERTY_VM_POWER_OFF_TO_SNAPSHOT_UID = 5102, }; VixError VixMsg_AllocGenericRequestMsg(int opCode, uint64 cookie, int credentialType, const char *userNamePassword, int options, VixPropertyListImpl *propertyList, VixCommandGenericRequest **request); VixError VixMsg_ParseGenericRequestMsg(const VixCommandGenericRequest *request, int *options, VixPropertyListImpl *propertyList); VixError VixMsg_ParseSimpleResponseWithString(const VixCommandResponseHeader *response, const char **result); void *VixMsg_MallocClientData(size_t size); void *VixMsg_ReallocClientData(void *ptr, size_t size); char *VixMsg_StrdupClientData(const char *s, Bool *allocateFailed); /* * Parser state used by VMAutomationMsgParser* group of functions. */ typedef struct { const char *currentPtr; const char *endPtr; } VMAutomationMsgParser; /* Keep the original type name around all the old code can stay the same. */ typedef VMAutomationMsgParser VMAutomationRequestParser; #define VMAutomationRequestParserInit VMAutomationMsgParserInitRequest #define VMAutomationMsgParserInitRequest(state, msg, fixedLength) \ __VMAutomationMsgParserInitRequest(__FUNCTION__, __LINE__, state, msg, fixedLength) VixError __VMAutomationMsgParserInitRequest(const char *caller, unsigned int line, VMAutomationMsgParser *state, const struct VixCommandRequestHeader *msg, size_t fixedLength); #define VMAutomationMsgParserInitResponse(state, msg, fixedLength) \ __VMAutomationMsgParserInitResponse(__FUNCTION__, __LINE__, state, msg, fixedLength) VixError __VMAutomationMsgParserInitResponse(const char *caller, unsigned int line, VMAutomationMsgParser *state, const struct VixCommandResponseHeader *msg, size_t fixedLength); #define VMAutomationRequestParserGetRemainingData \ VMAutomationMsgParserGetRemainingData const void * VMAutomationMsgParserGetRemainingData(VMAutomationMsgParser *state, size_t *length); #define VMAutomationRequestParserGetData VMAutomationMsgParserGetData #define VMAutomationMsgParserGetData(state, length, result) \ __VMAutomationMsgParserGetData(__FUNCTION__, __LINE__, \ state, length, (const char **)result) VixError __VMAutomationMsgParserGetData(const char *caller, unsigned int line, VMAutomationMsgParser *state, size_t length, const char **result); #define VMAutomationRequestParserGetOptionalString \ VMAutomationMsgParserGetOptionalString #define VMAutomationMsgParserGetOptionalString(state, length, result) \ __VMAutomationMsgParserGetOptionalString(__FUNCTION__, __LINE__, \ state, length, result) VixError __VMAutomationMsgParserGetOptionalString(const char *caller, unsigned int line, VMAutomationMsgParser *state, size_t length, const char **result); #define VMAutomationRequestParserGetOptionalStrings \ VMAutomationMsgParserGetOptionalStrings #define VMAutomationMsgParserGetOptionalStrings(state, count, length, \ result) \ __VMAutomationMsgParserGetOptionalStrings(__FUNCTION__, __LINE__, \ state, count, length, result) VixError __VMAutomationMsgParserGetOptionalStrings (const char *caller, unsigned int line, VMAutomationMsgParser *state, uint32 count, size_t length, const char **result); #define VMAutomationRequestParserGetString VMAutomationMsgParserGetString #define VMAutomationMsgParserGetString(state, length, result) \ __VMAutomationMsgParserGetString(__FUNCTION__, __LINE__, \ state, length, result) VixError __VMAutomationMsgParserGetString(const char *caller, unsigned int line, VMAutomationMsgParser *state, size_t length, const char **result); #define VMAutomationRequestParserGetPropertyList \ VMAutomationMsgParserGetPropertyList #define VMAutomationMsgParserGetPropertyList(state, length, propList) \ __VMAutomationMsgParserGetPropertyList(__FUNCTION__, __LINE__, \ state, length, propList) VixError __VMAutomationMsgParserGetPropertyList(const char *caller, unsigned int line, VMAutomationMsgParser *state, size_t length, VixPropertyListImpl *propList); #endif // VIX_HIDE_FROM_JAVA #if defined(__cplusplus) } // extern "C" #endif #endif // _VIX_COMMANDS_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vixOpenSource.h000066400000000000000000000677551321503522500254750ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2007-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * This header file is given out as part of the open source * tools. Things in this file are public, but they may not have * been tested or documented, and that may change in future releases. * The public Vix API is defined in vix.h * * These definitions are used by the implementation of the vix * client, the VMX process, and the tols. * */ #ifndef _VIXOpenSource_h_ #define _VIXOpenSource_h_ #if defined(__cplusplus) extern "C" { #endif /* * VIX_HIDE_BORA_DEPENDENCIES: * * This flag allows some mini-applications to use parts of Vix that will * someday make it into the public API, without including all of the include * directories in bora. Specifically, some VMware apps will want to use a * separate, more public, build tree, but still make use API that have not been * publicly released yet. */ /* * VIX_HIDE_FROM_JAVA * * Setting this flag minizes the functions exposed here. The java * binding is generated by processing this header, resulting in a * large number of currently unused functions. To keep the number * of functions that need to be exposed via vixWrapper, we hide all * but the needed functions to java. */ /* * If we're hiding functions from java, also hide the bora dependencies. */ #ifdef VIX_HIDE_FROM_JAVA #define VIX_HIDE_BORA_DEPENDENCIES #endif #include "vm_basic_types.h" #ifndef VIX_HIDE_BORA_DEPENDENCIES #include "cryptoError.h" #endif // VIX_HIDE_BORA_DEPENDENCIES #include "vix.h" // Vix Public API /* *----------------------------------------------------------------------------- * * Vix Errors -- * *----------------------------------------------------------------------------- */ #ifndef VIX_HIDE_BORA_DEPENDENCIES VixError Vix_TranslateSystemError(int systemError); VixError Vix_TranslateCryptoError(CryptoError cryptoError); VixError Vix_TranslateErrno(int systemError); #ifdef _WIN32 VixError Vix_TranslateCOMError(HRESULT comError); VixError Vix_TranslateGuestRegistryError(int systemError); #endif #endif // VIX_HIDE_BORA_DEPENDENCIES /* * This is an expanded view of a VixError * Every VixError is a 64-bit int, so it can fit into this struct. * * The flags, extraErrorType, and extraError are all optional. They * do not have to be set for any error. In fact, these are guaranteed * to be all 0 when the error is VIX_OK. This means that any program * that checks (VIX_OK == err) or (VIX_OK != err) will always work. * * The basic error field is a Vix error value, and it's the lsb * of the new struct. This means that a 64-bit error can be assigned * enum constant, like an integer. For example, err = VIX_E_FAIL; works. * This just leaves the flags and extraError fields as 0. */ typedef #include "vmware_pack_begin.h" struct VixErrorFields { uint16 error; uint8 flags; uint8 extraErrorType; uint32 extraError; } #include "vmware_pack_end.h" VixErrorFields; /* * These are the flags for a Vix error. */ enum { VIX_ERRORFLAG_GUEST = 0x0001, VIX_ERRORFLAG_REMOTE = 0x0002, }; /* * These are the types of extra error in a Vix error. */ enum { VIX_ERROREXTRATYPE_NONE = 0, VIX_ERROREXTRATYPE_SNAPSHOT = 1, VIX_ERROREXTRATYPE_DISKLIB = 2, VIX_ERROREXTRATYPE_WINDOWS = 3, VIX_ERROREXTRATYPE_LINUX = 4, VIX_ERROREXTRATYPE_FILE = 5, VIX_ERROREXTRATYPE_VMDB = 6, VIX_ERROREXTRATYPE_AIO = 7, VIX_ERROREXTRATYPE_CRYPTO = 8, VIX_ERROREXTRATYPE_KEYSAFE = 9, VIX_ERROREXTRATYPE_BLOCKLIST = 10, VIX_ERROREXTRATYPE_V2I = 11, VIX_ERROREXTRATYPE_MSGPOST = 12, VIX_ERROREXTRATYPE_NFC = 13, // NfcErrorCode }; /* * These are the types of extra error in a Vix error. */ #define VIX_ERROR_BASE_ERROR(err) ((VixErrorFields *) &err)->error #define VIX_ERROR_EXTRA_ERROR(err) ((VixErrorFields *) &err)->extraError #define VIX_ERROR_EXTRA_ERROR_TYPE(err) ((VixErrorFields *) &err)->extraErrorType #define VIX_ERROR_FROM_GUEST(err) (((VixErrorFields *) &err)->flags & VIX_ERRORFLAG_GUEST) #define VIX_ERROR_FROM_REMOTE(err) (((VixErrorFields *) &err)->flags & VIX_ERRORFLAG_REMOTE) #define VIX_ERROR_SET_FROM_GUEST(err) (((VixErrorFields *) &err)->flags |= VIX_ERRORFLAG_GUEST) #define VIX_ERROR_SET_FROM_REMOTE(err) (((VixErrorFields *) &err)->flags |= VIX_ERRORFLAG_REMOTE) #define VIX_SET_GUEST_WINDOWS_ERROR(err, vixError, winError) \ do { \ err = 0; \ VIX_ERROR_BASE_ERROR(err) = vixError; \ VIX_ERROR_EXTRA_ERROR(err) = winError; \ VIX_ERROR_EXTRA_ERROR_TYPE(err) = VIX_ERROREXTRATYPE_WINDOWS; \ VIX_ERROR_SET_FROM_GUEST(err); \ } while (0) #define VIX_ERROR_SET_ADDITIONAL_ERROR(err, vixError, additionalError) \ do { \ err = additionalError; \ err = (err << 32) | vixError; \ } while (0) #define VIX_SET_ERROR(err, vixError, origErrorType, origError) \ do { \ err = 0; \ VIX_ERROR_BASE_ERROR(err) = vixError; \ VIX_ERROR_EXTRA_ERROR_TYPE(err) = origErrorType; \ VIX_ERROR_EXTRA_ERROR(err) = origError; \ } while (0) /* * This defines additional error codes. * The public error codes are defined in vix.h * These error codes are in addition to those. */ enum { VIX_E_OP_NOT_SUPPORTED_ON_NON_VMWARE_VM = 3038, VIX_E_VI_OP_NOT_SUPPORTED_ON_GUEST = 3048, VIX_E_INVALID_LOGIN_CREDENTIALS = 3050, VIX_E_GUEST_AUTHTYPE_DISABLED = 3051, /* File Errors */ VIX_E_DIRECTORY_NOT_EMPTY = 20006, VIX_E_GUEST_AUTH_MULIPLE_MAPPINGS = 20007, /* Guest Reg Errors */ VIX_E_REG_KEY_INVALID = 20008, VIX_E_REG_KEY_HAS_SUBKEYS = 20009, VIX_E_REG_VALUE_NOT_FOUND = 20010, VIX_E_REG_KEY_ALREADY_EXISTS = 20011, VIX_E_REG_KEY_PARENT_VOLATILE = 20012, /* Generic Guest Errors */ VIX_E_HGFS_MOUNT_FAIL = 20050, /* Reg Errors*/ VIX_E_REG_INCORRECT_VALUE_TYPE = 25000 /* WARNING. Do not exceed 2**16 */ }; /* *----------------------------------------------------------------------------- * * VIX Handles -- * * These are common functions that apply to handles of several types. *----------------------------------------------------------------------------- */ /* * VIX Property ID's * * These are used in the tools, but they are not (yet) part of the public * API. They may be promoted, but for now they are not tested or documented. */ enum { VIX_PROPERTY_VM_GUEST_TEMP_DIR_PROPERTY = 203, /* VMX properties. */ VIX_PROPERTY_VMX_VERSION = 4400, VIX_PROPERTY_VMX_PRODUCT_NAME = 4401, /* DEPRECTATED VIX_PROPERTY_VMX_VIX_FEATURES = 4402, */ /* GuestOS and Tools properties. */ VIX_PROPERTY_GUEST_TOOLS_VERSION = 4500, VIX_PROPERTY_GUEST_TOOLS_API_OPTIONS = 4501, VIX_PROPERTY_GUEST_OS_FAMILY = 4502, VIX_PROPERTY_GUEST_OS_VERSION = 4503, VIX_PROPERTY_GUEST_OS_PACKAGE_LIST = 4504, VIX_PROPERTY_GUEST_NAME = 4505, VIX_PROPERTY_GUEST_POWER_OFF_SCRIPT = 4506, VIX_PROPERTY_GUEST_POWER_ON_SCRIPT = 4507, VIX_PROPERTY_GUEST_RESUME_SCRIPT = 4508, VIX_PROPERTY_GUEST_SUSPEND_SCRIPT = 4509, VIX_PROPERTY_GUEST_TOOLS_PRODUCT_NAM = 4511, VIX_PROPERTY_FOREIGN_VM_TOOLS_VERSION = 4512, VIX_PROPERTY_VM_DHCP_ENABLED = 4513, VIX_PROPERTY_VM_IP_ADDRESS = 4514, VIX_PROPERTY_VM_SUBNET_MASK = 4515, VIX_PROPERTY_VM_DEFAULT_GATEWAY = 4516, VIX_PROPERTY_VM_DNS_SERVER_DHCP_ENABLED = 4517, VIX_PROPERTY_VM_DNS_SERVER = 4518, VIX_PROPERTY_GUEST_TOOLS_WORD_SIZE = 4519, VIX_PROPERTY_GUEST_OS_VERSION_SHORT = 4520, VIX_PROPERTY_GUEST_AUTH_SSPI_TOKEN = 4531, VIX_PROPERTY_GUEST_AUTH_SSPI_SESSION_ID = 4532, VIX_PROPERTY_GUEST_AUTH_SESSION_TICKET = 4533, /* VI guest operation status */ VIX_PROPERTY_GUEST_START_PROGRAM_ENABLED = 4540, VIX_PROPERTY_GUEST_LIST_PROCESSES_ENABLED = 4541, VIX_PROPERTY_GUEST_TERMINATE_PROCESS_ENABLED = 4542, VIX_PROPERTY_GUEST_READ_ENVIRONMENT_VARIABLE_ENABLED = 4543, VIX_PROPERTY_GUEST_VALIDATE_CREDENTIALS_ENABLED = 4544, VIX_PROPERTY_GUEST_ACQUIRE_CREDENTIALS_ENABLED = 4545, VIX_PROPERTY_GUEST_RELEASE_CREDENTIALS_ENABLED = 4546, VIX_PROPERTY_GUEST_MAKE_DIRECTORY_ENABLED = 4547, VIX_PROPERTY_GUEST_DELETE_FILE_ENABLED = 4548, VIX_PROPERTY_GUEST_DELETE_DIRECTORY_ENABLED = 4549, VIX_PROPERTY_GUEST_MOVE_DIRECTORY_ENABLED = 4550, VIX_PROPERTY_GUEST_MOVE_FILE_ENABLED = 4551, VIX_PROPERTY_GUEST_CREATE_TEMP_FILE_ENABLED = 4552, VIX_PROPERTY_GUEST_CREATE_TEMP_DIRECTORY_ENABLED = 4553, VIX_PROPERTY_GUEST_LIST_FILES_ENABLED = 4554, VIX_PROPERTY_GUEST_CHANGE_FILE_ATTRIBUTES_ENABLED = 4555, VIX_PROPERTY_GUEST_INITIATE_FILE_TRANSFER_FROM_GUEST_ENABLED = 4556, VIX_PROPERTY_GUEST_INITIATE_FILE_TRANSFER_TO_GUEST_ENABLED = 4557, VIX_PROPERTY_GUEST_ADD_AUTH_ALIAS_ENABLED = 4558, VIX_PROPERTY_GUEST_REMOVE_AUTH_ALIAS_ENABLED = 4559, VIX_PROPERTY_GUEST_LIST_AUTH_ALIASES_ENABLED = 4560, VIX_PROPERTY_GUEST_LIST_MAPPED_ALIASES_ENABLED = 4561, VIX_PROPERTY_GUEST_CREATE_REGISTRY_KEY_ENABLED = 4562, VIX_PROPERTY_GUEST_LIST_REGISTRY_KEYS_ENABLED = 4563, VIX_PROPERTY_GUEST_DELETE_REGISTRY_KEY_ENABLED = 4564, VIX_PROPERTY_GUEST_SET_REGISTRY_VALUE_ENABLED = 4565, VIX_PROPERTY_GUEST_LIST_REGISTRY_VALUES_ENABLED = 4566, VIX_PROPERTY_GUEST_DELETE_REGISTRY_VALUE_ENABLED = 4567, VIX_PROPERTY_GUEST_REMOVE_AUTH_ALIAS_BY_CERT_ENABLED = 4568, }; /* *----------------------------------------------------------------------------- * * PropertyList -- * *----------------------------------------------------------------------------- */ /* * VIX Property Type */ enum { //VIX_PROPERTYTYPE_ANY = 0, //VIX_PROPERTYTYPE_INTEGER = 1, //VIX_PROPERTYTYPE_STRING = 2, //VIX_PROPERTYTYPE_BOOL = 3, //VIX_PROPERTYTYPE_HANDLE = 4, //VIX_PROPERTYTYPE_INT64 = 5, //VIX_PROPERTYTYPE_BLOB = 6, VIX_PROPERTYTYPE_POINTER = 7 }; #ifndef VIX_HIDE_FROM_JAVA /* * This is a single name/value pair. */ typedef struct VixPropertyValue { int propertyID; VixPropertyType type; union { Bool boolValue; char *strValue; int intValue; int64 int64Value; VixHandle handleValue; struct { unsigned char *blobContents; int blobSize; } blobValue; void *ptrValue; } value; Bool isDirty; Bool isSensitive; struct VixPropertyValue *next; } VixPropertyValue; /* * This is the entire list. */ typedef struct VixPropertyListImpl { VixPropertyValue *properties; } VixPropertyListImpl; /* * This defines what action Deserialize should take when it encounters * a string that is not UTF-8. */ typedef enum VixPropertyListBadEncodingAction { /* * Abort the deserialization and return an error. This is the recommended * value since it is the strictest; you don't have to think about how * any clients or library code will handle escaped values. * This should always be used when parsing property lists passing arguments * to RPCs since we should be very strict in terms of actions we take * based on arguments. */ VIX_PROPERTY_LIST_BAD_ENCODING_ERROR, /* * Escape any non-UTF-8 characters in the string, add the result to the * property list, and continue deserializing. This should only be used * when there are likely to be applications generated non-ASCII values * for the property list in question (e.g., the Tools properties sent by * pre-i18n Tools) and the properties are more informative then * actionable (something like the hostname of a guest, maybe). */ VIX_PROPERTY_LIST_BAD_ENCODING_ESCAPE, } VixPropertyListBadEncodingAction; void VixPropertyList_Initialize(VixPropertyListImpl *propList); void VixPropertyList_RemoveAllWithoutHandles(VixPropertyListImpl *propList); VixError VixPropertyList_Serialize(VixPropertyListImpl *propListImpl, Bool dirtyOnly, size_t *resultSize, char **resultBuffer); VixError VixPropertyList_Deserialize(VixPropertyListImpl *propListImpl, const char *buffer, size_t bufferSize, VixPropertyListBadEncodingAction action); VixError VixPropertyList_DeserializeNoClobber(VixPropertyListImpl *propListImpl, const char *buffer, size_t bufferSize, VixPropertyListBadEncodingAction action); VixError VixPropertyList_GetString(struct VixPropertyListImpl *propList, int propertyID, int index, char **resultValue); VixError VixPropertyList_SetStringSensitive(struct VixPropertyListImpl *propList, int propertyID, const char *value); VixError VixPropertyList_SetString(struct VixPropertyListImpl *propList, int propertyID, const char *value); VixError VixPropertyList_GetInteger(struct VixPropertyListImpl *propList, int propertyID, int index, int *resultValue); VixError VixPropertyList_SetInteger(struct VixPropertyListImpl *propList, int propertyID, int value); VixError VixPropertyList_GetBool(struct VixPropertyListImpl *propList, int propertyID, int index, Bool *resultValue); VixError VixPropertyList_SetBool(struct VixPropertyListImpl *propList, int propertyID, Bool value); VixError VixPropertyList_GetHandle(struct VixPropertyListImpl *propList, int propertyID, int index, VixHandle *resultValue); VixError VixPropertyList_SetHandle(struct VixPropertyListImpl *propList, int propertyID, VixHandle value); VixError VixPropertyList_GetInt64(struct VixPropertyListImpl *propList, int propertyID, int index, int64 *resultValue); VixError VixPropertyList_SetInt64(struct VixPropertyListImpl *propList, int propertyID, int64 value); VixError VixPropertyList_GetBlob(struct VixPropertyListImpl *propList, int propertyID, int index, int *resultSize, unsigned char **resultValue); VixError VixPropertyList_SetBlob(struct VixPropertyListImpl *propList, int propertyID, int blobSize, const unsigned char *value); VixError VixPropertyList_SetBlobSensitive(struct VixPropertyListImpl *propList, int propertyID, int blobSize, const unsigned char *value); VixError VixPropertyList_RemoveAll(VixHandle propertyListHandle); VixError VixPropertyList_Remove(VixHandle propertyListHandle, int propertyID); VixError VixPropertyList_RemoveFromImpl(VixPropertyListImpl *propList, int propertyID); VixError VixPropertyList_AppendProperties(VixHandle handle, int firstPropertyID, ...); VixError VixPropertyList_FindProperty(VixPropertyListImpl *propList, int propertyID, VixPropertyType type, int index, Bool createIfMissing, VixPropertyValue **resultEntry); Bool VixPropertyList_PropertyExists(VixPropertyListImpl *propList, int propertyID, VixPropertyType type); VixError VixPropertyListAppendProperty(VixPropertyListImpl *propList, int propertyID, VixPropertyType type, VixPropertyValue **resultEntry); int VixPropertyList_GetNumProperties(VixHandle propertyListHandle, int propertyID); VixError VixPropertyList_GetOptionalProperties(VixHandle propertyListHandle, int firstPropertyID, ...); VixError VixPropertyList_GetIndexedProperties(VixHandle propertyListHandle, Bool ignoreMissingProperties, int firstPropertyID, int firstPropertyIndex, ...); VixError VixPropertyList_GetPtr(VixPropertyListImpl *propList, int propertyID, int index, void **resultValue); VixError VixPropertyList_SetPtr(VixPropertyListImpl *propList, int propertyID, void *value); int VixPropertyList_NumItems(VixPropertyListImpl *propList); Bool VixPropertyList_Empty(VixPropertyListImpl *propList); void VixPropertyList_MarkAllSensitive(VixPropertyListImpl *propList); Bool Vix_XMLFindElementText(const char *pattern, char *str, char *endStr, char **startText, char **stopText, char **resumeSearch); Bool Vix_XMLFindStringElementText(const char *pattern, char *str, char *endStr, Bool doUnescape, char **startText, char **stopText, Bool *needToFree, char **resumeSearch); Bool Vix_XMLResultIsEscaped(const char *resultXML, const char *dataParentTag); Bool Vix_IsValidString(const char *str); #endif // VIX_HIDE_FROM_JAVA /* *----------------------------------------------------------------------------- * * VixVM -- * * This describes the persistent configuration state of a single VM. The * VM may or may not be running. * *----------------------------------------------------------------------------- */ #define VIX_FOREIGN_VM_TOOLS_VMX_VERSION_STRING "Foreign VM Tools" /* * These are the types of variable strings we can read in the VM. */ enum { //VIX_VM_GUEST_VARIABLE = 1, //VIX_VM_CONFIG_RUNTIME_ONLY = 2, //VIX_GUEST_ENVIRONMENT_VARIABLE = 3, VIX_GUEST_CONFIG = 4, VIX_VMDB_VARIABLE = 5, }; /* * Options for RunProgramInGuest(). */ enum { //VIX_RUNPROGRAM_RETURN_IMMEDIATELY = 0x0001, //VIX_RUNPROGRAM_ACTIVATE_WINDOW = 0x0002, /* DEPRECATED VIX_RUNPROGRAM_USE_INTERACTIVE_SESSION = 0x0004, */ VIX_RUNPROGRAM_RUN_AS_LOCAL_SYSTEM = 0x0008, }; /* * Options for VixVM_ListFileSystemsInGuest() */ enum { VIX_FILESYSTEMS_SHOW_ALL = 0x000, }; /* * These are the property flags for each file. This is a superset * of the values defined in the public header. */ enum { //VIX_FILE_ATTRIBUTES_DIRECTORY = 0x0001, //VIX_FILE_ATTRIBUTES_SYMLINK = 0x0002, VIX_FILE_ATTRIBUTES_HIDDEN = 0x0004, VIX_FILE_ATTRIBUTES_READONLY = 0x0008, }; /* * These are the propery flags for SetGuestFileAttributes request. */ enum { VIX_FILE_ATTRIBUTE_SET_ACCESS_DATE = 0x0001, VIX_FILE_ATTRIBUTE_SET_MODIFY_DATE = 0x0002, VIX_FILE_ATTRIBUTE_SET_READONLY = 0x0004, VIX_FILE_ATTRIBUTE_SET_HIDDEN = 0x0008, VIX_FILE_ATTRIBUTE_SET_UNIX_OWNERID = 0x0010, VIX_FILE_ATTRIBUTE_SET_UNIX_GROUPID = 0x0020, VIX_FILE_ATTRIBUTE_SET_UNIX_PERMISSIONS = 0x0040, }; /* * Subject types for Alias management. */ typedef enum VixGuestAuthSubjectType { VIX_GUEST_AUTH_SUBJECT_TYPE_NONE = 0, VIX_GUEST_AUTH_SUBJECT_TYPE_NAMED = 1, VIX_GUEST_AUTH_SUBJECT_TYPE_ANY = 2, } VixGuestAuthSubjectType; /* * Types for Windows Registry Management. */ /* * In a 64 bit Windows OS, the registry has two views: 32 bit and 64 bit. * Normally using "registry redirection", 32 bit applications automatically * access the 32 bit view, while 64 bit applications access 64 bit view. * However, applications can pass a flag to specifically access either 32 * or 64 bit registry view, irrespective of their own bitness. * * NOTE: 32 bit windows will ignore these flags if passed. * * Based on the above, and on the fact that in our case 32 bit tools run only * on 32 bit windows and 64 bit tools run only on 64 bit windows, we get the * following registry view access matrix: * Application wowNative wow32 wow64 * ----------- -------- ----- ----- * 32 bit tools 32 bit view 32 bit view 32 bit view * 64 bit tools 64 bit view 32 bit view 64 bit view * So in essence, we always access 32 bit view UNLESS its 64 bit tools and user * has specified either wowNative or wow64 as the registry access flag. */ typedef enum VixRegKeyWowBitness { VIX_REGISTRY_KEY_WOW_NATIVE = 0, VIX_REGISTRY_KEY_WOW_32 = 1, VIX_REGISTRY_KEY_WOW_64 = 2, } VixRegKeyWowBitness; typedef enum VixRegValueDataType { VIX_REGISTRY_VALUE_DWORD = 0, VIX_REGISTRY_VALUE_QWORD = 1, VIX_REGISTRY_VALUE_STRING = 2, VIX_REGISTRY_VALUE_EXPAND_STRING = 3, VIX_REGISTRY_VALUE_MULTI_STRING = 4, VIX_REGISTRY_VALUE_BINARY = 5, } VixRegValueDataType; /* *----------------------------------------------------------------------------- * * VixDebug -- * * Vix debug macros, to allow conditional printf debugging with file/line * information. * * Use as: * * VIX_DEBUG(("test debug message: %s %d\n", stringArg, intArg)); * * Output will go to logfile if VIX_DEBUG_PREFERENCE_NAME is non-zero * * VIX_DEBUG_LEVEL(3, ("test debug message: %s %d\n", stringArg, intArg)); * * Output will go to logfile if VIX_DEBUG_PREFERENCE_NAME is >= * the first argument to the macro. * *----------------------------------------------------------------------------- */ #ifndef VIX_HIDE_FROM_JAVA extern int vixDebugGlobalSpewLevel; extern int vixApiTraceGlobalSpewLevel; extern char *VixAllocDebugString(char *fmt, ...) PRINTF_DECL(1,2); extern void VixDebugInit(int debugLevel, int apiTraceLevel, Bool panicOnVixAssert); extern const char *VixDebug_GetFileBaseName(const char *path); extern void VixAssert(const char *cond, const char *file, int lineNum); extern VixError VixLogError(VixError err, const char *function, int line, const char *fileName, const char *fmt, ...) PRINTF_DECL(5, 6); /* * preference name for client and vmx */ #define VIX_DEBUG_PREFERENCE_NAME "vix.debugLevel" #define VIX_ASSERT_PREFERENCE_NAME "vix.doAssert" #define VIX_API_TRACE_PREFERENCE_NAME "vix.apiTraceLevel" /* * Assertions. Normally we'd just use ASSERT(), but we've hit many cases * where ASSERT() is desired by foundry developers, but not by foundry users. * So we have our own VIX_ASSERT(), which is configured via a preference, * vix.doAssert, off by default. */ #ifdef VMX86_DEBUG # ifdef __cplusplus # define VIX_ASSERT(cond) (UNLIKELY(!(cond)) ? VixAssert(#cond, __FILE__, __LINE__) : (void) 0) # else # define VIX_ASSERT(cond) (UNLIKELY(!(cond)) ? VixAssert(#cond, __FILE__, __LINE__) : 0) # endif #else #define VIX_ASSERT(cond) #endif #define DEFAULT_VIX_LOG_LEVEL 0 #define DEFAULT_VIX_API_TRACE_LEVEL 0 #define VIX_DEBUG_LEVEL(logLevel, s) if (logLevel <= vixDebugGlobalSpewLevel) \ { char *debugString = VixAllocDebugString s; \ Log("Vix: [%s:%d]: %s", \ VixDebug_GetFileBaseName(__FILE__), __LINE__, debugString); \ free(debugString); } #define VIX_DEBUG(s) if (0 != vixDebugGlobalSpewLevel) \ { char *debugString = VixAllocDebugString s; \ Log("Vix: [%s:%d]: %s", \ VixDebug_GetFileBaseName(__FILE__), __LINE__, debugString); \ free(debugString); } #define VIX_DEBUG_ALWAYS(s) { char *debugString = VixAllocDebugString s; \ Log("Vix: [%s:%d]: %s", \ VixDebug_GetFileBaseName(__FILE__), __LINE__, debugString); \ free(debugString); } #define VIX_API_TRACE_ON() (vixApiTraceGlobalSpewLevel > 0) #define VIX_API_LOG(s) if (VIX_API_TRACE_ON()) \ { char *debugString = VixAllocDebugString s; \ Log("VixApiLog: %s %s\n", __FUNCTION__, debugString); \ free(debugString); } // If no MSG is given, a description of err is suplemented. #define VIX_ERROR(err) (VIX_ERROR_MSG(err, NULL)) #define VIX_ERROR_MSG(err, ...) (VixLogError(err, __FUNCTION__, __LINE__, \ VixDebug_GetFileBaseName(__FILE__), __VA_ARGS__)) #endif // VIX_HIDE_FROM_JAVA #if defined(__cplusplus) } // extern "C" #endif #endif // _VIXOpenSource_h_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vmGuestLib.h000066400000000000000000000415511321503522500247270ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _VM_GUEST_LIB_H_ #define _VM_GUEST_LIB_H_ #include "vm_basic_types.h" #include "vmSessionId.h" #ifdef __cplusplus extern "C" { #endif /* * This is the VMware GuestLib, an API used for accessing various * performance statistics pertaining to the VMware virtual environment * from within a VMware Virtual Machine. */ /* * Error codes returned by GuestLib functions. * * XXX These should be unified with Foundry's error codes. */ typedef enum { VMGUESTLIB_ERROR_SUCCESS = 0, // No error VMGUESTLIB_ERROR_OTHER, // Other error VMGUESTLIB_ERROR_NOT_RUNNING_IN_VM, // Not running in a VM VMGUESTLIB_ERROR_NOT_ENABLED, // GuestLib not enabled on the host. VMGUESTLIB_ERROR_NOT_AVAILABLE, // This stat not available on this host. VMGUESTLIB_ERROR_NO_INFO, // UpdateInfo() has never been called. VMGUESTLIB_ERROR_MEMORY, // Not enough memory VMGUESTLIB_ERROR_BUFFER_TOO_SMALL, // Buffer too small VMGUESTLIB_ERROR_INVALID_HANDLE, // Handle is invalid VMGUESTLIB_ERROR_INVALID_ARG, // One or more arguments were invalid VMGUESTLIB_ERROR_UNSUPPORTED_VERSION // The host doesn't support this request } VMGuestLibError; char const * VMGuestLib_GetErrorText(VMGuestLibError error); // IN /* * GuestLib handle. * * This handle provides a context for accessing all GuestLib * state. Use VMGuestLib_OpenHandle to get a handle for use with other * GuestLib functions, and use VMGuestLib_CloseHandle to release a * handle previously acquired with VMGuestLib_OpenHandle. * * All of the statistics and session state are maintained per GuestLib * handle, so operating on one GuestLib handle will not affect the * state of another handle. */ struct _VMGuestLibHandle; typedef struct _VMGuestLibHandle* VMGuestLibHandle; VMGuestLibError VMGuestLib_OpenHandle(VMGuestLibHandle *handle); // OUT VMGuestLibError VMGuestLib_CloseHandle(VMGuestLibHandle handle); // IN /* * Update the info and session state for the given handle. * * Concurrency/thread safety: No locking is done internally around the * access of a handle. If a calling program uses multiple threads then * the caller must either ensure that each thread of execution is * using a separate handle, or the caller must implement locking * around calls to VMGuestLib_UpdateInfo() on a given handle to ensure * that two threads do not update the handle concurrently. * * Because the state is maintained per handle and no two handles can * be updated exactly simultaneously, the state of two handles may * differ even if they are updated one immediately after the other. * * VMGuestLib_UpdateInfo() is a fairly heavyweight function; it should * be viewed similar to a system call in terms of the computational * cost and performance hit. For this reason, a user of the API who * is concerned about performance will get best results by minimizing * the number of calls to VMGuestLib_UpdateInfo(). */ VMGuestLibError VMGuestLib_UpdateInfo(VMGuestLibHandle handle); // IN /* * Session ID * * This is used to detect changes in the "session" of a virtual * machine. "Session" in this context refers to the particular running * instance of this virtual machine on a given host. Moving a virtual * machine to another host using VMotion will cause a change in * session ID, as will suspending and resuming a virtual machine or * reverting to a snapshot. * * Any of the events above (VMotion, suspend/resume, snapshot revert) * are likely to render invalid any information previously retrieved * through this API, so the intention of the session ID is to provide * applications with a mechanism to detect those events and react * accordingly, e.g. by refreshing and resetting any state that relies * on validity of previously retrieved information. * * Use VMGuestLib_GetSessionId() to retrieve the ID for the current * session after calling VMGuestLib_UpdateInfo(). After a VMotion or * similar event, VMGuestLib_GetSessionId() will return a new value. * See code example below for an example of how to use this. * * If VMGuestLib_UpdateInfo() has never been called, * VMGUESTLIB_ERROR_NO_INFO is returned. * * The session ID should be considered opaque and cannot be compared * in any meaningful way with the session IDs from any other virtual * machine (e.g. to determine if two virtual machines are on the same * host). * * Here is simple pseudo-code (with no error checking) showing a naive * implementation of detecting stale information using the session ID. * * ----- * * VMSessionId sid = 0; * Bool done = FALSE; * * while (!done) { * VMSessionId tmp; * * VMGuestLib_UpdateInfo(); * VMGuestLib_GetSessionId(&tmp); * if (tmp != sid) { * ResetStats(); * sid = tmp; * } * } * * ----- */ VMGuestLibError VMGuestLib_GetSessionId(VMGuestLibHandle handle, // IN VMSessionId *id); // OUT /* * Specific Stat accessors. The values returned by these accessor * functions are up to date as of the last call to VMGuestLib_UpdateInfo(). * * If VMGuestLib_UpdateInfo() has never been called, * VMGUESTLIB_ERROR_NO_INFO is returned. */ /* CPU */ /* * Retrieves the minimum processing power in MHz available to the virtual * machine. Assigning a cpuReservationMhz ensures that even as other virtual * machines on a single host consume shared processing power, there is * still a certain minimum amount for this virtual machine. */ VMGuestLibError VMGuestLib_GetCpuReservationMHz(VMGuestLibHandle handle, // IN uint32 *cpuReservationMHz); // OUT /* * Retrieves the maximum processing power in MHz available to the virtual * machine. Assigning a cpuLimitMHz ensures that this virtual machine never * consumes more than a certain amount of the available processor power. By * limiting the amount of processing power consumed, a portion of this * shared resource is available to other virtual machines. */ VMGuestLibError VMGuestLib_GetCpuLimitMHz(VMGuestLibHandle handle, // IN uint32 *cpuLimitMHz); // OUT /* * Retrieves the number of CPU shares allocated to the virtual machine. */ VMGuestLibError VMGuestLib_GetCpuShares(VMGuestLibHandle handle, // IN uint32 *cpuShares); // OUT /* * Retrieves the number of milliseconds during which the virtual machine * has been using the CPU. This value is always less than or equal to * elapsedMS. This value, in conjunction with elapsedMS, can be used to * estimate efective virtual machine CPU speed. */ VMGuestLibError VMGuestLib_GetCpuUsedMs(VMGuestLibHandle handle, // IN uint64 *cpuUsedMs); // OUT /* * Host Processor speed. This can be used along with CpuUsedMs and * elapsed time to estimate approximate effective VM CPU speed * over a time interval. The following pseudocode illustrates how * to make this calculation: * * ------------------------------------ * * uint32 effectiveVMSpeed; * uint32 hostMhz; * uint64 elapsed1; * uint64 elapsed2; * uint64 used1; * uint64 used2; * * * VMGuestLib_UpdateInfo(handle); * VMGuestLib_GetHostProcessorSpeed(handle, &hostMhz); * VMGuestLib_GetElapsedMs(handle, &elapsed1); * VMGuestLib_GetUsedMs(handle, &used1); * .... * VMGuestLib_UpdateInfo(handle); * VMGuestLib_GetElapsedMs(handle, &elapsed2); * VMGuestLib_GetUsedMs(handle, &used2); * * effectiveVMSpeed = hostMhz * ((used2 - used1) / (elapsed2 - elapsed1)); * * * ------------------------------------ * * After this code executes, effectiveVMSpeed will be the approximate * average effective speed of the VM's virtual CPU over the time period * between the two calls to VMGuestLib_UpdateInfo(). * */ VMGuestLibError VMGuestLib_GetHostProcessorSpeed(VMGuestLibHandle handle, // IN uint32 *mhz); // OUT /* Memory */ /* * Retrieves the minimum amount of memory that is available to the virtual * machine. Assigning a cpuReservationMB ensures that even as other virtual * machines on a single host consume memory, there is still a certain * minimum amount for this virtual machine. */ VMGuestLibError VMGuestLib_GetMemReservationMB(VMGuestLibHandle handle, // IN uint32 *memReservationMB); // OUT /* * Retrieves the maximum amount of memory that is available to the virtual * machine. Assigning a cpuLimitMB ensures that this virtual machine never * consumes more than a certain amount of the available processor power. By * limiting the amount of processing power consumed, a portion of this * shared resource is available to other virtual machines. */ VMGuestLibError VMGuestLib_GetMemLimitMB(VMGuestLibHandle handle, // IN uint32 *memLimitMB); // OUT /* * Retrieves the number of memory shares allocated to the virtual machine. */ VMGuestLibError VMGuestLib_GetMemShares(VMGuestLibHandle handle, // IN uint32 *memShares); // OUT /* * Retrieves the mapped memory size of this virtual machine. This * is the current total amount of guest memory that is backed by * physical memory. Note that this number may include pages of * memory shared between multiple virtual machines and thus may be * an overestimate of the amount of physical host memory "consumed" * by this virtual machine. */ VMGuestLibError VMGuestLib_GetMemMappedMB(VMGuestLibHandle handle, // IN uint32 *memMappedSizeMB); // OUT /* * Retrieves the estimated amount of memory the virtual machine is actively * using. This method returns an estimated working set size for the virtual * machine. */ VMGuestLibError VMGuestLib_GetMemActiveMB(VMGuestLibHandle handle, // IN uint32 *memActiveMB); // OUT /* * Retrieves the amount of overhead memory associated with this virtual * machine consumed on the host system. */ VMGuestLibError VMGuestLib_GetMemOverheadMB(VMGuestLibHandle handle, // IN uint32 *memOverheadMB); // OUT /* * Retrieves the amount of memory that has been reclaimed from this virtual * machine via the VMware Memory Balloon mechanism. */ VMGuestLibError VMGuestLib_GetMemBalloonedMB(VMGuestLibHandle handle, // IN uint32 *memBalloonedMB); // OUT /* * Retrieves the amount of memory associated with this virtual machine that * has been swapped by the host system. */ VMGuestLibError VMGuestLib_GetMemSwappedMB(VMGuestLibHandle handle, // IN uint32 *memSwappedMB); // OUT /* * Retrieves the amount of physical memory associated with this virtual * machine that is copy-on-write (COW) shared on the host. */ VMGuestLibError VMGuestLib_GetMemSharedMB(VMGuestLibHandle handle, // IN uint32 *memSharedMB); // OUT /* * Retrieves the estimated amount of physical memory on the host saved * from copy-on-write (COW) shared guest physical memory. */ VMGuestLibError VMGuestLib_GetMemSharedSavedMB(VMGuestLibHandle handle, // IN uint32 *memSharedSavedMB); // OUT /* * Retrieves the estimated amount of physical host memory currently * consumed for this virtual machine's physical memory. This is the * same as (mapped memory) - (sharedSaved memory). */ VMGuestLibError VMGuestLib_GetMemUsedMB(VMGuestLibHandle handle, // IN uint32 *memUsedMB); // OUT /* Elapsed Time */ /* * Retrieves the number of milliseconds that have passed in real time since * the virtual machine started running on the current host system. The * elapsed time counter is reset any time the virtual machine is powered * on, resumed, or migrated via VMotion. This value, in conjunction with * cpuUsedMS, can be used to estimate effective virtual machine CPU speed. * The cpuUsedMS value is always less than or equal to this value. */ VMGuestLibError VMGuestLib_GetElapsedMs(VMGuestLibHandle handle, // IN uint64 *elapsedMs); // OUT /* * Resource Pool Path. * * Retrieves a string representation of the path to this virtual machine in * the resource pool namespace of the host system. * * pathBuffer is a pointer to a buffer that will receive the resource * pool path string. bufferSize is a pointer to the size of the * pathBuffer in bytes. If bufferSize is not large enough to * accomodate the path and NUL terminator, then * VMGUESTLIB_ERROR_BUFFER_TOO_SMALL is returned and bufferSize * contains the amount of memory needed (in bytes). */ VMGuestLibError VMGuestLib_GetResourcePoolPath(VMGuestLibHandle handle, // IN size_t *bufferSize, // IN/OUT char *pathBuffer); // OUT /* * CPU stolen time. The time (in ms) that the VM was runnable but not scheduled * to run. */ VMGuestLibError VMGuestLib_GetCpuStolenMs(VMGuestLibHandle handle, // IN uint64 *cpuStolenMs); // OUT /* * Memory Target Size. */ VMGuestLibError VMGuestLib_GetMemTargetSizeMB(VMGuestLibHandle handle, // IN uint64 *memTargetSizeMB); // OUT /* * Number of physical CPU cores on the host machine. */ VMGuestLibError VMGuestLib_GetHostNumCpuCores(VMGuestLibHandle handle, // IN uint32 *hostNumCpuCores); // OUT /* * Total CPU time used by host. */ VMGuestLibError VMGuestLib_GetHostCpuUsedMs(VMGuestLibHandle handle, // IN uint64 *hostCpuUsedMs); // OUT /* * Total memory swapped out on the host. */ VMGuestLibError VMGuestLib_GetHostMemSwappedMB(VMGuestLibHandle handle, // IN uint64 *hostMemSwappedMB); // OUT /* * Total COW (Copy-On-Write) memory on host. */ VMGuestLibError VMGuestLib_GetHostMemSharedMB(VMGuestLibHandle handle, // IN uint64 *hostMemSharedMB); // OUT /* * Total consumed memory on host. */ VMGuestLibError VMGuestLib_GetHostMemUsedMB(VMGuestLibHandle handle, // IN uint64 *hostMemUsedMB); // OUT /* * Total memory available to host OS kernel. */ VMGuestLibError VMGuestLib_GetHostMemPhysMB(VMGuestLibHandle handle, // IN uint64 *hostMemPhysMB); // OUT /* * Total physical memory free on host. */ VMGuestLibError VMGuestLib_GetHostMemPhysFreeMB(VMGuestLibHandle handle, // IN uint64 *hostMemPhysFreeMB); // OUT /* * Total host kernel memory overhead. */ VMGuestLibError VMGuestLib_GetHostMemKernOvhdMB(VMGuestLibHandle handle, // IN uint64 *hostMemKernOvhdMB); // OUT /* * Total mapped memory on host. */ VMGuestLibError VMGuestLib_GetHostMemMappedMB(VMGuestLibHandle handle, // IN uint64 *hostMemMappedMB); // OUT /* * Total unmapped memory on host. */ VMGuestLibError VMGuestLib_GetHostMemUnmappedMB(VMGuestLibHandle handle, // IN uint64 *hostMemUnmappedMB); // OUT /* * Semi-structured hypervisor stats collection, for troubleshooting. */ VMGuestLibError VMGuestLib_StatGet(const char *encoding, // IN const char *stat, // IN char **reply, // OUT size_t *replySize); // OUT /* * To avoid a use after free error in SWIG-generated code, it is * necessary to present SWIG with a modified function prototype * for VMGuestLib_StatFree in which reply is of type "void *" * rather than "char *." */ #ifndef SWIG void VMGuestLib_StatFree(char *reply, size_t replySize); #else void VMGuestLib_StatFree(void *reply, size_t replySize); #endif #ifdef __cplusplus } #endif #endif /* _VM_GUEST_LIB_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vmSessionId.h000066400000000000000000000021361321503522500251050ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2006-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ #ifndef _VM_SESSION_ID_H_ #define _VM_SESSION_ID_H_ #include "vm_basic_types.h" #if defined(__cplusplus) extern "C" { #endif typedef uint64 VMSessionId; #if defined(__cplusplus) } // extern "C" #endif #endif /* _VM_SESSION_ID_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vm_api.h000066400000000000000000000120741321503522500241170ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2010-2016 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * * vm_api.h -- * * Import/export macro definitions. */ #ifndef VM_API_H #define VM_API_H /* * API macros * * These macros can be used by libraries to export/import/hide symbols. * * The general approach is: * * 1) libfoo defines a macro, say EXPORT_FOO_API or STATIC_FOO_API, * in its Makefile/SCons file depending on the type of the library. * * 2) libfoo has the following code in a header file, e.g. foo/platform.h, * that is included by all headers that export/import/hide symbols: * * // In a file named platform.h * #include * * #ifdef STATIC_FOO_API * # define FOO_API VMW_LIB_STATIC * # define FOO_INLINE_API VMW_LIB_STATIC * #elif defined EXPORT_FOO_API * # define FOO_API VMW_LIB_DYNAMIC * # define FOO_INLINE_API VMW_LIB_DYNAMIC_INLINE * #else * # define FOO_API VMW_LIB_CLIENT * # define FOO_INLINE_API VMW_LIB_CLIENT_INLINE * #endif * * For example: * // In a file named FooTypes.h * #ifndef FOO_TYPES_H * #define FOO_TYPES_H * * #include * * class FOO_API FooObject { }; * FOO_API FooObject *GetFooObject(); * * class FOO_INLINE_API FooException { }; * FOO_INLINE_API int GetInt() { return 5; } * * #endif // FOO_TYPES_H * * DLL/DSO import/export macros. * * 3) Compiling a shared library - define EXPORT_FOO_API. * libfoo can now use FOO_API for all symbols it would like to export, * which resolves to VMW_LIB_DYNAMIC, while compiling libfoo as a dynamic * shared library. * On posix systems types that need to export RTTI information, including * exceptions, must have default visibility. However these types may not need * __declspec(dllexport) on Windows. Such classes should be marked with a * FOO_INLINE_API macro. * * 4) Linking against a shared library - no defines needed. * Whenever a client of libfoo includes its headers, these symbols will be * marked with VMW_LIB_CLIENT or VMW_LIB_CLIENT_INLINE, since EXPORT_FOO_API * and STATIC_FOO_API are not defined for the client. * * Static library macros. * * 3) Compiling a static library - define STATIC_FOO_API. * libfoo should hide all of its symbols so that they don't leak through to * another library, say libbar, which links libfoo statically. FOO_API and * FOO_INLINE_API would both resolve to VMW_LIB_STATIC while compiling libfoo * as a static library. * * 4) Linking against a static library - define STATIC_FOO_API. * Whenever a client of libfoo includes its headers, the libfoo symbols * should be hidden on posix systems, marked with VMW_LIB_STATIC. On Windows * defining STATIC_FOO_API is a must when linking against the libfoo static * library. If it's not defined then the libfoo symbols would get an * __declspec(dllimport) declaration. As a result the linker will try to * import them from the list of DLLs present in the link line instead of * linking them directly from the libfoo static library. * * NOTE: By default, symbols are hidden when compiling with MSC and exported * when compiling with GCC. Thus, it's best to compile with GCC's * -fvisibility=hidden and -fvisibility-inlines-hidden flags, so that only * symbols explicitly marked with VMW_LIB_DYNAMIC are exported. Also note that * these flags, as well as the attributes, are available in GCC 4 and later. * * @see http://gcc.gnu.org/wiki/Visibility */ #ifdef _MSC_VER # define VMW_LIB_STATIC # define VMW_LIB_CLIENT __declspec(dllimport) # define VMW_LIB_CLIENT_INLINE # define VMW_LIB_DYNAMIC __declspec(dllexport) # define VMW_LIB_DYNAMIC_INLINE #elif defined __GNUC__ && __GNUC__ >= 4 /* !_MSC_VER */ # define VMW_LIB_STATIC __attribute__ ((visibility ("hidden"))) # define VMW_LIB_CLIENT __attribute__ ((visibility ("default"))) # define VMW_LIB_CLIENT_INLINE __attribute__ ((visibility ("default"))) # define VMW_LIB_DYNAMIC __attribute__ ((visibility ("default"))) # define VMW_LIB_DYNAMIC_INLINE __attribute__ ((visibility ("default"))) #else # define VMW_LIB_STATIC # define VMW_LIB_CLIENT # define VMW_LIB_CLIENT_INLINE # define VMW_LIB_DYNAMIC # define VMW_LIB_DYNAMIC_INLINE #endif /* _MSC_VER */ #endif /* VM_API_H */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vm_assert.h000066400000000000000000000302221321503522500246420ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * vm_assert.h -- * * The basic assertion facility for all VMware code. * * For proper use, see bora/doc/assert and * http://vmweb.vmware.com/~mts/WebSite/guide/programming/asserts.html. */ #ifndef _VM_ASSERT_H_ #define _VM_ASSERT_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_VMMON #define INCLUDE_ALLOW_VMKERNEL #define INCLUDE_ALLOW_VMKDRIVERS #define INCLUDE_ALLOW_VMK_MODULE #define INCLUDE_ALLOW_DISTRIBUTE #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" // XXX not necessary except some places include vm_assert.h improperly #include "vm_basic_types.h" #ifdef __cplusplus extern "C" { #endif /* * Some bits of vmcore are used in VMKernel code and cannot have * the VMKERNEL define due to other header dependencies. */ #if defined(VMKERNEL) && !defined(VMKPANIC) #define VMKPANIC 1 #endif /* * Internal macros, functions, and strings * * The monitor wants to save space at call sites, so it has specialized * functions for each situation. User level wants to save on implementation * so it uses generic functions. */ #if !defined VMM || defined MONITOR_APP // { #if defined (VMKPANIC) #include "vmk_assert.h" #else /* !VMKPANIC */ #define _ASSERT_PANIC(name) \ Panic(_##name##Fmt "\n", __FILE__, __LINE__) #define _ASSERT_PANIC_BUG(bug, name) \ Panic(_##name##Fmt " bugNr=%d\n", __FILE__, __LINE__, bug) #define _ASSERT_PANIC_NORETURN(name) \ Panic(_##name##Fmt "\n", __FILE__, __LINE__) #define _ASSERT_PANIC_BUG_NORETURN(bug, name) \ Panic(_##name##Fmt " bugNr=%d\n", __FILE__, __LINE__, bug) #endif /* VMKPANIC */ #endif // } // These strings don't have newline so that a bug can be tacked on. #define _AssertPanicFmt "PANIC %s:%d" #define _AssertAssertFmt "ASSERT %s:%d" #define _AssertVerifyFmt "VERIFY %s:%d" #define _AssertNotImplementedFmt "NOT_IMPLEMENTED %s:%d" #define _AssertNotReachedFmt "NOT_REACHED %s:%d" #define _AssertMemAllocFmt "MEM_ALLOC %s:%d" #define _AssertNotTestedFmt "NOT_TESTED %s:%d" /* * Panic and log functions */ void Log(const char *fmt, ...) PRINTF_DECL(1, 2); void Warning(const char *fmt, ...) PRINTF_DECL(1, 2); #if defined VMKPANIC void Panic_SaveRegs(void); NORETURN void Panic_NoSave(const char *fmt, ...) PRINTF_DECL(1, 2); #define Panic(fmt...) do { \ Panic_SaveRegs(); \ Panic_NoSave(fmt); \ } while(0) #else NORETURN void Panic(const char *fmt, ...) PRINTF_DECL(1, 2); #endif void LogThrottled(uint32 *count, const char *fmt, ...) PRINTF_DECL(2, 3); void WarningThrottled(uint32 *count, const char *fmt, ...) PRINTF_DECL(2, 3); #ifndef ASSERT_IFNOT /* * PR 271512: When compiling with gcc, catch assignments inside an ASSERT. * * 'UNLIKELY' is defined with __builtin_expect, which does not warn when * passed an assignment (gcc bug 36050). To get around this, we put 'cond' * in an 'if' statement and make sure it never gets executed by putting * that inside of 'if (0)'. We use gcc's statement expression syntax to * make ASSERT an expression because some code uses it that way. * * Since statement expression syntax is a gcc extension and since it's * not clear if this is a problem with other compilers, the ASSERT * definition was not changed for them. Using a bare 'cond' with the * ternary operator may provide a solution. */ #ifdef __GNUC__ #define ASSERT_IFNOT(cond, panic) \ ({if (UNLIKELY(!(cond))) { panic; if (0) { if (cond) {;}}} (void)0;}) #else #define ASSERT_IFNOT(cond, panic) \ (UNLIKELY(!(cond)) ? (panic) : (void)0) #endif #endif /* * Assert, panic, and log macros * * Some of these are redefined below undef !VMX86_DEBUG. * ASSERT() is special cased because of interaction with Windows DDK. */ #if defined VMX86_DEBUG #undef ASSERT #define ASSERT(cond) ASSERT_IFNOT(cond, _ASSERT_PANIC(AssertAssert)) #define ASSERT_BUG(bug, cond) \ ASSERT_IFNOT(cond, _ASSERT_PANIC_BUG(bug, AssertAssert)) #endif #undef VERIFY #define VERIFY(cond) \ ASSERT_IFNOT(cond, _ASSERT_PANIC_NORETURN(AssertVerify)) #define VERIFY_BUG(bug, cond) \ ASSERT_IFNOT(cond, _ASSERT_PANIC_BUG_NORETURN(bug, AssertVerify)) #define PANIC() _ASSERT_PANIC(AssertPanic) #define PANIC_BUG(bug) _ASSERT_PANIC_BUG(bug, AssertPanic) #define ASSERT_NOT_IMPLEMENTED(cond) \ ASSERT_IFNOT(cond, NOT_IMPLEMENTED()) #if defined VMKPANIC || defined VMM #define NOT_IMPLEMENTED() _ASSERT_PANIC_NORETURN(AssertNotImplemented) #else #define NOT_IMPLEMENTED() _ASSERT_PANIC(AssertNotImplemented) #endif #if defined VMM #define NOT_IMPLEMENTED_BUG(bug) \ _ASSERT_PANIC_BUG_NORETURN(bug, AssertNotImplemented) #else #define NOT_IMPLEMENTED_BUG(bug) _ASSERT_PANIC_BUG(bug, AssertNotImplemented) #endif #if defined VMKPANIC || defined VMM #define NOT_REACHED() _ASSERT_PANIC_NORETURN(AssertNotReached) #else #define NOT_REACHED() _ASSERT_PANIC(AssertNotReached) #endif #define ASSERT_MEM_ALLOC(cond) \ ASSERT_IFNOT(cond, _ASSERT_PANIC(AssertMemAlloc)) #ifdef VMX86_DEVEL #define NOT_TESTED() Warning(_AssertNotTestedFmt "\n", __FILE__, __LINE__) #else #define NOT_TESTED() Log(_AssertNotTestedFmt "\n", __FILE__, __LINE__) #endif #define ASSERT_NO_INTERRUPTS() ASSERT(!INTERRUPTS_ENABLED()) #define ASSERT_HAS_INTERRUPTS() ASSERT(INTERRUPTS_ENABLED()) #define ASSERT_NOT_TESTED(cond) (UNLIKELY(!(cond)) ? NOT_TESTED() : (void)0) #define NOT_TESTED_ONCE() DO_ONCE(NOT_TESTED()) #define NOT_TESTED_1024() \ do { \ static uint16 count = 0; \ if (UNLIKELY(count == 0)) { NOT_TESTED(); } \ count = (count + 1) & 1023; \ } while (0) #define LOG_ONCE(_s) DO_ONCE(Log _s) /* * Redefine macros that are only in debug versions */ #if !defined VMX86_DEBUG // { #undef ASSERT #define ASSERT(cond) ((void)0) #define ASSERT_BUG(bug, cond) ((void)0) /* * Expand NOT_REACHED() as appropriate for each situation. * * Mainly, we want the compiler to infer the same control-flow * information as it would from Panic(). Otherwise, different * compilation options will lead to different control-flow-derived * errors, causing some make targets to fail while others succeed. * * VC++ has the __assume() built-in function which we don't trust * (see bug 43485); gcc has no such construct; we just panic in * userlevel code. The monitor doesn't want to pay the size penalty * (measured at 212 bytes for the release vmm for a minimal infinite * loop; panic would cost even more) so it does without and lives * with the inconsistency. */ #if defined VMKPANIC || defined VMM #undef NOT_REACHED #if defined __GNUC__ && (__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 5) #define NOT_REACHED() (__builtin_unreachable()) #else #define NOT_REACHED() ((void)0) #endif #else // keep debug definition #endif #undef LOG_UNEXPECTED #define LOG_UNEXPECTED(bug) ((void)0) #undef ASSERT_NOT_TESTED #define ASSERT_NOT_TESTED(cond) ((void)0) #undef NOT_TESTED #define NOT_TESTED() ((void)0) #undef NOT_TESTED_ONCE #define NOT_TESTED_ONCE() ((void)0) #undef NOT_TESTED_1024 #define NOT_TESTED_1024() ((void)0) #endif // !VMX86_DEBUG } /* * Compile-time assertions. * * ASSERT_ON_COMPILE does not use the common * switch (0) { case 0: case (e): ; } trick because some compilers (e.g. MSVC) * generate code for it. * * The implementation uses both enum and typedef because the typedef alone is * insufficient; gcc allows arrays to be declared with non-constant expressions * (even in typedefs, where it makes no sense). * * NOTE: if GCC ever changes so that it ignores unused types altogether, this * assert might not fire! We explicitly mark it as unused because GCC 4.8+ * uses -Wunused-local-typedefs as part of -Wall, which means the typedef will * generate a warning. */ #if defined(_Static_assert) || defined(__cplusplus) || \ !defined(__GNUC__) || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6) #define ASSERT_ON_COMPILE(e) \ do { \ enum { AssertOnCompileMisused = ((e) ? 1 : -1) }; \ UNUSED_TYPE(typedef char AssertOnCompileFailed[AssertOnCompileMisused]); \ } while (0) #else #define ASSERT_ON_COMPILE(e) \ do { \ _Static_assert(e, #e); \ } while (0) #endif /* * To put an ASSERT_ON_COMPILE() outside a function, wrap it * in MY_ASSERTS(). The first parameter must be unique in * each .c file where it appears. For example, * * MY_ASSERTS(FS3_INT, * ASSERT_ON_COMPILE(sizeof(FS3_DiskLock) == 128); * ASSERT_ON_COMPILE(sizeof(FS3_DiskLockReserved) == DISK_BLOCK_SIZE); * ASSERT_ON_COMPILE(sizeof(FS3_DiskBlock) == DISK_BLOCK_SIZE); * ASSERT_ON_COMPILE(sizeof(Hardware_DMIUUID) == 16); * ) * * Caution: ASSERT() within MY_ASSERTS() is silently ignored. * The same goes for anything else not evaluated at compile time. */ #define MY_ASSERTS(name, assertions) \ static INLINE void name(void) { \ assertions \ } #ifdef __cplusplus } /* extern "C" */ #endif #endif /* ifndef _VM_ASSERT_H_ */ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vm_atomic.h000066400000000000000000003001041321503522500246140ustar00rootroot00000000000000/********************************************************* * Copyright (C) 1998-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /* * vm_atomic.h -- * * Atomic power * * Note: Only partially tested on ARM processors: Works for View Open * Client, which shouldn't have threads, and ARMv8 processors. * * In ARM, GCC intrinsics (__sync*) compile but might not * work, while MS intrinsics (_Interlocked*) do not compile. */ #ifndef _ATOMIC_H_ #define _ATOMIC_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_VMMON #define INCLUDE_ALLOW_VMKDRIVERS #define INCLUDE_ALLOW_VMK_MODULE #define INCLUDE_ALLOW_VMKERNEL #define INCLUDE_ALLOW_DISTRIBUTE #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #include "vm_assert.h" #if defined __cplusplus extern "C" { #endif /* * In the Atomic_* definitions below, memory ordering and atomicity are somewhat * conflated in an inconsistent manner. First, we have Atomic_{Read,Write}, * which only guarantees single copy atomicity, i.e. that the read/write occurs * in an atomic fashion, but have no implication on memory ordering. The second * class of Atomics are all the non-unfenced operations excluding * Atomic_{Read,Write}*, which both imply atomicity and act as a memory barrier, * implying sequentially consistent ordering of the atomic operation with all * loads/stores prior to and after it. * * Since on x86, the second class of operations are associated with LOCK * semantics, assumptions have been made about the ordering these operations * imply on surrounding code (see for example the vmkernel's RefCount * implementation). As a result, on arm64 we have to provide these same * guarantees. We do this by making use of DMB barriers both before and after * the atomic ldrx/strx sequences. A barrier before and after is required to * avoid having part of the atomic operation reordered with surrounding code, * e.g. a store-load reordering of the strx with a following load outside the * Atomic_ op. For the first class of operations, Atomic_{Read,Write}, we do not * implement a barrier. * * This implementation of Atomic operations is suboptimal on arm64, since * both atomicity and memory ordering are fused together. Ideally the Atomic * operations would only imply atomicity, and an explicit memory barrier in the * surrounding code used to enforce ordering where necessary. This would eschew * the need for the DMBs. A middle ground can be implemented where we use the * arm64 load-acquire/store-release exclusive instructions to implement Atomics. * This would imply sequential consistency of the Atomic operations (but not * with any of the surrounding non-atomic operations) without the need for a * DMB. Using these without a DMB today can still result in problematic * reordering by the processor with surrounding non-atomic operations, e.g. a * store-load reordering with a stlxr. Future optimization for arm64 should * consider the wider change required at the call sites to minimize DMBs. * * For further details on x86 and ARM memory ordering see * https://wiki.eng.vmware.com/ARM/MemoryOrdering. */ #ifdef VM_ARM_64 # include "vm_atomic_arm64_begin.h" #endif /* Basic atomic types: 8, 16, 32, 64 and 128 bits */ typedef struct Atomic_uint8 { volatile uint8 value; } Atomic_uint8 ALIGNED(1); typedef struct Atomic_uint16 { volatile uint16 value; } Atomic_uint16 ALIGNED(2); typedef struct Atomic_uint32 { volatile uint32 value; } Atomic_uint32 ALIGNED(4); typedef struct Atomic_uint64 { volatile uint64 value; } Atomic_uint64 ALIGNED(8); #if defined __GNUC__ && defined VM_64BIT && \ (defined __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 || defined VM_ARM_64) typedef struct Atomic_uint128 { volatile uint128 value; } Atomic_uint128 ALIGNED(16); #endif /* * Prototypes for msft atomics. These are defined & inlined by the * compiler so no function definition is needed. The prototypes are * needed for C++. Since amd64 compiler doesn't support inline asm we * have to use these. Unfortunately, we still have to use some inline asm * for the 32 bit code since the and/or/xor implementations didn't show up * until XP or 2k3. * * The declarations for the intrinsic functions were taken from ntddk.h * in the DDK. The declarations must match otherwise the 64-bit C++ * compiler will complain about second linkage of the intrinsic functions. * We define the intrinsic using the basic types corresponding to the * Windows typedefs. This avoids having to include windows header files * to get to the windows types. */ #if defined _MSC_VER && _MSC_VER >= 1310 && !defined BORA_NO_WIN32_INTRINS #ifdef __cplusplus extern "C" { #endif long _InterlockedExchange(long volatile*, long); long _InterlockedCompareExchange(long volatile*, long, long); long _InterlockedExchangeAdd(long volatile*, long); long _InterlockedDecrement(long volatile*); long _InterlockedIncrement(long volatile*); __int64 _InterlockedCompareExchange64(__int64 volatile*, __int64, __int64); #pragma intrinsic(_InterlockedExchange, _InterlockedCompareExchange) #pragma intrinsic(_InterlockedExchangeAdd, _InterlockedDecrement) #pragma intrinsic(_InterlockedIncrement) #pragma intrinsic(_InterlockedCompareExchange64) # if _MSC_VER >= 1600 char _InterlockedExchange8(char volatile *, char); char _InterlockedCompareExchange8(char volatile *, char, char); #pragma intrinsic(_InterlockedCompareExchange8, _InterlockedCompareExchange8) #endif #if defined VM_X86_64 long _InterlockedAnd(long volatile*, long); __int64 _InterlockedAnd64(__int64 volatile*, __int64); long _InterlockedOr(long volatile*, long); __int64 _InterlockedOr64(__int64 volatile*, __int64); long _InterlockedXor(long volatile*, long); __int64 _InterlockedXor64(__int64 volatile*, __int64); __int64 _InterlockedExchangeAdd64(__int64 volatile*, __int64); __int64 _InterlockedIncrement64(__int64 volatile*); __int64 _InterlockedDecrement64(__int64 volatile*); __int64 _InterlockedExchange64(__int64 volatile*, __int64); #if !defined _WIN64 #pragma intrinsic(_InterlockedAnd, _InterlockedAnd64) #pragma intrinsic(_InterlockedOr, _InterlockedOr64) #pragma intrinsic(_InterlockedXor, _InterlockedXor64) #pragma intrinsic(_InterlockedExchangeAdd64, _InterlockedIncrement64) #pragma intrinsic(_InterlockedDecrement64, _InterlockedExchange64) #endif /* !_WIN64 */ #endif /* __x86_64__ */ #ifdef __cplusplus } #endif #endif /* _MSC_VER */ #if defined __arm__ /* * LDREX without STREX or CLREX may cause problems in environments where the * context switch may not clear the reference monitor - according ARM manual * the reference monitor should be cleared after a context switch, but some * may not like Linux kernel's non-preemptive context switch path. So use of * ARM routines in kernel code may not be safe. */ # if defined __ARM_ARCH_7__ || defined __ARM_ARCH_7A__ || \ defined __ARM_ARCH_7R__|| defined __ARM_ARCH_7M__ # define VM_ARM_V7 # ifdef __KERNEL__ # warning LDREX/STREX may not be safe in linux kernel, since it \ does not issue CLREX on context switch (as of 2011-09-29). # endif # else # error Only ARMv7 extends the synchronization primitives ldrex/strex. \ For the lower ARM version, please implement the atomic functions \ by kernel APIs. # endif #endif /* Data Memory Barrier */ #ifdef VM_ARM_V7 #define dmb() __asm__ __volatile__("dmb" : : : "memory") #endif /* Convert a volatile uint32 to Atomic_uint32. */ static INLINE Atomic_uint32 * Atomic_VolatileToAtomic32(volatile uint32 *var) // IN: { return (Atomic_uint32 *)var; } #define Atomic_VolatileToAtomic Atomic_VolatileToAtomic32 /* Convert a volatile uint64 to Atomic_uint64. */ static INLINE Atomic_uint64 * Atomic_VolatileToAtomic64(volatile uint64 *var) // IN: { return (Atomic_uint64 *)var; } /* * All the assembly code is tricky and written conservatively. * For example, to make sure gcc won't introduce copies, * we force the addressing mode like this: * * "xchgl %0, (%1)" * : "=r" (val) * : "r" (&var->value), * "0" (val) * : "memory" * * - edward * * Actually - turns out that gcc never generates memory aliases (it * still does generate register aliases though), so we can be a bit * more agressive with the memory constraints. The code above can be * modified like this: * * "xchgl %0, %1" * : "=r" (val), * "=m" (var->value), * : "0" (val), * "1" (var->value) * * The advantages are that gcc can use whatever addressing mode it * likes to access the memory value, and that we dont have to use a * way-too-generic "memory" clobber as there is now an explicit * declaration that var->value is modified. * * see also /usr/include/asm/atomic.h to convince yourself this is a * valid optimization. * * - walken */ #if defined _MSC_VER && _MSC_VER < 1600 && defined __x86_64__ uint8 VMWInterlockedExchange8(uint8 volatile *ptr, uint8 val); uint8 VMWInterlockedCompareExchange8(uint8 volatile *ptr, uint8 newVal, uint8 oldVal); #endif #if defined __GNUC__ && defined VM_ARM_32 /* Force the link step to fail for unimplemented functions. */ extern int AtomicUndefined(void const *); #endif /* *----------------------------------------------------------------------------- * * Atomic_ReadIfEqualWrite128 -- * * Compare and exchange a 16 byte tuple. * * Results: * old value * * Side effects: * None * *----------------------------------------------------------------------------- */ #if defined __GNUC__ && defined VM_64BIT && \ (defined __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 || defined VM_ARM_64) static INLINE uint128 Atomic_ReadIfEqualWrite128(Atomic_uint128 *ptr, // IN/OUT uint128 oldVal, // IN uint128 newVal) // IN { #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 return __sync_val_compare_and_swap(&ptr->value, oldVal, newVal); #elif defined VM_ARM_64 union { uint128 raw; struct { uint64 lo; uint64 hi; }; } res, _old = { oldVal }, _new = { newVal }; uint32 failed; SMP_RW_BARRIER_RW(); __asm__ __volatile__( "1: ldxp %x0, %x1, %3 \n\t" " cmp %x0, %x4 \n\t" " ccmp %x1, %x5, #0, eq \n\t" " b.ne 2f \n\t" " stxp %w2, %x6, %x7, %3 \n\t" " cbnz %w2, 1b \n\t" "2: \n\t" : "=&r" (res.lo), "=&r" (res.hi), "=&r" (failed), "+Q" (ptr->value) : "r" (_old.lo), "r" (_old.hi), "r" (_new.lo), "r" (_new.hi) : "cc" ); SMP_RW_BARRIER_RW(); return res.raw; #endif } #endif /* *----------------------------------------------------------------------------- * * Atomic_Read8 -- * * Read the value of the specified object atomically. * * Results: * The value of the atomic variable. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_Read8(Atomic_uint8 const *var) // IN: { uint8 val; #if defined __GNUC__ && defined VM_ARM_32 val = AtomicUndefined(var); #elif defined VM_ARM_64 val = _VMATOM_X(R, 8, &var->value); #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__) __asm__ __volatile__( "movb %1, %0" : "=q" (val) : "m" (var->value) ); #elif defined _MSC_VER val = var->value; #else #error No compiler defined for Atomic_Read8 #endif return val; } /* *----------------------------------------------------------------------------- * * Atomic_ReadWrite8 -- * * Read followed by write. * * Results: * The value of the atomic variable before the write. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_ReadWrite8(Atomic_uint8 *var, // IN/OUT: uint8 val) // IN: { #if defined __GNUC__ && defined VM_ARM_32 return AtomicUndefined(var + val); #elif defined VM_ARM_64 return _VMATOM_X(RW, 8, TRUE, &var->value, val); #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__) __asm__ __volatile__( "xchgb %0, %1" : "=q" (val), "+m" (var->value) : "0" (val) ); return val; #elif defined _MSC_VER && _MSC_VER >= 1600 return _InterlockedExchange8((volatile char *)&var->value, val); #elif defined _MSC_VER && defined __i386__ #pragma warning(push) #pragma warning(disable : 4035) // disable no-return warning { __asm movzx eax, val __asm mov ebx, var __asm xchg [ebx]Atomic_uint8.value, al } #pragma warning(pop) #elif defined _MSC_VER && defined __x86_64__ return VMWInterlockedExchange8(&var->value, val); #else #error No compiler defined for Atomic_ReadWrite8 #endif } /* *----------------------------------------------------------------------------- * * Atomic_Write8 -- * * Write the specified value to the specified object atomically. * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Write8(Atomic_uint8 *var, // IN/OUT: uint8 val) // IN: { #if defined __GNUC__ && defined VM_ARM_32 AtomicUndefined(var + val); #elif defined VM_ARM_64 _VMATOM_X(W, 8, &var->value, val); #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__) __asm__ __volatile__( "movb %1, %0" : "=m" (var->value) : "qn" (val) ); #elif defined _MSC_VER var->value = val; #else #error No compiler defined for Atomic_Write8 #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadIfEqualWrite8 -- * * Compare exchange: Read variable, if equal to oldVal, write newVal. * * Results: * The value of the atomic variable before the write. * * Side effects: * The variable may be modified. * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_ReadIfEqualWrite8(Atomic_uint8 *var, // IN/OUT: uint8 oldVal, // IN: uint8 newVal) // IN: { #if defined __GNUC__ && defined VM_ARM_32 return AtomicUndefined(var + oldVal + newVal); #elif defined VM_ARM_64 return _VMATOM_X(RIFEQW, 8, TRUE, &var->value, oldVal, newVal); #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__) uint8 val; __asm__ __volatile__( "lock; cmpxchgb %2, %1" : "=a" (val), "+m" (var->value) : "q" (newVal), "0" (oldVal) : "cc" ); return val; #elif defined _MSC_VER && _MSC_VER >= 1600 return _InterlockedCompareExchange8((volatile char *)&var->value, newVal, oldVal); #elif defined _MSC_VER && defined __i386__ #pragma warning(push) #pragma warning(disable : 4035) // disable no-return warning { __asm mov al, oldVal __asm mov ebx, var __asm mov cl, newVal __asm lock cmpxchg [ebx]Atomic_uint8.value, cl __asm movzx eax, al // eax is the return value, this is documented to work - edward } #pragma warning(pop) #elif defined _MSC_VER && defined __x86_64__ return VMWInterlockedCompareExchange8(&var->value, newVal, oldVal); #else #error No compiler defined for Atomic_ReadIfEqualWrite8 #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadAnd8 -- * * Atomic read (returned), bitwise AND with a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_ReadAnd8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { uint8 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 8, TRUE, &var->value, and, val); #else do { res = Atomic_Read8(var); } while (res != Atomic_ReadIfEqualWrite8(var, res, res & val)); #endif return res; } /* *----------------------------------------------------------------------------- * * Atomic_And8 -- * * Atomic read, bitwise AND with a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_And8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { #if defined VM_ARM_64 _VMATOM_X(OP, 8, TRUE, &var->value, and, val); #else (void)Atomic_ReadAnd8(var, val); #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadOr8 -- * * Atomic read (returned), bitwise OR with a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_ReadOr8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { uint8 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 8, TRUE, &var->value, orr, val); #else do { res = Atomic_Read8(var); } while (res != Atomic_ReadIfEqualWrite8(var, res, res | val)); #endif return res; } /* *----------------------------------------------------------------------------- * * Atomic_Or8 -- * * Atomic read, bitwise OR with a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Or8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { #if defined VM_ARM_64 _VMATOM_X(OP, 8, TRUE, &var->value, orr, val); #else (void)Atomic_ReadOr8(var, val); #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadXor8 -- * * Atomic read (returned), bitwise XOR with a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_ReadXor8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { uint8 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 8, TRUE, &var->value, eor, val); #else do { res = Atomic_Read8(var); } while (res != Atomic_ReadIfEqualWrite8(var, res, res ^ val)); #endif return res; } /* *----------------------------------------------------------------------------- * * Atomic_Xor8 -- * * Atomic read, bitwise XOR with a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Xor8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { #if defined VM_ARM_64 _VMATOM_X(OP, 8, TRUE, &var->value, eor, val); #else (void)Atomic_ReadXor8(var, val); #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadAdd8 -- * * Atomic read (returned), add a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_ReadAdd8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { uint8 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 8, TRUE, &var->value, add, val); #else do { res = Atomic_Read8(var); } while (res != Atomic_ReadIfEqualWrite8(var, res, res + val)); #endif return res; } /* *----------------------------------------------------------------------------- * * Atomic_Add8 -- * * Atomic read, add a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Add8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { #if defined VM_ARM_64 _VMATOM_X(OP, 8, TRUE, &var->value, add, val); #else (void)Atomic_ReadAdd8(var, val); #endif } /* *----------------------------------------------------------------------------- * * Atomic_Sub8 -- * * Atomic read, subtract a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Sub8(Atomic_uint8 *var, // IN/OUT uint8 val) // IN { #if defined VM_ARM_64 _VMATOM_X(OP, 8, TRUE, &var->value, sub, val); #else Atomic_Add8(var, -val); #endif } /* *----------------------------------------------------------------------------- * * Atomic_Inc8 -- * * Atomic read, increment, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Inc8(Atomic_uint8 *var) // IN/OUT { Atomic_Add8(var, 1); } /* *----------------------------------------------------------------------------- * * Atomic_Dec8 -- * * Atomic read, decrement, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Dec8(Atomic_uint8 *var) // IN/OUT { Atomic_Sub8(var, 1); } /* *----------------------------------------------------------------------------- * * Atomic_ReadInc8 -- * * Atomic read (returned), increment, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_ReadInc8(Atomic_uint8 *var) // IN/OUT { return Atomic_ReadAdd8(var, 1); } /* *----------------------------------------------------------------------------- * * Atomic_ReadDec8 -- * * Atomic read (returned), decrement, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint8 Atomic_ReadDec8(Atomic_uint8 *var) // IN/OUT { return Atomic_ReadAdd8(var, (uint8)-1); } /* *----------------------------------------------------------------------------- * * Atomic_Read32 -- * * Read * * Results: * The value of the atomic variable. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE uint32 Atomic_Read32(Atomic_uint32 const *var) // IN { uint32 value; #if defined VMM || defined VM_ARM_64 || defined VMKERNEL || defined VMKERNEL_MODULE ASSERT(((uintptr_t)var % 4) == 0); #endif #if defined __GNUC__ /* * Use inline assembler to force using a single load instruction to * ensure that the compiler doesn't split a transfer operation into multiple * instructions. */ #if defined VM_ARM_32 __asm__ __volatile__( "ldr %0, [%1]" : "=r" (value) : "r" (&var->value) ); #elif defined VM_ARM_64 value = _VMATOM_X(R, 32, &var->value); #else __asm__ __volatile__( "mov %1, %0" : "=r" (value) : "m" (var->value) ); #endif #elif defined _MSC_VER /* * Microsoft docs guarantee simple reads and writes to properly * aligned 32-bit variables use only a single instruction. * http://msdn.microsoft.com/en-us/library/ms684122%28VS.85%29.aspx */ value = var->value; #else #error No compiler defined for Atomic_Read #endif return value; } #define Atomic_Read Atomic_Read32 /* *----------------------------------------------------------------------------- * * Atomic_ReadWrite32 -- * * Read followed by write * * Results: * The value of the atomic variable before the write. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint32 Atomic_ReadWrite32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register volatile uint32 retVal; register volatile uint32 res; dmb(); __asm__ __volatile__( "1: ldrex %[retVal], [%[var]] \n\t" "strex %[res], %[val], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [retVal] "=&r" (retVal), [res] "=&r" (res) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); return retVal; #elif defined VM_ARM_64 return _VMATOM_X(RW, 32, TRUE, &var->value, val); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "xchgl %0, %1" : "=r" (val), "+m" (var->value) : "0" (val) ); return val; #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if _MSC_VER >= 1310 return _InterlockedExchange((long *)&var->value, (long)val); #else #pragma warning(push) #pragma warning(disable : 4035) // disable no-return warning { __asm mov eax, val __asm mov ebx, var __asm xchg [ebx]Atomic_uint32.value, eax // eax is the return value, this is documented to work - edward } #pragma warning(pop) #endif // _MSC_VER >= 1310 #else #error No compiler defined for Atomic_ReadWrite #endif // __GNUC__ } #define Atomic_ReadWrite Atomic_ReadWrite32 /* *----------------------------------------------------------------------------- * * Atomic_Write32 -- * * Write * * Results: * None. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Write32(Atomic_uint32 *var, // OUT uint32 val) // IN { #if defined VMM || defined VM_ARM_64 || defined VMKERNEL || defined VMKERNEL_MODULE ASSERT(((uintptr_t)var % 4) == 0); #endif #if defined __GNUC__ #if defined VM_ARM_64 _VMATOM_X(W, 32, &var->value, val); #elif defined VM_ARM_32 /* * Best left this way due to the intricacies of exclusive load/store * operations on legacy (32-bit) ARM. * * A3.4.1 ARM DDI 0406C: * * When a processor writes using any instruction other than a * Store-Exclusive: * * - if the write is to a physical address that is not covered by its local * monitor the write does not affect the state of the local monitor * - if the write is to a physical address that is covered by its local * monitor it is IMPLEMENTATION DEFINED whether the write affects the * state of the local monitor. * * A3.4.5 ARM DDI 0406C: * * If two STREX instructions are executed without an intervening LDREX the * second STREX returns a status value of 1. This means that: * * - ARM recommends that, in a given thread of execution, every STREX has a * preceding LDREX associated with it * - it is not necessary for every LDREX to have a subsequent STREX. */ Atomic_ReadWrite32(var, val); #else /* * Use inline assembler to force using a single store instruction to * ensure that the compiler doesn't split a transfer operation into multiple * instructions. */ __asm__ __volatile__( "mov %1, %0" : "=m" (var->value) : "r" (val) ); #endif #elif defined _MSC_VER /* * Microsoft docs guarantee simple reads and writes to properly * aligned 32-bit variables use only a single instruction. * http://msdn.microsoft.com/en-us/library/ms684122%28VS.85%29.aspx */ var->value = val; #else #error No compiler defined for Atomic_Write #endif } #define Atomic_Write Atomic_Write32 /* *----------------------------------------------------------------------------- * * Atomic_ReadIfEqualWrite32 -- * * Compare exchange: Read variable, if equal to oldVal, write newVal * * Results: * The value of the atomic variable before the write. * * Side effects: * The variable may be modified. * *----------------------------------------------------------------------------- */ static INLINE uint32 Atomic_ReadIfEqualWrite32(Atomic_uint32 *var, // IN/OUT uint32 oldVal, // IN uint32 newVal) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register uint32 retVal; register uint32 res; dmb(); __asm__ __volatile__( "1: ldrex %[retVal], [%[var]] \n\t" "mov %[res], #0 \n\t" "teq %[retVal], %[oldVal] \n\t" "strexeq %[res], %[newVal], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [retVal] "=&r" (retVal), [res] "=&r" (res) : [var] "r" (&var->value), [oldVal] "r" (oldVal), [newVal] "r" (newVal) : "cc" ); dmb(); return retVal; #elif defined VM_ARM_64 return _VMATOM_X(RIFEQW, 32, TRUE, &var->value, oldVal, newVal); #else /* VM_X86_ANY */ uint32 val; /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; cmpxchgl %2, %1" : "=a" (val), "+m" (var->value) : "r" (newVal), "0" (oldVal) : "cc" ); return val; #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if _MSC_VER >= 1310 return _InterlockedCompareExchange((long *)&var->value, (long)newVal, (long)oldVal); #else #pragma warning(push) #pragma warning(disable : 4035) // disable no-return warning { __asm mov eax, oldVal __asm mov ebx, var __asm mov ecx, newVal __asm lock cmpxchg [ebx]Atomic_uint32.value, ecx // eax is the return value, this is documented to work - edward } #pragma warning(pop) #endif #else #error No compiler defined for Atomic_ReadIfEqualWrite #endif } #define Atomic_ReadIfEqualWrite Atomic_ReadIfEqualWrite32 #if defined VM_64BIT || defined VM_ARM_V7 /* *----------------------------------------------------------------------------- * * Atomic_ReadIfEqualWrite64 -- * * Compare exchange: Read variable, if equal to oldVal, write newVal * * Results: * The value of the atomic variable before the write. * * Side effects: * The variable may be modified. * *----------------------------------------------------------------------------- */ static INLINE uint64 Atomic_ReadIfEqualWrite64(Atomic_uint64 *var, // IN/OUT uint64 oldVal, // IN uint64 newVal) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register uint64 retVal; register uint32 res; dmb(); /* * Under Apple LLVM version 5.0 (clang-500.2.76) (based on LLVM 3.3svn) * There will be a warning: * "value size does not match register size specified by the constraint * and modifier [-Wasm-operand-widths]" * on the lines: * : [var] "r" (&var->value), [oldVal] "r" (oldVal), [newVal] "r" (newVal) * ^ * : [var] "r" (&var->value), [oldVal] "r" (oldVal), [newVal] "r" (newVal) * ^ * * Furthermore, using a 32-bits register to store a * 64-bits value of an variable looks risky. */ #if defined __APPLE__ && __clang__ == 1 && __clang_major__ >= 5 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wasm-operand-widths" #endif __asm__ __volatile__( "1: ldrexd %[retVal], %H[retVal], [%[var]] \n\t" "mov %[res], #0 \n\t" "teq %[retVal], %[oldVal] \n\t" "teqeq %H[retVal], %H[oldVal] \n\t" "strexdeq %[res], %[newVal], %H[newVal], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [retVal] "=&r" (retVal), [res] "=&r" (res) : [var] "r" (&var->value), [oldVal] "r" (oldVal), [newVal] "r" (newVal) : "cc" ); #if defined __APPLE__ && __clang__ == 1 && __clang_major__ >= 5 #pragma clang diagnostic pop #endif // defined __APPLE__ && __clang__ == 1 && __clang_major__ >= 5 dmb(); return retVal; #elif defined VM_ARM_64 return _VMATOM_X(RIFEQW, 64, TRUE, &var->value, oldVal, newVal); #else /* VM_X86_64 */ uint64 val; /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "lock; cmpxchgq %2, %1" : "=a" (val), "+m" (var->value) : "r" (newVal), "0" (oldVal) : "cc" ); return val; #endif //VM_ARM_V7 #elif defined _MSC_VER return _InterlockedCompareExchange64((__int64 *)&var->value, (__int64)newVal, (__int64)oldVal); #else #error No compiler defined for Atomic_ReadIfEqualWrite64 #endif } #endif /* *----------------------------------------------------------------------------- * * Atomic_And32 -- * * Atomic read, bitwise AND with a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_And32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register volatile uint32 res; register volatile uint32 tmp; dmb(); __asm__ __volatile__( "1: ldrex %[tmp], [%[var]] \n\t" "and %[tmp], %[tmp], %[val] \n\t" "strex %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 32, TRUE, &var->value, and, val); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; andl %1, %0" : "+m" (var->value) : "ri" (val) : "cc" ); #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if defined __x86_64__ || defined VM_ARM_32 _InterlockedAnd((long *)&var->value, (long)val); #else __asm mov eax, val __asm mov ebx, var __asm lock and [ebx]Atomic_uint32.value, eax #endif #else #error No compiler defined for Atomic_And #endif } #define Atomic_And Atomic_And32 /* *----------------------------------------------------------------------------- * * Atomic_Or32 -- * * Atomic read, bitwise OR with a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Or32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register volatile uint32 res; register volatile uint32 tmp; dmb(); __asm__ __volatile__( "1: ldrex %[tmp], [%[var]] \n\t" "orr %[tmp], %[tmp], %[val] \n\t" "strex %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 32, TRUE, &var->value, orr, val); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; orl %1, %0" : "+m" (var->value) : "ri" (val) : "cc" ); #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if defined __x86_64__ || defined VM_ARM_32 _InterlockedOr((long *)&var->value, (long)val); #else __asm mov eax, val __asm mov ebx, var __asm lock or [ebx]Atomic_uint32.value, eax #endif #else #error No compiler defined for Atomic_Or #endif } #define Atomic_Or Atomic_Or32 /* *----------------------------------------------------------------------------- * * Atomic_Xor32 -- * * Atomic read, bitwise XOR with a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Xor32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register volatile uint32 res; register volatile uint32 tmp; dmb(); __asm__ __volatile__( "1: ldrex %[tmp], [%[var]] \n\t" "eor %[tmp], %[tmp], %[val] \n\t" "strex %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 32, TRUE, &var->value, eor, val); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; xorl %1, %0" : "+m" (var->value) : "ri" (val) : "cc" ); #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if defined __x86_64__ || defined VM_ARM_32 _InterlockedXor((long *)&var->value, (long)val); #else __asm mov eax, val __asm mov ebx, var __asm lock xor [ebx]Atomic_uint32.value, eax #endif #else #error No compiler defined for Atomic_Xor #endif } #define Atomic_Xor Atomic_Xor32 #if defined VM_64BIT /* *----------------------------------------------------------------------------- * * Atomic_Xor64 -- * * Atomic read, bitwise XOR with a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Xor64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { #if defined __GNUC__ #if defined VM_ARM_64 _VMATOM_X(OP, 64, TRUE, &var->value, eor, val); #else /* VM_X86_64 */ /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "lock; xorq %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #endif #elif defined _MSC_VER _InterlockedXor64((__int64 *)&var->value, (__int64)val); #else #error No compiler defined for Atomic_Xor64 #endif } #endif /* *----------------------------------------------------------------------------- * * Atomic_Add32 -- * * Atomic read, add a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Add32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register volatile uint32 res; register volatile uint32 tmp; dmb(); __asm__ __volatile__( "1: ldrex %[tmp], [%[var]] \n\t" "add %[tmp], %[tmp], %[val] \n\t" "strex %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 32, TRUE, &var->value, add, val); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; addl %1, %0" : "+m" (var->value) : "ri" (val) : "cc" ); #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if _MSC_VER >= 1310 _InterlockedExchangeAdd((long *)&var->value, (long)val); #else __asm mov eax, val __asm mov ebx, var __asm lock add [ebx]Atomic_uint32.value, eax #endif #else #error No compiler defined for Atomic_Add #endif } #define Atomic_Add Atomic_Add32 /* *----------------------------------------------------------------------------- * * Atomic_Sub32 -- * * Atomic read, subtract a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Sub32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register volatile uint32 res; register volatile uint32 tmp; dmb(); __asm__ __volatile__( "1: ldrex %[tmp], [%[var]] \n\t" "sub %[tmp], %[tmp], %[val] \n\t" "strex %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 32, TRUE, &var->value, sub, val); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; subl %1, %0" : "+m" (var->value) : "ri" (val) : "cc" ); #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if _MSC_VER >= 1310 _InterlockedExchangeAdd((long *)&var->value, (long)-val); #else __asm mov eax, val __asm mov ebx, var __asm lock sub [ebx]Atomic_uint32.value, eax #endif #else #error No compiler defined for Atomic_Sub #endif } #define Atomic_Sub Atomic_Sub32 /* *----------------------------------------------------------------------------- * * Atomic_Inc32 -- * * Atomic read, increment, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Inc32(Atomic_uint32 *var) // IN/OUT { #ifdef __GNUC__ #if defined VM_ARM_ANY Atomic_Add32(var, 1); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; incl %0" : "+m" (var->value) : : "cc" ); #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if _MSC_VER >= 1310 _InterlockedIncrement((long *)&var->value); #else __asm mov ebx, var __asm lock inc [ebx]Atomic_uint32.value #endif #else #error No compiler defined for Atomic_Inc #endif } #define Atomic_Inc Atomic_Inc32 /* *----------------------------------------------------------------------------- * * Atomic_Dec32 -- * * Atomic read, decrement, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Dec32(Atomic_uint32 *var) // IN/OUT { #ifdef __GNUC__ #if defined VM_ARM_ANY Atomic_Sub32(var, 1); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; decl %0" : "+m" (var->value) : : "cc" ); #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if _MSC_VER >= 1310 _InterlockedDecrement((long *)&var->value); #else __asm mov ebx, var __asm lock dec [ebx]Atomic_uint32.value #endif #else #error No compiler defined for Atomic_Dec #endif } #define Atomic_Dec Atomic_Dec32 /* * Note that the technique below can be used to implement ReadX(), where X is * an arbitrary mathematical function. */ /* *----------------------------------------------------------------------------- * * Atomic_ReadOr32 -- * * Atomic read (returned), bitwise OR with a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint32 Atomic_ReadOr32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { uint32 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 32, TRUE, &var->value, orr, val); #else do { res = Atomic_Read32(var); } while (res != Atomic_ReadIfEqualWrite32(var, res, res | val)); #endif return res; } /* *----------------------------------------------------------------------------- * * Atomic_ReadAnd32 -- * * Atomic read (returned), bitwise And with a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint32 Atomic_ReadAnd32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { uint32 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 32, TRUE, &var->value, and, val); #else do { res = Atomic_Read32(var); } while (res != Atomic_ReadIfEqualWrite32(var, res, res & val)); #endif return res; } #if defined VM_64BIT /* *----------------------------------------------------------------------------- * * Atomic_ReadOr64 -- * * Atomic read (returned), bitwise OR with a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint64 Atomic_ReadOr64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { uint64 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 64, TRUE, &var->value, orr, val); #else do { res = var->value; } while (res != Atomic_ReadIfEqualWrite64(var, res, res | val)); #endif return res; } /* *----------------------------------------------------------------------------- * * Atomic_ReadAnd64 -- * * Atomic read (returned), bitwise AND with a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint64 Atomic_ReadAnd64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { uint64 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 64, TRUE, &var->value, and, val); #else do { res = var->value; } while (res != Atomic_ReadIfEqualWrite64(var, res, res & val)); #endif return res; } #endif /* defined VM_64BIT */ /* *----------------------------------------------------------------------------- * * Atomic_ReadAdd32 -- * * Atomic read (returned), add a value, write. * * If you have to implement ReadAdd32() on an architecture other than * x86 or x86-64, you might want to consider doing something similar to * Atomic_ReadOr32(). * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint32 Atomic_ReadAdd32(Atomic_uint32 *var, // IN/OUT uint32 val) // IN { #if defined __GNUC__ #ifdef VM_ARM_V7 register volatile uint32 res; register volatile uint32 retVal; register volatile uint32 tmp; dmb(); __asm__ __volatile__( "1: ldrex %[retVal], [%[var]] \n\t" "add %[tmp], %[val], %[retVal] \n\t" "strex %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [tmp] "=&r" (tmp), [res] "=&r" (res), [retVal] "=&r" (retVal) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); return retVal; #elif defined VM_ARM_64 return _VMATOM_X(ROP, 32, TRUE, &var->value, add, val); #else /* VM_X86_ANY */ /* Checked against the Intel manual and GCC --walken */ __asm__ __volatile__( "lock; xaddl %0, %1" : "=r" (val), "+m" (var->value) : "0" (val) : "cc" ); return val; #endif /* VM_X86_ANY */ #elif defined _MSC_VER #if _MSC_VER >= 1310 return _InterlockedExchangeAdd((long *)&var->value, (long)val); #else #pragma warning(push) #pragma warning(disable : 4035) // disable no-return warning { __asm mov eax, val __asm mov ebx, var __asm lock xadd [ebx]Atomic_uint32.value, eax } #pragma warning(pop) #endif #else #error No compiler defined for Atomic_ReadAdd32 #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadInc32 -- * * Atomic read (returned), increment, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint32 Atomic_ReadInc32(Atomic_uint32 *var) // IN/OUT { return Atomic_ReadAdd32(var, 1); } /* *----------------------------------------------------------------------------- * * Atomic_ReadDec32 -- * * Atomic read (returned), decrement, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint32 Atomic_ReadDec32(Atomic_uint32 *var) // IN/OUT { return Atomic_ReadAdd32(var, (uint32)-1); } /* *----------------------------------------------------------------------------- * * Atomic_CMPXCHG64 -- * * Compare exchange: Read variable, if equal to oldVal, write newVal * * Results: * TRUE if equal, FALSE if not equal * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE Bool Atomic_CMPXCHG64(Atomic_uint64 *var, // IN/OUT uint64 oldVal, // IN uint64 newVal) // IN { #if defined __GNUC__ #if defined VM_ARM_ANY return Atomic_ReadIfEqualWrite64(var, oldVal, newVal) == oldVal; #else /* VM_X86_ANY */ Bool equal; /* Checked against the Intel manual and GCC --walken */ #if defined __x86_64__ uint64 dummy; __asm__ __volatile__( "lock; cmpxchgq %3, %0" "\n\t" "sete %1" : "+m" (*var), "=qm" (equal), "=a" (dummy) : "r" (newVal), "2" (oldVal) : "cc" ); #else /* 32-bit version for non-ARM */ typedef struct { uint32 lowValue; uint32 highValue; } S_uint64; int dummy1, dummy2; # if defined __PIC__ /* * Rules for __asm__ statements in __PIC__ code * -------------------------------------------- * * The compiler uses %ebx for __PIC__ code, so an __asm__ statement cannot * clobber %ebx. The __asm__ statement can temporarily modify %ebx, but _for * each parameter that is used while %ebx is temporarily modified_: * * 1) The constraint cannot be "m", because the memory location the compiler * chooses could then be relative to %ebx. * * 2) The constraint cannot be a register class which contains %ebx (such as * "r" or "q"), because the register the compiler chooses could then be * %ebx. (This happens when compiling the Fusion UI with gcc 4.2.1, Apple * build 5577.) * * 3) Using register classes even for other values is problematic, as gcc * can decide e.g. %ecx == %edi == 0 (as compile-time constants) and * ends up using one register for two things. Which breaks xchg's ability * to temporarily put the PIC pointer somewhere else. PR772455 * * For that reason alone, the __asm__ statement should keep the regions * where it temporarily modifies %ebx as small as possible, and should * prefer specific register assignments. */ __asm__ __volatile__( "xchgl %%ebx, %6" "\n\t" "lock; cmpxchg8b (%3)" "\n\t" "xchgl %%ebx, %6" "\n\t" "sete %0" : "=qm" (equal), "=a" (dummy1), "=d" (dummy2) : /* * See the "Rules for __asm__ statements in __PIC__ code" above: %3 * must use a register class which does not contain %ebx. * "a"/"c"/"d" are already used, so we are left with either "S" or "D". * * Note that this assembly uses ALL GP registers (with %esp reserved for * stack, %ebp reserved for frame, %ebx reserved for PIC). */ "S" (var), "1" (((S_uint64 *)&oldVal)->lowValue), "2" (((S_uint64 *)&oldVal)->highValue), "D" (((S_uint64 *)&newVal)->lowValue), "c" (((S_uint64 *)&newVal)->highValue) : "cc", "memory" ); # else __asm__ __volatile__( "lock; cmpxchg8b %0" "\n\t" "sete %1" : "+m" (*var), "=qm" (equal), "=a" (dummy1), "=d" (dummy2) : "2" (((S_uint64 *)&oldVal)->lowValue), "3" (((S_uint64 *)&oldVal)->highValue), "b" (((S_uint64 *)&newVal)->lowValue), "c" (((S_uint64 *)&newVal)->highValue) : "cc" ); # endif #endif return equal; #endif //VM_ARM_V7 #elif defined _MSC_VER return (__int64)oldVal == _InterlockedCompareExchange64((__int64 *)&var->value, (__int64)newVal, (__int64)oldVal); #else #error No compiler defined for Atomic_CMPXCHG64 #endif // !GNUC } /* *----------------------------------------------------------------------------- * * Atomic_CMPXCHG32 -- * * Compare exchange: Read variable, if equal to oldVal, write newVal * * Results: * TRUE if equal, FALSE if not equal * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE Bool Atomic_CMPXCHG32(Atomic_uint32 *var, // IN/OUT uint32 oldVal, // IN uint32 newVal) // IN { #if defined __GNUC__ #if defined VM_ARM_ANY return Atomic_ReadIfEqualWrite32(var, oldVal, newVal) == oldVal; #else /* VM_X86_ANY */ Bool equal; uint32 dummy; __asm__ __volatile__( "lock; cmpxchgl %3, %0" "\n\t" "sete %1" : "+m" (*var), "=qm" (equal), "=a" (dummy) : "r" (newVal), "2" (oldVal) : "cc" ); return equal; #endif /* VM_X86_ANY */ #else // defined __GNUC__ return Atomic_ReadIfEqualWrite32(var, oldVal, newVal) == oldVal; #endif // !defined __GNUC__ } /* *----------------------------------------------------------------------------- * * Atomic_Read64 -- * * Read and return. * * Results: * The value of the atomic variable. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE uint64 Atomic_Read64(Atomic_uint64 const *var) // IN { #if defined __GNUC__ uint64 value; #endif #if defined VMM || defined VM_ARM_64 || defined VMKERNEL || defined VMKERNEL_MODULE ASSERT((uintptr_t)var % 8 == 0); #endif #if defined __GNUC__ && defined __x86_64__ /* * Use asm to ensure we emit a single load. */ __asm__ __volatile__( "movq %1, %0" : "=r" (value) : "m" (var->value) ); #elif defined __GNUC__ && defined __i386__ /* * Since cmpxchg8b will replace the contents of EDX:EAX with the * value in memory if there is no match, we need only execute the * instruction once in order to atomically read 64 bits from * memory. The only constraint is that ECX:EBX must have the same * value as EDX:EAX so that if the comparison succeeds. We * intentionally don't tell gcc that we are using ebx and ecx as we * don't modify them and do not care what value they store. */ __asm__ __volatile__( "mov %%ebx, %%eax" "\n\t" "mov %%ecx, %%edx" "\n\t" "lock; cmpxchg8b %1" : "=&A" (value) : "m" (*var) : "cc" ); #elif defined _MSC_VER && defined __x86_64__ /* * Microsoft docs guarantee "Simple reads and writes to properly * aligned 64-bit variables are atomic on 64-bit Windows." * http://msdn.microsoft.com/en-us/library/ms684122%28VS.85%29.aspx * * XXX Verify that value is properly aligned. Bug 61315. */ return var->value; #elif defined _MSC_VER && defined VM_ARM_32 return _InterlockedAdd64((__int64 *)&var->value, 0); #elif defined _MSC_VER && defined __i386__ # pragma warning(push) # pragma warning(disable : 4035) // disable no-return warning { __asm mov ecx, var __asm mov edx, ecx __asm mov eax, ebx __asm lock cmpxchg8b [ecx] // edx:eax is the return value; this is documented to work. --mann } # pragma warning(pop) #elif defined __GNUC__ && defined VM_ARM_V7 __asm__ __volatile__( "ldrexd %[value], %H[value], [%[var]] \n\t" : [value] "=&r" (value) : [var] "r" (&var->value) ); #elif defined VM_ARM_64 value = _VMATOM_X(R, 64, &var->value); #endif #if defined __GNUC__ return value; #endif } /* *---------------------------------------------------------------------- * * Atomic_ReadUnaligned64 -- * * Atomically read a 64 bit integer, possibly misaligned. * This function can be *very* expensive, costing over 50 kcycles * on Nehalem. * * Note that "var" needs to be writable, even though it will not * be modified. * * Results: * The value of the atomic variable. * * Side effects: * None * *---------------------------------------------------------------------- */ #if defined VM_64BIT static INLINE uint64 Atomic_ReadUnaligned64(Atomic_uint64 const *var) // IN: { return Atomic_ReadIfEqualWrite64((Atomic_uint64*)var, 0, 0); } #endif /* *---------------------------------------------------------------------- * * Atomic_ReadAdd64 -- * * Atomically adds a 64-bit integer to another * * Results: * Returns the old value just prior to the addition * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE uint64 Atomic_ReadAdd64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { #if defined VM_ARM_64 return _VMATOM_X(ROP, 64, TRUE, &var->value, add, val); #elif defined __x86_64__ #if defined __GNUC__ __asm__ __volatile__( "lock; xaddq %0, %1" : "=r" (val), "+m" (var->value) : "0" (val) : "cc" ); return val; #elif defined _MSC_VER return _InterlockedExchangeAdd64((__int64 *)&var->value, (__int64)val); #else #error No compiler defined for Atomic_ReadAdd64 #endif #else uint64 oldVal; uint64 newVal; do { oldVal = var->value; newVal = oldVal + val; } while (!Atomic_CMPXCHG64(var, oldVal, newVal)); return oldVal; #endif } /* *---------------------------------------------------------------------- * * Atomic_ReadSub64 -- * * Atomically subtracts a 64-bit integer to another * * Results: * Returns the old value just prior to the subtraction * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE uint64 Atomic_ReadSub64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { #if defined VM_ARM_64 return _VMATOM_X(ROP, 64, TRUE, &var->value, sub, val); #else return Atomic_ReadAdd64(var, -val); #endif } /* *---------------------------------------------------------------------- * * Atomic_ReadInc64 -- * * Atomically increments a 64-bit integer * * Results: * Returns the old value just prior to incrementing * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE uint64 Atomic_ReadInc64(Atomic_uint64 *var) // IN/OUT { return Atomic_ReadAdd64(var, 1); } /* *---------------------------------------------------------------------- * * Atomic_ReadDec64 -- * * Atomically decrements a 64-bit integer * * Results: * Returns the old value just prior to decrementing * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE uint64 Atomic_ReadDec64(Atomic_uint64 *var) // IN/OUT { return Atomic_ReadAdd64(var, CONST64U(-1)); } /* *----------------------------------------------------------------------------- * * Atomic_Add64 -- * * Atomic read, add a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Add64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { #if !defined VM_64BIT Atomic_ReadAdd64(var, val); /* Return value is unused. */ #elif defined __GNUC__ #if defined VM_ARM_64 _VMATOM_X(OP, 64, TRUE, &var->value, add, val); #else /* defined VM_X86_64 */ /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "lock; addq %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #endif #elif defined _MSC_VER _InterlockedExchangeAdd64((__int64 *)&var->value, (__int64)val); #else #error No compiler defined for Atomic_Add64 #endif } /* *----------------------------------------------------------------------------- * * Atomic_Sub64 -- * * Atomic read, subtract a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Sub64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { #if !defined VM_64BIT Atomic_ReadSub64(var, val); /* Return value is unused. */ #elif defined __GNUC__ #if defined VM_ARM_64 _VMATOM_X(OP, 64, TRUE, &var->value, sub, val); #else /* VM_X86_64 */ /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "lock; subq %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #endif #elif defined _MSC_VER _InterlockedExchangeAdd64((__int64 *)&var->value, (__int64)-val); #else #error No compiler defined for Atomic_Sub64 #endif } /* *----------------------------------------------------------------------------- * * Atomic_Inc64 -- * * Atomic read, increment, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Inc64(Atomic_uint64 *var) // IN/OUT { #if defined VM_ARM_64 Atomic_Add64(var, 1); #elif !defined __x86_64__ Atomic_ReadInc64(var); /* Return value is unused. */ #elif defined __GNUC__ /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "lock; incq %0" : "+m" (var->value) : : "cc" ); #elif defined _MSC_VER _InterlockedIncrement64((__int64 *)&var->value); #else #error No compiler defined for Atomic_Inc64 #endif } /* *----------------------------------------------------------------------------- * * Atomic_Dec64 -- * * Atomic read, decrement, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Dec64(Atomic_uint64 *var) // IN/OUT { #if defined VM_ARM_64 Atomic_Sub64(var, 1); #elif !defined __x86_64__ Atomic_ReadDec64(var); /* Return value is unused. */ #elif defined __GNUC__ /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "lock; decq %0" : "+m" (var->value) : : "cc" ); #elif defined _MSC_VER _InterlockedDecrement64((__int64 *)&var->value); #else #error No compiler defined for Atomic_Dec64 #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadWrite64 -- * * Read followed by write * * Results: * The value of the atomic variable before the write. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint64 Atomic_ReadWrite64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { #if defined __x86_64__ #if defined __GNUC__ /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "xchgq %0, %1" : "=r" (val), "+m" (var->value) : "0" (val) ); return val; #elif defined _MSC_VER return _InterlockedExchange64((__int64 *)&var->value, (__int64)val); #else #error No compiler defined for Atomic_ReadWrite64 #endif #elif defined VM_ARM_64 return _VMATOM_X(RW, 64, TRUE, &var->value, val); #else uint64 oldVal; do { oldVal = var->value; } while (!Atomic_CMPXCHG64(var, oldVal, val)); return oldVal; #endif } /* *----------------------------------------------------------------------------- * * Atomic_Write64 -- * * Write * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Write64(Atomic_uint64 *var, // OUT uint64 val) // IN { #if defined VMM || defined VM_ARM_64 || defined VMKERNEL || defined VMKERNEL_MODULE ASSERT((uintptr_t)var % 8 == 0); #endif #if defined __x86_64__ #if defined __GNUC__ /* * There is no move instruction for 64-bit immediate to memory, so unless * the immediate value fits in 32-bit (i.e. can be sign-extended), GCC * breaks the assignment into two movl instructions. The code below forces * GCC to load the immediate value into a register first. */ __asm__ __volatile__( "movq %1, %0" : "=m" (var->value) : "r" (val) ); #elif defined _MSC_VER /* * Microsoft docs guarantee "Simple reads and writes to properly aligned * 64-bit variables are atomic on 64-bit Windows." * http://msdn.microsoft.com/en-us/library/ms684122%28VS.85%29.aspx * * XXX Verify that value is properly aligned. Bug 61315. */ var->value = val; #else #error No compiler defined for Atomic_Write64 #endif #elif defined VM_ARM_64 _VMATOM_X(W, 64, &var->value, val); #else (void)Atomic_ReadWrite64(var, val); #endif } /* *----------------------------------------------------------------------------- * * Atomic_Or64 -- * * Atomic read, bitwise OR with a 64-bit value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Or64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { #if defined __x86_64__ #if defined __GNUC__ /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "lock; orq %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #elif defined _MSC_VER _InterlockedOr64((__int64 *)&var->value, (__int64)val); #else #error No compiler defined for Atomic_Or64 #endif #elif defined VM_ARM_64 _VMATOM_X(OP, 64, TRUE, &var->value, orr, val); #else // __x86_64__ uint64 oldVal; uint64 newVal; do { oldVal = var->value; newVal = oldVal | val; } while (!Atomic_CMPXCHG64(var, oldVal, newVal)); #endif } /* *----------------------------------------------------------------------------- * * Atomic_And64 -- * * Atomic read, bitwise AND with a 64-bit value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_And64(Atomic_uint64 *var, // IN/OUT uint64 val) // IN { #if defined __x86_64__ #if defined __GNUC__ /* Checked against the AMD manual and GCC --hpreg */ __asm__ __volatile__( "lock; andq %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #elif defined _MSC_VER _InterlockedAnd64((__int64 *)&var->value, (__int64)val); #else #error No compiler defined for Atomic_And64 #endif #elif defined VM_ARM_64 _VMATOM_X(OP, 64, TRUE, &var->value, and, val); #else // __x86_64__ uint64 oldVal; uint64 newVal; do { oldVal = var->value; newVal = oldVal & val; } while (!Atomic_CMPXCHG64(var, oldVal, newVal)); #endif } /* *----------------------------------------------------------------------------- * * Atomic_SetBit64 -- * * Atomically set the bit 'bit' in var. Bit must be between 0 and 63. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_SetBit64(Atomic_uint64 *var, // IN/OUT unsigned bit) // IN { #if defined __x86_64__ && defined __GNUC__ ASSERT(bit <= 63); __asm__ __volatile__( "lock; btsq %1, %0" : "+m" (var->value) : "ri" ((uint64)bit) : "cc" ); #else uint64 oldVal; uint64 newVal; ASSERT(bit <= 63); do { oldVal = var->value; newVal = oldVal | (CONST64U(1) << bit); } while (!Atomic_CMPXCHG64(var, oldVal, newVal)); #endif } /* *----------------------------------------------------------------------------- * * Atomic_ClearBit64 -- * * Atomically clear the bit 'bit' in var. Bit must be between 0 and 63. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_ClearBit64(Atomic_uint64 *var, // IN/OUT unsigned bit) // IN { #if defined __x86_64__ && defined __GNUC__ ASSERT(bit <= 63); __asm__ __volatile__( "lock; btrq %1, %0" : "+m" (var->value) : "ri" ((uint64)bit) : "cc" ); #else uint64 oldVal; uint64 newVal; ASSERT(bit <= 63); do { oldVal = var->value; newVal = oldVal & ~(CONST64U(1) << bit); } while (!Atomic_CMPXCHG64(var, oldVal, newVal)); #endif } /* *----------------------------------------------------------------------------- * * Atomic_TestBit64 -- * * Read the bit 'bit' in var. Bit must be between 0 and 63. * * Results: * TRUE if the tested bit was set; else FALSE. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE Bool Atomic_TestBit64(Atomic_uint64 *var, // IN unsigned bit) // IN { Bool out; ASSERT(bit <= 63); #if defined __x86_64__ && defined __GNUC__ __asm__ __volatile__( "btq %2, %1; setc %0" : "=rm"(out) : "m" (var->value), "rJ" ((uint64)bit) : "cc" ); #else out = (var->value & (CONST64U(1) << bit)) != 0; #endif return out; } #if defined __GNUC__ /* *----------------------------------------------------------------------------- * * Atomic_Read16 -- * * Read and return. * * Results: * The value of the atomic variable. * * Side effects: * None. * *----------------------------------------------------------------------------- */ static INLINE uint16 Atomic_Read16(Atomic_uint16 const *var) // IN { uint16 value; #if defined VMM || defined VM_ARM_64 || defined VMKERNEL || defined VMKERNEL_MODULE ASSERT((uintptr_t)var % 2 == 0); #endif #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "movw %1, %0" : "=r" (value) : "m" (var->value) ); #elif defined VM_ARM_V7 NOT_TESTED(); __asm__ __volatile__( "ldrh %0, [%1]" : "=r" (value) : "r" (&var->value) ); #elif defined VM_ARM_64 value = _VMATOM_X(R, 16, &var->value); #else #error No 16-bits atomics. #endif #endif return value; } /* *----------------------------------------------------------------------------- * * Atomic_ReadWrite16 -- * * Read followed by write * * Results: * The value of the atomic variable before the write. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint16 Atomic_ReadWrite16(Atomic_uint16 *var, // IN/OUT: uint16 val) // IN: { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "xchgw %0, %1" : "=r" (val), "+m" (var->value) : "0" (val) ); return val; #elif defined VM_ARM_V7 register volatile uint16 retVal; register volatile uint16 res; NOT_TESTED(); dmb(); __asm__ __volatile__( "1: ldrexh %[retVal], [%[var]] \n\t" "strexh %[res], %[val], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [retVal] "=&r" (retVal), [res] "=&r" (res) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); return retVal; #elif defined VM_ARM_64 return _VMATOM_X(RW, 16, TRUE, &var->value, val); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_Write16 -- * * Write * * Results: * None. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Write16(Atomic_uint16 *var, // OUT: uint16 val) // IN: { #if defined VMM || defined VM_ARM_64 || defined VMKERNEL || defined VMKERNEL_MODULE ASSERT((uintptr_t)var % 2 == 0); #endif #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "movw %1, %0" : "=m" (var->value) : "r" (val) ); #elif defined VM_ARM_64 _VMATOM_X(W, 16, &var->value, val); #elif defined VM_ARM_32 /* * Best left this way due to the intricacies of exclusive load/store * operations on legacy (32-bit) ARM. */ Atomic_ReadWrite16(var, val); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadIfEqualWrite16 -- * * Compare exchange: Read variable, if equal to oldVal, write newVal * * Results: * The value of the atomic variable before the write. * * Side effects: * The variable may be modified. * *----------------------------------------------------------------------------- */ static INLINE uint16 Atomic_ReadIfEqualWrite16(Atomic_uint16 *var, // IN/OUT uint16 oldVal, // IN uint16 newVal) // IN { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ uint16 val; __asm__ __volatile__( "lock; cmpxchgw %2, %1" : "=a" (val), "+m" (var->value) : "r" (newVal), "0" (oldVal) : "cc" ); return val; #elif defined VM_ARM_V7 register uint16 retVal; register uint16 res; NOT_TESTED(); dmb(); __asm__ __volatile__( "1: ldrexh %[retVal], [%[var]] \n\t" "mov %[res], #0 \n\t" "teq %[retVal], %[oldVal] \n\t" "strexheq %[res], %[newVal], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [retVal] "=&r" (retVal), [res] "=&r" (res) : [var] "r" (&var->value), [oldVal] "r" (oldVal), [newVal] "r" (newVal) : "cc" ); dmb(); return retVal; #elif defined VM_ARM_64 return _VMATOM_X(RIFEQW, 16, TRUE, &var->value, oldVal, newVal); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_And16 -- * * Atomic read, bitwise AND with a 16-bit value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_And16(Atomic_uint16 *var, // IN/OUT uint16 val) // IN { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "lock; andw %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #elif defined VM_ARM_V7 register volatile uint16 res; register volatile uint16 tmp; NOT_TESTED(); dmb(); __asm__ __volatile__( "1: ldrexh %[tmp], [%[var]] \n\t" "and %[tmp], %[tmp], %[val] \n\t" "strexh %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 16, TRUE, &var->value, and, val); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_Or16 -- * * Atomic read, bitwise OR with a 16-bit value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Or16(Atomic_uint16 *var, // IN/OUT uint16 val) // IN { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "lock; orw %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #elif defined VM_ARM_V7 register volatile uint16 res; register volatile uint16 tmp; NOT_TESTED(); dmb(); __asm__ __volatile__( "1: ldrexh %[tmp], [%[var]] \n\t" "orr %[tmp], %[tmp], %[val] \n\t" "strexh %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 16, TRUE, &var->value, orr, val); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_Xor16 -- * * Atomic read, bitwise XOR with a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Xor16(Atomic_uint16 *var, // IN/OUT uint16 val) // IN { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "lock; xorw %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #elif defined VM_ARM_V7 register volatile uint16 res; register volatile uint16 tmp; NOT_TESTED(); dmb(); __asm__ __volatile__( "1: ldrexh %[tmp], [%[var]] \n\t" "eor %[tmp], %[tmp], %[val] \n\t" "strexh %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 16, TRUE, &var->value, eor, val); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_Add16 -- * * Atomic read, add a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Add16(Atomic_uint16 *var, // IN/OUT uint16 val) // IN { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "lock; addw %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #elif defined VM_ARM_V7 register volatile uint16 res; register volatile uint16 tmp; NOT_TESTED(); dmb(); __asm__ __volatile__( "1: ldrexh %[tmp], [%[var]] \n\t" "add %[tmp], %[tmp], %[val] \n\t" "strexh %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 16, TRUE, &var->value, add, val); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_Sub16 -- * * Atomic read, subtract a value, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Sub16(Atomic_uint16 *var, // IN/OUT uint16 val) // IN { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "lock; subw %1, %0" : "+m" (var->value) : "re" (val) : "cc" ); #elif defined VM_ARM_V7 register volatile uint16 res; register volatile uint16 tmp; NOT_TESTED(); dmb(); __asm__ __volatile__( "1: ldrexh %[tmp], [%[var]] \n\t" "sub %[tmp], %[tmp], %[val] \n\t" "strexh %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [res] "=&r" (res), [tmp] "=&r" (tmp) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); #elif defined VM_ARM_64 _VMATOM_X(OP, 16, TRUE, &var->value, sub, val); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_Inc16 -- * * Atomic read, increment, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Inc16(Atomic_uint16 *var) // IN/OUT { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "lock; incw %0" : "+m" (var->value) : : "cc" ); #elif defined VM_ARM_ANY Atomic_Add16(var, 1); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_Dec16 -- * * Atomic read, decrement, write. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE void Atomic_Dec16(Atomic_uint16 *var) // IN/OUT { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "lock; decw %0" : "+m" (var->value) : : "cc" ); #elif defined VM_ARM_ANY Atomic_Sub16(var, 1); #else #error No 16-bits atomics. #endif #endif } /* *----------------------------------------------------------------------------- * * Atomic_ReadOr16 -- * * Atomic read (returned), bitwise OR with a value, write. * * Results: * The value of the variable before the operation. * * Side effects: * None * *----------------------------------------------------------------------------- */ static INLINE uint16 Atomic_ReadOr16(Atomic_uint16 *var, // IN/OUT uint16 val) // IN { uint16 res; #if defined VM_ARM_64 res = _VMATOM_X(ROP, 16, TRUE, &var->value, orr, val); #else do { res = var->value; } while (res != Atomic_ReadIfEqualWrite16(var, res, res | val)); #endif return res; } /* *---------------------------------------------------------------------- * * Atomic_ReadAdd16 -- * * Atomically adds a 16-bit integer to another * * Results: * Returns the old value just prior to the addition * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE uint16 Atomic_ReadAdd16(Atomic_uint16 *var, // IN/OUT uint16 val) // IN: { #if defined __GNUC__ #if defined __x86_64__ || defined __i386__ __asm__ __volatile__( "lock; xaddw %0, %1" : "=r" (val), "+m" (var->value) : "0" (val) : "cc" ); return val; #elif defined VM_ARM_V7 register volatile uint16 res; register volatile uint16 retVal; register volatile uint16 tmp; NOT_TESTED(); dmb(); __asm__ __volatile__( "1: ldrexh %[retVal], [%[var]] \n\t" "add %[tmp], %[val], %[retVal] \n\t" "strexh %[res], %[tmp], [%[var]] \n\t" "teq %[res], #0 \n\t" "bne 1b" : [tmp] "=&r" (tmp), [res] "=&r" (res), [retVal] "=&r" (retVal) : [var] "r" (&var->value), [val] "r" (val) : "cc" ); dmb(); return retVal; #elif defined VM_ARM_64 return _VMATOM_X(ROP, 16, TRUE, &var->value, add, val); #else #error No 16-bits atomics. #endif #endif } /* *---------------------------------------------------------------------- * * Atomic_ReadInc16 -- * * Atomically increments a 64-bit integer * * Results: * Returns the old value just prior to incrementing * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE uint16 Atomic_ReadInc16(Atomic_uint16 *var) // IN/OUT { return Atomic_ReadAdd16(var, 1); } /* *---------------------------------------------------------------------- * * Atomic_ReadDec16 -- * * Atomically decrements a 64-bit integer * * Results: * Returns the old value just prior to decrementing * * Side effects: * None * *---------------------------------------------------------------------- */ static INLINE uint16 Atomic_ReadDec16(Atomic_uint16 *var) // IN/OUT { return Atomic_ReadAdd16(var, -1); } #endif /* * Template code for the Atomic_ type and its operators. * * The cast argument is an intermediate type cast to make some * compilers stop complaining about casting uint32 <-> void *, * even though we only do it in the 32-bit case so they are always * the same size. So for val of type uint32, instead of * (void *)val, we have (void *)(uintptr_t)val. * The specific problem case is the Windows ddk compiler * (as used by the SVGA driver). -- edward * * NOTE: See the comment in vm_assert.h for why we need UNUSED_TYPE in * AtomicAssertOnCompile(), and why we need to be very careful doing so. */ #define MAKE_ATOMIC_TYPE(name, size, in, out, cast) \ typedef Atomic_uint ## size Atomic_ ## name; \ \ \ static INLINE void \ AtomicAssertOnCompile ## name(void) \ { \ enum { AssertOnCompileMisused = 8 * sizeof (in) == size \ && 8 * sizeof (out) == size \ && 8 * sizeof (cast) == size \ ? 1 : -1 }; \ UNUSED_TYPE(typedef char AssertOnCompileFailed[AssertOnCompileMisused]);\ } \ \ \ static INLINE out \ Atomic_Read ## name(Atomic_ ## name const *var) \ { \ return (out)(cast)Atomic_Read ## size(var); \ } \ \ \ static INLINE void \ Atomic_Write ## name(Atomic_ ## name *var, \ in val) \ { \ Atomic_Write ## size(var, (uint ## size)(cast)val); \ } \ \ \ static INLINE out \ Atomic_ReadWrite ## name(Atomic_ ## name *var, \ in val) \ { \ return (out)(cast)Atomic_ReadWrite ## size(var, \ (uint ## size)(cast)val); \ } \ \ \ static INLINE out \ Atomic_ReadIfEqualWrite ## name(Atomic_ ## name *var, \ in oldVal, \ in newVal) \ { \ return (out)(cast)Atomic_ReadIfEqualWrite ## size(var, \ (uint ## size)(cast)oldVal, (uint ## size)(cast)newVal); \ } \ \ \ static INLINE void \ Atomic_And ## name(Atomic_ ## name *var, \ in val) \ { \ Atomic_And ## size(var, (uint ## size)(cast)val); \ } \ \ \ static INLINE void \ Atomic_Or ## name(Atomic_ ## name *var, \ in val) \ { \ Atomic_Or ## size(var, (uint ## size)(cast)val); \ } \ \ \ static INLINE void \ Atomic_Xor ## name(Atomic_ ## name *var, \ in val) \ { \ Atomic_Xor ## size(var, (uint ## size)(cast)val); \ } \ \ \ static INLINE void \ Atomic_Add ## name(Atomic_ ## name *var, \ in val) \ { \ Atomic_Add ## size(var, (uint ## size)(cast)val); \ } \ \ \ static INLINE void \ Atomic_Sub ## name(Atomic_ ## name *var, \ in val) \ { \ Atomic_Sub ## size(var, (uint ## size)(cast)val); \ } \ \ \ static INLINE void \ Atomic_Inc ## name(Atomic_ ## name *var) \ { \ Atomic_Inc ## size(var); \ } \ \ \ static INLINE void \ Atomic_Dec ## name(Atomic_ ## name *var) \ { \ Atomic_Dec ## size(var); \ } \ \ \ static INLINE out \ Atomic_ReadOr ## name(Atomic_ ## name *var, \ in val) \ { \ return (out)(cast)Atomic_ReadOr ## size(var, (uint ## size)(cast)val); \ } \ \ \ static INLINE out \ Atomic_ReadAdd ## name(Atomic_ ## name *var, \ in val) \ { \ return (out)(cast)Atomic_ReadAdd ## size(var, (uint ## size)(cast)val); \ } \ \ \ static INLINE out \ Atomic_ReadInc ## name(Atomic_ ## name *var) \ { \ return (out)(cast)Atomic_ReadInc ## size(var); \ } \ \ \ static INLINE out \ Atomic_ReadDec ## name(Atomic_ ## name *var) \ { \ return (out)(cast)Atomic_ReadDec ## size(var); \ } /* * Since we use a macro to generate these definitions, it is hard to look for * them. So DO NOT REMOVE THIS COMMENT and keep it up-to-date. --hpreg * * Atomic_Ptr * Atomic_ReadPtr -- * Atomic_WritePtr -- * Atomic_ReadWritePtr -- * Atomic_ReadIfEqualWritePtr -- * Atomic_AndPtr -- * Atomic_OrPtr -- * Atomic_XorPtr -- * Atomic_AddPtr -- * Atomic_SubPtr -- * Atomic_IncPtr -- * Atomic_DecPtr -- * Atomic_ReadOrPtr -- * Atomic_ReadAddPtr -- * Atomic_ReadIncPtr -- * Atomic_ReadDecPtr -- * * Atomic_Int * Atomic_ReadInt -- * Atomic_WriteInt -- * Atomic_ReadWriteInt -- * Atomic_ReadIfEqualWriteInt -- * Atomic_AndInt -- * Atomic_OrInt -- * Atomic_XorInt -- * Atomic_AddInt -- * Atomic_SubInt -- * Atomic_IncInt -- * Atomic_DecInt -- * Atomic_ReadOrInt -- * Atomic_ReadAddInt -- * Atomic_ReadIncInt -- * Atomic_ReadDecInt -- * * Atomic_Bool * Atomic_ReadBool -- * Atomic_WriteBool -- * Atomic_ReadWriteBool -- * Atomic_ReadIfEqualWriteBool -- * Atomic_AndBool -- * Atomic_OrBool -- * Atomic_XorBool -- * Atomic_AddBool -- * Atomic_SubBool -- * Atomic_IncBool -- * Atomic_DecBool -- * Atomic_ReadOrBool -- * Atomic_ReadAddBool -- * Atomic_ReadIncBool -- * Atomic_ReadDecBool -- */ #if defined VM_64BIT MAKE_ATOMIC_TYPE(Ptr, 64, void const *, void *, uintptr_t) #else MAKE_ATOMIC_TYPE(Ptr, 32, void const *, void *, uintptr_t) #endif MAKE_ATOMIC_TYPE(Int, 32, int, int, int) MAKE_ATOMIC_TYPE(Bool, 8, Bool, Bool, Bool) #ifdef VM_ARM_64 # include "vm_atomic_arm64_end.h" #endif #if defined __cplusplus } // extern "C" #endif #endif // ifndef _ATOMIC_H_ open-vm-tools-stable-10.2.0/open-vm-tools/lib/include/vm_basic_asm.h000066400000000000000000000724101321503522500252670ustar00rootroot00000000000000/********************************************************* * Copyright (C) 2003-2017 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * *********************************************************/ /********************************************************* * The contents of this file are subject to the terms of the Common * Development and Distribution License (the "License") version 1.0 * and no later version. You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1.php * * See the License for the specific language governing permissions * and limitations under the License. * *********************************************************/ /* * vm_basic_asm.h * * Basic asm macros */ #ifndef _VM_BASIC_ASM_H_ #define _VM_BASIC_ASM_H_ #define INCLUDE_ALLOW_USERLEVEL #define INCLUDE_ALLOW_MODULE #define INCLUDE_ALLOW_VMMON #define INCLUDE_ALLOW_VMK_MODULE #define INCLUDE_ALLOW_VMKERNEL #define INCLUDE_ALLOW_DISTRIBUTE #define INCLUDE_ALLOW_VMCORE #include "includeCheck.h" #include "vm_basic_types.h" #if defined VM_X86_64 #include "vm_basic_asm_x86_common.h" #include "vm_basic_asm_x86_64.h" #elif defined VM_X86_32 #include "vm_basic_asm_x86_common.h" #include "vm_basic_asm_x86.h" #elif defined VM_ARM_32 #include "vm_basic_asm_arm32.h" #define MUL64_NO_ASM 1 #include "mul64.h" #elif defined VM_ARM_64 #include "arm64_basic_defs.h" #include "vm_basic_asm_arm64.h" #else #define MUL64_NO_ASM 1 #include "mul64.h" #endif #if defined __cplusplus extern "C" { #endif /* * Locate most and least significant bit set functions. Use our own name * space to avoid namespace collisions. The new names follow a pattern, *